| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251 |
- <?php
-
- namespace App\Http\Controllers;
-
- use App\Commerce\Couriers;
- use App\Commerce\Shipping\EasyParcel\EasyParcel;
- use App\Commerce\Shipping\EasyParcel\EasyParcelException;
- use App\Commerce\Shipping\EasyParcel\Parcel;
- use App\Commerce\Shipping\EasyParcel\Quote;
- use App\Mail\OrderShipped;
- use App\Models\Order;
- use App\Models\Store;
- use App\Support\MalaysianPhone;
- use Carbon\CarbonInterface;
- use Illuminate\Http\RedirectResponse;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Mail;
- use Illuminate\Validation\Rule;
- use Inertia\Inertia;
- use Inertia\Response;
-
- /**
- * The merchant's view of a store's orders.
- */
- class OrderController extends Controller
- {
- public function index(Request $request, string $slug): Response
- {
- $store = $this->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<string, mixed>>|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<string, list<string>>
- */
- 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<string, mixed> $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();
- }
- }
|