reports.php 14 KB

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