project.php 11 KB

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