AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

variant-editor.tsx 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. import { Plus, X } from 'lucide-react';
  2. import { useState } from 'react';
  3. import InputError from '@/components/input-error';
  4. import { Button } from '@/components/ui/button';
  5. import { Checkbox } from '@/components/ui/checkbox';
  6. import { Input } from '@/components/ui/input';
  7. import { Label } from '@/components/ui/label';
  8. import type { Product, ProductVariantRow } from '@/types';
  9. type OptionInput = { name: string; values: string };
  10. type Prices = { price: string; compare_at_price: string; stock: string };
  11. const MAX_OPTIONS = 2;
  12. /** "250g, 500g, 250g" becomes ["250g", "500g"]. */
  13. function choices(line: string): string[] {
  14. const seen = new Set<string>();
  15. return line
  16. .split(',')
  17. .map((value) => value.trim())
  18. .filter((value) => {
  19. const key = value.toLowerCase();
  20. if (value === '' || seen.has(key)) {
  21. return false;
  22. }
  23. seen.add(key);
  24. return true;
  25. });
  26. }
  27. function comboKey(first: string, second: string | null): string {
  28. return `${first.toLowerCase()}|${(second ?? '').toLowerCase()}`;
  29. }
  30. /**
  31. * Options such as Size and Flavour, and a price and stock for every combination of their choices.
  32. * The inputs carry the names the server reads: options[i][name], variants[j][price] and so on.
  33. */
  34. export default function VariantEditor({
  35. product,
  36. enabled,
  37. onEnabledChange,
  38. errors,
  39. }: {
  40. product?: Product;
  41. enabled: boolean;
  42. onEnabledChange: (enabled: boolean) => void;
  43. errors: Record<string, string>;
  44. }) {
  45. const [options, setOptions] = useState<OptionInput[]>(
  46. product && product.options.length > 0
  47. ? product.options
  48. : [{ name: '', values: '' }],
  49. );
  50. const [prices, setPrices] = useState<Record<string, Prices>>(() =>
  51. Object.fromEntries(
  52. (product?.variants ?? []).map((row: ProductVariantRow) => [
  53. comboKey(row.option1, row.option2),
  54. {
  55. price: row.price,
  56. compare_at_price: row.compare_at_price ?? '',
  57. stock: String(row.stock),
  58. },
  59. ]),
  60. ),
  61. );
  62. const first = choices(options[0]?.values ?? '');
  63. const second = options[1] ? choices(options[1].values) : [];
  64. const combinations: [string, string | null][] = first.flatMap((a) =>
  65. second.length > 0
  66. ? second.map((b): [string, string | null] => [a, b])
  67. : [[a, null]],
  68. );
  69. function setOption(index: number, field: keyof OptionInput, value: string) {
  70. setOptions((current) =>
  71. current.map((option, i) =>
  72. i === index ? { ...option, [field]: value } : option,
  73. ),
  74. );
  75. }
  76. function setPrice(key: string, field: keyof Prices, value: string) {
  77. const empty: Prices = { price: '', compare_at_price: '', stock: '0' };
  78. setPrices((current) => ({
  79. ...current,
  80. [key]: { ...(current[key] ?? empty), [field]: value },
  81. }));
  82. }
  83. /** Copy the first row's price and stock to every row. */
  84. function fillAll() {
  85. const firstKey = combinations[0]
  86. ? comboKey(combinations[0][0], combinations[0][1])
  87. : null;
  88. const source = firstKey ? prices[firstKey] : undefined;
  89. if (!source) {
  90. return;
  91. }
  92. setPrices((current) => {
  93. const next = { ...current };
  94. for (const [a, b] of combinations) {
  95. next[comboKey(a, b)] = { ...source };
  96. }
  97. return next;
  98. });
  99. }
  100. const optionErrors = Object.entries(errors)
  101. .filter(([key]) => key === 'options' || key.startsWith('options.'))
  102. .map(([, message]) => message);
  103. const variantErrors = [
  104. ...new Set(
  105. Object.entries(errors)
  106. .filter(
  107. ([key]) =>
  108. key === 'variants' || key.startsWith('variants.'),
  109. )
  110. .map(([, message]) => message),
  111. ),
  112. ];
  113. return (
  114. <div className="space-y-4 rounded-xl border p-4">
  115. <div className="flex items-start gap-3">
  116. <Checkbox
  117. id="has-options"
  118. className="mt-0.5"
  119. checked={enabled}
  120. onCheckedChange={(checked) =>
  121. onEnabledChange(checked === true)
  122. }
  123. />
  124. <div>
  125. <Label htmlFor="has-options">
  126. This product has options
  127. </Label>
  128. <p className="mt-0.5 text-sm text-muted-foreground">
  129. Such as sizes, colours or flavours, each with its own
  130. price and stock.
  131. </p>
  132. </div>
  133. </div>
  134. {enabled && (
  135. <>
  136. <div className="space-y-3">
  137. {options.map((option, index) => (
  138. <div
  139. key={index}
  140. className="grid gap-3 sm:grid-cols-[180px_1fr_auto] sm:items-start"
  141. >
  142. <div className="grid gap-1.5">
  143. <Label htmlFor={`option-name-${index}`}>
  144. Option {index + 1}
  145. </Label>
  146. <Input
  147. id={`option-name-${index}`}
  148. name={`options[${index}][name]`}
  149. maxLength={30}
  150. value={option.name}
  151. onChange={(event) =>
  152. setOption(
  153. index,
  154. 'name',
  155. event.target.value,
  156. )
  157. }
  158. placeholder={
  159. index === 0 ? 'Size' : 'Flavour'
  160. }
  161. />
  162. </div>
  163. <div className="grid gap-1.5">
  164. <Label htmlFor={`option-values-${index}`}>
  165. Choices, separated by commas
  166. </Label>
  167. <Input
  168. id={`option-values-${index}`}
  169. name={`options[${index}][values]`}
  170. value={option.values}
  171. onChange={(event) =>
  172. setOption(
  173. index,
  174. 'values',
  175. event.target.value,
  176. )
  177. }
  178. placeholder={
  179. index === 0
  180. ? '250g, 500g'
  181. : 'Original, Pedas'
  182. }
  183. />
  184. </div>
  185. {index > 0 && (
  186. <Button
  187. type="button"
  188. variant="ghost"
  189. size="icon"
  190. className="sm:mt-6"
  191. aria-label={`Remove option ${index + 1}`}
  192. onClick={() =>
  193. setOptions((current) =>
  194. current.filter(
  195. (_, i) => i !== index,
  196. ),
  197. )
  198. }
  199. >
  200. <X />
  201. </Button>
  202. )}
  203. </div>
  204. ))}
  205. {options.length < MAX_OPTIONS && (
  206. <Button
  207. type="button"
  208. variant="outline"
  209. size="sm"
  210. onClick={() =>
  211. setOptions((current) => [
  212. ...current,
  213. { name: '', values: '' },
  214. ])
  215. }
  216. >
  217. <Plus />
  218. Add a second option
  219. </Button>
  220. )}
  221. {optionErrors.map((message) => (
  222. <InputError key={message} message={message} />
  223. ))}
  224. </div>
  225. {combinations.length > 0 && (
  226. <div className="space-y-2">
  227. <div className="flex flex-wrap items-center justify-between gap-2">
  228. <p className="text-sm font-medium">
  229. Price and stock for each choice (
  230. {combinations.length})
  231. </p>
  232. {combinations.length > 1 && (
  233. <Button
  234. type="button"
  235. variant="ghost"
  236. size="sm"
  237. onClick={fillAll}
  238. >
  239. Copy first row to all
  240. </Button>
  241. )}
  242. </div>
  243. <div className="overflow-x-auto rounded-md border">
  244. <table className="w-full text-sm">
  245. <thead className="bg-muted/40 text-left text-muted-foreground">
  246. <tr>
  247. <th className="px-3 py-2 font-medium">
  248. Choice
  249. </th>
  250. <th className="px-3 py-2 font-medium">
  251. Price (RM)
  252. </th>
  253. <th className="px-3 py-2 font-medium">
  254. Before discount
  255. </th>
  256. <th className="px-3 py-2 font-medium">
  257. Stock
  258. </th>
  259. </tr>
  260. </thead>
  261. <tbody className="divide-y">
  262. {combinations.map(([a, b], row) => {
  263. const key = comboKey(a, b);
  264. const value = prices[key];
  265. const label = b ? `${a} / ${b}` : a;
  266. return (
  267. <tr key={key}>
  268. <td className="px-3 py-2 whitespace-nowrap">
  269. {label}
  270. <input
  271. type="hidden"
  272. name={`variants[${row}][option1]`}
  273. value={a}
  274. />
  275. {b && (
  276. <input
  277. type="hidden"
  278. name={`variants[${row}][option2]`}
  279. value={b}
  280. />
  281. )}
  282. </td>
  283. <td className="px-3 py-1.5">
  284. <Input
  285. name={`variants[${row}][price]`}
  286. aria-label={`Price for ${label}`}
  287. inputMode="decimal"
  288. className="h-8 min-w-24"
  289. value={
  290. value?.price ??
  291. ''
  292. }
  293. onChange={(event) =>
  294. setPrice(
  295. key,
  296. 'price',
  297. event.target
  298. .value,
  299. )
  300. }
  301. placeholder="12.90"
  302. />
  303. </td>
  304. <td className="px-3 py-1.5">
  305. <Input
  306. name={`variants[${row}][compare_at_price]`}
  307. aria-label={`Price before discount for ${label}`}
  308. inputMode="decimal"
  309. className="h-8 min-w-24"
  310. value={
  311. value?.compare_at_price ??
  312. ''
  313. }
  314. onChange={(event) =>
  315. setPrice(
  316. key,
  317. 'compare_at_price',
  318. event.target
  319. .value,
  320. )
  321. }
  322. placeholder="Optional"
  323. />
  324. </td>
  325. <td className="px-3 py-1.5">
  326. <Input
  327. name={`variants[${row}][stock]`}
  328. aria-label={`Stock for ${label}`}
  329. type="number"
  330. min={0}
  331. step={1}
  332. className="h-8 min-w-20"
  333. value={
  334. value?.stock ??
  335. '0'
  336. }
  337. onChange={(event) =>
  338. setPrice(
  339. key,
  340. 'stock',
  341. event.target
  342. .value,
  343. )
  344. }
  345. />
  346. </td>
  347. </tr>
  348. );
  349. })}
  350. </tbody>
  351. </table>
  352. </div>
  353. {variantErrors.map((message) => (
  354. <InputError key={message} message={message} />
  355. ))}
  356. </div>
  357. )}
  358. </>
  359. )}
  360. </div>
  361. );
  362. }