import { createColumnHelper } from "@tanstack/react-table" import React, { ChangeEvent, useCallback, useMemo } from "react" import { Controller, useWatch } from "react-hook-form" import { useTranslation } from "react-i18next" import CopyToClipboard from "../../../../components/atoms/copy-to-clipboard" import Thumbnail from "../../../../components/atoms/thumbnail" import IndeterminateCheckbox from "../../../../components/molecules/indeterminate-checkbox" import { NestedForm } from "../../../../utils/nested-form" import { formatAmountWithSymbol } from "../../../../utils/prices" import TableQuantitySelector from "../table-quantity-selector" import { ItemsToReceiveFormType, ReceiveReturnObject, } from "./items-to-receive-form" const columnHelper = createColumnHelper() type Props = { form: NestedForm orderCurrency: string } export const useItemsToReceiveColumns = ({ form, orderCurrency }: Props) => { const { t } = useTranslation() const { control, setValue, getValues, path } = form const updateQuantity = useCallback( (index: number, change: number) => { const pathToQuantity = path(`items.${index}.quantity`) const selectedQuantity = getValues(pathToQuantity) setValue(pathToQuantity, selectedQuantity + change) }, [getValues, path, setValue] ) const items = useWatch({ control, name: path("items"), }) const toggleAllRowsSelected = useCallback( (e: ChangeEvent) => { items.forEach((_item, index) => { setValue(path(`items.${index}.receive`), e.target.checked, { shouldDirty: true, }) }) }, [items, path, setValue] ) const colums = useMemo( () => [ columnHelper.display({ id: "selection", maxSize: 36, header: ({ table }) => { return (
{ table.toggleAllRowsSelected(e.target.checked) toggleAllRowsSelected(e) }} indeterminate={table.getIsSomeRowsSelected()} />
) }, cell: ({ row: { index, getToggleSelectedHandler } }) => { return ( { return (
) => { getToggleSelectedHandler()(v) onChange(v) }} />
) }} /> ) }, }), columnHelper.accessor("variant_title", { header: t("items-to-receive-form-product", "Product"), cell: ({ getValue, row: { original } }) => { const value = getValue() return (

{original.product_title}

{value &&

({value})

}
{original.sku && ( )}
) }, }), columnHelper.display({ id: "quantity", header: () => (

{t("items-to-receive-form-quantity", "Quantity")}

), maxSize: 50, cell: ({ row: { index, original: { original_quantity }, }, }) => { return ( ) }, }), columnHelper.accessor("refundable", { maxSize: 80, header: () => (

{t("items-to-receive-form-refundable", "Refundable")}

), cell: ({ getValue }) => { return (

{formatAmountWithSymbol({ amount: getValue() || 0, currency: orderCurrency, })}

) }, }), columnHelper.display({ id: "order_currency", maxSize: 20, cell: () => { return (

{orderCurrency.toUpperCase()}

) }, }), ], [control, orderCurrency, path, toggleAllRowsSelected, updateQuantity] ) return colums }