project.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. <?php /** @noinspection PhpIncludeInspection */
  2. use Carbon\CarbonImmutable;
  3. /**
  4. * @property int $id
  5. * @property int $customer_id
  6. * @property int $template_id
  7. * @property string $template_keys
  8. * @property string $name
  9. * @property int $test_count
  10. * @property int $min_age
  11. * @property int $max_age
  12. * @property float $default_customer_fee
  13. * @property float $default_tester_fee
  14. * @property string $time_of_day
  15. * @property bool $tester_can_claim
  16. * @property string $template_overrides_json
  17. * @property string $dts_start
  18. * @property string $dts_deadline
  19. * @property string $dts_created
  20. * @property string $dts_updated
  21. * @property string $dts_report
  22. * @property string $dts_finished
  23. * @property int $user_id_finished
  24. */
  25. class Project extends Model {
  26. public const TOD_ANYTIME = "A";
  27. public const TOD_DAYTIME = "D";
  28. public const TOD_NIGHTTIME = "N";
  29. protected static $table = "project";
  30. protected static $id_field = "id";
  31. protected static $fillable_fields = ["customer_id", "template_id", "template_keys", "name", "test_count", "min_age", "max_age", "default_customer_fee", "default_tester_fee", "time_of_day", "tester_can_claim", "template_overrides_json", "dts_start", "dts_deadline", "dts_created", "dts_updated", "dts_report", "dts_finished", "user_id_finished"];
  32. /**
  33. * @var Test[] $tests
  34. */
  35. protected $tests;
  36. // Static methods
  37. public static function getTimeOfDayOptions(): array {
  38. return [
  39. self::TOD_ANYTIME => "Anytime",
  40. self::TOD_DAYTIME => "Daytime",
  41. self::TOD_NIGHTTIME => "Night",
  42. ];
  43. }
  44. /**
  45. * @param string $processing_file
  46. * @param Project[] $projects
  47. * @throws Exception
  48. */
  49. public static function exportCSV(string $processing_file, /** @noinspection PhpUnusedParameterInspection */ array $projects = []): void {
  50. // Get processing file
  51. $processing_file_path = ROOT_DIR . "/export_processing/{$processing_file}";
  52. if(!file_exists($processing_file_path)) throw new Exception("Processing file not found.");
  53. // Output
  54. HTTP::setDownloadHeaders("export.csv");
  55. $handle = fopen("php://output", "wb");
  56. require $processing_file_path;
  57. fclose($handle);
  58. }
  59. /**
  60. * @return string[]
  61. * @throws Exception
  62. */
  63. public static function getReportMonths(): array {
  64. $current_report_month = new DateTime("2018-01-01", new DateTimeZone("UTC"));
  65. $month_interval = new DateInterval("P1M");
  66. $report_months = [];
  67. do {
  68. $key = $current_report_month->format("Y-m");
  69. $report_months[$key] = $current_report_month->format("M Y");
  70. $current_report_month->add($month_interval);
  71. $time = $current_report_month->format("U");
  72. if($time > time()) break;
  73. } while(true);
  74. return $report_months;
  75. }
  76. // Object methods
  77. /**
  78. * @return Customer
  79. * @throws Exception
  80. */
  81. public function getCustomer(): Customer {
  82. return Customer::get($this->customer_id);
  83. }
  84. /**
  85. * @return Test[]
  86. * @throws Exception
  87. */
  88. public function getTests(): array {
  89. if($this->tests !== null) return $this->tests;
  90. $nvp = [];
  91. $nvp["project_id"] = $this->id;
  92. $nvp["status"] = (new Constraint("MORE_THAN"))->setValues(Test::STATUS_CANCELLED);
  93. $this->tests = Test::query($nvp);
  94. return $this->tests;
  95. }
  96. /**
  97. * @return int
  98. * @throws Exception
  99. */
  100. public function getTestCount(): int {
  101. if(is_null($this->tests)) $this->getTests();
  102. return count($this->tests);
  103. }
  104. /**
  105. * @return int
  106. * @throws Exception
  107. */
  108. public function getPassCount(): int {
  109. $count = 0;
  110. $tests = $this->getTests();
  111. foreach($tests as $test) {
  112. if(!$test->isPass()) continue;
  113. ++$count;
  114. }
  115. return $count;
  116. }
  117. /**
  118. * @return int
  119. * @throws Exception
  120. */
  121. public function getFailCount(): int {
  122. $count = 0;
  123. $tests = $this->getTests();
  124. foreach($tests as $test) {
  125. if(!$test->isFail()) continue;
  126. ++$count;
  127. }
  128. return $count;
  129. }
  130. /**
  131. * @return int
  132. * @throws Exception
  133. */
  134. public function getPendingCount(): int {
  135. $count = 0;
  136. $tests = $this->getTests();
  137. foreach($tests as $test) {
  138. if(!$test->isPending()) continue;
  139. ++$count;
  140. }
  141. return $count;
  142. }
  143. /**
  144. * @return string
  145. * @throws Exception
  146. */
  147. public function getPassRate(): string {
  148. $pass_count = $this->getPassCount();
  149. $fail_count = $this->getFailCount();
  150. $pass_fail_count = $pass_count + $fail_count;
  151. if($pass_fail_count === 0) return "0%";
  152. return (number_format($pass_count / $pass_fail_count, 4) * 100) . "%";
  153. }
  154. /**
  155. * @return Location[]
  156. * @throws Exception
  157. */
  158. public function getLocations(): array {
  159. $tests = $this->getTests();
  160. return Location::query(["id" => array_column($tests, "location_id")]);
  161. }
  162. /**
  163. * @return string
  164. */
  165. public function getDisplayAgeRange(): string {
  166. if($this->min_age && $this->max_age) {
  167. return $this->min_age . " to " . $this->max_age;
  168. }
  169. if($this->min_age) {
  170. return "At least " . $this->min_age;
  171. }
  172. if($this->max_age) {
  173. return "Up to " . $this->max_age;
  174. }
  175. return "No age restriction";
  176. }
  177. /**
  178. * @return string
  179. */
  180. public function getNameHtml(): string {
  181. if($this->isAnytime()) {
  182. return htmlspecialchars($this->name);
  183. }
  184. $icon = $this->getTimeOfDayIcon();
  185. $time_of_day = $this->getTimeOfDayText();
  186. return htmlspecialchars($this->name) . " <i class=\"fa fa-fw fa-{$icon}\" data-toggle=\"tooltip\" title=\"{$time_of_day}\"></i>";
  187. }
  188. /**
  189. * @return array
  190. * @throws Exception
  191. */
  192. public function getCompletedTests(): array {
  193. $tests = $this->getTests();
  194. return array_filter($tests, static function($test) {
  195. return (int) $test->status === Test::STATUS_COMPLETED;
  196. });
  197. }
  198. /**
  199. * @return int
  200. * @throws Exception
  201. */
  202. public function getCompletedTestCount(): int {
  203. return count($this->getCompletedTests());
  204. }
  205. /**
  206. * @return float
  207. * @throws Exception
  208. */
  209. public function getCompletedPercentage(): float {
  210. return floor((count($this->getCompletedTests()) / $this->test_count) * 100);
  211. }
  212. /**
  213. * @return Template
  214. * @throws Exception
  215. */
  216. public function getTemplate(): Template {
  217. return Template::get($this->template_id);
  218. }
  219. /**
  220. * @return array
  221. */
  222. public function getTemplateOverrides(): array {
  223. return json_decode($this->template_overrides_json) ?: [];
  224. }
  225. /**
  226. * @return string
  227. */
  228. public function getTimeOfDayText(): string {
  229. switch($this->time_of_day) {
  230. default:
  231. case self::TOD_ANYTIME: return "Any";
  232. case self::TOD_DAYTIME: return "Day";
  233. case self::TOD_NIGHTTIME: return "Night";
  234. }
  235. }
  236. /**
  237. * @return string
  238. */
  239. public function getTimeOfDayIcon(): string {
  240. switch($this->time_of_day) {
  241. default:
  242. case self::TOD_ANYTIME: return "adjust";
  243. case self::TOD_DAYTIME: return "sun";
  244. case self::TOD_NIGHTTIME: return "moon";
  245. }
  246. }
  247. /**
  248. * @return string
  249. */
  250. public function getURL(): string {
  251. return "/account/projects/{$this->id}";
  252. }
  253. /**
  254. * @return string
  255. */
  256. public function getDirectory(): string {
  257. $directory = ROOT_DIR . "/files/projects/" . $this->id;
  258. if(!file_exists($directory) && !mkdir($directory, 0777, true) && !is_dir($directory)) {
  259. throw new RuntimeException(sprintf('Directory "%s" was not created', $directory));
  260. }
  261. return $directory;
  262. }
  263. /**
  264. * @return bool
  265. */
  266. public function hasInvoicePDF(): bool {
  267. $directory = $this->getDirectory();
  268. return file_exists($directory . "/invoice.pdf");
  269. }
  270. /**
  271. * @return bool
  272. */
  273. public function isAnytime(): bool {
  274. return $this->time_of_day === self::TOD_ANYTIME;
  275. }
  276. /**
  277. * @return bool
  278. */
  279. public function isDaytime(): bool {
  280. return $this->time_of_day === self::TOD_DAYTIME;
  281. }
  282. /**
  283. * @return bool
  284. */
  285. public function isNighttime(): bool {
  286. return $this->time_of_day === self::TOD_NIGHTTIME;
  287. }
  288. /**
  289. * @return bool
  290. */
  291. public function isPastDeadline(): bool {
  292. $deadline_unix = Util::getUnixTimeFromUTC($this->dts_deadline);
  293. return time() > $deadline_unix;
  294. }
  295. /**
  296. * @return bool
  297. */
  298. public function isFinished(): bool {
  299. return $this->dts_finished !== null;
  300. }
  301. /**
  302. * @return bool
  303. * @throws Exception
  304. */
  305. public function markFinished(): bool {
  306. if(!Core::$user) throw new Exception("Trying to mark project as finished while not logged in.");
  307. if(!Core::$user->isAdmin()) throw new Exception("Trying to mark project as finished with non-admin account.");
  308. $this->dts_finished = Util::getUTCDateTime();
  309. $this->user_id_finished = Core::$user->id;
  310. return $this->commit();
  311. }
  312. /**
  313. * @return bool
  314. * @throws Exception
  315. */
  316. public function markUnfinished(): bool {
  317. $this->dts_finished = null;
  318. $this->user_id_finished = null;
  319. return $this->commit();
  320. }
  321. /**
  322. * @return string
  323. * @throws Exception
  324. */
  325. public function getDisplayReportMonth(): string {
  326. $report_month = "-";
  327. if($this->dts_report) {
  328. $dt_report = new DateTime($this->dts_report . " UTC");
  329. $report_month = $dt_report->format("M Y");
  330. }
  331. return $report_month;
  332. }
  333. /**
  334. * @return array
  335. * @throws Exception
  336. */
  337. public function getDataTableRow(): array {
  338. $tests = $this->getTests();
  339. return [
  340. "id" => (int) $this->id,
  341. "rowId" => "project-row-{$this->id}",
  342. "name" => $this->name,
  343. "testCount" => count($tests),
  344. "timeOfDay" => $this->getTimeOfDayText(),
  345. "unixStart" => Util::getUnixTimeFromUTC($this->dts_start),
  346. "unixEnd" => Util::getUnixTimeFromUTC($this->dts_deadline),
  347. "reportMonth" => $this->getDisplayReportMonth(),
  348. "unixReport" => $this->dts_report ? Util::getUnixTimeFromUTC($this->dts_report) : 0,
  349. ];
  350. }
  351. /**
  352. * @return string
  353. * @throws Exception
  354. */
  355. public function getTestResultsUrl(): string {
  356. $customer = $this->getCustomer();
  357. $customer_slug = Util::slugWithId($customer->name, $customer->id);
  358. $project_slug = Util::slugWithId($this->name, $this->id);
  359. return "/account/test-results/{$customer_slug}/{$project_slug}";
  360. }
  361. /**
  362. * @return Invoice
  363. * @throws Exception
  364. */
  365. public function getCustomerInvoice(): Invoice {
  366. $invoice = new Invoice;
  367. $invoice->setReference($this->getInvoiceReference());
  368. $test_line_items = $this->getTestInvoiceLineItems();
  369. $field_line_items = $this->getFieldInvoiceLineItems();
  370. $invoice->addLineItems($test_line_items);
  371. $invoice->addLineItems($field_line_items);
  372. return $invoice;
  373. }
  374. /**
  375. * @return string
  376. * @throws Exception
  377. */
  378. private function getInvoiceReference(): string {
  379. $customer = $this->getCustomer();
  380. return
  381. "P" . str_pad($this->id, 3, "0", STR_PAD_LEFT) .
  382. "/C" . str_pad($customer->id, 3, "0", STR_PAD_LEFT);
  383. }
  384. /**
  385. * @return InvoiceLineItem[]
  386. * @throws Exception
  387. */
  388. private function getTestInvoiceLineItems(): array {
  389. /**
  390. * @var InvoiceLineItem[] $items
  391. */
  392. $template = $this->getTemplate();
  393. $default_customer_fee = $this->default_customer_fee;
  394. $tests = $this->getTests();
  395. $items = [];
  396. foreach($tests as $test) {
  397. $fee = $test->customer_fee ?? $default_customer_fee;
  398. $key = "fee_{$fee}";
  399. $item = $items[$key] ?? null;
  400. if(!$item) {
  401. $item = new InvoiceLineItem(__("%s Testing", $template->name));
  402. $item->setPrice($fee);
  403. }
  404. $item->incrementQuantity();
  405. $items[$key] = $item;
  406. }
  407. return array_values($items);
  408. }
  409. /**
  410. * @return InvoiceLineItem[]
  411. * @throws Exception
  412. */
  413. private function getFieldInvoiceLineItems(): array {
  414. $template = $this->getTemplate();
  415. $invoice_fields = $template->getCustomerInvoiceFields();
  416. $tests = $this->getTests();
  417. $items = [];
  418. foreach($tests as $test) {
  419. $values = $test->getValues(true);
  420. foreach($invoice_fields as $field) {
  421. $item = $items[$field->name] ?? (new InvoiceLineItem($field->label));
  422. $item->addPrice((float) ($values[$field->name] ?? 0));
  423. $items[$field->name] = $item;
  424. }
  425. }
  426. return $items;
  427. }
  428. public function setTemplateKeys($keys): void {
  429. if(!is_array($keys)) $keys = [];
  430. $this->template_keys = json_encode($keys);
  431. }
  432. /**
  433. * @return string[]
  434. */
  435. public function getTemplateKeys(): array {
  436. $keys = json_decode($this->template_keys);
  437. return $keys ?: [];
  438. }
  439. public function getDateTimeStart(): CarbonImmutable {
  440. return CarbonImmutable::parse($this->dts_start, "UTC");
  441. }
  442. public function getDateTimeDeadline(): CarbonImmutable {
  443. return CarbonImmutable::parse($this->dts_deadline, "UTC");
  444. }
  445. public function getDateTimeReport(): ?CarbonImmutable {
  446. if(!$this->dts_report) return null;
  447. return CarbonImmutable::parse($this->dts_report, "UTC");
  448. }
  449. /**
  450. * @param int $location_id
  451. * @return Test
  452. * @throws Exception
  453. */
  454. public function createTestForLocationId(int $location_id): Test {
  455. $test = new Test;
  456. $test->project_id = $this->id;
  457. $test->location_id = $location_id;
  458. $test->status = Test::STATUS_UNASSIGNED;
  459. $test->dts_created = Util::getDateTime();
  460. $success = $test->commit();
  461. if(!$success) throw new Exception("Test cannot be created, please try again later.");
  462. return $test;
  463. }
  464. /**
  465. * @param int $location_id
  466. * @return Test|null
  467. * @throws Exception
  468. */
  469. public function getActiveTestForLocationId(int $location_id): ?Test {
  470. return Test::queryOne([
  471. "project_id" => $this->id,
  472. "location_id" => $location_id,
  473. "status" => (new Constraint("MORE_THAN"))->setValues(Test::STATUS_CANCELLED)
  474. ]);
  475. }
  476. public function getTimeDeadline(): int {
  477. if($this->dts_deadline === null) {
  478. return 0;
  479. }
  480. return $this->getDateTimeDeadline()->getTimestamp();
  481. }
  482. public function isOverdue(): bool {
  483. return time() > $this->getTimeDeadline();
  484. }
  485. public function isAgeValid(int $age): bool {
  486. if($this->min_age && $this->max_age && ($age < $this->min_age || $age > $this->max_age)) {
  487. return false;
  488. }
  489. if($this->min_age && $age < $this->min_age) {
  490. return false;
  491. }
  492. if($this->max_age && $age > $this->max_age) {
  493. return false;
  494. }
  495. return true;
  496. }
  497. }