reports.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. // Filter down locations
  194. $locations = Location::load(array_column($tests, "location_id"));
  195. // Get test values
  196. $test_ids = array_column($tests, "id");
  197. $test_values = TestValue::query([
  198. "test_id" => $test_ids,
  199. ]);
  200. $test_values_map = [];
  201. foreach($test_values as $test_value) {
  202. $test_id = $test_value->test_id;
  203. $name = $test_value->name;
  204. if(!isset($test_values_map[$test_id])) {
  205. $test_values_map[$test_id] = new stdClass;
  206. }
  207. $test_values_map[$test_id]->{$name} = $test_value->value;
  208. }
  209. // Load users
  210. User::load(array_column($tests, "tester_id"));
  211. // Get region and area manager IDs
  212. $regions = array_filter(array_column($locations, "region"));
  213. $area_managers = array_filter(array_column($locations, "area_manager"));
  214. $brands = array_filter(array_column($locations, "brand"));
  215. $operations_managers = array_filter(array_column($locations, "operations_manager_name"));
  216. uksort($regions, "strnatcasecmp");
  217. uksort($area_managers, "strnatcasecmp");
  218. uksort($brands, "strnatcasecmp");
  219. foreach($regions as $region) {
  220. $region_data[$region] = [];
  221. }
  222. foreach($area_managers as $area_manager) {
  223. $area_manager_data[$area_manager] = [];
  224. }
  225. foreach($brands as $brand) {
  226. $brand_data[$brand] = [];
  227. }
  228. foreach($operations_managers as $operations_manager) {
  229. $operations_manager_data[$operations_manager] = [];
  230. }
  231. $has_regions = !empty($region_data);
  232. $has_area_managers = !empty($area_manager_data);
  233. $has_brands = !empty($brand_data);
  234. $has_operation_managers = !empty($operations_manager_data);
  235. foreach($locations as $location) {
  236. if($has_regions && !$location->region) $locations_missing_region[] = $location;
  237. if($has_area_managers && !$location->area_manager) $locations_missing_area_manager[] = $location;
  238. if($has_brands && !$location->brand) $locations_missing_brand[] = $location;
  239. if($has_operation_managers && !$location->operations_manager_name) $locations_missing_operations_manager[] = $location;
  240. }
  241. // Check if date range is same year
  242. $same_year = ($min_year === $max_year);
  243. // Empty data objects hook
  244. require $template->getProcessingFilePath("reports_create_empty_objects.php");
  245. $has_pass_fail = isset($empty_data->passCount);
  246. // Initialise date-array based on date range and resolution
  247. $keys = [];
  248. $key_labels = [];
  249. $resolution_name = "Quarter";
  250. for($year = $min_year; $year <= $max_year; $year++) {
  251. switch($date_resolution) {
  252. case "monthly":
  253. $resolution_name = "Month";
  254. foreach(range(1, 12) as $month) {
  255. if(!$same_year) $label = date("M Y", mktime(0, 0, 0, $month, 1, date("Y")));
  256. else $label = date("M", mktime(0, 0, 0, $month, 1, date("Y")));
  257. $month = str_pad($month, 2, "0", STR_PAD_LEFT);
  258. $keys[] = "$year-$month";
  259. $key_labels[] = $label;
  260. }
  261. break;
  262. case "quarterly":
  263. default:
  264. $resolution_name = "Quarter";
  265. foreach(range(1, 4) as $quarter) {
  266. if(!$same_year) $label = "Q$quarter $year";
  267. else $label = "Q$quarter";
  268. $keys[] = "$year-$quarter";
  269. $key_labels[] = $label;
  270. }
  271. break;
  272. }
  273. }
  274. /**
  275. * @var object $empty_data
  276. */
  277. foreach($keys as $index => $key) {
  278. $label = $key_labels[$index];
  279. $data[$key] = clone $empty_data;
  280. $data[$key]->label = $label;
  281. foreach($region_data as &$r) {
  282. $r[$key] = clone $empty_data;
  283. $r[$key]->label = $label;
  284. }
  285. unset($r);
  286. foreach($area_manager_data as &$a) {
  287. $a[$key] = clone $empty_data;
  288. $a[$key]->label = $label;
  289. }
  290. unset($a);
  291. foreach($brand_data as &$b) {
  292. $b[$key] = clone $empty_data;
  293. $b[$key]->label = $label;
  294. }
  295. unset($b);
  296. foreach($operations_manager_data as &$om) {
  297. $om[$key] = clone $empty_data;
  298. $om[$key]->label = $label;
  299. }
  300. unset($om);
  301. }
  302. $max_unix = 0;
  303. $venue_type_data = [];
  304. // Process locations
  305. foreach($tests as $test) {
  306. foreach($test->getLocation()->getVenueTypes() as $type) {
  307. $venue_type_data[$type->name] = [
  308. "passCount" => 0,
  309. "failCount" => 0,
  310. "testCount" => 0,
  311. "stageCounts" => [0, 0, 0, 0, 0]
  312. ];
  313. }
  314. }
  315. // Process test results
  316. /** @var Test $test */
  317. foreach($tests as $test) {
  318. $tester = $test->getTester();
  319. /** @var Location $location */
  320. $location = $test->getLocation();
  321. $venue_types = $location->getVenueTypes();
  322. $project = $test->getProject();
  323. $test_values = $test_values_map[$test->id] ?? new stdClass;
  324. if($template->hasPassFail()) {
  325. foreach($location->getVenueTypes() as $type) {
  326. $venue_type_data[$type->name]["testCount"]++;
  327. if($test->isPass()) {
  328. $venue_type_data[$type->name]["passCount"]++;
  329. }
  330. else {
  331. $venue_type_data[$type->name]["failCount"]++;
  332. }
  333. if($test->challenge_stage > 0) {
  334. $venue_type_data[$type->name]["stageCounts"][$test->challenge_stage - 1]++;
  335. }
  336. }
  337. }
  338. $region = $location->region;
  339. $area_manager = $location->area_manager;
  340. $brand = $location->brand;
  341. $operations_manager = $location->operations_manager_name;
  342. $dts = $project->dts_report ?: $test->dts_start;
  343. $dt = new DateTime($dts . " UTC");
  344. $dt->setTimezone(new DateTimeZone(TIMEZONE));
  345. $unix = $dt->format("U");
  346. $year = $dt->format("Y");
  347. $month = $dt->format("m");
  348. $quarter = ceil($month / 3);
  349. if($unix > $max_unix) {
  350. $max_unix = $unix;
  351. }
  352. switch($date_resolution) {
  353. case "monthly":
  354. $key = "$year-$month";
  355. break;
  356. case "quarterly":
  357. default:
  358. $key = "$year-$quarter";
  359. break;
  360. }
  361. // Skip processing if test is void
  362. if($test->isVoid()) {
  363. $data[$key]->voidCount++;
  364. $total_data->voidCount++;
  365. }
  366. else {
  367. $total_data->testCount++;
  368. $data[$key]->testCount++;
  369. if($region) {
  370. $region_data[$region][$key]->testCount++;
  371. }
  372. if($area_manager) {
  373. $area_manager_data[$area_manager][$key]->testCount++;
  374. }
  375. if($brand) {
  376. $brand_data[$brand][$key]->testCount++;
  377. }
  378. if($operations_manager) {
  379. $operations_manager_data[$operations_manager][$key]->testCount++;
  380. }
  381. if($tester->gender === "M") {
  382. $data[$key]->maleTesterCount++;
  383. $total_data->maleTesterCount++;
  384. }
  385. if($tester->gender === "F") {
  386. $data[$key]->femaleTesterCount++;
  387. $total_data->femaleTesterCount++;
  388. }
  389. // Process test hook
  390. require $template->getProcessingFilePath("reports_process_test.php");
  391. }
  392. }
  393. $current_month = date("m", $max_unix);
  394. $current_quarter = ceil(date("n", $max_unix) / 3);
  395. // Initialise generator
  396. $generator = new ChartGenerator($total_data, $data);
  397. $generator->setDateRangeLabel($date_range_label);
  398. $generator->setResolutionName($resolution_name);
  399. $generator->setPeriodKeysAndLabels($keys, $key_labels);
  400. $generator->setRegionData($region_data);
  401. $generator->setBrandData($brand_data);
  402. $generator->setAreaManagerData($area_manager_data);
  403. $generator->setOperationsManagerData($operations_manager_data);
  404. $generator->setTemplate($template);
  405. $generator->setCustomer($customer);
  406. // Build charts hook
  407. require $template->getProcessingFilePath("reports_build_charts.php");
  408. }
  409. catch(FormException $e) {
  410. $e->generateAlerts();
  411. }
  412. catch(Exception $e) {
  413. Core::addAlert("danger", $e->getMessage());
  414. }
  415. // Export hook
  416. if(!empty($action)) {
  417. switch($action) {
  418. case "export-pptx":
  419. case "export-odp":
  420. require "reports_presentation.php";
  421. break;
  422. default:
  423. break;
  424. }
  425. }
  426. }
  427. View::includeOnce("header", compact("page_title"));
  428. 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"));
  429. View::includeOnce("footer");
  430. file_put_contents("periodic_data.bin", serialize($data));
  431. file_put_contents("total_data.bin", serialize($total_data));