AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

courier-booking.tsx 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import { Form, Link, router, usePage } from '@inertiajs/react';
  2. import {
  3. ExternalLink,
  4. MapPin,
  5. Printer,
  6. RefreshCw,
  7. Store as StoreIcon,
  8. Truck,
  9. } from 'lucide-react';
  10. import { useState } from 'react';
  11. import OrderController from '@/actions/App/Http/Controllers/OrderController';
  12. import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
  13. import InputError from '@/components/input-error';
  14. import { Badge } from '@/components/ui/badge';
  15. import { Button } from '@/components/ui/button';
  16. import {
  17. Card,
  18. CardContent,
  19. CardDescription,
  20. CardHeader,
  21. CardTitle,
  22. } from '@/components/ui/card';
  23. import { Input } from '@/components/ui/input';
  24. import { Label } from '@/components/ui/label';
  25. import { Spinner } from '@/components/ui/spinner';
  26. import { formatRinggit } from '@/lib/money';
  27. import { cn } from '@/lib/utils';
  28. import type { Order, StoreSummary } from '@/types';
  29. export type CourierQuote = {
  30. service_id: string;
  31. courier: string;
  32. service: string;
  33. logo: string | null;
  34. /** In ringgit. */
  35. price: number;
  36. pickup: boolean;
  37. dropoff: boolean;
  38. delivery: string | null;
  39. /** Something to know, such as "Pickup needs at least 3 parcels". */
  40. note: string | null;
  41. };
  42. export type EasyParcelState = {
  43. connected: boolean;
  44. has_pickup_address: boolean;
  45. parcel: { weight: number; length: number; width: number; height: number };
  46. /** The first day a courier can collect, YYYY-MM-DD. */
  47. collection_date: string;
  48. };
  49. type Parcel = {
  50. weight: string;
  51. length: string;
  52. width: string;
  53. height: string;
  54. };
  55. /**
  56. * Book a courier through the merchant's EasyParcel account:
  57. * type the parcel, see each courier's price, pick one, book, print the label.
  58. */
  59. export function CourierBooking({
  60. store,
  61. order,
  62. easyparcel,
  63. quotes,
  64. }: {
  65. store: StoreSummary;
  66. order: Order;
  67. easyparcel: EasyParcelState;
  68. quotes: CourierQuote[] | { error: string } | undefined;
  69. }) {
  70. if (order.shipment) {
  71. return <BookedCourier store={store} order={order} />;
  72. }
  73. if (!easyparcel.connected || !easyparcel.has_pickup_address) {
  74. return (
  75. <Card data-test="courier-booking-setup">
  76. <CardHeader>
  77. <CardTitle className="flex items-center gap-2">
  78. <Truck className="size-5" />
  79. Book a courier
  80. </CardTitle>
  81. <CardDescription>
  82. Compare courier prices and print the label here, through
  83. your own EasyParcel account.{' '}
  84. {!easyparcel.connected
  85. ? 'Connect EasyParcel and add your pickup address in Settings to start.'
  86. : 'Add your pickup address in Settings to start.'}
  87. </CardDescription>
  88. </CardHeader>
  89. <CardContent>
  90. <Button variant="outline" size="sm" asChild>
  91. <Link
  92. href={`${StoreSettingsController.edit.url(store.slug)}#easyparcel`}
  93. >
  94. Set up in Settings
  95. </Link>
  96. </Button>
  97. </CardContent>
  98. </Card>
  99. );
  100. }
  101. return (
  102. <QuoteAndBook
  103. store={store}
  104. order={order}
  105. easyparcel={easyparcel}
  106. quotes={quotes}
  107. />
  108. );
  109. }
  110. function QuoteAndBook({
  111. store,
  112. order,
  113. easyparcel,
  114. quotes,
  115. }: {
  116. store: StoreSummary;
  117. order: Order;
  118. easyparcel: EasyParcelState;
  119. quotes: CourierQuote[] | { error: string } | undefined;
  120. }) {
  121. // A failed booking comes back as a fresh page, without the courier list, so its message is shown up here.
  122. const bookingError = usePage().props.errors.booking as string | undefined;
  123. const [parcel, setParcel] = useState<Parcel>({
  124. weight: String(easyparcel.parcel.weight),
  125. length: String(easyparcel.parcel.length),
  126. width: String(easyparcel.parcel.width),
  127. height: String(easyparcel.parcel.height),
  128. });
  129. const [loading, setLoading] = useState(false);
  130. const [chosen, setChosen] = useState<string | null>(null);
  131. // Prices are for the parcel as it was typed. Changing it asks for new prices.
  132. const [pricedFor, setPricedFor] = useState<string | null>(null);
  133. const typed = JSON.stringify(parcel);
  134. const list = Array.isArray(quotes) ? quotes : null;
  135. const fresh = list !== null && pricedFor === typed;
  136. const picked = fresh
  137. ? (list.find((quote) => quote.service_id === chosen) ?? null)
  138. : null;
  139. const seePrices = () => {
  140. setLoading(true);
  141. setChosen(null);
  142. router.reload({
  143. only: ['courier_quotes'],
  144. data: parcel,
  145. onSuccess: () => setPricedFor(typed),
  146. onFinish: () => setLoading(false),
  147. });
  148. };
  149. const field = (key: keyof Parcel, label: string, step: string) => (
  150. <div className="grid gap-1.5">
  151. <Label htmlFor={`parcel-${key}`} className="text-xs">
  152. {label}
  153. </Label>
  154. <Input
  155. id={`parcel-${key}`}
  156. inputMode="decimal"
  157. type="number"
  158. min={key === 'weight' ? 0.01 : 1}
  159. step={step}
  160. value={parcel[key]}
  161. onChange={(event) =>
  162. setParcel({ ...parcel, [key]: event.target.value })
  163. }
  164. />
  165. </div>
  166. );
  167. return (
  168. <Card data-test="courier-booking">
  169. <CardHeader>
  170. <CardTitle className="flex items-center gap-2">
  171. <Truck className="size-5" />
  172. Book a courier
  173. </CardTitle>
  174. <CardDescription>
  175. Through your EasyParcel account. The price is taken from
  176. your EasyParcel credit.
  177. </CardDescription>
  178. </CardHeader>
  179. <CardContent className="space-y-5">
  180. <div>
  181. <p className="mb-2 text-sm font-medium">The parcel</p>
  182. <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
  183. {field('weight', 'Weight (kg)', '0.01')}
  184. {field('length', 'Length (cm)', '1')}
  185. {field('width', 'Width (cm)', '1')}
  186. {field('height', 'Height (cm)', '1')}
  187. </div>
  188. <Button
  189. type="button"
  190. variant="outline"
  191. className="mt-3"
  192. onClick={seePrices}
  193. disabled={loading}
  194. data-test="see-courier-prices"
  195. >
  196. {loading && <Spinner />}
  197. {loading
  198. ? 'Asking couriers…'
  199. : fresh
  200. ? 'Refresh prices'
  201. : 'See courier prices'}
  202. </Button>
  203. </div>
  204. {bookingError && !fresh && (
  205. <p
  206. className="rounded-md bg-destructive/10 p-3 text-sm text-destructive"
  207. role="alert"
  208. data-test="booking-error"
  209. >
  210. Not booked. {bookingError}
  211. </p>
  212. )}
  213. {quotes && !Array.isArray(quotes) && pricedFor === typed && (
  214. <p
  215. className="rounded-md bg-destructive/10 p-3 text-sm text-destructive"
  216. role="alert"
  217. >
  218. {quotes.error}
  219. </p>
  220. )}
  221. {fresh && list.length === 0 && (
  222. <p className="text-sm text-muted-foreground">
  223. No courier can take this parcel. Check its weight and
  224. size, or your pickup address.
  225. </p>
  226. )}
  227. {fresh && list.length > 0 && (
  228. <fieldset>
  229. <legend className="mb-2 text-sm font-medium">
  230. Choose a courier
  231. </legend>
  232. <div
  233. className="grid max-h-[26rem] gap-2 overflow-y-auto pr-1"
  234. data-test="courier-quotes"
  235. >
  236. {list.map((quote) => (
  237. <label
  238. key={quote.service_id}
  239. className={cn(
  240. 'flex cursor-pointer items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50',
  241. chosen === quote.service_id &&
  242. 'border-primary bg-primary/5 ring-1 ring-primary',
  243. )}
  244. >
  245. <input
  246. type="radio"
  247. name="courier_choice"
  248. className="sr-only"
  249. checked={chosen === quote.service_id}
  250. onChange={() =>
  251. setChosen(quote.service_id)
  252. }
  253. />
  254. {quote.logo ? (
  255. <img
  256. src={quote.logo}
  257. alt=""
  258. className="size-10 shrink-0 rounded bg-white object-contain p-0.5"
  259. />
  260. ) : (
  261. <span className="flex size-10 shrink-0 items-center justify-center rounded bg-muted">
  262. <Truck className="size-5 text-muted-foreground" />
  263. </span>
  264. )}
  265. <span className="min-w-0 flex-1">
  266. <span className="block truncate text-sm font-medium">
  267. {quote.courier}
  268. </span>
  269. <span className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
  270. {quote.pickup && (
  271. <Badge
  272. variant="secondary"
  273. className="gap-1 font-normal"
  274. >
  275. <MapPin className="size-3" />
  276. Picks up from you
  277. </Badge>
  278. )}
  279. {quote.dropoff && (
  280. <Badge
  281. variant="secondary"
  282. className="gap-1 font-normal"
  283. >
  284. <StoreIcon className="size-3" />
  285. Drop off at a counter
  286. </Badge>
  287. )}
  288. {quote.delivery && (
  289. <span>{quote.delivery}</span>
  290. )}
  291. {quote.note && (
  292. <span className="text-amber-700 dark:text-amber-400">
  293. {quote.note}
  294. </span>
  295. )}
  296. </span>
  297. </span>
  298. <span className="text-sm font-semibold tabular-nums">
  299. {formatRinggit(quote.price)}
  300. </span>
  301. </label>
  302. ))}
  303. </div>
  304. <p className="mt-2 text-xs text-muted-foreground">
  305. The shopper paid{' '}
  306. {order.shipping_total === 0
  307. ? 'no shipping (free)'
  308. : `${formatRinggit(order.shipping_total)} for shipping`}
  309. .
  310. </p>
  311. </fieldset>
  312. )}
  313. {picked && (
  314. <Form
  315. {...OrderController.book.form({
  316. slug: store.slug,
  317. order: order.id,
  318. })}
  319. options={{ preserveScroll: true }}
  320. className="space-y-4 border-t pt-4"
  321. >
  322. {({ processing, errors }) => (
  323. <>
  324. <input
  325. type="hidden"
  326. name="service_id"
  327. value={picked.service_id}
  328. />
  329. <input
  330. type="hidden"
  331. name="courier"
  332. value={picked.courier}
  333. />
  334. {Object.entries(parcel).map(([key, value]) => (
  335. <input
  336. key={key}
  337. type="hidden"
  338. name={key}
  339. value={value}
  340. />
  341. ))}
  342. <div className="grid gap-1.5 sm:max-w-56">
  343. <Label htmlFor="collection_date">
  344. {picked.pickup
  345. ? 'Collection day'
  346. : 'Day you drop it off'}
  347. </Label>
  348. <Input
  349. id="collection_date"
  350. name="collection_date"
  351. type="date"
  352. min={easyparcel.collection_date}
  353. defaultValue={
  354. easyparcel.collection_date
  355. }
  356. required
  357. />
  358. <InputError
  359. message={errors.collection_date}
  360. />
  361. </div>
  362. <InputError
  363. message={
  364. errors.booking ??
  365. errors.service_id ??
  366. errors.weight ??
  367. errors.length ??
  368. errors.width ??
  369. errors.height
  370. }
  371. />
  372. <Button
  373. disabled={processing}
  374. data-test="book-courier-button"
  375. >
  376. {processing && <Spinner />}
  377. Book {picked.courier} for{' '}
  378. {formatRinggit(picked.price)}
  379. </Button>
  380. </>
  381. )}
  382. </Form>
  383. )}
  384. </CardContent>
  385. </Card>
  386. );
  387. }
  388. function BookedCourier({
  389. store,
  390. order,
  391. }: {
  392. store: StoreSummary;
  393. order: Order;
  394. }) {
  395. const shipment = order.shipment!;
  396. return (
  397. <Card data-test="courier-booked">
  398. <CardHeader>
  399. <CardTitle className="flex items-center gap-2">
  400. <Truck className="size-5" />
  401. Courier booked
  402. </CardTitle>
  403. <CardDescription>
  404. {order.shipping_courier} · EasyParcel {shipment.number}
  405. {shipment.cost !== null &&
  406. ` · Paid ${formatRinggit(shipment.cost)}`}
  407. </CardDescription>
  408. </CardHeader>
  409. <CardContent className="space-y-4 text-sm">
  410. {order.tracking_number ? (
  411. <p>
  412. Tracking number{' '}
  413. <span className="font-medium tabular-nums">
  414. {order.tracking_number}
  415. </span>
  416. {order.shipped_at &&
  417. '. The customer was emailed this number.'}
  418. </p>
  419. ) : (
  420. <p className="text-muted-foreground">
  421. The courier is preparing the label. It usually takes a
  422. minute or two.
  423. </p>
  424. )}
  425. <div className="flex flex-wrap gap-2">
  426. {shipment.label_url && (
  427. <Button asChild>
  428. <a
  429. href={shipment.label_url}
  430. target="_blank"
  431. rel="noreferrer"
  432. data-test="print-label"
  433. >
  434. <Printer />
  435. Print label
  436. </a>
  437. </Button>
  438. )}
  439. {shipment.tracking_url && (
  440. <Button variant="outline" asChild>
  441. <a
  442. href={shipment.tracking_url}
  443. target="_blank"
  444. rel="noreferrer"
  445. >
  446. <ExternalLink />
  447. Track parcel
  448. </a>
  449. </Button>
  450. )}
  451. {(!shipment.label_url || !order.tracking_number) && (
  452. <Form
  453. {...OrderController.refreshLabel.form({
  454. slug: store.slug,
  455. order: order.id,
  456. })}
  457. options={{ preserveScroll: true }}
  458. >
  459. {({ processing, errors }) => (
  460. <>
  461. <Button
  462. variant="outline"
  463. disabled={processing}
  464. data-test="refresh-label"
  465. >
  466. <RefreshCw
  467. className={cn(
  468. processing && 'animate-spin',
  469. )}
  470. />
  471. Check for the label
  472. </Button>
  473. <InputError
  474. className="mt-2"
  475. message={errors.booking}
  476. />
  477. </>
  478. )}
  479. </Form>
  480. )}
  481. </div>
  482. {shipment.label_url && (
  483. <p className="text-xs text-muted-foreground">
  484. Print the label, stick it on the parcel, and hand it to
  485. the courier (or drop it off at a counter).
  486. </p>
  487. )}
  488. </CardContent>
  489. </Card>
  490. );
  491. }