lines(); $subtotal = (int) $lines->sum('line_total'); if ($lines->isEmpty()) { throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'cart_empty')]); } if ($subtotal < self::MINIMUM_TOTAL) { throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'minimum_total')]); } $language = $store->language->value; $applied = $cart->discount($subtotal); // The code stopped working since the shopper last saw the cart: stop, so the total never surprises them. if ($cart->discountWasRemoved()) { throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'discount_changed')]); } // A code that still needs a bigger cart is worth nothing; the cart already showed that. $usable = $applied !== null && $applied->problem === null ? $applied : null; $discount = $usable !== null ? $usable->amount : 0; $discountCode = $usable !== null && $discount > 0 ? $usable->code->code : null; // Free shipping is decided on what the shopper pays for the products, after the discount. $shipping = $this->shipping->quote($store, $subtotal - $discount, $details['state']); if ($subtotal - $discount + $shipping < self::MINIMUM_TOTAL) { throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'discount_total_too_low')]); } return DB::transaction(function () use ($store, $lines, $subtotal, $discount, $discountCode, $shipping, $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->discount_code = $discountCode; $order->discount_total = $discount; $order->shipping_total = $shipping; $order->total = $subtotal - $discount + $shipping; $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(); } } // A code counts as used only once the order is paid. if ($locked->discount_code !== null) { DiscountCode::query() ->where('store_id', $locked->store_id) ->where('code', $locked->discount_code) ->increment('times_used'); } return true; }); $order->refresh(); if ($marked) { Mail::to($order->customer_email)->send(new OrderConfirmation($order)); } return $marked; } }