project.php 15 KB

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