1
0

reports.php 12 KB

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