AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Checkout.php 11KB

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