reports.php 10 KB

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