AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

checkout.tsx 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import { useForm } from '@inertiajs/react';
  2. import type { FormEvent, ReactNode } from 'react';
  3. import { useStorefront } from '../context';
  4. import { storefrontText } from '../text';
  5. import { formatPrice } from '../theme';
  6. import type { PayWay } from '../types';
  7. import { Container, SfLink } from '../ui';
  8. const inputClass =
  9. 'w-full rounded-(--sf-radius) border border-(--sf-border) bg-(--sf-bg) px-3 py-2.5 text-base text-(--sf-fg) outline-none focus-visible:border-(--sf-primary) focus-visible:ring-2 focus-visible:ring-(--sf-primary)/30';
  10. function Field({
  11. id,
  12. label,
  13. error,
  14. children,
  15. }: {
  16. id: string;
  17. label: string;
  18. error?: string;
  19. children: ReactNode;
  20. }) {
  21. return (
  22. <div className="grid gap-1.5">
  23. <label htmlFor={id} className="text-sm font-medium">
  24. {label}
  25. </label>
  26. {children}
  27. {error && (
  28. <p id={`${id}-error`} className="text-sm text-red-700">
  29. {error}
  30. </p>
  31. )}
  32. </div>
  33. );
  34. }
  35. /** The name shoppers see for a payment provider's page. */
  36. function providerName(key: string): string {
  37. return key === 'hitpay' ? 'HitPay' : 'Stripe';
  38. }
  39. /** The shopper's details and address, before going to the payment page. */
  40. export function CheckoutPage({
  41. states,
  42. shippingByState,
  43. takingOrders,
  44. payWays,
  45. }: {
  46. states: string[];
  47. shippingByState: Record<string, number>;
  48. takingOrders: boolean;
  49. payWays: PayWay[];
  50. }) {
  51. const { cart, language, baseUrl } = useStorefront();
  52. const t = storefrontText(language);
  53. const form = useForm({
  54. name: '',
  55. email: '',
  56. phone: '',
  57. line1: '',
  58. line2: '',
  59. city: '',
  60. postcode: '',
  61. state: '',
  62. pay_with: payWays[0]?.key ?? '',
  63. });
  64. // "cart" errors come from the server: an empty cart, or the payment page could not be opened.
  65. const errors = form.errors as typeof form.errors & { cart?: string };
  66. const shipping = form.data.state
  67. ? (shippingByState[form.data.state] ?? null)
  68. : null;
  69. function submit(event: FormEvent) {
  70. event.preventDefault();
  71. form.post(`${baseUrl}/checkout`, { preserveScroll: true });
  72. }
  73. /** "Card, FPX online banking or GrabPay". */
  74. function methodList(way: PayWay): string {
  75. const names = way.methods.map((method) => t.payMethods[method]);
  76. return names.length > 1
  77. ? `${names.slice(0, -1).join(', ')} ${t.or} ${names[names.length - 1]}`
  78. : (names[0] ?? '');
  79. }
  80. function text(
  81. name: Exclude<keyof typeof form.data, 'pay_with'>,
  82. label: string,
  83. props: React.InputHTMLAttributes<HTMLInputElement> = {},
  84. ) {
  85. return (
  86. <Field id={name} label={label} error={form.errors[name]}>
  87. <input
  88. id={name}
  89. name={name}
  90. value={form.data[name]}
  91. onChange={(event) => form.setData(name, event.target.value)}
  92. aria-invalid={form.errors[name] ? true : undefined}
  93. aria-describedby={
  94. form.errors[name] ? `${name}-error` : undefined
  95. }
  96. className={inputClass}
  97. {...props}
  98. />
  99. </Field>
  100. );
  101. }
  102. return (
  103. <main className="py-10 md:py-14">
  104. <Container>
  105. <SfLink
  106. href="/cart"
  107. className="text-sm text-(--sf-muted) transition-colors hover:text-(--sf-fg)"
  108. >
  109. ← {t.backToCart}
  110. </SfLink>
  111. <h1 className="sf-heading mt-4 text-4xl font-semibold sm:text-5xl">
  112. {t.checkout}
  113. </h1>
  114. <div className="mt-10 grid gap-10 lg:grid-cols-[1fr_360px] lg:gap-14">
  115. <form onSubmit={submit} className="space-y-10" noValidate>
  116. {!takingOrders && !errors.cart && (
  117. <p
  118. role="status"
  119. data-test="not-taking-orders"
  120. className="rounded-(--sf-radius-card) border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900"
  121. >
  122. {t.notTakingOrders}
  123. </p>
  124. )}
  125. {errors.cart && (
  126. <p
  127. role="alert"
  128. className="rounded-(--sf-radius-card) border border-red-300 bg-red-50 p-4 text-sm text-red-800"
  129. >
  130. {errors.cart}
  131. </p>
  132. )}
  133. <fieldset className="space-y-5">
  134. <legend className="sf-heading text-xl font-semibold">
  135. {t.contactDetails}
  136. </legend>
  137. {text('name', t.fullName, {
  138. autoComplete: 'name',
  139. required: true,
  140. })}
  141. <div className="grid gap-5 sm:grid-cols-2">
  142. {text('email', t.email, {
  143. type: 'email',
  144. autoComplete: 'email',
  145. required: true,
  146. })}
  147. {text('phone', t.phone, {
  148. type: 'tel',
  149. autoComplete: 'tel',
  150. required: true,
  151. })}
  152. </div>
  153. </fieldset>
  154. <fieldset className="space-y-5">
  155. <legend className="sf-heading text-xl font-semibold">
  156. {t.deliveryAddress}
  157. </legend>
  158. {text('line1', t.addressLine1, {
  159. autoComplete: 'address-line1',
  160. required: true,
  161. })}
  162. {text('line2', t.addressLine2, {
  163. autoComplete: 'address-line2',
  164. })}
  165. <div className="grid gap-5 sm:grid-cols-3">
  166. {text('postcode', t.postcode, {
  167. inputMode: 'numeric',
  168. autoComplete: 'postal-code',
  169. maxLength: 5,
  170. required: true,
  171. })}
  172. {text('city', t.city, {
  173. autoComplete: 'address-level2',
  174. required: true,
  175. })}
  176. <Field
  177. id="state"
  178. label={t.state}
  179. error={form.errors.state}
  180. >
  181. <select
  182. id="state"
  183. name="state"
  184. value={form.data.state}
  185. onChange={(event) =>
  186. form.setData(
  187. 'state',
  188. event.target.value,
  189. )
  190. }
  191. autoComplete="address-level1"
  192. required
  193. aria-invalid={
  194. form.errors.state ? true : undefined
  195. }
  196. className={inputClass}
  197. >
  198. <option value="" disabled>
  199. {t.chooseState}
  200. </option>
  201. {states.map((state) => (
  202. <option key={state} value={state}>
  203. {state}
  204. </option>
  205. ))}
  206. </select>
  207. </Field>
  208. </div>
  209. </fieldset>
  210. {payWays.length > 1 && (
  211. <fieldset
  212. className="space-y-3"
  213. data-test="pay-ways"
  214. >
  215. <legend className="sf-heading mb-5 text-xl font-semibold">
  216. {t.howToPay}
  217. </legend>
  218. {payWays.map((way) => (
  219. <label
  220. key={way.key}
  221. className="flex cursor-pointer items-center gap-3 rounded-(--sf-radius) border border-(--sf-border) bg-(--sf-bg) p-4 has-checked:border-(--sf-primary) has-checked:ring-1 has-checked:ring-(--sf-primary)"
  222. >
  223. <input
  224. type="radio"
  225. name="pay_with"
  226. value={way.key}
  227. checked={
  228. form.data.pay_with === way.key
  229. }
  230. onChange={() =>
  231. form.setData(
  232. 'pay_with',
  233. way.key,
  234. )
  235. }
  236. className="size-4 shrink-0 appearance-none rounded-full border border-(--sf-muted) bg-(--sf-bg) checked:border-[5px] checked:border-(--sf-primary) focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary)"
  237. />
  238. <span className="text-sm font-medium">
  239. {methodList(way)}
  240. </span>
  241. </label>
  242. ))}
  243. </fieldset>
  244. )}
  245. <div>
  246. <button
  247. type="submit"
  248. disabled={form.processing || !takingOrders}
  249. className="sf-btn-primary inline-flex w-full items-center justify-center rounded-(--sf-radius) bg-(--sf-primary) px-6 py-3 text-sm font-semibold text-(--sf-primary-fg) transition-opacity hover:opacity-85 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary) disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
  250. >
  251. {t.payNow}
  252. </button>
  253. <p className="mt-2 text-xs text-(--sf-muted)">
  254. {t.paySecure(providerName(form.data.pay_with))}
  255. </p>
  256. </div>
  257. </form>
  258. <aside className="sf-card h-fit rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-surface) p-6">
  259. <h2 className="font-medium">{t.orderSummary}</h2>
  260. <ul className="mt-4 space-y-3 text-sm">
  261. {cart.lines.map((line) => (
  262. <li
  263. key={line.key}
  264. className="flex justify-between gap-4"
  265. >
  266. <span>
  267. {line.product.name}
  268. {line.variant &&
  269. ` (${line.variant.name})`}{' '}
  270. <span className="text-(--sf-muted)">
  271. × {line.quantity}
  272. </span>
  273. </span>
  274. <span className="tabular-nums">
  275. {formatPrice(line.line_total)}
  276. </span>
  277. </li>
  278. ))}
  279. </ul>
  280. <div className="mt-5 space-y-2 border-t border-(--sf-border) pt-4 text-sm">
  281. <div className="flex justify-between gap-4">
  282. <span>{t.subtotal}</span>
  283. <span className="tabular-nums">
  284. {formatPrice(cart.subtotal)}
  285. </span>
  286. </div>
  287. {cart.applied && (
  288. <div className="flex justify-between gap-4">
  289. <span>
  290. {t.discount} ({cart.applied.name})
  291. </span>
  292. <span className="tabular-nums">
  293. −{formatPrice(cart.applied.amount)}
  294. </span>
  295. </div>
  296. )}
  297. <div className="flex justify-between gap-4">
  298. <span>{t.shipping}</span>
  299. <span
  300. className="tabular-nums"
  301. aria-live="polite"
  302. >
  303. {shipping === null
  304. ? '—'
  305. : shipping === 0
  306. ? t.shippingFree
  307. : formatPrice(shipping)}
  308. </span>
  309. </div>
  310. {shipping === null && (
  311. <p className="text-xs text-(--sf-muted)">
  312. {t.chooseStateForShipping}
  313. </p>
  314. )}
  315. </div>
  316. <div className="mt-4 flex items-baseline justify-between gap-4 border-t border-(--sf-border) pt-4">
  317. <span className="font-medium">{t.total}</span>
  318. <span className="text-xl font-semibold tabular-nums">
  319. {formatPrice(cart.total + (shipping ?? 0))}
  320. </span>
  321. </div>
  322. </aside>
  323. </div>
  324. </Container>
  325. </main>
  326. );
  327. }