test.php 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. $mail->setSubject($subject);
  360. $mail->send();
  361. return true;
  362. }
  363. /**
  364. * @return bool
  365. * @throws Exception
  366. */
  367. public function decline(): bool {
  368. $this->sendDeclineEmail();
  369. $user_id = $this->tester_id;
  370. $location_id = $this->location_id;
  371. $this->status = self::STATUS_UNASSIGNED;
  372. $this->tester_id = null;
  373. $this->dts_due = null;
  374. $this->dts_assigned = null;
  375. $this->dts_rejected = Util::getDateTime();
  376. $this->dts_updated = Util::getDateTime();
  377. $this->commit();
  378. $reject = UserLocationReject::get($user_id, $location_id);
  379. if(!$reject) {
  380. $reject = new UserLocationReject();
  381. $reject->user_id = $user_id;
  382. $reject->location_id = $location_id;
  383. $reject->reject_count = 0;
  384. }
  385. $reject->reject_count++;
  386. $reject->dts_last_rejected = DB::dts();
  387. $reject->commit();
  388. return true;
  389. }
  390. /**
  391. * @return string
  392. */
  393. public function getChallengeStageText(): string {
  394. if(is_null($this->challenge_stage)) return "";
  395. return self::STAGES[$this->challenge_stage];
  396. }
  397. /**
  398. * @return string
  399. */
  400. public function getStatusText(): string {
  401. return self::STATUSES[$this->status];
  402. }
  403. /**
  404. * @return string
  405. */
  406. public function getStatusClass(): string {
  407. switch($this->status) {
  408. case self::STATUS_CANCELLED:
  409. return "secondary";
  410. case self::STATUS_UNASSIGNED:
  411. return "danger";
  412. case self::STATUS_ASSIGNED:
  413. case self::STATUS_CONFIRMED:
  414. case self::STATUS_STARTED:
  415. return "warning";
  416. case self::STATUS_PENDING_VERIFICATION:
  417. return "primary";
  418. case self::STATUS_COMPLETED:
  419. return "success";
  420. }
  421. return "";
  422. }
  423. /**
  424. * @return Project
  425. * @throws Exception
  426. */
  427. public function getProject(): Project {
  428. return Project::get($this->project_id);
  429. }
  430. /**
  431. * @return Location
  432. * @throws Exception
  433. */
  434. public function getLocation(): Location {
  435. return Location::get($this->location_id);
  436. }
  437. /**
  438. * @return User
  439. * @throws Exception
  440. */
  441. public function getTester(): ?User {
  442. return User::get($this->tester_id);
  443. }
  444. /**
  445. * @return User
  446. * @throws Exception
  447. */
  448. public function getVerifier(): ?User {
  449. return User::get($this->verifier_id);
  450. }
  451. /**
  452. * @param bool $as_assoc_array
  453. * @return TestValue[]
  454. * @throws Exception
  455. */
  456. public function getValues(bool $as_assoc_array = false): array {
  457. $rows = TestValue::query(["test_id" => $this->id]);
  458. if($as_assoc_array) {
  459. $values = [];
  460. foreach($rows as $row) {
  461. $values[$row->name] = $row->value;
  462. }
  463. }
  464. else {
  465. $values = $rows;
  466. }
  467. return $values;
  468. }
  469. /**
  470. * @return string
  471. */
  472. public function getDirectory(): string {
  473. $directory = ROOT_DIR . "/files/tests/" . $this->id;
  474. if(!file_exists($directory)) mkdir($directory, 0777, true);
  475. return $directory;
  476. }
  477. /**
  478. * @return bool|float|int
  479. */
  480. public function getDuration() {
  481. if($this->dts_end === null) return false;
  482. return Util::getDurationFromDTS($this->dts_start, $this->dts_end);
  483. }
  484. /**
  485. * @return string
  486. */
  487. public function getDisplayDuration(): string {
  488. $secs = $this->getDuration();
  489. $mins = floor($secs / 60);
  490. $secs %= 60;
  491. return "$mins min. $secs sec.";
  492. }
  493. /**
  494. * @return string Bootstrap class name
  495. */
  496. public function getPassClass(): string {
  497. if($this->isVoid()) return "muted";
  498. if($this->pass === null) return "secondary";
  499. return $this->pass ? "success" : "danger";
  500. }
  501. /**
  502. * @return string FA icon name without prefix
  503. */
  504. public function getPassIcon(): string {
  505. if($this->isVoid()) return "minus-circle";
  506. if($this->pass === null) return "clock";
  507. return $this->pass ? "check-circle" : "times-circle";
  508. }
  509. /**
  510. * @return string Pending, Pass or Fail
  511. */
  512. public function getPassText(): string {
  513. if($this->isVoid() || $this->isPrimaryVoid()) return __("Void");
  514. if($this->pass === null) return __("Pending");
  515. return $this->pass ? __("Pass") : __("Fail");
  516. }
  517. /** @noinspection PhpUnusedLocalVariableInspection */
  518. public function getMPDF(): Mpdf {
  519. $id = $this->id;
  520. $output = false;
  521. require ROOT_DIR . "/controllers/test_pdf.php";
  522. /** @var Mpdf $mpdf */
  523. return $mpdf;
  524. }
  525. /**
  526. * @param User $tester
  527. * @return bool
  528. * @throws Exception
  529. */
  530. public function assignTester(User $tester): bool {
  531. $this->tester_id = $tester->id;
  532. $this->dts_assigned = Util::getDateTime();
  533. $this->dts_rejected = null;
  534. // TODO: Notify tester
  535. return $this->commit();
  536. }
  537. /**
  538. * @return Test|null
  539. * @throws Exception
  540. */
  541. public function getPreviousTest(): ?Test {
  542. if($this->previous_test_id) {
  543. return self::get($this->previous_test_id);
  544. }
  545. if($this->dts_start === null) {
  546. return null;
  547. }
  548. $nvp = [
  549. "dts_start" => Constraint::lessThan($this->dts_start),
  550. "location_id" => $this->location_id,
  551. "status" => self::STATUS_COMPLETED,
  552. ];
  553. $tests = self::query($nvp, [
  554. "sort" => "dts_start",
  555. "order" => "desc",
  556. ]);
  557. return $tests ? $tests[0] : null;
  558. }
  559. /**
  560. * @return Test|null
  561. * @throws Exception
  562. */
  563. public function getNextTest(): ?Test {
  564. $test = self::queryOne(["previous_test_id" => $this->id]);
  565. if($test) {
  566. return $test;
  567. }
  568. if($this->dts_start === null) {
  569. return null;
  570. }
  571. $nvp = [
  572. "dts_start" => Constraint::moreThan($this->dts_start),
  573. "location_id" => $this->location_id,
  574. ];
  575. $tests = self::query($nvp, [
  576. "sort" => "dts_start",
  577. "order" => "asc",
  578. ]);
  579. return $tests ? $tests[0] : null;
  580. }
  581. /**
  582. * @return bool
  583. * @throws Exception
  584. */
  585. public function unassignTester(): bool {
  586. $this->status = self::STATUS_UNASSIGNED;
  587. $this->tester_id = null;
  588. $this->dts_due = null;
  589. $this->dts_assigned = null;
  590. $this->dts_rejected = null;
  591. return $this->commit();
  592. }
  593. /**
  594. * @return bool
  595. */
  596. public function isPass(): bool {
  597. return (int) $this->pass === 1;
  598. }
  599. /**
  600. * @return bool
  601. */
  602. public function isPending(): bool {
  603. return $this->pass === null;
  604. }
  605. /**
  606. * @return bool
  607. */
  608. public function isFail(): bool {
  609. return (int) $this->pass === 0;
  610. }
  611. /**
  612. * @return bool
  613. */
  614. public function isCompleted(): bool {
  615. return $this->getStatus() === self::STATUS_COMPLETED;
  616. }
  617. public function isDone(): bool {
  618. return in_array($this->getStatus(), [self::STATUS_CANCELLED, self::STATUS_COMPLETED]);
  619. }
  620. /**
  621. * @return bool
  622. */
  623. public function isPendingVerification(): bool {
  624. return $this->getStatus() === self::STATUS_PENDING_VERIFICATION;
  625. }
  626. public function getPDFPath(): string {
  627. $directory = $this->getDirectory();
  628. return sprintf("%s/pdf.pdf", $directory);
  629. }
  630. /**
  631. * @return bool
  632. */
  633. public function hasPDF(): bool {
  634. return file_exists($this->getPDFPath());
  635. }
  636. /**
  637. * @return string
  638. */
  639. public function getPDFUrl(): string {
  640. return "/account/tests/{$this->id}/files/pdf";
  641. }
  642. public function getTesterInvoicePDFPath(): string {
  643. return sprintf("%s/tester_invoice.pdf", $this->getDirectory());
  644. }
  645. /**
  646. * @return bool
  647. */
  648. public function hasTesterInvoicePDF(): bool {
  649. return file_exists($this->getTesterInvoicePDFPath());
  650. }
  651. public function getTravelCostsPhotoPath(): string {
  652. return sprintf("%s/travel_costs.jpg", $this->getDirectory());
  653. }
  654. public function hasTravelCostsPhoto(): bool {
  655. return file_exists($this->getTravelCostsPhotoPath());
  656. }
  657. /**
  658. * @return bool
  659. * @throws Exception
  660. */
  661. public function markTesterInvoicePaid(): bool {
  662. if($this->getTesterInvoiceStatus() === self::STATUS_TESTER_INVOICE_PENDING) {
  663. $this->status_tester_invoice = self::STATUS_TESTER_INVOICE_PAID;
  664. $this->dts_tester_invoice_paid = Util::getDateTime();
  665. return $this->commit();
  666. }
  667. return false;
  668. }
  669. /**
  670. * @return bool
  671. * @throws Exception
  672. */
  673. public function rejectTesterInvoice(): bool {
  674. if($this->getTesterInvoiceStatus() === self::STATUS_TESTER_INVOICE_PENDING) {
  675. $this->status_tester_invoice = self::STATUS_TESTER_INVOICE_NONE;
  676. $this->dts_tester_invoice_generated = null;
  677. if($this->hasTesterInvoicePDF()) {
  678. unlink($this->getTesterInvoicePDFPath());
  679. }
  680. if($this->hasTravelCostsPhoto()) {
  681. unlink($this->getTravelCostsPhotoPath());
  682. }
  683. return $this->commit();
  684. }
  685. return false;
  686. }
  687. /**
  688. * @return string
  689. * @throws Exception
  690. */
  691. public function getTesterInvoiceReference(): string {
  692. $location = $this->getLocation();
  693. $tester = $this->getTester();
  694. return
  695. "T" . str_pad($this->id, 3, "0", STR_PAD_LEFT) .
  696. "/L" . str_pad($location->id, 3, "0", STR_PAD_LEFT) .
  697. "/U" . str_pad($tester->id, 3, "0", STR_PAD_LEFT);
  698. }
  699. /**
  700. * @return float
  701. * @throws Exception
  702. */
  703. public function getTestFee(): float {
  704. return $this->test_fee !== null ? (float) $this->test_fee : (float) $this->getProject()->default_tester_fee;
  705. }
  706. public function getTravelCosts(): float {
  707. return (float) $this->test_travel_cost;
  708. }
  709. /**
  710. * @return float
  711. * @throws Exception
  712. */
  713. public function getInvoiceTotal(): float {
  714. $template = $this->getProject()->getTemplate();
  715. $values = $this->getValues(true);
  716. // Base cost
  717. $fee = $this->getTestFee();
  718. $travel_cost = $this->getTravelCosts();
  719. $invoice_total = $fee + $travel_cost;
  720. // Additional tester invoice fields
  721. $tester_invoice_fields = $template->getTesterInvoiceFields();
  722. foreach($tester_invoice_fields as $field) {
  723. $invoice_total += (float) ($values[$field->name] ?? 0);
  724. }
  725. return $invoice_total;
  726. }
  727. public function isVoid(): bool {
  728. return (bool) $this->void;
  729. }
  730. public function isPrimaryVoid(): bool {
  731. return (bool) $this->void_primary;
  732. }
  733. public function getStatus(): int {
  734. return $this->status;
  735. }
  736. public function getTesterId(): int {
  737. return $this->tester_id;
  738. }
  739. /**
  740. * @return bool Whether the tester has accepted the test
  741. */
  742. public function isConfirmed(): bool {
  743. return $this->getStatus() === self::STATUS_CONFIRMED;
  744. }
  745. public function hasStarted(): bool {
  746. return $this->getStatus() === self::STATUS_STARTED;
  747. }
  748. public function isAssigned(): bool {
  749. return $this->getStatus() === self::STATUS_ASSIGNED;
  750. }
  751. /**
  752. * @return array
  753. * @throws Exception
  754. */
  755. public function getFieldsForVerifyForm(): array {
  756. $json = json_decode($this->getProject()->getTemplate()->getJSON());
  757. return array_merge($json->beforeTest, [(object) ["type" => "hr"]], $json->duringTest);
  758. }
  759. public function getTesterInvoiceStatus(): int {
  760. return $this->status_tester_invoice;
  761. }
  762. public function isCancelled(): bool {
  763. return $this->getStatus() === self::STATUS_CANCELLED;
  764. }
  765. public function hasDueDateTime(): bool {
  766. return $this->dts_due !== null;
  767. }
  768. public function getTimeDue(): int {
  769. if(!$this->dts_due) {
  770. return 0;
  771. }
  772. return $this->getDateTimeDue()->getTimestamp();
  773. }
  774. public function hasNotStarted(): bool {
  775. return $this->status < self::STATUS_STARTED;
  776. }
  777. public function isOverdue(): bool {
  778. return time() > $this->getTimeDue();
  779. }
  780. public function getDateTimeDue(): ?CarbonImmutable {
  781. return Util::getDateTimeFromUtcString($this->dts_due);
  782. }
  783. public function getDateTimeStart(): ?CarbonImmutable {
  784. return Util::getDateTimeFromUtcString($this->dts_start);
  785. }
  786. public function getDateTimeEnd(): ?CarbonImmutable {
  787. return Util::getDateTimeFromUtcString($this->dts_end);
  788. }
  789. public function getVerifierNotesHtml(): string {
  790. return nl2br(htmlspecialchars($this->verifier_notes));
  791. }
  792. /**
  793. * @return float
  794. * @throws Exception
  795. */
  796. public function getTesterInvoiceCosts(): float {
  797. return $this->getProject()->getTemplate()->getTesterInvoiceCosts($this->getValues(true));
  798. }
  799. public function getDateTimeRejected(): ?CarbonImmutable {
  800. if(!$this->dts_rejected) {
  801. return null;
  802. }
  803. return CarbonImmutable::parse($this->dts_rejected, "UTC");
  804. }
  805. public function renderTestStatus(User $user): void {
  806. ?>
  807. <a href="/account/tests/<?=$this->id?>">
  808. <?php
  809. if($this->isPass()) {
  810. ?>
  811. <i class="fa fa-fw fa-check-circle text-success"></i> Passed on <?=$user->formatDate($this->getDateTimeStart())?>
  812. <?php
  813. }
  814. elseif($this->isVoid()) {
  815. ?>
  816. <i class="fa fa-fw fa-minus-circle text-secondary"></i> Void on <?=$user->formatDate($this->getDateTimeStart())?>
  817. <?php
  818. }
  819. elseif($this->isFail()) {
  820. ?>
  821. <i class="fa fa-fw fa-times-circle text-danger"></i> Failed on <?=$user->formatDate($this->getDateTimeStart())?>
  822. <?php
  823. }
  824. else {
  825. ?>
  826. <i class="fa fa-fw fa-question-circle text-warning"></i> Result Pending (Test <?=htmlspecialchars($this->getStatusText())?>)
  827. <?php
  828. }
  829. ?>
  830. </a>
  831. <?php
  832. }
  833. /**
  834. * @return string
  835. * @throws Exception
  836. */
  837. public function getCustomerFee(): string {
  838. $project = $this->getProject();
  839. if($this->customer_fee) {
  840. $fee = $this->customer_fee;
  841. }
  842. elseif($this->retest) {
  843. $fee = $project->getDefaultRetestFee();
  844. }
  845. else {
  846. $fee = $project->default_customer_fee;
  847. }
  848. return $fee;
  849. }
  850. }