ownedStore($request, $slug); return Inertia::render('stores/orders/index', [ 'store' => ['name' => $store->name, 'slug' => $store->slug], 'orders' => $store->orders() ->with('items') ->latest('id') ->limit(200) ->get() ->map(fn (Order $order) => $order->toDisplay()), ]); } public function show(Request $request, string $slug, int $order, EasyParcel $easyparcel): Response { $store = $this->ownedStore($request, $slug); $order = $store->orders()->with('items')->whereKey($order)->firstOrFail(); $customerWhatsapp = MalaysianPhone::normalize($order->customer_phone); $size = $store->parcel_size ?? self::DEFAULT_SIZE; return Inertia::render('stores/orders/show', [ 'store' => ['name' => $store->name, 'slug' => $store->slug], 'order' => $order->toDisplay(), 'couriers' => Couriers::ALL, // Booking a courier through the merchant's EasyParcel account. 'easyparcel' => [ 'connected' => $store->easyparcel()->exists(), 'has_pickup_address' => $store->pickup_address !== null, 'parcel' => ['weight' => $store->parcel_weight / 1000, ...$size], 'collection_date' => self::firstCollectionDate()->toDateString(), ], // Asked for only when the merchant clicks "See courier prices", with the parcel they typed. 'courier_quotes' => Inertia::optional(fn () => $this->quotes($request, $store, $order, $easyparcel)), // A chat with the shopper, with a first message already typed in the store's language. 'customer_whatsapp_url' => $customerWhatsapp !== null ? MalaysianPhone::whatsappLink($customerWhatsapp, $store->language->value === 'ms' ? "Hai {$order->customer_name}, terima kasih atas pesanan #{$order->number} daripada {$store->name}." : "Hi {$order->customer_name}, thank you for your order #{$order->number} from {$store->name}.") : null, ]); } /** * Record that a paid order was sent. The shopper is emailed the first time only; * later saves just correct the courier or tracking number. */ public function ship(Request $request, string $slug, int $order): RedirectResponse { $store = $this->ownedStore($request, $slug); $order = $store->orders()->whereKey($order)->firstOrFail(); abort_unless($order->isPaid(), 404); $validated = $request->validate([ 'shipping_courier' => ['required', Rule::in(Couriers::ALL)], 'tracking_number' => ['nullable', 'string', 'max:80', 'regex:/^[A-Za-z0-9\-\s]+$/'], ], [ 'tracking_number.regex' => __('Use only letters, numbers, spaces and dashes.'), ]); $firstTime = $order->shipped_at === null; $order->shipping_courier = $validated['shipping_courier']; $order->tracking_number = filled($validated['tracking_number'] ?? null) ? trim($validated['tracking_number']) : null; $order->shipped_at ??= now(); $order->save(); if ($firstTime) { Mail::to($order->customer_email)->send(new OrderShipped($order)); } Inertia::flash('toast', ['type' => 'success', 'message' => $firstTime ? __('Marked as shipped. We emailed the customer.') : __('Shipping details saved.')]); return to_route('stores.orders.show', [$store->slug, $order->id]); } /** * Book the chosen courier on the merchant's EasyParcel account, and print its label. * The shopper gets the "on its way" email once the courier's tracking number is known. */ public function book(Request $request, string $slug, int $order, EasyParcel $easyparcel): RedirectResponse { $store = $this->ownedStore($request, $slug); $order = $store->orders()->whereKey($order)->firstOrFail(); abort_unless($order->isPaid(), 404); if ($order->shipment_number !== null) { Inertia::flash('toast', ['type' => 'error', 'message' => __('A courier is already booked for this order.')]); return to_route('stores.orders.show', [$store->slug, $order->id]); } $today = now(self::TIMEZONE)->startOfDay(); $lastDay = $today->addDays(14); $validated = $request->validate([ ...self::parcelRules(), 'service_id' => ['required', 'string', 'max:40'], 'courier' => ['nullable', 'string', 'max:60'], 'collection_date' => ['required', 'date_format:Y-m-d', 'after_or_equal:'.$today->toDateString(), 'before_or_equal:'.$lastDay->toDateString()], ], [ 'collection_date.after_or_equal' => __('Choose today or a later day.'), 'collection_date.before_or_equal' => __('Choose a day within the next two weeks.'), ]); try { $easyparcel->book($store, $order, self::parcelFrom($validated), $validated['service_id'], $validated['collection_date'], $validated['courier'] ?? null); } catch (EasyParcelException $e) { return back()->withErrors(['booking' => $e->getMessage()]); } $emailed = $this->markShipped($order); Inertia::flash('toast', ['type' => 'success', 'message' => match (true) { $emailed => __('Courier booked. Print the label and stick it on the parcel. We emailed the customer.'), $order->tracking_number !== null => __('Courier booked. Print the label and stick it on the parcel.'), default => __('Courier booked. The label is being prepared; check again in a minute.'), }]); return to_route('stores.orders.show', [$store->slug, $order->id]); } /** * Some couriers give the label and tracking number a little after booking. Ask EasyParcel again. */ public function refreshLabel(Request $request, string $slug, int $order, EasyParcel $easyparcel): RedirectResponse { $store = $this->ownedStore($request, $slug); $order = $store->orders()->whereKey($order)->whereNotNull('shipment_number')->firstOrFail(); try { $easyparcel->refreshLabel($store, $order); } catch (EasyParcelException $e) { return back()->withErrors(['booking' => $e->getMessage()]); } $emailed = $this->markShipped($order); Inertia::flash('toast', $order->label_url !== null ? ['type' => 'success', 'message' => $emailed ? __('The label is ready. We emailed the customer.') : __('The label is ready.')] : ['type' => 'info', 'message' => __('The label is not ready yet. Try again in a minute.')]); return to_route('stores.orders.show', [$store->slug, $order->id]); } /** A box most small parcels fit, in cm, when the merchant has not set their own. */ public const array DEFAULT_SIZE = ['length' => 20, 'width' => 15, 'height' => 10]; private const string TIMEZONE = 'Asia/Kuala_Lumpur'; /** * @return list>|array{error: string} */ private function quotes(Request $request, Store $store, Order $order, EasyParcel $easyparcel): array { $validator = validator($request->query(), self::parcelRules()); if ($validator->fails()) { return ['error' => (string) $validator->errors()->first()]; } try { return array_map(fn (Quote $quote) => $quote->toArray(), $easyparcel->quotes($store, $order, self::parcelFrom($validator->validated()))); } catch (EasyParcelException $e) { return ['error' => $e->getMessage()]; } } /** * @return array> */ private static function parcelRules(): array { return [ 'weight' => ['required', 'numeric', 'min:0.01', 'max:70'], 'length' => ['required', 'integer', 'min:1', 'max:200'], 'width' => ['required', 'integer', 'min:1', 'max:200'], 'height' => ['required', 'integer', 'min:1', 'max:200'], ]; } /** * @param array $input */ private static function parcelFrom(array $input): Parcel { return new Parcel((int) round(((float) $input['weight']) * 1000), (int) $input['length'], (int) $input['width'], (int) $input['height']); } /** * Couriers collect on working days, and same-day collection is only booked before noon. */ private static function firstCollectionDate(): CarbonInterface { $now = now(self::TIMEZONE); $day = ($now->hour < 12 ? $now : $now->addDay())->startOfDay(); return $day->isSunday() ? $day->addDay() : $day; } /** * Once a booked parcel has its tracking number, the order counts as shipped and the shopper is emailed once. */ private function markShipped(Order $order): bool { if ($order->shipped_at !== null || $order->tracking_number === null) { return false; } $order->shipped_at = now(); $order->save(); Mail::to($order->customer_email)->send(new OrderShipped($order)); return true; } private function ownedStore(Request $request, string $slug): Store { return $request->user()->stores()->where('slug', $slug)->firstOrFail(); } }