1
0

project.php 15 KB

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