project.php 15 KB

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