reports.php 11 KB

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