1
0

test.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. <?php /** @noinspection HtmlDeprecatedTag */
  2. /** @noinspection HtmlDeprecatedAttribute */
  3. use Carbon\CarbonImmutable;
  4. use Mpdf\Mpdf;
  5. /**
  6. * @property int $id
  7. * @property int $project_id
  8. * @property int $location_id
  9. * @property int $tester_id
  10. * @property int $previous_test_id
  11. * @property int $stripe_invoice_id
  12. * @property int $status
  13. * @property int $status_tester_invoice
  14. * @property int $payment_required
  15. * @property float $customer_fee
  16. * @property float $test_fee
  17. * @property string $test_time
  18. * @property float $test_travel_cost
  19. * @property string $test_travel_cost_description
  20. * @property string $shop_left
  21. * @property string $shop_right
  22. * @property string $attire
  23. * @property int $challenge_stage
  24. * @property string $challenge_description
  25. * @property string $challenger_name
  26. * @property string $challenger_description
  27. * @property string $challenger_gender
  28. * @property string $challenger_eye_contact
  29. * @property string $additional_notes
  30. * @property string $dts_due
  31. * @property string $dts_start
  32. * @property string $dts_end
  33. * @property string $dts_tester_invoice_generated
  34. * @property string $dts_tester_invoice_paid
  35. * @property int $verifier_id
  36. * @property string $verifier_notes
  37. * @property int $pass
  38. * @property int $retest
  39. * @property int $void
  40. * @property int $void_primary
  41. * @property int $void_secondary
  42. * @property string $void_notes
  43. * @property string $dts_created
  44. * @property string $dts_updated
  45. * @property string $dts_assigned
  46. * @property string $dts_rejected
  47. * @property string $dts_verified
  48. * @property string $dts_paid
  49. */
  50. class Test extends Model {
  51. protected static $table = "test";
  52. protected static $id_field = "id";
  53. protected static $fillable_fields = [
  54. "project_id", "location_id", "tester_id", "previous_test_id", "stripe_invoice_id",
  55. "status", "status_tester_invoice",
  56. "payment_required",
  57. "customer_fee", "test_fee", "test_time", "test_travel_cost", "test_travel_cost_description",
  58. "shop_left", "shop_right", "attire",
  59. "challenge_stage",
  60. "challenge_description", "challenger_name", "challenger_description", "challenger_gender", "challenger_eye_contact",
  61. "additional_notes",
  62. "dts_due", "dts_start", "dts_end", "dts_tester_invoice_generated", "dts_tester_invoice_paid",
  63. "verifier_id", "verifier_notes",
  64. "pass", "retest",
  65. "void", "void_notes",
  66. "void_primary",
  67. "void_secondary",
  68. "dts_created", "dts_updated",
  69. "dts_assigned", "dts_rejected", "dts_verified", "dts_paid",
  70. ];
  71. public const TEST_FIELDS = ["shop_left", "shop_right", "attire", "challenge_stage", "challenge_description", "challenger_name", "challenger_description", "challenger_gender", "challenger_eye_contact", "additional_notes"];
  72. // Constants
  73. public const STATUS_CANCELLED = 0;
  74. public const STATUS_UNASSIGNED = 1; // Location needs a tester
  75. public const STATUS_ASSIGNED = 2; // Tester assigned
  76. public const STATUS_CONFIRMED = 3; // Tester has said they can do it
  77. public const STATUS_STARTED = 4;
  78. public const STATUS_PENDING_VERIFICATION = 8;
  79. public const STATUS_COMPLETED = 16;
  80. public const STATUS_TESTER_INVOICE_NONE = 0;
  81. public const STATUS_TESTER_INVOICE_PENDING = 100;
  82. public const STATUS_TESTER_INVOICE_PAID = 200;
  83. public const STATUSES = [
  84. 0 => "Cancelled",
  85. 1 => "Unassigned",
  86. 2 => "Assigned",
  87. 3 => "Confirmed",
  88. 4 => "Started",
  89. 8 => "Pending Verification",
  90. 16 => "Completed",
  91. ];
  92. public const STATUSES_TESTER_INVOICE = [
  93. Test::STATUS_TESTER_INVOICE_NONE,
  94. Test::STATUS_TESTER_INVOICE_PENDING,
  95. Test::STATUS_TESTER_INVOICE_PAID
  96. ];
  97. public const STAGES = [
  98. 0 => "",
  99. 1 => "Challenge on entry",
  100. 2 => "Challenge while browsing",
  101. 3 => "Challenge during play",
  102. 4 => "Challenge on exit",
  103. 5 => "No challenge",
  104. ];
  105. // Static methods
  106. /**
  107. * @param int $status
  108. * @return string
  109. */
  110. public static function getStatusTesterInvoiceText(int $status): string {
  111. switch($status) {
  112. case self::STATUS_TESTER_INVOICE_NONE:
  113. return __("No Invoice Generated");
  114. case self::STATUS_TESTER_INVOICE_PENDING:
  115. return __("Pending Payment");
  116. case self::STATUS_TESTER_INVOICE_PAID:
  117. return __("Paid");
  118. }
  119. return __("Unknown");
  120. }
  121. /**
  122. * @param int $status
  123. * @return string
  124. */
  125. public static function getStatusTesterInvoiceClass(int $status): string {
  126. switch($status) {
  127. case self::STATUS_TESTER_INVOICE_NONE:
  128. return "secondary";
  129. case self::STATUS_TESTER_INVOICE_PENDING:
  130. return "warning";
  131. case self::STATUS_TESTER_INVOICE_PAID:
  132. return "success";
  133. }
  134. return "";
  135. }
  136. /**
  137. * @param string $processing_file
  138. * @param array $tests
  139. * @throws Exception
  140. */
  141. public static function exportCSV(string $processing_file, array $tests = []): void {
  142. // Preload
  143. Project::load(array_column($tests, "project_id"));
  144. Location::load(array_column($tests, "location_id"));
  145. User::load(array_column($tests, "tester_id"));
  146. // Get processing file
  147. $processing_file_path = ROOT_DIR . "/export_processing/{$processing_file}";
  148. if(!file_exists($processing_file_path)) throw new Exception("Processing file not found.");
  149. // Output
  150. HTTP::setDownloadHeaders("export.csv");
  151. $handle = fopen("php://output", "wb");
  152. /** @noinspection PhpIncludeInspection */
  153. require $processing_file_path;
  154. fclose($handle);
  155. }
  156. // Object methods
  157. /**
  158. * @param string $message
  159. * @return bool
  160. * @throws Exception
  161. */
  162. public function sendAssignEmail(string $message): bool {
  163. $tester = $this->getTester();
  164. $location = $this->getLocation();
  165. $project = $this->getProject();
  166. // Content
  167. $name = htmlspecialchars($tester->first_name);
  168. $message = htmlspecialchars($message);
  169. $base_url = htmlspecialchars(PROTOCOL . "://" . DOMAIN . "/account/tests/" . $this->id);
  170. $address = htmlspecialchars($location->name . ", " . $location->getDisplayAddress(["address_1", "address_2", "city", "county", "postal_code"]));
  171. $date_due = date("j M Y", strtotime($this->dts_due));
  172. $admin_first_name = htmlspecialchars(Core::$user->first_name);
  173. $admin_phone = htmlspecialchars(Core::$user->phone);
  174. // Build
  175. $builder = new EmailBuilder;
  176. $builder->addParagraph("<b>" . sprintf(__("Hi %s"), $name) . "</b>");
  177. $builder->addLeadParagraph(__("Congrats, you have been allocated a test!"));
  178. if($project->isNighttime()) {
  179. $builder->addParagraph("<b><font color=\"red\">" . __("Evening Test to be done between 7PM and midnight.") . "</font></b>");
  180. }
  181. if($message) {
  182. $builder->addParagraph($message);
  183. }
  184. $builder->addParagraph(sprintf(__("We need you to confirm if you are able to do the test. Please check the details below and then confirm by pressing the %sAccept%s or %sDecline%s buttons and once you tap %sAccept%s, the test will be allocated to you."),
  185. '<b>', '</b>',
  186. '<b>', '</b>',
  187. '<b>', '</b>'
  188. ));
  189. $builder->addAcceptDeclineButtons($base_url);
  190. $builder->addParagraph(sprintf(__("The site address is: %s"), "<b>{$address}</b>"));
  191. $builder->addParagraph(sprintf(__("The date that need to complete and submit the results by is: %s"), "<font color=\"red\"><b>$date_due</b></font>"));
  192. $builder->addParagraph(sprintf(__("For methodology and further notes please check the %sUseful Documents%s section on the %sAccount%s page."),
  193. '<b>', '</b>',
  194. '<b>', '</b>'
  195. ));
  196. $builder->addParagraph(sprintf(__("If you agree to conduct the test, log in and then go to %sTests%s where you will be able to see the tests available to you. Please tap the %sBegin%s button and follow the instructions that is shown."),
  197. '<b>', '</b>',
  198. '<b>', '</b>'
  199. ));
  200. $builder->addParagraph(sprintf(__("If you have any questions please send them to %s or call %s on %s."),
  201. "<a href=\"mailto:tests@check-policy.com\">tests@check-policy.com</a>",
  202. "<b>$admin_first_name</b>",
  203. "<b>$admin_phone</b>"
  204. ));
  205. $builder->addParagraph(sprintf(__("If you are unable to submit the results via the web-based app please contact us and we can send you an offline form to complete. Please accept the test by tapping the %sAccept%s button and email us back saying you would like an offline form."),
  206. '<b>', '</b>'
  207. ));
  208. $content = $builder->build();
  209. // Send
  210. $mail = new Email;
  211. $mail->setHtmlContent($content);
  212. $mail->setFrom(EMAIL_CONTACT, EMAIL_FROM_NAME);
  213. $mail->addAddress($tester->email, $tester->getDisplayName());
  214. $mail->setSubject(__("You have been allocated a test"));
  215. $mail->send();
  216. return true;
  217. }
  218. /**
  219. * @return bool
  220. * @throws Exception
  221. */
  222. public function sendClaimedEmail(): bool {
  223. $tester = $this->getTester();
  224. $location = $this->getLocation();
  225. $project = $this->getProject();
  226. // Content
  227. $name = htmlspecialchars($tester->first_name);
  228. $address = htmlspecialchars($location->name . ", " . $location->getDisplayAddress(["address_1", "address_2", "city", "county", "postal_code"]));
  229. $date_due = date("j M Y", strtotime($this->dts_due));
  230. // Build
  231. $builder = new EmailBuilder;
  232. $builder->addParagraph("<b>" . sprintf(__("Hi %s"), $name) . "</b>");
  233. $builder->addLeadParagraph(__("Congrats, you have claimed a test!"));
  234. if($project->isNighttime()) {
  235. $builder->addParagraph("<b><font color=\"red\">" . __("Evening Test to be done between 7PM and midnight.") . "</font></b>");
  236. }
  237. $builder->addParagraph(sprintf(__("The site address is: %s"), "<b>$address</b>"));
  238. $builder->addParagraph(sprintf(__("The date that need to complete and submit the results by is: %s"), "<font color=\"red\"><b>$date_due</b></font>"));
  239. $builder->addParagraph(sprintf(__("For methodology and further notes please check the %sUseful Documents%s section on the %sAccount%s page."),
  240. '<b>', '</b>',
  241. '<b>', '</b>'
  242. ));
  243. $builder->addParagraph(sprintf(__("Log in and then go to %sTests%s where you will be able to see the tests available to you. Please tap the %sBegin%s button and follow the instructions that is shown."),
  244. '<b>', '</b>',
  245. '<b>', '</b>'
  246. ));
  247. $builder->addParagraph(sprintf(__("If you have any questions please send them to %s."),
  248. "<a href=\"mailto:tests@check-policy.com\">tests@check-policy.com</a>"
  249. ));
  250. $builder->addParagraph(__("If you are unable to submit the results via the web-based app please contact us and we can send you an offline form to complete."));
  251. $content = $builder->build();
  252. // Send
  253. $mail = new Email;
  254. $mail->setHtmlContent($content);
  255. $mail->setFrom(EMAIL_CONTACT, EMAIL_FROM_NAME);
  256. $mail->addAddress($tester->email, $tester->getDisplayName());
  257. $mail->setSubject(__("You have claimed a test"));
  258. $mail->send();
  259. return true;
  260. }
  261. /**
  262. * @return bool
  263. * @throws Exception
  264. */
  265. public function sendDeclineEmail(): bool {
  266. $tester = $this->getTester();
  267. $location = $this->getLocation();
  268. $project = $this->getProject();
  269. // Content
  270. $name = htmlspecialchars($tester->getDisplayName());
  271. $address = htmlspecialchars($location->name . ", " . $location->getDisplayAddress(["address_1", "address_2", "city", "county", "postal_code"]));
  272. $project_name = htmlspecialchars($project->name);
  273. $project_url = htmlspecialchars(PROTOCOL . "://" . DOMAIN . "/account/projects/" . $project->id);
  274. $internal_id = "N/A";
  275. if($location->internal_id) $internal_id = htmlspecialchars($location->internal_id);
  276. // Build
  277. $builder = new EmailBuilder;
  278. $builder->addParagraph("<b>Hi,</b>");
  279. $builder->addLeadParagraph("A tester has declined a test.");
  280. $builder->addParagraph("<b>Project:</b><br />$project_name");
  281. $builder->addParagraph("<b>Site:</b><br />$address<br />ID: $location->id | Internal ID: $internal_id");
  282. $builder->addParagraph("<b>Who:</b><br />$name<br />ID: $tester->id");
  283. $builder->addParagraph("<a href=\"$project_url\">Click here</a> to manage the project and reassign the test.");
  284. $content = $builder->build();
  285. // Send
  286. $mail = new Email;
  287. $mail->setHtmlContent($content);
  288. $mail->setFrom(EMAIL_NO_REPLY, EMAIL_FROM_NAME);
  289. $mail->addAddress(EMAIL_CONTACT, APP_NAME . " Contact");
  290. $mail->setSubject("Test declined: $project->name / $location->name");
  291. $mail->send();
  292. return true;
  293. }
  294. /**
  295. * @param string $to_address
  296. * @param bool $include_previous_test
  297. * @return bool
  298. * @throws Exception
  299. */
  300. public function sendResultEmail(string $to_address, bool $include_previous_test): bool {
  301. $location = $this->getLocation();
  302. $project = $this->getProject();
  303. $template = $project->getTemplate();
  304. $subject_format_file_path = $template->getProcessingFilePath("result_email_subject_format.txt");
  305. $subject_format = file_get_contents($subject_format_file_path);
  306. // Content
  307. $pass_text = strtoupper($this->getPassText());
  308. $stage = $this->challenge_stage;
  309. $location_parts = [$location->internal_id, $location->name];
  310. $location_string = implode(" : ", array_filter($location_parts));
  311. $unix_start = strtotime($this->dts_start . " UTC");
  312. $date_time = date("d/m/Y H:i", $unix_start);
  313. // Subject
  314. $search_replace = [
  315. "{pass}" => $pass_text,
  316. "{stage}" => $stage,
  317. "{location}" => $location_string,
  318. "{date-time}" => $date_time,
  319. ];
  320. $subject = str_replace(
  321. array_keys($search_replace),
  322. array_values($search_replace),
  323. $subject_format
  324. );
  325. // Attachments
  326. $pdf_path = $this->getDirectory() . "/pdf.pdf";
  327. $pdf_name = implode(" - ", array_filter([$location->internal_id, date("jS M Y")])) . ".pdf";
  328. // Lead paragraph
  329. $lead_paragraph = "";
  330. if($this->pass) {
  331. $lead_paragraph .= "Congratulations!<br />";
  332. }
  333. $lead_paragraph .= "A test has been completed at your location.";
  334. // Build
  335. $builder = new EmailBuilder;
  336. $builder->addLeadParagraph($lead_paragraph);
  337. $builder->addParagraph("Please see attached PDF and do not hesitate to contact us if you have any questions.");
  338. // Previous test
  339. $previous_pdf_path = $previous_pdf_name = null;
  340. if($include_previous_test) {
  341. $previous_test = $this->getPreviousTest();
  342. if($previous_test && $previous_test->hasPDF()) {
  343. $builder->addParagraph("The previous test result has also been attached for your reference.");
  344. $previous_dt = new DateTime($previous_test->dts_start, new DateTimeZone("UTC"));
  345. $previous_pdf_path = $previous_test->getPDFPath();
  346. $previous_pdf_name = implode(" - ", array_filter([$location->internal_id, $previous_dt->format("jS M Y")])) . ".pdf";
  347. }
  348. }
  349. $content = $builder->build();
  350. // Send
  351. $mail = new Email();
  352. $mail->setHtmlContent($content);
  353. $mail->setFrom(EMAIL_PDF_FROM_ADDRESS, EMAIL_FROM_NAME);
  354. $mail->addAddress($to_address);
  355. $mail->addAttachment($pdf_path, $pdf_name);
  356. if($previous_pdf_name) {
  357. $mail->addAttachment($previous_pdf_path, $previous_pdf_name);
  358. }
  359. if(defined("FAIL_ATTACHMENTS") && !($this->isPass() || $this->isVoid())) {
  360. foreach(FAIL_ATTACHMENTS as $rel_path) {
  361. $abs_path = realpath(ROOT_DIR . $rel_path);
  362. if($abs_path && file_exists($abs_path)) {
  363. $mail->addAttachment($abs_path, basename($abs_path));
  364. }
  365. }
  366. }
  367. $mail->setSubject($subject);
  368. $mail->send();
  369. return true;
  370. }
  371. /**
  372. * @return bool
  373. * @throws Exception
  374. */
  375. public function decline(): bool {
  376. $this->sendDeclineEmail();
  377. $user_id = $this->tester_id;
  378. $location_id = $this->location_id;
  379. $this->status = self::STATUS_UNASSIGNED;
  380. $this->tester_id = null;
  381. $this->dts_due = null;
  382. $this->dts_assigned = null;
  383. $this->dts_rejected = Util::getDateTime();
  384. $this->dts_updated = Util::getDateTime();
  385. $this->commit();
  386. $reject = UserLocationReject::get($user_id, $location_id);
  387. if(!$reject) {
  388. $reject = new UserLocationReject();
  389. $reject->user_id = $user_id;
  390. $reject->location_id = $location_id;
  391. $reject->reject_count = 0;
  392. }
  393. $reject->reject_count++;
  394. $reject->dts_last_rejected = DB::dts();
  395. $reject->commit();
  396. return true;
  397. }
  398. /**
  399. * @return string
  400. */
  401. public function getChallengeStageText(): string {
  402. if(is_null($this->challenge_stage)) return "";
  403. return self::STAGES[$this->challenge_stage];
  404. }
  405. /**
  406. * @return string
  407. */
  408. public function getStatusText(): string {
  409. return self::STATUSES[$this->status];
  410. }
  411. /**
  412. * @return string
  413. */
  414. public function getStatusClass(): string {
  415. switch($this->status) {
  416. case self::STATUS_CANCELLED:
  417. return "secondary";
  418. case self::STATUS_UNASSIGNED:
  419. return "danger";
  420. case self::STATUS_ASSIGNED:
  421. case self::STATUS_CONFIRMED:
  422. case self::STATUS_STARTED:
  423. return "warning";
  424. case self::STATUS_PENDING_VERIFICATION:
  425. return "primary";
  426. case self::STATUS_COMPLETED:
  427. return "success";
  428. }
  429. return "";
  430. }
  431. /**
  432. * @return Project|null
  433. * @throws Exception
  434. */
  435. public function getProject(): ?Project {
  436. return Project::get($this->project_id);
  437. }
  438. /**
  439. * @return Location
  440. * @throws Exception
  441. */
  442. public function getLocation(): Location {
  443. return Location::get($this->location_id);
  444. }
  445. /**
  446. * @return User
  447. * @throws Exception
  448. */
  449. public function getTester(): ?User {
  450. return User::get($this->tester_id);
  451. }
  452. /**
  453. * @return User
  454. * @throws Exception
  455. */
  456. public function getVerifier(): ?User {
  457. return User::get($this->verifier_id);
  458. }
  459. /**
  460. * @param bool $as_assoc_array
  461. * @return TestValue[]
  462. * @throws Exception
  463. */
  464. public function getValues(bool $as_assoc_array = false): array {
  465. $rows = TestValue::query(["test_id" => $this->id]);
  466. if($as_assoc_array) {
  467. $values = [];
  468. foreach($rows as $row) {
  469. $values[$row->name] = $row->value;
  470. }
  471. }
  472. else {
  473. $values = $rows;
  474. }
  475. return $values;
  476. }
  477. /**
  478. * @return string
  479. */
  480. public function getDirectory(): string {
  481. $directory = ROOT_DIR . "/files/tests/" . $this->id;
  482. if(!file_exists($directory)) mkdir($directory, 0777, true);
  483. return $directory;
  484. }
  485. /**
  486. * @return bool|float|int
  487. */
  488. public function getDuration() {
  489. if($this->dts_end === null) return false;
  490. return Util::getDurationFromDTS($this->dts_start, $this->dts_end);
  491. }
  492. /**
  493. * @return string
  494. */
  495. public function getDisplayDuration(): string {
  496. $secs = $this->getDuration();
  497. $mins = floor($secs / 60);
  498. $secs %= 60;
  499. return "$mins min. $secs sec.";
  500. }
  501. /**
  502. * @return string Bootstrap class name
  503. */
  504. public function getPassClass(): string {
  505. if($this->isVoid() || $this->isPrimaryVoid()) return "muted";
  506. if($this->pass === null) return "secondary";
  507. return $this->pass ? "success" : "danger";
  508. }
  509. /**
  510. * @return string FA icon name without prefix
  511. */
  512. public function getPassIcon(): string {
  513. if($this->isVoid() || $this->isPrimaryVoid()) return "minus-circle";
  514. if($this->pass === null) return "clock";
  515. return $this->pass ? "check-circle" : "times-circle";
  516. }
  517. /**
  518. * @return string Pending, Pass or Fail
  519. */
  520. public function getPassText(): string {
  521. if($this->isVoid() || $this->isPrimaryVoid()) return __("Void");
  522. if($this->pass === null) return __("Pending");
  523. return $this->pass ? __("Pass") : __("Fail");
  524. }
  525. /** @noinspection PhpUnusedLocalVariableInspection */
  526. public function getMPDF(): Mpdf {
  527. $id = $this->id;
  528. $output = false;
  529. require ROOT_DIR . "/controllers/test_pdf.php";
  530. /** @var Mpdf $mpdf */
  531. return $mpdf;
  532. }
  533. /**
  534. * @param User $tester
  535. * @param CarbonImmutable|null $dt_due
  536. * @param string|null $message
  537. * @return bool
  538. * @throws Exception
  539. */
  540. public function assignTester(User $tester, ?CarbonImmutable $dt_due = null, ?string $message = null): bool {
  541. if($tester->level === User::LEVEL_BANNED) {
  542. throw new RuntimeException("A test cannot be assigned to an banned user.");
  543. }
  544. if($tester->level === User::LEVEL_REGISTERED) {
  545. throw new RuntimeException("A test cannot be assigned to an unverified user.");
  546. }
  547. if($tester->level === User::LEVEL_UNVERIFIED) {
  548. throw new RuntimeException("A test cannot be assigned to an unverified user.");
  549. }
  550. if($tester->level === User::LEVEL_DEACTIVATED) {
  551. throw new RuntimeException("A test cannot be assigned to a deactivated user.");
  552. }
  553. if($tester->level !== User::LEVEL_TESTER) {
  554. throw new RuntimeException("A test cannot be assigned to a user that's not a tester.");
  555. }
  556. $this->tester_id = $tester->id;
  557. $this->status = self::STATUS_ASSIGNED;
  558. $this->dts_assigned = Util::getDateTime();
  559. $this->dts_rejected = null;
  560. $this->dts_updated = Util::getDateTime();
  561. $this->dts_due = $dt_due ? $dt_due->utc()->toDateTimeString() : null;
  562. if($this->dts_due) {
  563. $project = $this->getProject();
  564. if(strcmp($this->dts_due, $project->dts_start) < 0) {
  565. throw new RuntimeException("The date due cannot be before the project start date.");
  566. }
  567. if(strcmp($this->dts_due, $project->dts_deadline) > 0) {
  568. throw new RuntimeException("The date due cannot be beyond the project deadline.");
  569. }
  570. }
  571. $success = $this->commit();
  572. if($success) {
  573. $this->sendAssignEmail($message ?? "");
  574. }
  575. return $success;
  576. }
  577. /**
  578. * @return Test|null
  579. * @throws Exception
  580. */
  581. public function getPreviousTest(): ?Test {
  582. if($this->previous_test_id) {
  583. return self::get($this->previous_test_id);
  584. }
  585. if($this->dts_start === null) {
  586. return null;
  587. }
  588. $nvp = [
  589. "dts_start" => Constraint::lessThan($this->dts_start),
  590. "location_id" => $this->location_id,
  591. "status" => self::STATUS_COMPLETED,
  592. ];
  593. $tests = self::query($nvp, [
  594. "sort" => "dts_start",
  595. "order" => "desc",
  596. ]);
  597. return $tests ? $tests[0] : null;
  598. }
  599. /**
  600. * @return Test|null
  601. * @throws Exception
  602. */
  603. public function getNextTest(): ?Test {
  604. $test = self::queryOne(["previous_test_id" => $this->id]);
  605. if($test) {
  606. return $test;
  607. }
  608. if($this->dts_start === null) {
  609. return null;
  610. }
  611. $nvp = [
  612. "dts_start" => Constraint::moreThan($this->dts_start),
  613. "location_id" => $this->location_id,
  614. ];
  615. $tests = self::query($nvp, [
  616. "sort" => "dts_start",
  617. "order" => "asc",
  618. ]);
  619. return $tests ? $tests[0] : null;
  620. }
  621. /**
  622. * @return bool
  623. * @throws Exception
  624. */
  625. public function unassignTester(): bool {
  626. $this->status = self::STATUS_UNASSIGNED;
  627. $this->tester_id = null;
  628. $this->dts_due = null;
  629. $this->dts_assigned = null;
  630. $this->dts_rejected = null;
  631. $this->dts_updated = Util::getDateTime();
  632. return $this->commit();
  633. }
  634. /**
  635. * @return bool
  636. */
  637. public function isPass(): bool {
  638. return (int) $this->pass === 1;
  639. }
  640. /**
  641. * @return bool
  642. */
  643. public function isPending(): bool {
  644. return $this->pass === null;
  645. }
  646. /**
  647. * @return bool
  648. */
  649. public function isFail(): bool {
  650. return (int) $this->pass === 0;
  651. }
  652. /**
  653. * @return bool
  654. */
  655. public function isCompleted(): bool {
  656. return $this->getStatus() === self::STATUS_COMPLETED;
  657. }
  658. public function isDone(): bool {
  659. return in_array($this->getStatus(), [self::STATUS_CANCELLED, self::STATUS_COMPLETED]);
  660. }
  661. /**
  662. * @return bool
  663. */
  664. public function isPendingVerification(): bool {
  665. return $this->getStatus() === self::STATUS_PENDING_VERIFICATION;
  666. }
  667. public function getPDFPath(): string {
  668. $directory = $this->getDirectory();
  669. return sprintf("%s/pdf.pdf", $directory);
  670. }
  671. /**
  672. * @return bool
  673. */
  674. public function hasPDF(): bool {
  675. return file_exists($this->getPDFPath());
  676. }
  677. /**
  678. * @return string
  679. */
  680. public function getPDFUrl(): string {
  681. return "/account/tests/{$this->id}/files/pdf";
  682. }
  683. public function getTesterInvoicePDFPath(): string {
  684. return sprintf("%s/tester_invoice.pdf", $this->getDirectory());
  685. }
  686. /**
  687. * @return bool
  688. */
  689. public function hasTesterInvoicePDF(): bool {
  690. return file_exists($this->getTesterInvoicePDFPath());
  691. }
  692. public function getTravelCostsPhotoPath(): string {
  693. return sprintf("%s/travel_costs.jpg", $this->getDirectory());
  694. }
  695. public function hasTravelCostsPhoto(): bool {
  696. return file_exists($this->getTravelCostsPhotoPath());
  697. }
  698. /**
  699. * @return bool
  700. * @throws Exception
  701. */
  702. public function markTesterInvoicePaid(): bool {
  703. if($this->getTesterInvoiceStatus() === self::STATUS_TESTER_INVOICE_PENDING) {
  704. $this->status_tester_invoice = self::STATUS_TESTER_INVOICE_PAID;
  705. $this->dts_tester_invoice_paid = Util::getDateTime();
  706. return $this->commit();
  707. }
  708. return false;
  709. }
  710. /**
  711. * @return bool
  712. * @throws Exception
  713. */
  714. public function rejectTesterInvoice(): bool {
  715. if($this->getTesterInvoiceStatus() === self::STATUS_TESTER_INVOICE_PENDING) {
  716. $this->status_tester_invoice = self::STATUS_TESTER_INVOICE_NONE;
  717. $this->dts_tester_invoice_generated = null;
  718. if($this->hasTesterInvoicePDF()) {
  719. unlink($this->getTesterInvoicePDFPath());
  720. }
  721. if($this->hasTravelCostsPhoto()) {
  722. unlink($this->getTravelCostsPhotoPath());
  723. }
  724. return $this->commit();
  725. }
  726. return false;
  727. }
  728. /**
  729. * @return string
  730. * @throws Exception
  731. */
  732. public function getTesterInvoiceReference(): string {
  733. $location = $this->getLocation();
  734. $tester = $this->getTester();
  735. return
  736. "T" . str_pad($this->id, 3, "0", STR_PAD_LEFT) .
  737. "/L" . str_pad($location->id, 3, "0", STR_PAD_LEFT) .
  738. "/U" . str_pad($tester->id, 3, "0", STR_PAD_LEFT);
  739. }
  740. /**
  741. * @return float
  742. * @throws Exception
  743. */
  744. public function getTestFee(): float {
  745. return $this->test_fee !== null ? (float) $this->test_fee : (float) $this->getProject()->default_tester_fee;
  746. }
  747. public function getTravelCosts(): float {
  748. return (float) $this->test_travel_cost;
  749. }
  750. /**
  751. * @return float
  752. * @throws Exception
  753. */
  754. public function getInvoiceTotal(): float {
  755. $template = $this->getProject()->getTemplate();
  756. $values = $this->getValues(true);
  757. // Base cost
  758. $fee = $this->getTestFee();
  759. $travel_cost = $this->getTravelCosts();
  760. $invoice_total = $fee + $travel_cost;
  761. // Additional tester invoice fields
  762. $tester_invoice_fields = $template->getTesterInvoiceFields();
  763. foreach($tester_invoice_fields as $field) {
  764. $invoice_total += (float) ($values[$field->name] ?? 0);
  765. }
  766. return $invoice_total;
  767. }
  768. public function isVoid(): bool {
  769. return (bool) $this->void;
  770. }
  771. public function isPrimaryVoid(): bool {
  772. return (bool) $this->void_primary;
  773. }
  774. public function getStatus(): int {
  775. return $this->status;
  776. }
  777. public function getTesterId(): int {
  778. return $this->tester_id;
  779. }
  780. /**
  781. * @return bool Whether the tester has accepted the test
  782. */
  783. public function isConfirmed(): bool {
  784. return $this->getStatus() === self::STATUS_CONFIRMED;
  785. }
  786. public function hasStarted(): bool {
  787. return $this->getStatus() === self::STATUS_STARTED;
  788. }
  789. public function isAssigned(): bool {
  790. return $this->getStatus() === self::STATUS_ASSIGNED;
  791. }
  792. /**
  793. * @return array
  794. * @throws Exception
  795. */
  796. public function getFieldsForVerifyForm(): array {
  797. $json = json_decode($this->getProject()->getTemplate()->getJSON());
  798. return array_merge($json->beforeTest, [(object) ["type" => "hr"]], $json->duringTest);
  799. }
  800. public function getTesterInvoiceStatus(): int {
  801. return $this->status_tester_invoice;
  802. }
  803. public function isCancelled(): bool {
  804. return $this->getStatus() === self::STATUS_CANCELLED;
  805. }
  806. public function hasDueDateTime(): bool {
  807. return $this->dts_due !== null;
  808. }
  809. public function getTimeDue(): int {
  810. if(!$this->dts_due) {
  811. return 0;
  812. }
  813. return $this->getDateTimeDue()->getTimestamp();
  814. }
  815. public function hasNotStarted(): bool {
  816. return $this->status < self::STATUS_STARTED;
  817. }
  818. public function isOverdue(): bool {
  819. return time() > $this->getTimeDue();
  820. }
  821. public function getDateTimeDue(): ?CarbonImmutable {
  822. return Util::getDateTimeFromUtcString($this->dts_due);
  823. }
  824. public function getDateTimeStart(): ?CarbonImmutable {
  825. return Util::getDateTimeFromUtcString($this->dts_start);
  826. }
  827. public function getDateTimeEnd(): ?CarbonImmutable {
  828. return Util::getDateTimeFromUtcString($this->dts_end);
  829. }
  830. public function getDateTimeAssigned(): ?CarbonImmutable {
  831. return Util::getDateTimeFromUtcString($this->dts_assigned);
  832. }
  833. public function getVerifierNotesHtml(): string {
  834. return nl2br(htmlspecialchars($this->verifier_notes));
  835. }
  836. /**
  837. * @return float
  838. * @throws Exception
  839. */
  840. public function getTesterInvoiceCosts(): float {
  841. return $this->getProject()->getTemplate()->getTesterInvoiceCosts($this->getValues(true));
  842. }
  843. public function getDateTimeRejected(): ?CarbonImmutable {
  844. if(!$this->dts_rejected) {
  845. return null;
  846. }
  847. return CarbonImmutable::parse($this->dts_rejected, "UTC");
  848. }
  849. public function renderTestStatus(User $user): void {
  850. ?>
  851. <a href="/account/tests/<?=$this->id?>">
  852. <?php
  853. if($this->isPass()) {
  854. ?>
  855. <i class="fa fa-fw fa-check-circle text-success"></i> Passed on <?=$user->formatDate($this->getDateTimeStart())?>
  856. <?php
  857. }
  858. elseif($this->isVoid()) {
  859. ?>
  860. <i class="fa fa-fw fa-minus-circle text-secondary"></i> Void on <?=$user->formatDate($this->getDateTimeStart())?>
  861. <?php
  862. }
  863. elseif($this->isFail()) {
  864. ?>
  865. <i class="fa fa-fw fa-times-circle text-danger"></i> Failed on <?=$user->formatDate($this->getDateTimeStart())?>
  866. <?php
  867. }
  868. else {
  869. ?>
  870. <i class="fa fa-fw fa-question-circle text-warning"></i> Result Pending (Test <?=htmlspecialchars($this->getStatusText())?>)
  871. <?php
  872. }
  873. ?>
  874. </a>
  875. <?php
  876. }
  877. /**
  878. * @return string
  879. * @throws Exception
  880. */
  881. public function getCustomerFee(): string {
  882. $project = $this->getProject();
  883. if($this->customer_fee) {
  884. $fee = $this->customer_fee;
  885. }
  886. elseif($this->retest) {
  887. $fee = $project->getDefaultRetestFee();
  888. }
  889. else {
  890. $fee = $project->default_customer_fee;
  891. }
  892. return $fee;
  893. }
  894. }