| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218 |
- 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 { BundleChoice, Product } from '@/types';
-
- type Row = { item: string; quantity: string };
-
- const MAX_ITEMS = 10;
-
- const selectClass =
- 'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 md:text-sm';
-
- /**
- * A bundle: other products of the store sold together at one price.
- * Its stock is not typed in; it follows the stock of what is inside.
- * The inputs carry the names the server reads: is_bundle, bundle_items[i][item] and bundle_items[i][quantity].
- */
- export default function BundleEditor({
- product,
- choices,
- enabled,
- onEnabledChange,
- errors,
- }: {
- product?: Product;
- choices: BundleChoice[];
- enabled: boolean;
- onEnabledChange: (enabled: boolean) => void;
- errors: Record<string, string>;
- }) {
- const [rows, setRows] = useState<Row[]>(
- product && product.bundle_items.length > 0
- ? product.bundle_items.map((row) => ({
- item: row.item,
- quantity: String(row.quantity),
- }))
- : [{ item: '', quantity: '1' }],
- );
-
- const byKey = new Map(choices.map((choice) => [choice.key, choice]));
- const filled = rows
- .map((row) => ({
- choice: byKey.get(row.item),
- quantity: Math.max(1, Number(row.quantity) || 1),
- }))
- .filter((row) => row.choice !== undefined);
-
- // What the items cost bought one by one, and how many bundles their stock allows.
- const separately = filled.reduce(
- (sum, row) => sum + Number(row.choice!.price) * row.quantity,
- 0,
- );
- const stock =
- filled.length > 0
- ? Math.min(
- ...filled.map((row) =>
- Math.floor(row.choice!.stock / row.quantity),
- ),
- )
- : 0;
-
- function setRow(index: number, field: keyof Row, value: string) {
- setRows((current) =>
- current.map((row, i) =>
- i === index ? { ...row, [field]: value } : row,
- ),
- );
- }
-
- const rowErrors = (index: number) =>
- errors[`bundle_items.${index}.item`] ??
- errors[`bundle_items.${index}.quantity`];
-
- return (
- <div className="space-y-4 rounded-xl border p-4">
- <div className="flex items-start gap-3">
- <Checkbox
- id="is-bundle"
- className="mt-0.5"
- checked={enabled}
- onCheckedChange={(checked) =>
- onEnabledChange(checked === true)
- }
- />
- <div>
- <Label htmlFor="is-bundle">This is a bundle</Label>
- <p className="mt-0.5 text-sm text-muted-foreground">
- Sell some of your products together at one price. The
- stock follows the products inside.
- </p>
- </div>
- </div>
-
- {enabled && (
- <>
- <input type="hidden" name="is_bundle" value="1" />
-
- {choices.length === 0 ? (
- <p className="text-sm text-muted-foreground">
- Add the products that go inside first. Then come
- back to make the bundle.
- </p>
- ) : (
- <div className="space-y-3">
- <p className="text-sm font-medium">
- What is inside
- </p>
-
- {rows.map((row, index) => (
- <div key={index} className="space-y-1">
- <div className="flex items-center gap-2">
- <select
- name={`bundle_items[${index}][item]`}
- aria-label={`Product ${index + 1}`}
- value={row.item}
- onChange={(event) =>
- setRow(
- index,
- 'item',
- event.target.value,
- )
- }
- className={selectClass}
- >
- <option value="">
- Choose a product
- </option>
- {choices.map((choice) => (
- <option
- key={choice.key}
- value={choice.key}
- >
- {choice.label} · RM{' '}
- {choice.price} ·{' '}
- {choice.stock} in stock
- </option>
- ))}
- </select>
- <span className="text-sm text-muted-foreground">
- ×
- </span>
- <Input
- name={`bundle_items[${index}][quantity]`}
- aria-label={`How many of product ${index + 1}`}
- type="number"
- min={1}
- max={20}
- step={1}
- className="w-20"
- value={row.quantity}
- onChange={(event) =>
- setRow(
- index,
- 'quantity',
- event.target.value,
- )
- }
- />
- <Button
- type="button"
- variant="ghost"
- size="icon"
- aria-label={`Remove product ${index + 1}`}
- disabled={rows.length === 1}
- onClick={() =>
- setRows((current) =>
- current.filter(
- (_, i) => i !== index,
- ),
- )
- }
- >
- <X />
- </Button>
- </div>
- <InputError message={rowErrors(index)} />
- </div>
- ))}
-
- {rows.length < MAX_ITEMS && (
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() =>
- setRows((current) => [
- ...current,
- { item: '', quantity: '1' },
- ])
- }
- >
- <Plus />
- Add a product
- </Button>
- )}
-
- {filled.length > 0 && (
- <p className="text-sm text-muted-foreground tabular-nums">
- Bought one by one: RM{' '}
- {separately.toFixed(2)} · Bundles you can
- sell now: {stock}
- </p>
- )}
- </div>
- )}
-
- <InputError
- message={errors.bundle_items ?? errors.is_bundle}
- />
- </>
- )}
- </div>
- );
- }
|