reports.php 14 KB

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