1
0

reports.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. if($has_brands && !$location->brand) $locations_missing_brand[] = $location;
  172. }
  173. // Check if date range is same year
  174. $same_year = ($min_year === $max_year);
  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. $resolution_name = "Quarter";
  182. for($year = $min_year; $year <= $max_year; $year++) {
  183. switch($date_resolution) {
  184. case "monthly":
  185. $resolution_name = "Month";
  186. foreach(range(1, 12) as $month) {
  187. if(!$same_year) $label = date("M Y", mktime(0, 0, 0, $month, 1, date("Y")));
  188. else $label = date("M", mktime(0, 0, 0, $month, 1, date("Y")));
  189. $month = str_pad($month, 2, "0", STR_PAD_LEFT);
  190. $keys[] = "$year-$month";
  191. $key_labels[] = $label;
  192. }
  193. break;
  194. case "quarterly":
  195. default:
  196. $resolution_name = "Quarter";
  197. foreach(range(1, 4) as $quarter) {
  198. if(!$same_year) $label = "Q$quarter $year";
  199. else $label = "Q$quarter";
  200. $keys[] = "$year-$quarter";
  201. $key_labels[] = $label;
  202. }
  203. break;
  204. }
  205. }
  206. foreach($keys as $index => $key) {
  207. $label = $key_labels[$index];
  208. /** @var object $empty_data */
  209. $data[$key] = clone $empty_data;
  210. $data[$key]->label = $label;
  211. foreach($region_data as &$r) {
  212. $r[$key] = clone $empty_data;
  213. $r[$key]->label = $label;
  214. }
  215. unset($r);
  216. foreach($area_manager_data as &$a) {
  217. $a[$key] = clone $empty_data;
  218. $a[$key]->label = $label;
  219. }
  220. unset($a);
  221. foreach($brand_data as &$b) {
  222. $b[$key] = clone $empty_data;
  223. $b[$key]->label = $label;
  224. }
  225. unset($b);
  226. }
  227. $max_unix = 0;
  228. $venue_type_data = [];
  229. // Process locations
  230. foreach($tests as $test) {
  231. foreach($test->getLocation()->getVenueTypes() as $type) {
  232. $venue_type_data[$type->name] = [
  233. "passCount" => 0,
  234. "failCount" => 0,
  235. "testCount" => 0,
  236. "stageCounts" => [0, 0, 0, 0, 0]
  237. ];
  238. }
  239. }
  240. // Process test results
  241. foreach($tests as $test) {
  242. $tester = $test->getTester();
  243. $location = $test->getLocation();
  244. $venue_types = $location->getVenueTypes();
  245. $project = $test->getProject();
  246. $test_values = $test_values_map[$test->id] ?? new stdClass;
  247. if($template->hasPassFail()) {
  248. foreach($location->getVenueTypes() as $type) {
  249. $venue_type_data[$type->name]["testCount"]++;
  250. if($test->isPass()) {
  251. $venue_type_data[$type->name]["passCount"]++;
  252. }
  253. else {
  254. $venue_type_data[$type->name]["failCount"]++;
  255. }
  256. if($test->challenge_stage > 0) {
  257. $venue_type_data[$type->name]["stageCounts"][$test->challenge_stage - 1]++;
  258. }
  259. }
  260. }
  261. $region = $location->region;
  262. $area_manager = $location->area_manager;
  263. $brand = $location->brand;
  264. $dts = $project->dts_report ?: $test->dts_start;
  265. $dt = new DateTime($dts . " UTC");
  266. $dt->setTimezone(new DateTimeZone(TIMEZONE));
  267. $unix = $dt->format("U");
  268. $year = $dt->format("Y");
  269. $month = $dt->format("m");
  270. $quarter = ceil($month / 3);
  271. if($unix > $max_unix) {
  272. $max_unix = $unix;
  273. }
  274. switch($date_resolution) {
  275. case "monthly":
  276. $key = "$year-$month";
  277. break;
  278. case "quarterly":
  279. default:
  280. $key = "$year-$quarter";
  281. break;
  282. }
  283. // Skip processing if test is void
  284. if($test->isVoid()) {
  285. $data[$key]->voidCount++;
  286. $total_data->voidCount++;
  287. }
  288. else {
  289. $total_data->testCount++;
  290. $data[$key]->testCount++;
  291. if($region) {
  292. $region_data[$region][$key]->testCount++;
  293. }
  294. if($area_manager) {
  295. $area_manager_data[$area_manager][$key]->testCount++;
  296. }
  297. if($brand) {
  298. $brand_data[$brand][$key]->testCount++;
  299. }
  300. if($tester->gender === "M") {
  301. $data[$key]->maleTesterCount++;
  302. $total_data->maleTesterCount++;
  303. }
  304. if($tester->gender === "F") {
  305. $data[$key]->femaleTesterCount++;
  306. $total_data->femaleTesterCount++;
  307. }
  308. // Process test hook
  309. require $template->getProcessingFilePath("reports_process_test.php");
  310. }
  311. }
  312. $current_month = date("m", $max_unix);
  313. $current_quarter = ceil(date("n", $max_unix) / 3);
  314. // Initialise generator
  315. $generator = new ChartGenerator($total_data, $data);
  316. $generator->setDateRangeLabel($date_range_label);
  317. $generator->setResolutionName($resolution_name);
  318. $generator->setPeriodKeysAndLabels($keys, $key_labels);
  319. $generator->setRegionData($region_data);
  320. $generator->setBrandData($brand_data);
  321. $generator->setAreaManagerData($area_manager_data);
  322. $generator->setTemplate($template);
  323. // Build charts hook
  324. require $template->getProcessingFilePath("reports_build_charts.php");
  325. }
  326. catch(FormException $e) {
  327. $e->generateAlerts();
  328. }
  329. catch(Exception $e) {
  330. Core::addAlert("danger", $e->getMessage());
  331. }
  332. // Export hook
  333. if(!empty($action)) {
  334. switch($action) {
  335. case "export-pptx":
  336. case "export-odp":
  337. require "reports_presentation.php";
  338. break;
  339. default:
  340. break;
  341. }
  342. }
  343. }
  344. View::includeOnce("header", compact("page_title"));
  345. 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"));
  346. View::includeOnce("footer");