| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510 |
- import { Form, Link, router, usePage } from '@inertiajs/react';
- import {
- ExternalLink,
- MapPin,
- Printer,
- RefreshCw,
- Store as StoreIcon,
- Truck,
- } from 'lucide-react';
- import { useState } from 'react';
- import OrderController from '@/actions/App/Http/Controllers/OrderController';
- import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
- import InputError from '@/components/input-error';
- import { Badge } from '@/components/ui/badge';
- import { Button } from '@/components/ui/button';
- import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
- } from '@/components/ui/card';
- import { Input } from '@/components/ui/input';
- import { Label } from '@/components/ui/label';
- import { Spinner } from '@/components/ui/spinner';
- import { formatRinggit } from '@/lib/money';
- import { cn } from '@/lib/utils';
- import type { Order, StoreSummary } from '@/types';
-
- export type CourierQuote = {
- service_id: string;
- courier: string;
- service: string;
- logo: string | null;
- /** In ringgit. */
- price: number;
- pickup: boolean;
- dropoff: boolean;
- delivery: string | null;
- /** Something to know, such as "Pickup needs at least 3 parcels". */
- note: string | null;
- };
-
- export type EasyParcelState = {
- connected: boolean;
- has_pickup_address: boolean;
- parcel: { weight: number; length: number; width: number; height: number };
- /** The first day a courier can collect, YYYY-MM-DD. */
- collection_date: string;
- };
-
- type Parcel = {
- weight: string;
- length: string;
- width: string;
- height: string;
- };
-
- /**
- * Book a courier through the merchant's EasyParcel account:
- * type the parcel, see each courier's price, pick one, book, print the label.
- */
- export function CourierBooking({
- store,
- order,
- easyparcel,
- quotes,
- }: {
- store: StoreSummary;
- order: Order;
- easyparcel: EasyParcelState;
- quotes: CourierQuote[] | { error: string } | undefined;
- }) {
- if (order.shipment) {
- return <BookedCourier store={store} order={order} />;
- }
-
- if (!easyparcel.connected || !easyparcel.has_pickup_address) {
- return (
- <Card data-test="courier-booking-setup">
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Truck className="size-5" />
- Book a courier
- </CardTitle>
- <CardDescription>
- Compare courier prices and print the label here, through
- your own EasyParcel account.{' '}
- {!easyparcel.connected
- ? 'Connect EasyParcel and add your pickup address in Settings to start.'
- : 'Add your pickup address in Settings to start.'}
- </CardDescription>
- </CardHeader>
- <CardContent>
- <Button variant="outline" size="sm" asChild>
- <Link
- href={`${StoreSettingsController.edit.url(store.slug)}#easyparcel`}
- >
- Set up in Settings
- </Link>
- </Button>
- </CardContent>
- </Card>
- );
- }
-
- return (
- <QuoteAndBook
- store={store}
- order={order}
- easyparcel={easyparcel}
- quotes={quotes}
- />
- );
- }
-
- function QuoteAndBook({
- store,
- order,
- easyparcel,
- quotes,
- }: {
- store: StoreSummary;
- order: Order;
- easyparcel: EasyParcelState;
- quotes: CourierQuote[] | { error: string } | undefined;
- }) {
- // A failed booking comes back as a fresh page, without the courier list, so its message is shown up here.
- const bookingError = usePage().props.errors.booking as string | undefined;
- const [parcel, setParcel] = useState<Parcel>({
- weight: String(easyparcel.parcel.weight),
- length: String(easyparcel.parcel.length),
- width: String(easyparcel.parcel.width),
- height: String(easyparcel.parcel.height),
- });
- const [loading, setLoading] = useState(false);
- const [chosen, setChosen] = useState<string | null>(null);
- // Prices are for the parcel as it was typed. Changing it asks for new prices.
- const [pricedFor, setPricedFor] = useState<string | null>(null);
- const typed = JSON.stringify(parcel);
- const list = Array.isArray(quotes) ? quotes : null;
- const fresh = list !== null && pricedFor === typed;
- const picked = fresh
- ? (list.find((quote) => quote.service_id === chosen) ?? null)
- : null;
-
- const seePrices = () => {
- setLoading(true);
- setChosen(null);
- router.reload({
- only: ['courier_quotes'],
- data: parcel,
- onSuccess: () => setPricedFor(typed),
- onFinish: () => setLoading(false),
- });
- };
-
- const field = (key: keyof Parcel, label: string, step: string) => (
- <div className="grid gap-1.5">
- <Label htmlFor={`parcel-${key}`} className="text-xs">
- {label}
- </Label>
- <Input
- id={`parcel-${key}`}
- inputMode="decimal"
- type="number"
- min={key === 'weight' ? 0.01 : 1}
- step={step}
- value={parcel[key]}
- onChange={(event) =>
- setParcel({ ...parcel, [key]: event.target.value })
- }
- />
- </div>
- );
-
- return (
- <Card data-test="courier-booking">
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Truck className="size-5" />
- Book a courier
- </CardTitle>
- <CardDescription>
- Through your EasyParcel account. The price is taken from
- your EasyParcel credit.
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-5">
- <div>
- <p className="mb-2 text-sm font-medium">The parcel</p>
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
- {field('weight', 'Weight (kg)', '0.01')}
- {field('length', 'Length (cm)', '1')}
- {field('width', 'Width (cm)', '1')}
- {field('height', 'Height (cm)', '1')}
- </div>
- <Button
- type="button"
- variant="outline"
- className="mt-3"
- onClick={seePrices}
- disabled={loading}
- data-test="see-courier-prices"
- >
- {loading && <Spinner />}
- {loading
- ? 'Asking couriers…'
- : fresh
- ? 'Refresh prices'
- : 'See courier prices'}
- </Button>
- </div>
-
- {bookingError && !fresh && (
- <p
- className="rounded-md bg-destructive/10 p-3 text-sm text-destructive"
- role="alert"
- data-test="booking-error"
- >
- Not booked. {bookingError}
- </p>
- )}
-
- {quotes && !Array.isArray(quotes) && pricedFor === typed && (
- <p
- className="rounded-md bg-destructive/10 p-3 text-sm text-destructive"
- role="alert"
- >
- {quotes.error}
- </p>
- )}
-
- {fresh && list.length === 0 && (
- <p className="text-sm text-muted-foreground">
- No courier can take this parcel. Check its weight and
- size, or your pickup address.
- </p>
- )}
-
- {fresh && list.length > 0 && (
- <fieldset>
- <legend className="mb-2 text-sm font-medium">
- Choose a courier
- </legend>
- <div
- className="grid max-h-[26rem] gap-2 overflow-y-auto pr-1"
- data-test="courier-quotes"
- >
- {list.map((quote) => (
- <label
- key={quote.service_id}
- className={cn(
- 'flex cursor-pointer items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50',
- chosen === quote.service_id &&
- 'border-primary bg-primary/5 ring-1 ring-primary',
- )}
- >
- <input
- type="radio"
- name="courier_choice"
- className="sr-only"
- checked={chosen === quote.service_id}
- onChange={() =>
- setChosen(quote.service_id)
- }
- />
- {quote.logo ? (
- <img
- src={quote.logo}
- alt=""
- className="size-10 shrink-0 rounded bg-white object-contain p-0.5"
- />
- ) : (
- <span className="flex size-10 shrink-0 items-center justify-center rounded bg-muted">
- <Truck className="size-5 text-muted-foreground" />
- </span>
- )}
- <span className="min-w-0 flex-1">
- <span className="block truncate text-sm font-medium">
- {quote.courier}
- </span>
- <span className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
- {quote.pickup && (
- <Badge
- variant="secondary"
- className="gap-1 font-normal"
- >
- <MapPin className="size-3" />
- Picks up from you
- </Badge>
- )}
- {quote.dropoff && (
- <Badge
- variant="secondary"
- className="gap-1 font-normal"
- >
- <StoreIcon className="size-3" />
- Drop off at a counter
- </Badge>
- )}
- {quote.delivery && (
- <span>{quote.delivery}</span>
- )}
- {quote.note && (
- <span className="text-amber-700 dark:text-amber-400">
- {quote.note}
- </span>
- )}
- </span>
- </span>
- <span className="text-sm font-semibold tabular-nums">
- {formatRinggit(quote.price)}
- </span>
- </label>
- ))}
- </div>
- <p className="mt-2 text-xs text-muted-foreground">
- The shopper paid{' '}
- {order.shipping_total === 0
- ? 'no shipping (free)'
- : `${formatRinggit(order.shipping_total)} for shipping`}
- .
- </p>
- </fieldset>
- )}
-
- {picked && (
- <Form
- {...OrderController.book.form({
- slug: store.slug,
- order: order.id,
- })}
- options={{ preserveScroll: true }}
- className="space-y-4 border-t pt-4"
- >
- {({ processing, errors }) => (
- <>
- <input
- type="hidden"
- name="service_id"
- value={picked.service_id}
- />
- <input
- type="hidden"
- name="courier"
- value={picked.courier}
- />
- {Object.entries(parcel).map(([key, value]) => (
- <input
- key={key}
- type="hidden"
- name={key}
- value={value}
- />
- ))}
- <div className="grid gap-1.5 sm:max-w-56">
- <Label htmlFor="collection_date">
- {picked.pickup
- ? 'Collection day'
- : 'Day you drop it off'}
- </Label>
- <Input
- id="collection_date"
- name="collection_date"
- type="date"
- min={easyparcel.collection_date}
- defaultValue={
- easyparcel.collection_date
- }
- required
- />
- <InputError
- message={errors.collection_date}
- />
- </div>
- <InputError
- message={
- errors.booking ??
- errors.service_id ??
- errors.weight ??
- errors.length ??
- errors.width ??
- errors.height
- }
- />
- <Button
- disabled={processing}
- data-test="book-courier-button"
- >
- {processing && <Spinner />}
- Book {picked.courier} for{' '}
- {formatRinggit(picked.price)}
- </Button>
- </>
- )}
- </Form>
- )}
- </CardContent>
- </Card>
- );
- }
-
- function BookedCourier({
- store,
- order,
- }: {
- store: StoreSummary;
- order: Order;
- }) {
- const shipment = order.shipment!;
-
- return (
- <Card data-test="courier-booked">
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Truck className="size-5" />
- Courier booked
- </CardTitle>
- <CardDescription>
- {order.shipping_courier} · EasyParcel {shipment.number}
- {shipment.cost !== null &&
- ` · Paid ${formatRinggit(shipment.cost)}`}
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4 text-sm">
- {order.tracking_number ? (
- <p>
- Tracking number{' '}
- <span className="font-medium tabular-nums">
- {order.tracking_number}
- </span>
- {order.shipped_at &&
- '. The customer was emailed this number.'}
- </p>
- ) : (
- <p className="text-muted-foreground">
- The courier is preparing the label. It usually takes a
- minute or two.
- </p>
- )}
-
- <div className="flex flex-wrap gap-2">
- {shipment.label_url && (
- <Button asChild>
- <a
- href={shipment.label_url}
- target="_blank"
- rel="noreferrer"
- data-test="print-label"
- >
- <Printer />
- Print label
- </a>
- </Button>
- )}
- {shipment.tracking_url && (
- <Button variant="outline" asChild>
- <a
- href={shipment.tracking_url}
- target="_blank"
- rel="noreferrer"
- >
- <ExternalLink />
- Track parcel
- </a>
- </Button>
- )}
- {(!shipment.label_url || !order.tracking_number) && (
- <Form
- {...OrderController.refreshLabel.form({
- slug: store.slug,
- order: order.id,
- })}
- options={{ preserveScroll: true }}
- >
- {({ processing, errors }) => (
- <>
- <Button
- variant="outline"
- disabled={processing}
- data-test="refresh-label"
- >
- <RefreshCw
- className={cn(
- processing && 'animate-spin',
- )}
- />
- Check for the label
- </Button>
- <InputError
- className="mt-2"
- message={errors.booking}
- />
- </>
- )}
- </Form>
- )}
- </div>
-
- {shipment.label_url && (
- <p className="text-xs text-muted-foreground">
- Print the label, stick it on the parcel, and hand it to
- the courier (or drop it off at a counter).
- </p>
- )}
- </CardContent>
- </Card>
- );
- }
|