AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. <?php
  2. namespace App\Commerce;
  3. use App\Commerce\Payments\PaymentStatus;
  4. use App\Commerce\Shipping\ShippingProvider;
  5. use App\Enums\OrderStatus;
  6. use App\Mail\OrderConfirmation;
  7. use App\Models\BundleItem;
  8. use App\Models\DiscountCode;
  9. use App\Models\Order;
  10. use App\Models\Product;
  11. use App\Models\ProductVariant;
  12. use App\Models\Store;
  13. use App\Storefront\StorefrontText;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Mail;
  16. use Illuminate\Support\Str;
  17. use Illuminate\Validation\ValidationException;
  18. /**
  19. * Turns a cart into an order, and an order into a paid order.
  20. */
  21. class Checkout
  22. {
  23. public function __construct(private readonly ShippingProvider $shipping) {}
  24. /** Stripe does not accept payments below RM 2.00. */
  25. public const int MINIMUM_TOTAL = 200;
  26. /** The first order number of every store. */
  27. private const int FIRST_NUMBER = 1001;
  28. /**
  29. * Save the cart as an order that is waiting for payment.
  30. * The order keeps its own copy of each product's name and price.
  31. *
  32. * @param array{name: string, email: string, phone: string, line1: string, line2?: string|null, city: string, postcode: string, state: string} $details
  33. *
  34. * @throws ValidationException When the cart is empty or the total is too small.
  35. */
  36. public function placeOrder(Store $store, Cart $cart, array $details): Order
  37. {
  38. $lines = $cart->lines();
  39. $subtotal = (int) $lines->sum('line_total');
  40. if ($lines->isEmpty()) {
  41. throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'cart_empty')]);
  42. }
  43. if ($subtotal < self::MINIMUM_TOTAL) {
  44. throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'minimum_total')]);
  45. }
  46. $language = $store->language->value;
  47. // A bundle and its items bought separately draw on the same stock, so check them together.
  48. if (! $this->enoughStock($lines)) {
  49. throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'not_enough_stock')]);
  50. }
  51. // The code, or an automatic discount, whichever saves more. Only one applies.
  52. $applied = $cart->applied($lines);
  53. // The code stopped working since the shopper last saw the cart: stop, so the total never surprises them.
  54. if ($cart->discountWasRemoved()) {
  55. throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'discount_changed')]);
  56. }
  57. $discount = $applied !== null ? $applied->amount : 0;
  58. $discountCode = $applied?->code?->code;
  59. $discountName = $applied?->offer?->name;
  60. // Free shipping is decided on what the shopper pays for the products, after the discount.
  61. $shipping = $this->shipping->quote($store, $subtotal - $discount, $details['state']);
  62. if ($subtotal - $discount + $shipping < self::MINIMUM_TOTAL) {
  63. throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'discount_total_too_low')]);
  64. }
  65. return DB::transaction(function () use ($store, $lines, $subtotal, $discount, $discountCode, $discountName, $shipping, $details): Order {
  66. // Lock the store row so two orders placed at the same moment cannot get the same number.
  67. Store::query()->whereKey($store->id)->lockForUpdate()->first();
  68. $order = new Order;
  69. $order->store_id = $store->id;
  70. $order->public_id = (string) Str::ulid();
  71. $order->number = max(self::FIRST_NUMBER, (int) $store->orders()->max('number') + 1);
  72. $order->status = OrderStatus::Pending;
  73. $order->customer_name = $details['name'];
  74. $order->customer_email = $details['email'];
  75. $order->customer_phone = $details['phone'];
  76. $order->shipping_address = [
  77. 'line1' => $details['line1'],
  78. 'line2' => $details['line2'] ?? null,
  79. 'city' => $details['city'],
  80. 'postcode' => $details['postcode'],
  81. 'state' => $details['state'],
  82. 'country' => 'MY',
  83. ];
  84. $order->subtotal = $subtotal;
  85. $order->discount_code = $discountCode;
  86. $order->discount_name = $discountName;
  87. $order->discount_total = $discount;
  88. $order->shipping_total = $shipping;
  89. $order->total = $subtotal - $discount + $shipping;
  90. $order->currency = 'MYR';
  91. $order->save();
  92. foreach ($lines as $line) {
  93. $variantName = $line['variant']?->name();
  94. $product = $line['product'];
  95. $order->items()->create([
  96. 'store_id' => $store->id,
  97. 'product_id' => $line['product']->id,
  98. 'variant_id' => $line['variant']?->id,
  99. // "Sambal Hijau (500g / Pedas)", so every place that shows the order shows the choice too.
  100. 'name' => $line['product']->name.($variantName !== null ? " ({$variantName})" : ''),
  101. 'variant_name' => $variantName,
  102. 'bundle_contents' => $product->isBundle()
  103. ? $product->bundleItems->map(fn (BundleItem $item) => [
  104. 'product_id' => $item->product_id,
  105. 'variant_id' => $item->variant_id,
  106. 'quantity' => $item->quantity,
  107. 'label' => $item->label(),
  108. ])->values()->all()
  109. : null,
  110. 'unit_price' => $line['unit_price'],
  111. 'quantity' => $line['quantity'],
  112. 'line_total' => $line['line_total'],
  113. ]);
  114. }
  115. return $order->load('items');
  116. });
  117. }
  118. /**
  119. * Record that an order was paid: mark it, lower the stock, and email the shopper.
  120. *
  121. * Safe to call more than once for the same order (the return page and the webhook may both call it).
  122. * Only the first call does anything. Returns true when this call marked the order paid.
  123. */
  124. public function markPaid(Order $order, PaymentStatus $payment): bool
  125. {
  126. if (! $payment->paid || $payment->checkoutId !== $order->payment_checkout_id) {
  127. return false;
  128. }
  129. // The provider must have collected the full order total.
  130. if ($payment->amount !== null && $payment->amount !== $order->total) {
  131. report(new \RuntimeException("Order {$order->id}: paid amount {$payment->amount} does not match total {$order->total}."));
  132. return false;
  133. }
  134. $marked = DB::transaction(function () use ($order, $payment): bool {
  135. $locked = Order::query()->whereKey($order->id)->lockForUpdate()->firstOrFail();
  136. if ($locked->isPaid()) {
  137. return false;
  138. }
  139. $locked->status = OrderStatus::Paid;
  140. $locked->payment_reference = $payment->reference;
  141. $locked->paid_at = now();
  142. $locked->save();
  143. foreach ($locked->items as $item) {
  144. if ($item->bundle_contents !== null) {
  145. // A bundle has no stock of its own: lower the stock of what was inside it.
  146. foreach ($item->bundle_contents as $part) {
  147. $this->lowerStock($part['product_id'], $part['variant_id'], $part['quantity'] * $item->quantity);
  148. }
  149. continue;
  150. }
  151. $this->lowerStock($item->product_id, $item->variant_id, $item->quantity);
  152. }
  153. BundleStock::refresh($locked->store_id);
  154. // A code counts as used only once the order is paid.
  155. if ($locked->discount_code !== null) {
  156. DiscountCode::query()
  157. ->where('store_id', $locked->store_id)
  158. ->where('code', $locked->discount_code)
  159. ->increment('times_used');
  160. }
  161. return true;
  162. });
  163. $order->refresh();
  164. if ($marked) {
  165. Mail::to($order->customer_email)->send(new OrderConfirmation($order));
  166. }
  167. return $marked;
  168. }
  169. /**
  170. * Take stock off a product or one of its variants. Either may have been deleted since the order was placed.
  171. * Never below zero, even if stock was changed by hand in the meantime.
  172. */
  173. private function lowerStock(?int $productId, ?int $variantId, int $quantity): void
  174. {
  175. $product = $productId !== null ? Product::query()->whereKey($productId)->lockForUpdate()->first() : null;
  176. if ($variantId !== null) {
  177. $variant = ProductVariant::query()->whereKey($variantId)->lockForUpdate()->first();
  178. if ($variant !== null) {
  179. $variant->stock = max(0, $variant->stock - $quantity);
  180. $variant->save();
  181. $product?->syncFromVariants();
  182. }
  183. return;
  184. }
  185. if ($product !== null) {
  186. $product->stock = max(0, $product->stock - $quantity);
  187. $product->save();
  188. }
  189. }
  190. /**
  191. * Whether there is stock for every line at once, counting what bundles hold.
  192. * A bundle of 2 sambal plus 3 sambal bought on their own needs 5 sambal.
  193. *
  194. * @param iterable<array{product: Product, variant: ProductVariant|null, quantity: int}> $lines
  195. */
  196. private function enoughStock(iterable $lines): bool
  197. {
  198. $needed = [];
  199. $left = [];
  200. $count = function (Product $product, ?ProductVariant $variant, int $quantity) use (&$needed, &$left): void {
  201. $key = $variant !== null ? 'v'.$variant->id : 'p'.$product->id;
  202. $needed[$key] = ($needed[$key] ?? 0) + $quantity;
  203. $left[$key] = $variant !== null ? $variant->stock : $product->stock;
  204. };
  205. foreach ($lines as $line) {
  206. if ($line['product']->isBundle()) {
  207. foreach ($line['product']->bundleItems as $item) {
  208. $count($item->product, $item->variant, $item->quantity * $line['quantity']);
  209. }
  210. } else {
  211. $count($line['product'], $line['variant'], $line['quantity']);
  212. }
  213. }
  214. foreach ($needed as $key => $quantity) {
  215. if ($quantity > $left[$key]) {
  216. return false;
  217. }
  218. }
  219. return true;
  220. }
  221. }