AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Product.php 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. <?php
  2. namespace App\Models;
  3. use App\Enums\ProductStatus;
  4. use Carbon\CarbonInterface;
  5. use Database\Factories\ProductFactory;
  6. use Illuminate\Database\Eloquent\Attributes\Fillable;
  7. use Illuminate\Database\Eloquent\Builder;
  8. use Illuminate\Database\Eloquent\Collection;
  9. use Illuminate\Database\Eloquent\Factories\HasFactory;
  10. use Illuminate\Database\Eloquent\Model;
  11. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  12. use Illuminate\Database\Eloquent\Relations\HasMany;
  13. use Illuminate\Support\Str;
  14. /**
  15. * Something a store sells. Prices are saved in sen (1 ringgit = 100 sen).
  16. *
  17. * @property int $id
  18. * @property int $store_id
  19. * @property string $name
  20. * @property string $slug
  21. * @property string|null $description
  22. * @property list<array{title: string, body: string}>|null $details Folding sections on the product page, such as "How to use"
  23. * @property list<array{name: string, values: list<string>}>|null $options Up to 2 options. Null for a simple product.
  24. * @property bool $is_bundle True for a bundle: its stock comes from the products inside it.
  25. * @property int $price
  26. * @property int|null $compare_at_price
  27. * @property int $stock
  28. * @property ProductStatus $status
  29. * @property CarbonInterface|null $created_at
  30. * @property CarbonInterface|null $updated_at
  31. * @property-read Store $store
  32. * @property-read Collection<int, ProductImage> $images
  33. * @property-read Collection<int, ProductVariant> $variants
  34. * @property-read Collection<int, BundleItem> $bundleItems
  35. */
  36. #[Fillable(['name', 'description', 'details', 'price', 'compare_at_price', 'stock', 'status'])]
  37. class Product extends Model
  38. {
  39. /** @use HasFactory<ProductFactory> */
  40. use HasFactory;
  41. /** The most folding sections one product may have. */
  42. public const int MAX_DETAILS = 5;
  43. /** What the storefront needs loaded to show a product. */
  44. public const array STOREFRONT_RELATIONS = ['images', 'variants', 'bundleItems.product', 'bundleItems.variant'];
  45. protected static function booted(): void
  46. {
  47. static::creating(function (Product $product): void {
  48. $product->slug = $product->uniqueSlug($product->name);
  49. });
  50. // The database removes the image rows by itself. The files need removing here.
  51. static::deleting(function (Product $product): void {
  52. $product->images->each->delete();
  53. });
  54. }
  55. /**
  56. * A web-address name made from the product name, unique within its store.
  57. */
  58. private function uniqueSlug(string $name): string
  59. {
  60. $base = Str::slug($name) ?: 'product';
  61. $slug = $base;
  62. $suffix = 2;
  63. while (static::query()->where('store_id', $this->store_id)->where('slug', $slug)->exists()) {
  64. $slug = $base.'-'.$suffix++;
  65. }
  66. return $slug;
  67. }
  68. /**
  69. * @return BelongsTo<Store, $this>
  70. */
  71. public function store(): BelongsTo
  72. {
  73. return $this->belongsTo(Store::class);
  74. }
  75. /**
  76. * @return HasMany<ProductImage, $this>
  77. */
  78. public function images(): HasMany
  79. {
  80. return $this->hasMany(ProductImage::class)->orderBy('position')->orderBy('id');
  81. }
  82. /**
  83. * @return HasMany<ProductVariant, $this>
  84. */
  85. public function variants(): HasMany
  86. {
  87. return $this->hasMany(ProductVariant::class)->orderBy('position')->orderBy('id');
  88. }
  89. /**
  90. * For a bundle: what is inside it.
  91. *
  92. * @return HasMany<BundleItem, $this>
  93. */
  94. public function bundleItems(): HasMany
  95. {
  96. return $this->hasMany(BundleItem::class, 'bundle_id')->orderBy('position')->orderBy('id');
  97. }
  98. /**
  99. * The bundles this product (or one of its variants) is inside.
  100. *
  101. * @return HasMany<BundleItem, $this>
  102. */
  103. public function usedInBundles(): HasMany
  104. {
  105. return $this->hasMany(BundleItem::class, 'product_id');
  106. }
  107. public function isBundle(): bool
  108. {
  109. return $this->is_bundle;
  110. }
  111. /**
  112. * True when the product comes in options, such as sizes. Then price and stock live on each variant.
  113. */
  114. public function hasVariants(): bool
  115. {
  116. return ! empty($this->options);
  117. }
  118. /**
  119. * For a product with options: the product's own price and stock follow its variants
  120. * (the lowest price, and the stock of all variants together), so lists and cards stay right.
  121. */
  122. public function syncFromVariants(): void
  123. {
  124. $variants = $this->variants()->get();
  125. if (! $this->hasVariants() || $variants->isEmpty()) {
  126. return;
  127. }
  128. $cheapest = $variants->sortBy('price')->first();
  129. $this->price = (int) $cheapest->price;
  130. $this->compare_at_price = $cheapest->compare_at_price;
  131. $this->stock = (int) $variants->sum('stock');
  132. $this->save();
  133. }
  134. /**
  135. * Products shoppers may see.
  136. *
  137. * @param Builder<Product> $query
  138. */
  139. public function scopeActive(Builder $query): void
  140. {
  141. $query->where('status', ProductStatus::Active);
  142. }
  143. /**
  144. * What the storefront is allowed to see. Prices are in ringgit here.
  145. *
  146. * @return array<string, mixed>
  147. */
  148. public function toStorefront(): array
  149. {
  150. $images = $this->images->map(fn (ProductImage $image) => $image->url())->all();
  151. return [
  152. 'id' => $this->id,
  153. 'name' => $this->name,
  154. 'slug' => $this->slug,
  155. 'description' => $this->description,
  156. 'details' => $this->details ?? [],
  157. 'price' => $this->price / 100,
  158. 'compare_at_price' => $this->compare_at_price !== null ? $this->compare_at_price / 100 : null,
  159. 'in_stock' => $this->stock > 0,
  160. 'stock_left' => $this->stock,
  161. 'image' => $images[0] ?? null,
  162. 'images' => $images,
  163. 'options' => $this->hasVariants() ? $this->options : [],
  164. 'variants' => $this->hasVariants()
  165. ? $this->variants->map(fn (ProductVariant $variant) => $variant->toStorefront())->all()
  166. : [],
  167. // True when variants cost different amounts, so lists show "From RM X".
  168. 'price_varies' => $this->hasVariants() && $this->variants->pluck('price')->unique()->count() > 1,
  169. // For a bundle: what is inside, such as [{"name": "Sambal Hijau (250g)", "quantity": 2}].
  170. 'bundle' => $this->isBundle()
  171. ? $this->bundleItems->map(fn (BundleItem $item) => [
  172. 'name' => $item->name(),
  173. 'quantity' => $item->quantity,
  174. // A link to the item's own page, when shoppers can see it.
  175. 'slug' => $item->product->status === ProductStatus::Active ? $item->product->slug : null,
  176. ])->all()
  177. : [],
  178. ];
  179. }
  180. /**
  181. * @return array<string, string>
  182. */
  183. protected function casts(): array
  184. {
  185. return [
  186. 'status' => ProductStatus::class,
  187. 'price' => 'integer',
  188. 'compare_at_price' => 'integer',
  189. 'stock' => 'integer',
  190. 'options' => 'array',
  191. 'details' => 'array',
  192. 'is_bundle' => 'boolean',
  193. ];
  194. }
  195. }