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

Checkout.php 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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\DiscountCode;
  8. use App\Models\Order;
  9. use App\Models\Product;
  10. use App\Models\ProductVariant;
  11. use App\Models\Store;
  12. use App\Storefront\StorefrontText;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Mail;
  15. use Illuminate\Support\Str;
  16. use Illuminate\Validation\ValidationException;
  17. /**
  18. * Turns a cart into an order, and an order into a paid order.
  19. */
  20. class Checkout
  21. {
  22. public function __construct(private readonly ShippingProvider $shipping) {}
  23. /** Stripe does not accept payments below RM 2.00. */
  24. public const int MINIMUM_TOTAL = 200;
  25. /** The first order number of every store. */
  26. private const int FIRST_NUMBER = 1001;
  27. /**
  28. * Save the cart as an order that is waiting for payment.
  29. * The order keeps its own copy of each product's name and price.
  30. *
  31. * @param array{name: string, email: string, phone: string, line1: string, line2?: string|null, city: string, postcode: string, state: string} $details
  32. *
  33. * @throws ValidationException When the cart is empty or the total is too small.
  34. */
  35. public function placeOrder(Store $store, Cart $cart, array $details): Order
  36. {
  37. $lines = $cart->lines();
  38. $subtotal = (int) $lines->sum('line_total');
  39. if ($lines->isEmpty()) {
  40. throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'cart_empty')]);
  41. }
  42. if ($subtotal < self::MINIMUM_TOTAL) {
  43. throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'minimum_total')]);
  44. }
  45. $language = $store->language->value;
  46. $applied = $cart->discount($subtotal);
  47. // The code stopped working since the shopper last saw the cart: stop, so the total never surprises them.
  48. if ($cart->discountWasRemoved()) {
  49. throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'discount_changed')]);
  50. }
  51. // A code that still needs a bigger cart is worth nothing; the cart already showed that.
  52. $usable = $applied !== null && $applied->problem === null ? $applied : null;
  53. $discount = $usable !== null ? $usable->amount : 0;
  54. $discountCode = $usable !== null && $discount > 0 ? $usable->code->code : null;
  55. // Free shipping is decided on what the shopper pays for the products, after the discount.
  56. $shipping = $this->shipping->quote($store, $subtotal - $discount, $details['state']);
  57. if ($subtotal - $discount + $shipping < self::MINIMUM_TOTAL) {
  58. throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'discount_total_too_low')]);
  59. }
  60. return DB::transaction(function () use ($store, $lines, $subtotal, $discount, $discountCode, $shipping, $details): Order {
  61. // Lock the store row so two orders placed at the same moment cannot get the same number.
  62. Store::query()->whereKey($store->id)->lockForUpdate()->first();
  63. $order = new Order;
  64. $order->store_id = $store->id;
  65. $order->public_id = (string) Str::ulid();
  66. $order->number = max(self::FIRST_NUMBER, (int) $store->orders()->max('number') + 1);
  67. $order->status = OrderStatus::Pending;
  68. $order->customer_name = $details['name'];
  69. $order->customer_email = $details['email'];
  70. $order->customer_phone = $details['phone'];
  71. $order->shipping_address = [
  72. 'line1' => $details['line1'],
  73. 'line2' => $details['line2'] ?? null,
  74. 'city' => $details['city'],
  75. 'postcode' => $details['postcode'],
  76. 'state' => $details['state'],
  77. 'country' => 'MY',
  78. ];
  79. $order->subtotal = $subtotal;
  80. $order->discount_code = $discountCode;
  81. $order->discount_total = $discount;
  82. $order->shipping_total = $shipping;
  83. $order->total = $subtotal - $discount + $shipping;
  84. $order->currency = 'MYR';
  85. $order->save();
  86. foreach ($lines as $line) {
  87. $variantName = $line['variant']?->name();
  88. $order->items()->create([
  89. 'store_id' => $store->id,
  90. 'product_id' => $line['product']->id,
  91. 'variant_id' => $line['variant']?->id,
  92. // "Sambal Hijau (500g / Pedas)", so every place that shows the order shows the choice too.
  93. 'name' => $line['product']->name.($variantName !== null ? " ({$variantName})" : ''),
  94. 'variant_name' => $variantName,
  95. 'unit_price' => $line['unit_price'],
  96. 'quantity' => $line['quantity'],
  97. 'line_total' => $line['line_total'],
  98. ]);
  99. }
  100. return $order->load('items');
  101. });
  102. }
  103. /**
  104. * Record that an order was paid: mark it, lower the stock, and email the shopper.
  105. *
  106. * Safe to call more than once for the same order (the return page and the webhook may both call it).
  107. * Only the first call does anything. Returns true when this call marked the order paid.
  108. */
  109. public function markPaid(Order $order, PaymentStatus $payment): bool
  110. {
  111. if (! $payment->paid || $payment->checkoutId !== $order->payment_checkout_id) {
  112. return false;
  113. }
  114. // The provider must have collected the full order total.
  115. if ($payment->amount !== null && $payment->amount !== $order->total) {
  116. report(new \RuntimeException("Order {$order->id}: paid amount {$payment->amount} does not match total {$order->total}."));
  117. return false;
  118. }
  119. $marked = DB::transaction(function () use ($order, $payment): bool {
  120. $locked = Order::query()->whereKey($order->id)->lockForUpdate()->firstOrFail();
  121. if ($locked->isPaid()) {
  122. return false;
  123. }
  124. $locked->status = OrderStatus::Paid;
  125. $locked->payment_reference = $payment->reference;
  126. $locked->paid_at = now();
  127. $locked->save();
  128. foreach ($locked->items as $item) {
  129. // The product or variant may have been deleted since the order was placed.
  130. $product = $item->product_id !== null
  131. ? Product::query()->whereKey($item->product_id)->lockForUpdate()->first()
  132. : null;
  133. $variant = $item->variant_id !== null
  134. ? ProductVariant::query()->whereKey($item->variant_id)->lockForUpdate()->first()
  135. : null;
  136. if ($variant !== null) {
  137. // Never below zero, even if stock was changed by hand in the meantime.
  138. $variant->stock = max(0, $variant->stock - $item->quantity);
  139. $variant->save();
  140. $product?->syncFromVariants();
  141. } elseif ($product !== null && $item->variant_id === null) {
  142. $product->stock = max(0, $product->stock - $item->quantity);
  143. $product->save();
  144. }
  145. }
  146. // A code counts as used only once the order is paid.
  147. if ($locked->discount_code !== null) {
  148. DiscountCode::query()
  149. ->where('store_id', $locked->store_id)
  150. ->where('code', $locked->discount_code)
  151. ->increment('times_used');
  152. }
  153. return true;
  154. });
  155. $order->refresh();
  156. if ($marked) {
  157. Mail::to($order->customer_email)->send(new OrderConfirmation($order));
  158. }
  159. return $marked;
  160. }
  161. }