| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595 |
- <?php /** @noinspection PhpIncludeInspection */
- use Carbon\CarbonImmutable;
- /**
- * @property int $id
- * @property int $customer_id
- * @property int $template_id
- * @property string $template_keys
- * @property string $name
- * @property int $test_count
- * @property int $min_age
- * @property int $max_age
- * @property float $default_customer_fee
- * @property float $default_tester_fee
- * @property string $time_of_day
- * @property bool $tester_can_claim
- * @property string $template_overrides_json
- * @property string $dts_start
- * @property string $dts_deadline
- * @property string $dts_created
- * @property string $dts_updated
- * @property string $dts_report
- * @property string $dts_finished
- * @property int $user_id_finished
- */
- class Project extends Model {
- public const TOD_ANYTIME = "A";
- public const TOD_DAYTIME = "D";
- public const TOD_NIGHTTIME = "N";
- protected static $table = "project";
- protected static $id_field = "id";
- 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"];
- /**
- * @var Test[] $tests
- */
- protected $tests;
- // Static methods
- public static function getTimeOfDayOptions(): array {
- return [
- self::TOD_ANYTIME => "Anytime",
- self::TOD_DAYTIME => "Daytime",
- self::TOD_NIGHTTIME => "Night",
- ];
- }
- /**
- * @param string $processing_file
- * @param Project[] $projects
- * @throws Exception
- */
- public static function exportCSV(string $processing_file, /** @noinspection PhpUnusedParameterInspection */ array $projects = []): void {
- // Get processing file
- $processing_file_path = ROOT_DIR . "/export_processing/{$processing_file}";
- if(!file_exists($processing_file_path)) throw new Exception("Processing file not found.");
- // Output
- HTTP::setDownloadHeaders("export.csv");
- $handle = fopen("php://output", "wb");
- require $processing_file_path;
- fclose($handle);
- }
- /**
- * @return string[]
- * @throws Exception
- */
- public static function getReportMonths(): array {
- $current_report_month = new DateTime("2018-01-01", new DateTimeZone("UTC"));
- $month_interval = new DateInterval("P1M");
- $report_months = [];
- do {
- $key = $current_report_month->format("Y-m");
- $report_months[$key] = $current_report_month->format("M Y");
- $current_report_month->add($month_interval);
- $time = $current_report_month->format("U");
- if($time > time()) break;
- } while(true);
- return $report_months;
- }
- // Object methods
- /**
- * @return Customer
- * @throws Exception
- */
- public function getCustomer(): Customer {
- return Customer::get($this->customer_id);
- }
- /**
- * @return Test[]
- * @throws Exception
- */
- public function getTests(): array {
- if($this->tests !== null) return $this->tests;
- $nvp = [];
- $nvp["project_id"] = $this->id;
- $nvp["status"] = (new Constraint("MORE_THAN"))->setValues(Test::STATUS_CANCELLED);
- $this->tests = Test::query($nvp);
- return $this->tests;
- }
- /**
- * @return int
- * @throws Exception
- */
- public function getTestCount(): int {
- if(is_null($this->tests)) $this->getTests();
- return count($this->tests);
- }
- /**
- * @return int
- * @throws Exception
- */
- public function getPassCount(): int {
- $count = 0;
- $tests = $this->getTests();
- foreach($tests as $test) {
- if(!$test->isPass()) continue;
- ++$count;
- }
- return $count;
- }
- /**
- * @return int
- * @throws Exception
- */
- public function getFailCount(): int {
- $count = 0;
- $tests = $this->getTests();
- foreach($tests as $test) {
- if(!$test->isFail()) continue;
- ++$count;
- }
- return $count;
- }
- /**
- * @return int
- * @throws Exception
- */
- public function getPendingCount(): int {
- $count = 0;
- $tests = $this->getTests();
- foreach($tests as $test) {
- if(!$test->isPending()) continue;
- ++$count;
- }
- return $count;
- }
- /**
- * @return string
- * @throws Exception
- */
- public function getPassRate(): string {
- $pass_count = $this->getPassCount();
- $fail_count = $this->getFailCount();
- $pass_fail_count = $pass_count + $fail_count;
- if($pass_fail_count === 0) return "0%";
- return (number_format($pass_count / $pass_fail_count, 4) * 100) . "%";
- }
- /**
- * @return Location[]
- * @throws Exception
- */
- public function getLocations(): array {
- $tests = $this->getTests();
- return Location::query(["id" => array_column($tests, "location_id")]);
- }
- /**
- * @return string
- */
- public function getDisplayAgeRange(): string {
- if($this->min_age && $this->max_age) {
- return $this->min_age . " to " . $this->max_age;
- }
- if($this->min_age) {
- return "At least " . $this->min_age;
- }
- if($this->max_age) {
- return "Up to " . $this->max_age;
- }
- return "No age restriction";
- }
- /**
- * @return string
- */
- public function getNameHtml(): string {
- if($this->isAnytime()) {
- return htmlspecialchars($this->name);
- }
- $icon = $this->getTimeOfDayIcon();
- $time_of_day = $this->getTimeOfDayText();
- return htmlspecialchars($this->name) . " <i class=\"fa fa-fw fa-{$icon}\" data-toggle=\"tooltip\" title=\"{$time_of_day}\"></i>";
- }
- /**
- * @return array
- * @throws Exception
- */
- public function getCompletedTests(): array {
- $tests = $this->getTests();
- return array_filter($tests, static function($test) {
- return (int) $test->status === Test::STATUS_COMPLETED;
- });
- }
- /**
- * @return int
- * @throws Exception
- */
- public function getCompletedTestCount(): int {
- return count($this->getCompletedTests());
- }
- /**
- * @return float
- * @throws Exception
- */
- public function getCompletedPercentage(): float {
- return floor((count($this->getCompletedTests()) / $this->test_count) * 100);
- }
- /**
- * @return Template
- * @throws Exception
- */
- public function getTemplate(): Template {
- return Template::get($this->template_id);
- }
- /**
- * @return array
- */
- public function getTemplateOverrides(): array {
- return json_decode($this->template_overrides_json) ?: [];
- }
- /**
- * @return string
- */
- public function getTimeOfDayText(): string {
- switch($this->time_of_day) {
- default:
- case self::TOD_ANYTIME: return "Any";
- case self::TOD_DAYTIME: return "Day";
- case self::TOD_NIGHTTIME: return "Night";
- }
- }
- /**
- * @return string
- */
- public function getTimeOfDayIcon(): string {
- switch($this->time_of_day) {
- default:
- case self::TOD_ANYTIME: return "adjust";
- case self::TOD_DAYTIME: return "sun";
- case self::TOD_NIGHTTIME: return "moon";
- }
- }
- /**
- * @return string
- */
- public function getURL(): string {
- return "/account/projects/{$this->id}";
- }
- /**
- * @return string
- */
- public function getDirectory(): string {
- $directory = ROOT_DIR . "/files/projects/" . $this->id;
- if(!file_exists($directory) && !mkdir($directory, 0777, true) && !is_dir($directory)) {
- throw new RuntimeException(sprintf('Directory "%s" was not created', $directory));
- }
- return $directory;
- }
- /**
- * @return bool
- */
- public function hasInvoicePDF(): bool {
- $directory = $this->getDirectory();
- return file_exists($directory . "/invoice.pdf");
- }
- /**
- * @return bool
- */
- public function isAnytime(): bool {
- return $this->time_of_day === self::TOD_ANYTIME;
- }
- /**
- * @return bool
- */
- public function isDaytime(): bool {
- return $this->time_of_day === self::TOD_DAYTIME;
- }
- /**
- * @return bool
- */
- public function isNighttime(): bool {
- return $this->time_of_day === self::TOD_NIGHTTIME;
- }
- /**
- * @return bool
- */
- public function isPastDeadline(): bool {
- $deadline_unix = Util::getUnixTimeFromUTC($this->dts_deadline);
- return time() > $deadline_unix;
- }
- /**
- * @return bool
- */
- public function isFinished(): bool {
- return $this->dts_finished !== null;
- }
- /**
- * @return bool
- * @throws Exception
- */
- public function markFinished(): bool {
- if(!Core::$user) throw new Exception("Trying to mark project as finished while not logged in.");
- if(!Core::$user->isAdmin()) throw new Exception("Trying to mark project as finished with non-admin account.");
- $this->dts_finished = Util::getUTCDateTime();
- $this->user_id_finished = Core::$user->id;
- return $this->commit();
- }
- /**
- * @return bool
- * @throws Exception
- */
- public function markUnfinished(): bool {
- $this->dts_finished = null;
- $this->user_id_finished = null;
- return $this->commit();
- }
- /**
- * @return string
- * @throws Exception
- */
- public function getDisplayReportMonth(): string {
- $report_month = "-";
- if($this->dts_report) {
- $dt_report = new DateTime($this->dts_report . " UTC");
- $report_month = $dt_report->format("M Y");
- }
- return $report_month;
- }
- /**
- * @return array
- * @throws Exception
- */
- public function getDataTableRow(): array {
- $tests = $this->getTests();
- return [
- "id" => (int) $this->id,
- "rowId" => "project-row-{$this->id}",
- "name" => $this->name,
- "testCount" => count($tests),
- "timeOfDay" => $this->getTimeOfDayText(),
- "unixStart" => Util::getUnixTimeFromUTC($this->dts_start),
- "unixEnd" => Util::getUnixTimeFromUTC($this->dts_deadline),
- "reportMonth" => $this->getDisplayReportMonth(),
- "unixReport" => $this->dts_report ? Util::getUnixTimeFromUTC($this->dts_report) : 0,
- ];
- }
- /**
- * @return string
- * @throws Exception
- */
- public function getTestResultsUrl(): string {
- $customer = $this->getCustomer();
- $customer_slug = Util::slugWithId($customer->name, $customer->id);
- $project_slug = Util::slugWithId($this->name, $this->id);
- return "/account/test-results/{$customer_slug}/{$project_slug}";
- }
- /**
- * @return Invoice
- * @throws Exception
- */
- public function getCustomerInvoice(): Invoice {
- $invoice = new Invoice;
- $invoice->setReference($this->getInvoiceReference());
- $test_line_items = $this->getTestInvoiceLineItems();
- $field_line_items = $this->getFieldInvoiceLineItems();
- $invoice->addLineItems($test_line_items);
- $invoice->addLineItems($field_line_items);
- return $invoice;
- }
- /**
- * @return string
- * @throws Exception
- */
- private function getInvoiceReference(): string {
- $customer = $this->getCustomer();
- return
- "P" . str_pad($this->id, 3, "0", STR_PAD_LEFT) .
- "/C" . str_pad($customer->id, 3, "0", STR_PAD_LEFT);
- }
- /**
- * @return InvoiceLineItem[]
- * @throws Exception
- */
- private function getTestInvoiceLineItems(): array {
- /**
- * @var InvoiceLineItem[] $items
- */
- $template = $this->getTemplate();
- $default_customer_fee = $this->default_customer_fee;
- $tests = $this->getTests();
- $items = [];
- foreach($tests as $test) {
- $fee = $test->customer_fee ?? $default_customer_fee;
- $key = "fee_{$fee}";
- $item = $items[$key] ?? null;
- if(!$item) {
- $item = new InvoiceLineItem(__("%s Testing", $template->name));
- $item->setPrice($fee);
- }
- $item->incrementQuantity();
- $items[$key] = $item;
- }
- return array_values($items);
- }
- /**
- * @return InvoiceLineItem[]
- * @throws Exception
- */
- private function getFieldInvoiceLineItems(): array {
- $template = $this->getTemplate();
- $invoice_fields = $template->getCustomerInvoiceFields();
- $tests = $this->getTests();
- $items = [];
- foreach($tests as $test) {
- $values = $test->getValues(true);
- foreach($invoice_fields as $field) {
- $item = $items[$field->name] ?? (new InvoiceLineItem($field->label));
- $item->addPrice((float) ($values[$field->name] ?? 0));
- $items[$field->name] = $item;
- }
- }
- return $items;
- }
- public function setTemplateKeys($keys): void {
- if(!is_array($keys)) $keys = [];
- $this->template_keys = json_encode($keys);
- }
- /**
- * @return string[]
- */
- public function getTemplateKeys(): array {
- $keys = json_decode($this->template_keys);
- return $keys ?: [];
- }
- public function getDateTimeStart(): CarbonImmutable {
- return CarbonImmutable::parse($this->dts_start, "UTC");
- }
- public function getDateTimeDeadline(): CarbonImmutable {
- return CarbonImmutable::parse($this->dts_deadline, "UTC");
- }
- public function getDateTimeReport(): ?CarbonImmutable {
- if(!$this->dts_report) return null;
- return CarbonImmutable::parse($this->dts_report, "UTC");
- }
- /**
- * @param int $location_id
- * @return Test
- * @throws Exception
- */
- public function createTestForLocationId(int $location_id): Test {
- $test = new Test;
- $test->project_id = $this->id;
- $test->location_id = $location_id;
- $test->status = Test::STATUS_UNASSIGNED;
- $test->dts_created = Util::getDateTime();
- $success = $test->commit();
- if(!$success) throw new Exception("Test cannot be created, please try again later.");
- return $test;
- }
- /**
- * @param int $location_id
- * @return Test|null
- * @throws Exception
- */
- public function getActiveTestForLocationId(int $location_id): ?Test {
- return Test::queryOne([
- "project_id" => $this->id,
- "location_id" => $location_id,
- "status" => (new Constraint("MORE_THAN"))->setValues(Test::STATUS_CANCELLED)
- ]);
- }
- public function getTimeDeadline(): int {
- if($this->dts_deadline === null) {
- return 0;
- }
- return $this->getDateTimeDeadline()->getTimestamp();
- }
- public function isOverdue(): bool {
- return time() > $this->getTimeDeadline();
- }
- }
|