AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

Checkout.php 7.0KB

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