| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220 |
- <?php
-
- namespace App\Models;
-
- use App\Enums\ProductStatus;
- use Carbon\CarbonInterface;
- use Database\Factories\ProductFactory;
- use Illuminate\Database\Eloquent\Attributes\Fillable;
- use Illuminate\Database\Eloquent\Builder;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Database\Eloquent\Factories\HasFactory;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
- use Illuminate\Database\Eloquent\Relations\HasMany;
- use Illuminate\Support\Str;
-
- /**
- * Something a store sells. Prices are saved in sen (1 ringgit = 100 sen).
- *
- * @property int $id
- * @property int $store_id
- * @property string $name
- * @property string $slug
- * @property string|null $description
- * @property list<array{title: string, body: string}>|null $details Folding sections on the product page, such as "How to use"
- * @property list<array{name: string, values: list<string>}>|null $options Up to 2 options. Null for a simple product.
- * @property bool $is_bundle True for a bundle: its stock comes from the products inside it.
- * @property int $price
- * @property int|null $compare_at_price
- * @property int $stock
- * @property ProductStatus $status
- * @property CarbonInterface|null $created_at
- * @property CarbonInterface|null $updated_at
- * @property-read Store $store
- * @property-read Collection<int, ProductImage> $images
- * @property-read Collection<int, ProductVariant> $variants
- * @property-read Collection<int, BundleItem> $bundleItems
- */
- #[Fillable(['name', 'description', 'details', 'price', 'compare_at_price', 'stock', 'status'])]
- class Product extends Model
- {
- /** @use HasFactory<ProductFactory> */
- use HasFactory;
-
- /** The most folding sections one product may have. */
- public const int MAX_DETAILS = 5;
-
- /** What the storefront needs loaded to show a product. */
- public const array STOREFRONT_RELATIONS = ['images', 'variants', 'bundleItems.product', 'bundleItems.variant'];
-
- protected static function booted(): void
- {
- static::creating(function (Product $product): void {
- $product->slug = $product->uniqueSlug($product->name);
- });
-
- // The database removes the image rows by itself. The files need removing here.
- static::deleting(function (Product $product): void {
- $product->images->each->delete();
- });
- }
-
- /**
- * A web-address name made from the product name, unique within its store.
- */
- private function uniqueSlug(string $name): string
- {
- $base = Str::slug($name) ?: 'product';
- $slug = $base;
- $suffix = 2;
-
- while (static::query()->where('store_id', $this->store_id)->where('slug', $slug)->exists()) {
- $slug = $base.'-'.$suffix++;
- }
-
- return $slug;
- }
-
- /**
- * @return BelongsTo<Store, $this>
- */
- public function store(): BelongsTo
- {
- return $this->belongsTo(Store::class);
- }
-
- /**
- * @return HasMany<ProductImage, $this>
- */
- public function images(): HasMany
- {
- return $this->hasMany(ProductImage::class)->orderBy('position')->orderBy('id');
- }
-
- /**
- * @return HasMany<ProductVariant, $this>
- */
- public function variants(): HasMany
- {
- return $this->hasMany(ProductVariant::class)->orderBy('position')->orderBy('id');
- }
-
- /**
- * For a bundle: what is inside it.
- *
- * @return HasMany<BundleItem, $this>
- */
- public function bundleItems(): HasMany
- {
- return $this->hasMany(BundleItem::class, 'bundle_id')->orderBy('position')->orderBy('id');
- }
-
- /**
- * The bundles this product (or one of its variants) is inside.
- *
- * @return HasMany<BundleItem, $this>
- */
- public function usedInBundles(): HasMany
- {
- return $this->hasMany(BundleItem::class, 'product_id');
- }
-
- public function isBundle(): bool
- {
- return $this->is_bundle;
- }
-
- /**
- * True when the product comes in options, such as sizes. Then price and stock live on each variant.
- */
- public function hasVariants(): bool
- {
- return ! empty($this->options);
- }
-
- /**
- * For a product with options: the product's own price and stock follow its variants
- * (the lowest price, and the stock of all variants together), so lists and cards stay right.
- */
- public function syncFromVariants(): void
- {
- $variants = $this->variants()->get();
-
- if (! $this->hasVariants() || $variants->isEmpty()) {
- return;
- }
-
- $cheapest = $variants->sortBy('price')->first();
-
- $this->price = (int) $cheapest->price;
- $this->compare_at_price = $cheapest->compare_at_price;
- $this->stock = (int) $variants->sum('stock');
- $this->save();
- }
-
- /**
- * Products shoppers may see.
- *
- * @param Builder<Product> $query
- */
- public function scopeActive(Builder $query): void
- {
- $query->where('status', ProductStatus::Active);
- }
-
- /**
- * What the storefront is allowed to see. Prices are in ringgit here.
- *
- * @return array<string, mixed>
- */
- public function toStorefront(): array
- {
- $images = $this->images->map(fn (ProductImage $image) => $image->url())->all();
-
- return [
- 'id' => $this->id,
- 'name' => $this->name,
- 'slug' => $this->slug,
- 'description' => $this->description,
- 'details' => $this->details ?? [],
- 'price' => $this->price / 100,
- 'compare_at_price' => $this->compare_at_price !== null ? $this->compare_at_price / 100 : null,
- 'in_stock' => $this->stock > 0,
- 'stock_left' => $this->stock,
- 'image' => $images[0] ?? null,
- 'images' => $images,
- 'options' => $this->hasVariants() ? $this->options : [],
- 'variants' => $this->hasVariants()
- ? $this->variants->map(fn (ProductVariant $variant) => $variant->toStorefront())->all()
- : [],
- // True when variants cost different amounts, so lists show "From RM X".
- 'price_varies' => $this->hasVariants() && $this->variants->pluck('price')->unique()->count() > 1,
- // For a bundle: what is inside, such as [{"name": "Sambal Hijau (250g)", "quantity": 2}].
- 'bundle' => $this->isBundle()
- ? $this->bundleItems->map(fn (BundleItem $item) => [
- 'name' => $item->name(),
- 'quantity' => $item->quantity,
- // A link to the item's own page, when shoppers can see it.
- 'slug' => $item->product->status === ProductStatus::Active ? $item->product->slug : null,
- ])->all()
- : [],
- ];
- }
-
- /**
- * @return array<string, string>
- */
- protected function casts(): array
- {
- return [
- 'status' => ProductStatus::class,
- 'price' => 'integer',
- 'compare_at_price' => 'integer',
- 'stock' => 'integer',
- 'options' => 'array',
- 'details' => 'array',
- 'is_bundle' => 'boolean',
- ];
- }
- }
|