project.php 12 KB

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