AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Product.php 6.7KB

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