AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Checkout.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. $applied = $cart->discount($subtotal);
  52. // The code stopped working since the shopper last saw the cart: stop, so the total never surprises them.
  53. if ($cart->discountWasRemoved()) {
  54. throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'discount_changed')]);
  55. }
  56. // A code that still needs a bigger cart is worth nothing; the cart already showed that.
  57. $usable = $applied !== null && $applied->problem === null ? $applied : null;
  58. $discount = $usable !== null ? $usable->amount : 0;
  59. $discountCode = $usable !== null && $discount > 0 ? $usable->code->code : null;
  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, $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_total = $discount;
  87. $order->shipping_total = $shipping;
  88. $order->total = $subtotal - $discount + $shipping;
  89. $order->currency = 'MYR';
  90. $order->save();
  91. foreach ($lines as $line) {
  92. $variantName = $line['variant']?->name();
  93. $product = $line['product'];
  94. $order->items()->create([
  95. 'store_id' => $store->id,
  96. 'product_id' => $line['product']->id,
  97. 'variant_id' => $line['variant']?->id,
  98. // "Sambal Hijau (500g / Pedas)", so every place that shows the order shows the choice too.
  99. 'name' => $line['product']->name.($variantName !== null ? " ({$variantName})" : ''),
  100. 'variant_name' => $variantName,
  101. 'bundle_contents' => $product->isBundle()
  102. ? $product->bundleItems->map(fn (BundleItem $item) => [
  103. 'product_id' => $item->product_id,
  104. 'variant_id' => $item->variant_id,
  105. 'quantity' => $item->quantity,
  106. 'label' => $item->label(),
  107. ])->values()->all()
  108. : null,
  109. 'unit_price' => $line['unit_price'],
  110. 'quantity' => $line['quantity'],
  111. 'line_total' => $line['line_total'],
  112. ]);
  113. }
  114. return $order->load('items');
  115. });
  116. }
  117. /**
  118. * Record that an order was paid: mark it, lower the stock, and email the shopper.
  119. *
  120. * Safe to call more than once for the same order (the return page and the webhook may both call it).
  121. * Only the first call does anything. Returns true when this call marked the order paid.
  122. */
  123. public function markPaid(Order $order, PaymentStatus $payment): bool
  124. {
  125. if (! $payment->paid || $payment->checkoutId !== $order->payment_checkout_id) {
  126. return false;
  127. }
  128. // The provider must have collected the full order total.
  129. if ($payment->amount !== null && $payment->amount !== $order->total) {
  130. report(new \RuntimeException("Order {$order->id}: paid amount {$payment->amount} does not match total {$order->total}."));
  131. return false;
  132. }
  133. $marked = DB::transaction(function () use ($order, $payment): bool {
  134. $locked = Order::query()->whereKey($order->id)->lockForUpdate()->firstOrFail();
  135. if ($locked->isPaid()) {
  136. return false;
  137. }
  138. $locked->status = OrderStatus::Paid;
  139. $locked->payment_reference = $payment->reference;
  140. $locked->paid_at = now();
  141. $locked->save();
  142. foreach ($locked->items as $item) {
  143. if ($item->bundle_contents !== null) {
  144. // A bundle has no stock of its own: lower the stock of what was inside it.
  145. foreach ($item->bundle_contents as $part) {
  146. $this->lowerStock($part['product_id'], $part['variant_id'], $part['quantity'] * $item->quantity);
  147. }
  148. continue;
  149. }
  150. $this->lowerStock($item->product_id, $item->variant_id, $item->quantity);
  151. }
  152. BundleStock::refresh($locked->store_id);
  153. // A code counts as used only once the order is paid.
  154. if ($locked->discount_code !== null) {
  155. DiscountCode::query()
  156. ->where('store_id', $locked->store_id)
  157. ->where('code', $locked->discount_code)
  158. ->increment('times_used');
  159. }
  160. return true;
  161. });
  162. $order->refresh();
  163. if ($marked) {
  164. Mail::to($order->customer_email)->send(new OrderConfirmation($order));
  165. }
  166. return $marked;
  167. }
  168. /**
  169. * Take stock off a product or one of its variants. Either may have been deleted since the order was placed.
  170. * Never below zero, even if stock was changed by hand in the meantime.
  171. */
  172. private function lowerStock(?int $productId, ?int $variantId, int $quantity): void
  173. {
  174. $product = $productId !== null ? Product::query()->whereKey($productId)->lockForUpdate()->first() : null;
  175. if ($variantId !== null) {
  176. $variant = ProductVariant::query()->whereKey($variantId)->lockForUpdate()->first();
  177. if ($variant !== null) {
  178. $variant->stock = max(0, $variant->stock - $quantity);
  179. $variant->save();
  180. $product?->syncFromVariants();
  181. }
  182. return;
  183. }
  184. if ($product !== null) {
  185. $product->stock = max(0, $product->stock - $quantity);
  186. $product->save();
  187. }
  188. }
  189. /**
  190. * Whether there is stock for every line at once, counting what bundles hold.
  191. * A bundle of 2 sambal plus 3 sambal bought on their own needs 5 sambal.
  192. *
  193. * @param iterable<array{product: Product, variant: ProductVariant|null, quantity: int}> $lines
  194. */
  195. private function enoughStock(iterable $lines): bool
  196. {
  197. $needed = [];
  198. $left = [];
  199. $count = function (Product $product, ?ProductVariant $variant, int $quantity) use (&$needed, &$left): void {
  200. $key = $variant !== null ? 'v'.$variant->id : 'p'.$product->id;
  201. $needed[$key] = ($needed[$key] ?? 0) + $quantity;
  202. $left[$key] = $variant !== null ? $variant->stock : $product->stock;
  203. };
  204. foreach ($lines as $line) {
  205. if ($line['product']->isBundle()) {
  206. foreach ($line['product']->bundleItems as $item) {
  207. $count($item->product, $item->variant, $item->quantity * $line['quantity']);
  208. }
  209. } else {
  210. $count($line['product'], $line['variant'], $line['quantity']);
  211. }
  212. }
  213. foreach ($needed as $key => $quantity) {
  214. if ($quantity > $left[$key]) {
  215. return false;
  216. }
  217. }
  218. return true;
  219. }
  220. }