| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389 |
- import { Plus, X } from 'lucide-react';
- import { useState } from 'react';
- import InputError from '@/components/input-error';
- import { Button } from '@/components/ui/button';
- import { Checkbox } from '@/components/ui/checkbox';
- import { Input } from '@/components/ui/input';
- import { Label } from '@/components/ui/label';
- import type { Product, ProductVariantRow } from '@/types';
-
- type OptionInput = { name: string; values: string };
- type Prices = { price: string; compare_at_price: string; stock: string };
-
- const MAX_OPTIONS = 2;
-
- /** "250g, 500g, 250g" becomes ["250g", "500g"]. */
- function choices(line: string): string[] {
- const seen = new Set<string>();
-
- return line
- .split(',')
- .map((value) => value.trim())
- .filter((value) => {
- const key = value.toLowerCase();
-
- if (value === '' || seen.has(key)) {
- return false;
- }
-
- seen.add(key);
-
- return true;
- });
- }
-
- function comboKey(first: string, second: string | null): string {
- return `${first.toLowerCase()}|${(second ?? '').toLowerCase()}`;
- }
-
- /**
- * Options such as Size and Flavour, and a price and stock for every combination of their choices.
- * The inputs carry the names the server reads: options[i][name], variants[j][price] and so on.
- */
- export default function VariantEditor({
- product,
- enabled,
- onEnabledChange,
- errors,
- }: {
- product?: Product;
- enabled: boolean;
- onEnabledChange: (enabled: boolean) => void;
- errors: Record<string, string>;
- }) {
- const [options, setOptions] = useState<OptionInput[]>(
- product && product.options.length > 0
- ? product.options
- : [{ name: '', values: '' }],
- );
- const [prices, setPrices] = useState<Record<string, Prices>>(() =>
- Object.fromEntries(
- (product?.variants ?? []).map((row: ProductVariantRow) => [
- comboKey(row.option1, row.option2),
- {
- price: row.price,
- compare_at_price: row.compare_at_price ?? '',
- stock: String(row.stock),
- },
- ]),
- ),
- );
-
- const first = choices(options[0]?.values ?? '');
- const second = options[1] ? choices(options[1].values) : [];
- const combinations: [string, string | null][] = first.flatMap((a) =>
- second.length > 0
- ? second.map((b): [string, string | null] => [a, b])
- : [[a, null]],
- );
-
- function setOption(index: number, field: keyof OptionInput, value: string) {
- setOptions((current) =>
- current.map((option, i) =>
- i === index ? { ...option, [field]: value } : option,
- ),
- );
- }
-
- function setPrice(key: string, field: keyof Prices, value: string) {
- const empty: Prices = { price: '', compare_at_price: '', stock: '0' };
-
- setPrices((current) => ({
- ...current,
- [key]: { ...(current[key] ?? empty), [field]: value },
- }));
- }
-
- /** Copy the first row's price and stock to every row. */
- function fillAll() {
- const firstKey = combinations[0]
- ? comboKey(combinations[0][0], combinations[0][1])
- : null;
- const source = firstKey ? prices[firstKey] : undefined;
-
- if (!source) {
- return;
- }
-
- setPrices((current) => {
- const next = { ...current };
-
- for (const [a, b] of combinations) {
- next[comboKey(a, b)] = { ...source };
- }
-
- return next;
- });
- }
-
- const optionErrors = Object.entries(errors)
- .filter(([key]) => key === 'options' || key.startsWith('options.'))
- .map(([, message]) => message);
- const variantErrors = [
- ...new Set(
- Object.entries(errors)
- .filter(
- ([key]) =>
- key === 'variants' || key.startsWith('variants.'),
- )
- .map(([, message]) => message),
- ),
- ];
-
- return (
- <div className="space-y-4 rounded-xl border p-4">
- <div className="flex items-start gap-3">
- <Checkbox
- id="has-options"
- className="mt-0.5"
- checked={enabled}
- onCheckedChange={(checked) =>
- onEnabledChange(checked === true)
- }
- />
- <div>
- <Label htmlFor="has-options">
- This product has options
- </Label>
- <p className="mt-0.5 text-sm text-muted-foreground">
- Such as sizes, colours or flavours, each with its own
- price and stock.
- </p>
- </div>
- </div>
-
- {enabled && (
- <>
- <div className="space-y-3">
- {options.map((option, index) => (
- <div
- key={index}
- className="grid gap-3 sm:grid-cols-[180px_1fr_auto] sm:items-start"
- >
- <div className="grid gap-1.5">
- <Label htmlFor={`option-name-${index}`}>
- Option {index + 1}
- </Label>
- <Input
- id={`option-name-${index}`}
- name={`options[${index}][name]`}
- maxLength={30}
- value={option.name}
- onChange={(event) =>
- setOption(
- index,
- 'name',
- event.target.value,
- )
- }
- placeholder={
- index === 0 ? 'Size' : 'Flavour'
- }
- />
- </div>
- <div className="grid gap-1.5">
- <Label htmlFor={`option-values-${index}`}>
- Choices, separated by commas
- </Label>
- <Input
- id={`option-values-${index}`}
- name={`options[${index}][values]`}
- value={option.values}
- onChange={(event) =>
- setOption(
- index,
- 'values',
- event.target.value,
- )
- }
- placeholder={
- index === 0
- ? '250g, 500g'
- : 'Original, Pedas'
- }
- />
- </div>
- {index > 0 && (
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="sm:mt-6"
- aria-label={`Remove option ${index + 1}`}
- onClick={() =>
- setOptions((current) =>
- current.filter(
- (_, i) => i !== index,
- ),
- )
- }
- >
- <X />
- </Button>
- )}
- </div>
- ))}
-
- {options.length < MAX_OPTIONS && (
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() =>
- setOptions((current) => [
- ...current,
- { name: '', values: '' },
- ])
- }
- >
- <Plus />
- Add a second option
- </Button>
- )}
-
- {optionErrors.map((message) => (
- <InputError key={message} message={message} />
- ))}
- </div>
-
- {combinations.length > 0 && (
- <div className="space-y-2">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <p className="text-sm font-medium">
- Price and stock for each choice (
- {combinations.length})
- </p>
- {combinations.length > 1 && (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={fillAll}
- >
- Copy first row to all
- </Button>
- )}
- </div>
-
- <div className="overflow-x-auto rounded-md border">
- <table className="w-full text-sm">
- <thead className="bg-muted/40 text-left text-muted-foreground">
- <tr>
- <th className="px-3 py-2 font-medium">
- Choice
- </th>
- <th className="px-3 py-2 font-medium">
- Price (RM)
- </th>
- <th className="px-3 py-2 font-medium">
- Before discount
- </th>
- <th className="px-3 py-2 font-medium">
- Stock
- </th>
- </tr>
- </thead>
- <tbody className="divide-y">
- {combinations.map(([a, b], row) => {
- const key = comboKey(a, b);
- const value = prices[key];
- const label = b ? `${a} / ${b}` : a;
-
- return (
- <tr key={key}>
- <td className="px-3 py-2 whitespace-nowrap">
- {label}
- <input
- type="hidden"
- name={`variants[${row}][option1]`}
- value={a}
- />
- {b && (
- <input
- type="hidden"
- name={`variants[${row}][option2]`}
- value={b}
- />
- )}
- </td>
- <td className="px-3 py-1.5">
- <Input
- name={`variants[${row}][price]`}
- aria-label={`Price for ${label}`}
- inputMode="decimal"
- className="h-8 min-w-24"
- value={
- value?.price ??
- ''
- }
- onChange={(event) =>
- setPrice(
- key,
- 'price',
- event.target
- .value,
- )
- }
- placeholder="12.90"
- />
- </td>
- <td className="px-3 py-1.5">
- <Input
- name={`variants[${row}][compare_at_price]`}
- aria-label={`Price before discount for ${label}`}
- inputMode="decimal"
- className="h-8 min-w-24"
- value={
- value?.compare_at_price ??
- ''
- }
- onChange={(event) =>
- setPrice(
- key,
- 'compare_at_price',
- event.target
- .value,
- )
- }
- placeholder="Optional"
- />
- </td>
- <td className="px-3 py-1.5">
- <Input
- name={`variants[${row}][stock]`}
- aria-label={`Stock for ${label}`}
- type="number"
- min={0}
- step={1}
- className="h-8 min-w-20"
- value={
- value?.stock ??
- '0'
- }
- onChange={(event) =>
- setPrice(
- key,
- 'stock',
- event.target
- .value,
- )
- }
- />
- </td>
- </tr>
- );
- })}
- </tbody>
- </table>
- </div>
-
- {variantErrors.map((message) => (
- <InputError key={message} message={message} />
- ))}
- </div>
- )}
- </>
- )}
- </div>
- );
- }
|