reports.php 17 KB

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