| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144 |
- <?php
-
- namespace App\Commerce;
-
- use App\Commerce\Payments\PaymentStatus;
- use App\Enums\OrderStatus;
- use App\Mail\OrderConfirmation;
- use App\Models\Order;
- use App\Models\Product;
- use App\Models\Store;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Mail;
- use Illuminate\Support\Str;
- use Illuminate\Validation\ValidationException;
-
- /**
- * Turns a cart into an order, and an order into a paid order.
- */
- class Checkout
- {
- /** Stripe does not accept payments below RM 2.00. */
- public const int MINIMUM_TOTAL = 200;
-
- /** The first order number of every store. */
- private const int FIRST_NUMBER = 1001;
-
- /**
- * Save the cart as an order that is waiting for payment.
- * The order keeps its own copy of each product's name and price.
- *
- * @param array{name: string, email: string, phone: string, line1: string, line2?: string|null, city: string, postcode: string, state: string} $details
- *
- * @throws ValidationException When the cart is empty or the total is too small.
- */
- public function placeOrder(Store $store, Cart $cart, array $details): Order
- {
- $lines = $cart->lines();
- $subtotal = (int) $lines->sum('line_total');
-
- if ($lines->isEmpty()) {
- throw ValidationException::withMessages(['cart' => __('Your cart is empty.')]);
- }
-
- if ($subtotal < self::MINIMUM_TOTAL) {
- throw ValidationException::withMessages(['cart' => __('The order total must be at least RM 2.00.')]);
- }
-
- return DB::transaction(function () use ($store, $lines, $subtotal, $details): Order {
- // Lock the store row so two orders placed at the same moment cannot get the same number.
- Store::query()->whereKey($store->id)->lockForUpdate()->first();
-
- $order = new Order;
- $order->store_id = $store->id;
- $order->public_id = (string) Str::ulid();
- $order->number = max(self::FIRST_NUMBER, (int) $store->orders()->max('number') + 1);
- $order->status = OrderStatus::Pending;
- $order->customer_name = $details['name'];
- $order->customer_email = $details['email'];
- $order->customer_phone = $details['phone'];
- $order->shipping_address = [
- 'line1' => $details['line1'],
- 'line2' => $details['line2'] ?? null,
- 'city' => $details['city'],
- 'postcode' => $details['postcode'],
- 'state' => $details['state'],
- 'country' => 'MY',
- ];
- $order->subtotal = $subtotal;
- $order->shipping_total = 0;
- $order->total = $subtotal;
- $order->currency = 'MYR';
- $order->save();
-
- foreach ($lines as $line) {
- $order->items()->create([
- 'store_id' => $store->id,
- 'product_id' => $line['product']->id,
- 'name' => $line['product']->name,
- 'unit_price' => $line['product']->price,
- 'quantity' => $line['quantity'],
- 'line_total' => $line['line_total'],
- ]);
- }
-
- return $order->load('items');
- });
- }
-
- /**
- * Record that an order was paid: mark it, lower the stock, and email the shopper.
- *
- * Safe to call more than once for the same order (the return page and the webhook may both call it).
- * Only the first call does anything. Returns true when this call marked the order paid.
- */
- public function markPaid(Order $order, PaymentStatus $payment): bool
- {
- if (! $payment->paid || $payment->checkoutId !== $order->payment_checkout_id) {
- return false;
- }
-
- // The provider must have collected the full order total.
- if ($payment->amount !== null && $payment->amount !== $order->total) {
- report(new \RuntimeException("Order {$order->id}: paid amount {$payment->amount} does not match total {$order->total}."));
-
- return false;
- }
-
- $marked = DB::transaction(function () use ($order, $payment): bool {
- $locked = Order::query()->whereKey($order->id)->lockForUpdate()->firstOrFail();
-
- if ($locked->isPaid()) {
- return false;
- }
-
- $locked->status = OrderStatus::Paid;
- $locked->payment_reference = $payment->reference;
- $locked->paid_at = now();
- $locked->save();
-
- foreach ($locked->items as $item) {
- // The product may have been deleted since the order was placed.
- $product = $item->product_id !== null
- ? Product::query()->whereKey($item->product_id)->lockForUpdate()->first()
- : null;
-
- if ($product !== null) {
- // Never below zero, even if stock was changed by hand in the meantime.
- $product->stock = max(0, $product->stock - $item->quantity);
- $product->save();
- }
- }
-
- return true;
- });
-
- $order->refresh();
-
- if ($marked) {
- Mail::to($order->customer_email)->send(new OrderConfirmation($order));
- }
-
- return $marked;
- }
- }
|