reports.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <?php /** @noinspection PhpIncludeInspection */
  2. /** @noinspection PhpUnhandledExceptionInspection */
  3. Core::addScript("public/js/Chart.bundle.min.js");
  4. Core::addScript("public/js/chartjs-plugin-datalabels.min.js");
  5. Core::addScript("public/js/app-reports.js");
  6. Core::addBreadcrumb("/account", "Account");
  7. Core::addBreadcrumb("/account/reports", "Reports");
  8. $customer = Customer::getForAdmin();
  9. if(!$customer) throw new Exception("You do not have permission to access this page.");
  10. $customer_slug = Util::slug($customer->name);
  11. $customer_slug = str_replace("-", "_", $customer_slug);
  12. $logo_file_path = ROOT_DIR . "/public/img/customer_logos/{$customer_slug}_logo.png";
  13. $has_logo = file_exists($logo_file_path);
  14. $page_title = "$customer->name Reports";
  15. Core::addBreadcrumb("/account/reports?customer_id=$customer->id", $page_title);
  16. $date_range = http::value("date_range");
  17. if(!$date_range) $date_range = "ytd";
  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)) $exclude_project_ids = [];
  23. $location_ids = http::value("location_ids");
  24. if(!empty($location_ids)) {
  25. $location_ids = explode(" ", $location_ids);
  26. $location_ids = array_map("intval", $location_ids);
  27. $location_ids = array_filter($location_ids);
  28. }
  29. $retests = http::value("retests", "int");
  30. if(!is_array($location_ids)) {
  31. $location_ids = [];
  32. }
  33. $all_projects = Project::query([
  34. "customer_id" => $customer->id
  35. ]);
  36. if(Core::$user->isCustomer()) {
  37. // Filter to only projects that have past the deadline
  38. $all_projects = array_filter($all_projects, function(Project $project) {
  39. return $project->isPastDeadline();
  40. });
  41. }
  42. $project_table_data = [];
  43. foreach($all_projects as $p) {
  44. $project_table_data[] = $p->getDataTableRow();
  45. }
  46. $data = [];
  47. $region_data = [];
  48. $area_manager_data = [];
  49. $total_data = new stdClass;
  50. $locations_missing_region = [];
  51. $locations_missing_area_manager = [];
  52. $charts = [];
  53. $submit = http::value("submit");
  54. if($submit) {
  55. try {
  56. Core::validateCSRFToken($submit);
  57. $form_exception = new FormException;
  58. // Get all projects
  59. $projects = Project::query([
  60. "customer_id" => $customer->id,
  61. "id" => (new Constraint("NOT_IN"))->setValues(...$exclude_project_ids)
  62. ]);
  63. $project_ids = array_column($projects, "id");
  64. // Enforce unique template ID in selection
  65. $template_ids = array_unique(array_column($projects, "template_id"));
  66. if(count($template_ids) > 1) $form_exception->addError("Projects with different templates have been selected.");
  67. // Check template exists
  68. $template_id = array_shift($template_ids);
  69. $template = Template::get($template_id);
  70. if(!$template) $form_exception->addError("Template cannot be found.");
  71. if($form_exception->hasErrors()) throw $form_exception;
  72. // Get all completed tests
  73. $test_nvp = [
  74. "project_id" => $project_ids,
  75. "status" => Test::STATUS_COMPLETED
  76. ];
  77. if($location_ids) {
  78. $test_nvp["location_id"] = $location_ids;
  79. }
  80. if($retests !== false) {
  81. $test_nvp["retest"] = $retests;
  82. }
  83. $tests = Test::query($test_nvp);
  84. $test_count = count($tests);
  85. // Get test values
  86. $test_ids = array_column($tests, "id");
  87. $test_values = TestValue::query([
  88. "test_id" => $test_ids,
  89. ]);
  90. $test_values_map = [];
  91. foreach($test_values as $test_value) {
  92. $test_id = $test_value->test_id;
  93. $name = $test_value->name;
  94. if(!isset($test_values_map[$test_id])) {
  95. $test_values_map[$test_id] = new stdClass;
  96. }
  97. $test_values_map[$test_id]->{$name} = $test_value->value;
  98. }
  99. // Load users
  100. User::load(array_column($tests, "tester_id"));
  101. // Load locations
  102. $locations = Location::load(array_column($tests, "location_id"));
  103. // Get region and area manager IDs
  104. $regions = array_filter(array_column($locations, "region"));
  105. $area_managers = array_filter(array_column($locations, "area_manager"));
  106. uksort($regions, "strnatcasecmp");
  107. uksort($area_managers, "strnatcasecmp");
  108. foreach($regions as $region) {
  109. $region_data[$region] = [];
  110. }
  111. foreach($area_managers as $area_manager) {
  112. $area_manager_data[$area_manager] = [];
  113. }
  114. $has_regions = !empty($region_data);
  115. $has_area_managers = !empty($area_manager_data);
  116. foreach($locations as $location) {
  117. if($has_regions && !$location->region) $locations_missing_region[] = $location;
  118. if($has_area_managers && !$location->area_manager) $locations_missing_area_manager[] = $location;
  119. }
  120. // Calculate date ranges
  121. $min_year = date("Y");
  122. $max_year = date("Y");
  123. $min_unix = strtotime("$min_year-01-01 UTC");
  124. $max_unix = strtotime("$max_year-12-31 23:59:59 UTC");
  125. switch($date_range) {
  126. case "ytd":
  127. // Nothing to do
  128. $date_range_label = "YTD";
  129. break;
  130. case "unbound":
  131. // Work out year range
  132. foreach($tests as $test) {
  133. $dt = new DateTime($test->dts_start . " UTC");
  134. $dt->setTimezone(new DateTimeZone(TIMEZONE));
  135. $year = $dt->format("Y");
  136. if($year < $min_year) $min_year = $year;
  137. if($year > $max_year) $max_year = $year;
  138. }
  139. $date_range_label = "$min_year - $max_year";
  140. break;
  141. case "custom":
  142. $check = strcmp($date_start, $date_end);
  143. if($check > 0) {
  144. $temp = $date_end;
  145. $date_start = $date_end;
  146. $date_start = $temp;
  147. }
  148. list($min_year, $min_month, $min_day) = explode("-", $date_start);
  149. list($max_year, $max_month, $max_day) = explode("-", $date_end);
  150. $min_unix = strtotime("{$date_start} 00:00:00 UTC");
  151. $max_unix = strtotime("{$date_end} 23:59:59 UTC");
  152. $date_range_label = date("d/m/Y", $min_unix) . " - " . date("d/m/Y", $max_unix);
  153. if(preg_match("/01-01$/", $date_start) && preg_match("/12-31$/", $date_end)) {
  154. if($min_year == $max_year) {
  155. $date_range_label = $min_year;
  156. }
  157. else {
  158. $date_range_label = "{$min_year} - {$max_year}";
  159. }
  160. }
  161. break;
  162. }
  163. // Check if date range is same year
  164. $same_year = ($min_year == $max_year);
  165. // Filter tests based on date range
  166. $tests = array_filter($tests, function(Test $test) use ($min_unix, $max_unix) {
  167. $project = $test->getProject();
  168. $dts = $project->dts_report ?: $test->dts_start;
  169. $dt = new DateTime($dts . " UTC");
  170. $unix = $dt->format("U");
  171. if($unix < $min_unix) return false;
  172. if($unix > $max_unix) return false;
  173. return true;
  174. });
  175. // Empty data objects hook
  176. require $template->getProcessingFilePath("reports_create_empty_objects.php");
  177. $has_pass_fail = isset($empty_data->passCount);
  178. // Initialise date-array based on date range and resolution
  179. $keys = [];
  180. $key_labels = [];
  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. $data[$key] = clone $empty_data;
  208. $data[$key]->label = $label;
  209. foreach($region_data as &$r) {
  210. $r[$key] = clone $empty_data;
  211. $r[$key]->label = $label;
  212. }
  213. foreach($area_manager_data as &$a) {
  214. $a[$key] = clone $empty_data;
  215. $a[$key]->label = $label;
  216. }
  217. }
  218. $max_unix = 0;
  219. // Process test results
  220. foreach($tests as $test) {
  221. $tester = $test->getTester();
  222. $location = $test->getLocation();
  223. $project = $test->getProject();
  224. $test_values = $test_values_map[$test->id] ?? new stdClass;
  225. $region = $location->region;
  226. $area_manager = $location->area_manager;
  227. $dts = $project->dts_report ?: $test->dts_start;
  228. $dt = new DateTime($dts . " UTC");
  229. $dt->setTimezone(new DateTimeZone(TIMEZONE));
  230. $unix = $dt->format("U");
  231. $year = $dt->format("Y");
  232. $month = $dt->format("m");
  233. $quarter = ceil($month / 3);
  234. if($unix > $max_unix) {
  235. $max_unix = $unix;
  236. }
  237. switch($date_resolution) {
  238. case "monthly":
  239. $key = "$year-$month";
  240. break;
  241. case "quarterly":
  242. default:
  243. $key = "$year-$quarter";
  244. break;
  245. }
  246. $total_data->testCount++;
  247. $data[$key]->testCount++;
  248. if($region) $region_data[$region][$key]->testCount++;
  249. if($area_manager) $area_manager_data[$area_manager][$key]->testCount++;
  250. if($tester->gender == "M") {
  251. $data[$key]->maleTesterCount++;
  252. $total_data->maleTesterCount++;
  253. }
  254. if($tester->gender == "F") {
  255. $data[$key]->femaleTesterCount++;
  256. $total_data->femaleTesterCount++;
  257. }
  258. // Process test hook
  259. require $template->getProcessingFilePath("reports_process_test.php");
  260. }
  261. $current_month = date("m", $max_unix);
  262. $current_quarter = ceil(date("n", $max_unix) / 3);
  263. // Initialise generator
  264. $generator = new ChartGenerator($total_data, $data);
  265. $generator->setDateRangeLabel($date_range_label);
  266. $generator->setResolutionName($resolution_name);
  267. $generator->setPeriodKeysAndLabels($keys, $key_labels);
  268. $generator->setRegionData($region_data);
  269. $generator->setAreaManagerData($area_manager_data);
  270. // Build charts hook
  271. require $template->getProcessingFilePath("reports_build_charts.php");
  272. }
  273. catch(FormException $e) {
  274. $e->generateAlerts();
  275. }
  276. catch(Exception $e) {
  277. Core::addAlert("danger", $e->getMessage());
  278. }
  279. // Export hook
  280. if(!empty($action)) {
  281. switch($action) {
  282. case "export-pptx":
  283. case "export-odp":
  284. require "reports_presentation.php";
  285. break;
  286. default:
  287. break;
  288. }
  289. }
  290. }
  291. View::includeOnce("header", compact("page_title"));
  292. 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", "key_labels", "has_pass_fail"));
  293. View::includeOnce("footer");