import { ProductSelector } from '@components/admin/ProductSelector.js'; import { NumberField } from '@components/common/form/NumberField.js'; import { Button } from '@components/common/ui/Button.js'; import { Dialog, DialogContent, DialogHeader, DialogTrigger, DialogTitle } from '@components/common/ui/Dialog.js'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@components/common/ui/Table.js'; import { _ } from '@evershop/evershop/lib/locale/translate/_'; import React, { useEffect } from 'react'; import { useFieldArray, useFormContext } from 'react-hook-form'; interface Product { sku: string; buyQty: string | number; getQty: string | number; maxY: string | number; discount: string | number; } const SkuSelector: React.FC<{ product: Product; updateProduct: (product: Product) => void; }> = ({ product, updateProduct }) => { const onSelect = (sku) => { updateProduct({ ...product, sku }); }; return ( {_('Choose Product SKU')} ({ sku: p.sku, uuid: undefined, productId: undefined }))} onSelect={onSelect} onUnSelect={() => {}} /> ); }; interface Field { sku: string; buyQty: number; getQty: number; maxY: number; discount: number; } interface BuyXGetY { buyx_gety: Field[]; } const BuyXGetYList: React.FC<{ requireProducts: Array; }> = ({ requireProducts }) => { const { unregister } = useFormContext(); const { fields, append, remove, update, replace } = useFieldArray({ name: 'buyx_gety' }); useEffect(() => { replace( requireProducts.map( (product) => ({ sku: product.sku, buyQty: typeof product.buyQty === 'string' ? parseInt(product.buyQty) || 1 : product.buyQty, getQty: typeof product.getQty === 'string' ? parseInt(product.getQty) || 1 : product.getQty, maxY: typeof product.maxY === 'string' ? parseInt(product.maxY) || 2 : product.maxY, discount: typeof product.discount === 'string' ? parseInt(product.discount) || 100 : product.discount } as Field) ) ); return () => { unregister('buyx_gety'); // Cleanup: unregister field when component unmounts }; }, []); return (
{_('SKU')} {_('X')} {_('Y')} {_('Max of Y')} {_('Discount percent')} {fields.map((p, i) => ( { update(i, { ...p, sku: product.sku }); }} /> { e.preventDefault(); remove(i); }} > ))}
{ e.preventDefault(); append({ sku: '', buyQty: 1, getQty: 1, maxY: 2, discount: 100 } as Field); }} > {_('Add product')}
); }; const BuyXGetY: React.FC<{ requireProducts: Array; discountType: string; }> = ({ requireProducts }) => { const { watch } = useFormContext(); const watchDiscountType = watch('discount_type'); if (watchDiscountType !== 'buy_x_get_y') { return null; } return ; }; export { BuyXGetY };