reports.php 15 KB

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