Product.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace App;
  3. use App\Traits\DateTimeTrait;
  4. use App\Traits\SoftDeleteTrait;
  5. use Exception;
  6. /**
  7. * Class Product
  8. * @property int $id
  9. * @property int $supplier_id
  10. * @property string $name
  11. * @property string $sku
  12. * @property int $type
  13. * @property string $price
  14. * @property string $url
  15. */
  16. class Product extends Model implements \JsonSerializable {
  17. protected static $table = "product";
  18. protected static $idField = "id";
  19. protected static $fillableFields = [
  20. "supplier_id",
  21. "name", "type", "sku", "price", "url",
  22. "dts_created", "dts_updated", "dts_deleted"
  23. ];
  24. use DateTimeTrait;
  25. use SoftDeleteTrait;
  26. public const TYPE_MACHINE = 1;
  27. public const TYPE_SPARE_PART = 2;
  28. public const TYPE_CONSUMABLE = 3;
  29. public const TYPE_DELIVERY_CHARGE = 4;
  30. // Static methods
  31. public static function getTypeOptions(): array {
  32. return [
  33. self::TYPE_MACHINE => __("Machine"),
  34. self::TYPE_SPARE_PART => __("Spare Part"),
  35. self::TYPE_CONSUMABLE => __("Consumable"),
  36. self::TYPE_DELIVERY_CHARGE => __("Delivery Charge"),
  37. ];
  38. }
  39. // Object methods
  40. /**
  41. * @return Supplier
  42. * @throws Exception
  43. */
  44. public function getSupplier(): Supplier {
  45. return Supplier::get($this->supplier_id);
  46. }
  47. public function getSlug(): string {
  48. return Util::slug("$this->name $this->id");
  49. }
  50. public function getUrl(): string {
  51. return sprintf("/products/%s", $this->getSlug());
  52. }
  53. public function getWebsiteUrl(): ?string {
  54. return $this->url;
  55. }
  56. public function getDisplayType(): string {
  57. return self::getTypeOptions()[$this->type] ?? "";
  58. }
  59. public function getDisplayPrice(): string {
  60. return number_format($this->price, 2);
  61. }
  62. public function jsonSerialize(): array {
  63. return [
  64. "id" => (int) $this->id,
  65. "supplierId" => (int) $this->supplier_id,
  66. "name" => $this->name,
  67. "sku" => $this->sku,
  68. "type" => (int) $this->type,
  69. "price" => $this->price,
  70. ];
  71. }
  72. public function getBrochurePath(): string {
  73. return $_ENV["DIR_ROOT"] . "/files/product/" . $this->id . ".pdf";
  74. }
  75. public function hasBrochure(): bool {
  76. return file_exists($this->getBrochurePath());
  77. }
  78. public function deleteBrochure(): bool {
  79. return !$this->hasBrochure() || unlink($this->getBrochurePath());
  80. }
  81. }