1
0

reports.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. <?php /** @noinspection PhpIncludeInspection */
  2. /** @noinspection PhpUnhandledExceptionInspection */
  3. Core::addScript("public/js/app-reports.js");
  4. Core::addBreadcrumb("/account", "Account");
  5. Core::addBreadcrumb("/account/reports", "Reports");
  6. $customer = Customer::getForAdmin();
  7. if(!$customer) throw new Exception("You do not have permission to access this page.");
  8. $customer_slug = Util::slug($customer->name);
  9. $customer_slug = str_replace("-", "_", $customer_slug);
  10. $logo_file_path = ROOT_DIR . "/public/img/customer_logos/{$customer_slug}_logo.png";
  11. $has_logo = file_exists($logo_file_path);
  12. $page_title = "$customer->name Reports";
  13. Core::addBreadcrumb("/account/reports?customer_id=$customer->id", $page_title);
  14. $date_range = http::value("date_range");
  15. if(!$date_range) {
  16. $date_range = "ytd";
  17. }
  18. $date_resolution = http::value("date_resolution");
  19. $date_start = http::value("date_start");
  20. $date_end = http::value("date_end");
  21. $exclude_project_ids = http::value("exclude_project_ids", "int");
  22. if(!is_array($exclude_project_ids)) {
  23. $exclude_project_ids = [];
  24. }
  25. $location_ids = http::value("location_ids");
  26. if(!empty($location_ids)) {
  27. $location_ids = explode(" ", $location_ids);
  28. $location_ids = array_map("intval", $location_ids);
  29. $location_ids = array_filter($location_ids);
  30. }
  31. $retests = http::value("retests", "int");
  32. $location_filters = [
  33. ["field" => "region", "values" => http::value("regions", "trim")],
  34. ["field" => "area_manager", "values" => http::value("area_managers", "trim")],
  35. ["field" => "operations_manager_name", "values" => http::value("operations_managers", "trim")],
  36. ["field" => "gaming_manager_name", "values" => http::value("gaming_managers", "trim")],
  37. ["field" => "senior_gaming_manager_name", "values" => http::value("senior_gaming_managers", "trim")],
  38. ["field" => "brand", "values" => http::value("brands", "trim")],
  39. ];
  40. if(!is_array($location_ids)) {
  41. $location_ids = [];
  42. }
  43. $all_projects = Project::query([
  44. "customer_id" => $customer->id
  45. ]);
  46. if(Core::$user->isCustomer()) {
  47. // Filter to only projects that have past the deadline
  48. $all_projects = array_filter($all_projects, static function(Project $project) {
  49. return $project->isFinished();
  50. });
  51. }
  52. $project_table_data = [];
  53. foreach($all_projects as $p) {
  54. $project_table_data[] = $p->getDataTableRow();
  55. }
  56. $all_project_ids = array_column($all_projects, "id");
  57. $data = [];
  58. $region_data = [];
  59. $area_manager_data = [];
  60. $brand_data = [];
  61. $total_data = new stdClass;
  62. $locations_missing_region = [];
  63. $locations_missing_area_manager = [];
  64. $locations_missing_brand = [];
  65. $charts = [];
  66. $key_labels = [];
  67. $has_pass_fail = false;
  68. $submit = http::value("submit");
  69. if($submit) {
  70. try {
  71. Core::validateCSRFToken($submit);
  72. $form_exception = new FormException;
  73. // Get all projects
  74. $projects = Project::query([
  75. "customer_id" => $customer->id,
  76. "id" => Constraint::notIn($exclude_project_ids)
  77. ]);
  78. $project_ids = array_intersect($all_project_ids, array_column($projects, "id"));
  79. // Enforce unique template ID in selection
  80. $template_ids = array_unique(array_column($projects, "template_id"));
  81. if(count($template_ids) > 1) {
  82. $form_exception->addError("Projects with different templates have been selected.");
  83. }
  84. // Check template exists
  85. $template_id = array_shift($template_ids);
  86. $template = Template::get($template_id);
  87. if(!$template) {
  88. $form_exception->addError("Template cannot be found.");
  89. }
  90. if($form_exception->hasErrors()) {
  91. throw $form_exception;
  92. }
  93. // Get all completed tests
  94. $test_nvp = [
  95. "project_id" => $project_ids,
  96. "status" => Test::STATUS_COMPLETED
  97. ];
  98. if($location_ids) {
  99. $test_nvp["location_id"] = $location_ids;
  100. }
  101. if($retests !== null) {
  102. $test_nvp["retest"] = $retests;
  103. }
  104. $tests = Test::query($test_nvp);
  105. $test_result_set = new TestResultSet($tests);
  106. // Calculate date ranges
  107. $min_year = date("Y");
  108. $max_year = date("Y");
  109. switch($date_range) {
  110. case "ytd":
  111. default:
  112. // Nothing to do
  113. $date_range_label = "YTD";
  114. $min_dts = "$min_year-01-01";
  115. $max_dts = "$max_year-12-31 23:59:59";
  116. break;
  117. case "unbound":
  118. // Work out year range
  119. foreach($tests as $test) {
  120. $dt = new DateTime($test->dts_start . " UTC");
  121. $dt->setTimezone(new DateTimeZone(TIMEZONE));
  122. $year = $dt->format("Y");
  123. if($year < $min_year) $min_year = $year;
  124. if($year > $max_year) $max_year = $year;
  125. }
  126. $date_range_label = "$min_year - $max_year";
  127. $min_dts = "$min_year-01-01";
  128. $max_dts = "$max_year-12-31 23:59:59";
  129. break;
  130. case "custom":
  131. $check = strcmp($date_start, $date_end);
  132. if($check > 0) {
  133. $temp = $date_start;
  134. $date_start = $date_end;
  135. $date_end = $temp;
  136. }
  137. [$min_year, $min_month, $min_day] = explode("-", $date_start);
  138. [$max_year, $max_month, $max_day] = explode("-", $date_end);
  139. $min_dts = "$date_start 00:00:00";
  140. $max_dts = "$date_end 23:59:59";
  141. $min_time = strtotime($min_dts);
  142. $max_time = strtotime($max_dts);
  143. $date_range_label = sprintf("%s - %s", date("j M y", $min_time), date("j M y", $max_time));
  144. if(preg_match("/01-01$/", $date_start) && preg_match("/12-31$/", $date_end)) {
  145. $date_range_label = $min_year === $max_year ? $min_year : "$min_year - $max_year";
  146. }
  147. break;
  148. }
  149. $tests = $test_result_set->filterByDateRange($min_dts, $max_dts);
  150. // Load locations
  151. $locations = Location::load(array_column($tests, "location_id"));
  152. // Filter by location fields
  153. $tests = array_filter($tests, static function(Test $test) use ($location_filters) {
  154. $location = $test->getLocation();
  155. foreach($location_filters as $filter) {
  156. $field = $filter["field"];
  157. $values = $filter["values"];
  158. if($values && !in_array($location->$field, $values)) {
  159. return false;
  160. }
  161. }
  162. return true;
  163. });
  164. // Get test values
  165. $test_ids = array_column($tests, "id");
  166. $test_values = TestValue::query([
  167. "test_id" => $test_ids,
  168. ]);
  169. $test_values_map = [];
  170. foreach($test_values as $test_value) {
  171. $test_id = $test_value->test_id;
  172. $name = $test_value->name;
  173. if(!isset($test_values_map[$test_id])) {
  174. $test_values_map[$test_id] = new stdClass;
  175. }
  176. $test_values_map[$test_id]->{$name} = $test_value->value;
  177. }
  178. // Load users
  179. User::load(array_column($tests, "tester_id"));
  180. // Get region and area manager IDs
  181. $regions = array_filter(array_column($locations, "region"));
  182. $area_managers = array_filter(array_column($locations, "area_manager"));
  183. $brands = array_filter(array_column($locations, "brand"));
  184. uksort($regions, "strnatcasecmp");
  185. uksort($area_managers, "strnatcasecmp");
  186. uksort($brands, "strnatcasecmp");
  187. foreach($regions as $region) {
  188. $region_data[$region] = [];
  189. }
  190. foreach($area_managers as $area_manager) {
  191. $area_manager_data[$area_manager] = [];
  192. }
  193. foreach($brands as $brand) {
  194. $brand_data[$brand] = [];
  195. }
  196. $has_regions = !empty($region_data);
  197. $has_area_managers = !empty($area_manager_data);
  198. $has_brands = !empty($brand_data);
  199. foreach($locations as $location) {
  200. if($has_regions && !$location->region) $locations_missing_region[] = $location;
  201. if($has_area_managers && !$location->area_manager) $locations_missing_area_manager[] = $location;
  202. if($has_brands && !$location->brand) $locations_missing_brand[] = $location;
  203. }
  204. // Check if date range is same year
  205. $same_year = ($min_year === $max_year);
  206. // Empty data objects hook
  207. require $template->getProcessingFilePath("reports_create_empty_objects.php");
  208. $has_pass_fail = isset($empty_data->passCount);
  209. // Initialise date-array based on date range and resolution
  210. $keys = [];
  211. $key_labels = [];
  212. $resolution_name = "Quarter";
  213. for($year = $min_year; $year <= $max_year; $year++) {
  214. switch($date_resolution) {
  215. case "monthly":
  216. $resolution_name = "Month";
  217. foreach(range(1, 12) as $month) {
  218. if(!$same_year) $label = date("M Y", mktime(0, 0, 0, $month, 1, date("Y")));
  219. else $label = date("M", mktime(0, 0, 0, $month, 1, date("Y")));
  220. $month = str_pad($month, 2, "0", STR_PAD_LEFT);
  221. $keys[] = "$year-$month";
  222. $key_labels[] = $label;
  223. }
  224. break;
  225. case "quarterly":
  226. default:
  227. $resolution_name = "Quarter";
  228. foreach(range(1, 4) as $quarter) {
  229. if(!$same_year) $label = "Q$quarter $year";
  230. else $label = "Q$quarter";
  231. $keys[] = "$year-$quarter";
  232. $key_labels[] = $label;
  233. }
  234. break;
  235. }
  236. }
  237. foreach($keys as $index => $key) {
  238. $label = $key_labels[$index];
  239. /** @var object $empty_data */
  240. $data[$key] = clone $empty_data;
  241. $data[$key]->label = $label;
  242. foreach($region_data as &$r) {
  243. $r[$key] = clone $empty_data;
  244. $r[$key]->label = $label;
  245. }
  246. unset($r);
  247. foreach($area_manager_data as &$a) {
  248. $a[$key] = clone $empty_data;
  249. $a[$key]->label = $label;
  250. }
  251. unset($a);
  252. foreach($brand_data as &$b) {
  253. $b[$key] = clone $empty_data;
  254. $b[$key]->label = $label;
  255. }
  256. unset($b);
  257. }
  258. $max_unix = 0;
  259. $venue_type_data = [];
  260. // Process locations
  261. foreach($tests as $test) {
  262. foreach($test->getLocation()->getVenueTypes() as $type) {
  263. $venue_type_data[$type->name] = [
  264. "passCount" => 0,
  265. "failCount" => 0,
  266. "testCount" => 0,
  267. "stageCounts" => [0, 0, 0, 0, 0]
  268. ];
  269. }
  270. }
  271. // Process test results
  272. foreach($tests as $test) {
  273. $tester = $test->getTester();
  274. $location = $test->getLocation();
  275. $venue_types = $location->getVenueTypes();
  276. $project = $test->getProject();
  277. $test_values = $test_values_map[$test->id] ?? new stdClass;
  278. if($template->hasPassFail()) {
  279. foreach($location->getVenueTypes() as $type) {
  280. $venue_type_data[$type->name]["testCount"]++;
  281. if($test->isPass()) {
  282. $venue_type_data[$type->name]["passCount"]++;
  283. }
  284. else {
  285. $venue_type_data[$type->name]["failCount"]++;
  286. }
  287. if($test->challenge_stage > 0) {
  288. $venue_type_data[$type->name]["stageCounts"][$test->challenge_stage - 1]++;
  289. }
  290. }
  291. }
  292. $region = $location->region;
  293. $area_manager = $location->area_manager;
  294. $brand = $location->brand;
  295. $dts = $project->dts_report ?: $test->dts_start;
  296. $dt = new DateTime($dts . " UTC");
  297. $dt->setTimezone(new DateTimeZone(TIMEZONE));
  298. $unix = $dt->format("U");
  299. $year = $dt->format("Y");
  300. $month = $dt->format("m");
  301. $quarter = ceil($month / 3);
  302. if($unix > $max_unix) {
  303. $max_unix = $unix;
  304. }
  305. switch($date_resolution) {
  306. case "monthly":
  307. $key = "$year-$month";
  308. break;
  309. case "quarterly":
  310. default:
  311. $key = "$year-$quarter";
  312. break;
  313. }
  314. // Skip processing if test is void
  315. if($test->isVoid()) {
  316. $data[$key]->voidCount++;
  317. $total_data->voidCount++;
  318. }
  319. else {
  320. $total_data->testCount++;
  321. $data[$key]->testCount++;
  322. if($region) {
  323. $region_data[$region][$key]->testCount++;
  324. }
  325. if($area_manager) {
  326. $area_manager_data[$area_manager][$key]->testCount++;
  327. }
  328. if($brand) {
  329. $brand_data[$brand][$key]->testCount++;
  330. }
  331. if($tester->gender === "M") {
  332. $data[$key]->maleTesterCount++;
  333. $total_data->maleTesterCount++;
  334. }
  335. if($tester->gender === "F") {
  336. $data[$key]->femaleTesterCount++;
  337. $total_data->femaleTesterCount++;
  338. }
  339. // Process test hook
  340. require $template->getProcessingFilePath("reports_process_test.php");
  341. }
  342. }
  343. $current_month = date("m", $max_unix);
  344. $current_quarter = ceil(date("n", $max_unix) / 3);
  345. // Initialise generator
  346. $generator = new ChartGenerator($total_data, $data);
  347. $generator->setDateRangeLabel($date_range_label);
  348. $generator->setResolutionName($resolution_name);
  349. $generator->setPeriodKeysAndLabels($keys, $key_labels);
  350. $generator->setRegionData($region_data);
  351. $generator->setBrandData($brand_data);
  352. $generator->setAreaManagerData($area_manager_data);
  353. $generator->setTemplate($template);
  354. // Build charts hook
  355. require $template->getProcessingFilePath("reports_build_charts.php");
  356. }
  357. catch(FormException $e) {
  358. $e->generateAlerts();
  359. }
  360. catch(Exception $e) {
  361. Core::addAlert("danger", $e->getMessage());
  362. }
  363. // Export hook
  364. if(!empty($action)) {
  365. switch($action) {
  366. case "export-pptx":
  367. case "export-odp":
  368. require "reports_presentation.php";
  369. break;
  370. default:
  371. break;
  372. }
  373. }
  374. }
  375. View::includeOnce("header", compact("page_title"));
  376. View::include("reports", compact("customer", "date_range", "date_start", "date_end", "date_resolution", "all_projects", "project_table_data", "exclude_project_ids", "location_ids", "retests", "charts", "data", "total_data", "locations_missing_region", "locations_missing_area_manager", "locations_missing_brand", "region_data", "area_manager_data", "brand_data", "key_labels", "has_pass_fail"));
  377. View::includeOnce("footer");