mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-24 15:25:46 +00:00
refactor(FE-177-166-167): separate table repeater component and adjust data types with new API Payload
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import * as Yup from 'yup';
|
||||
import {
|
||||
SalesOrderProductFormValues,
|
||||
SalesOrderProductSchema,
|
||||
} from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
|
||||
|
||||
type MarketingSchemaType = {
|
||||
customer_id: number | undefined;
|
||||
sales_person_id: number | undefined;
|
||||
customer:
|
||||
| {
|
||||
value: number;
|
||||
label: string;
|
||||
}
|
||||
| undefined
|
||||
| null;
|
||||
so_date: string | undefined;
|
||||
notes: string | undefined;
|
||||
};
|
||||
|
||||
type SalesOrderSchemaType = MarketingSchemaType & {
|
||||
sales_order: SalesOrderProductFormValues[];
|
||||
};
|
||||
|
||||
export const SalesOrderSchema: Yup.ObjectSchema<SalesOrderSchemaType> =
|
||||
Yup.object({
|
||||
customer_id: Yup.number().required('Customer wajib diisi!'),
|
||||
sales_person_id: Yup.number().required('Sales Person wajib diisi!'),
|
||||
customer: Yup.object({
|
||||
value: Yup.number().required(),
|
||||
label: Yup.string().required(),
|
||||
}).nullable(),
|
||||
so_date: Yup.string().required('Tanggal wajib diisi!'),
|
||||
notes: Yup.string().required('Catatan wajib diisi!'),
|
||||
sales_order: Yup.array()
|
||||
.of(SalesOrderProductSchema)
|
||||
.min(1, 'Produk wajib diisi!')
|
||||
.required('Produk wajib diisi!'),
|
||||
});
|
||||
|
||||
export const UpdateSalesOrderSchema = SalesOrderSchema;
|
||||
|
||||
export type SalesOrderFormValues = Yup.InferType<typeof SalesOrderSchema>;
|
||||
@@ -0,0 +1,417 @@
|
||||
'use client';
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import Card from '@/components/Card';
|
||||
import { FormHeader } from '@/components/helper/form/FormHeader';
|
||||
import DateInput from '@/components/input/DateInput';
|
||||
import SelectInput, {
|
||||
OptionType,
|
||||
useSelect,
|
||||
} from '@/components/input/SelectInput';
|
||||
import TextArea from '@/components/input/TextArea';
|
||||
import Modal, { useModal } from '@/components/Modal';
|
||||
import { formatCurrency, formatDate } from '@/lib/helper';
|
||||
import {
|
||||
BaseSalesOrder,
|
||||
CreateSalesOrderPayload,
|
||||
CreateSalesOrderProductPayload,
|
||||
Marketing,
|
||||
} from '@/types/api/marketing/marketing';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Customer } from '@/types/api/master-data/customer';
|
||||
import { CustomerApi } from '@/services/api/master-data';
|
||||
import { useFormik } from 'formik';
|
||||
import { SalesOrderFormValues, SalesOrderSchema } from './MarketingForm.schema';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
import { MarketingApi } from '@/services/api/marketing/marketing';
|
||||
import { SalesOrderProductFormValues } from './repeater/sales-order/SalesOrderProduct.schema';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import SalesOrderProductTable from './table-view/SalesOrderProductTable';
|
||||
import SalesOrderProductForm from './repeater/sales-order/SalesOrderProductForm';
|
||||
|
||||
const MarketingProductToFieldValues = (
|
||||
product: BaseSalesOrder
|
||||
): SalesOrderProductFormValues => {
|
||||
return {
|
||||
kandang_id: product.product_warehouse.warehouse.id,
|
||||
kandang: {
|
||||
value: product.product_warehouse.warehouse.id,
|
||||
label: product.product_warehouse.warehouse.name,
|
||||
},
|
||||
product_warehouse: {
|
||||
value: product.product_warehouse.id,
|
||||
label: product.product_warehouse.product.name,
|
||||
},
|
||||
product_warehouse_id: product.product_warehouse.id,
|
||||
unit_price: product.unit_price,
|
||||
total_weight: product.total_weight,
|
||||
qty: product.qty,
|
||||
avg_weight: product.avg_weight,
|
||||
total_price: product.total_price,
|
||||
};
|
||||
};
|
||||
|
||||
const SalesForm = ({
|
||||
formType = 'add',
|
||||
initialValues,
|
||||
afterSubmit,
|
||||
}: {
|
||||
formType?: 'add' | 'edit' | 'deliver';
|
||||
initialValues?: Marketing;
|
||||
afterSubmit?: () => void;
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
const addProductModal = useModal();
|
||||
const deleteModal = useModal();
|
||||
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedMarketingProduct, setSelectedMarketingProduct] =
|
||||
useState<SalesOrderProductFormValues | null>(null);
|
||||
const [rawMarketingProducts, setRawMarketingProducts] = useState<
|
||||
SalesOrderProductFormValues[]
|
||||
>(
|
||||
initialValues?.sales_order.map((item) =>
|
||||
MarketingProductToFieldValues(item)
|
||||
) || []
|
||||
);
|
||||
const [selectedCustomer, setSelectedCustomer] = useState<OptionType | null>(
|
||||
initialValues?.customer
|
||||
? { value: initialValues.customer.id, label: initialValues.customer.name }
|
||||
: null
|
||||
);
|
||||
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||
const selectedRowIds = Object.keys(rowSelection).map((item) =>
|
||||
parseInt(item)
|
||||
);
|
||||
const [grandTotal, setGrandTotal] = useState<number>(
|
||||
initialValues?.sales_order
|
||||
?.map((item) => item.total_price)
|
||||
.reduce((a, b) => a + b, 0) ?? 0
|
||||
);
|
||||
|
||||
const {
|
||||
options: customerOptions,
|
||||
isLoadingOptions: isLoadingCustomerOptions,
|
||||
} = useSelect<Customer>(CustomerApi.basePath, 'id', 'name');
|
||||
|
||||
const handleDeleteProduct = useCallback(
|
||||
(product_warehouse_id: number, kandang_id: number) => {
|
||||
setRawMarketingProducts((prev) =>
|
||||
prev.filter(
|
||||
(p) =>
|
||||
p.product_warehouse_id !== product_warehouse_id &&
|
||||
p.kandang_id !== kandang_id
|
||||
)
|
||||
);
|
||||
},
|
||||
[]
|
||||
);
|
||||
const handleBulkDeleteProduct = () => {
|
||||
setRawMarketingProducts((prev) =>
|
||||
prev.filter(
|
||||
(product) =>
|
||||
!selectedRowIds.includes(
|
||||
parseInt(`${product.product_warehouse_id}${product.kandang_id}`)
|
||||
)
|
||||
)
|
||||
);
|
||||
};
|
||||
const handleDelete = () => {
|
||||
deleteModal.openModal();
|
||||
};
|
||||
|
||||
const handleAddProductClick = useCallback(() => {
|
||||
setSelectedMarketingProduct(null); // Pastikan form tambah
|
||||
addProductModal.openModal();
|
||||
}, [addProductModal]);
|
||||
const handleAddSubmitProduct = useCallback(
|
||||
async (values: SalesOrderProductFormValues) => {
|
||||
setRawMarketingProducts((prev) => [...prev, values]);
|
||||
formik.setValues({
|
||||
...formik.values,
|
||||
sales_order: [...formik.values.sales_order, values],
|
||||
});
|
||||
setGrandTotal((prev) => prev + (values.total_price as number));
|
||||
addProductModal.closeModal();
|
||||
},
|
||||
[rawMarketingProducts.length, addProductModal]
|
||||
);
|
||||
const handleChangeCustomer = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
setSelectedCustomer(val as OptionType);
|
||||
formik.setFieldValue('customer_id', (val as OptionType)?.value);
|
||||
formik.setFieldValue('customer', val as OptionType);
|
||||
},
|
||||
[selectedCustomer, setSelectedCustomer]
|
||||
);
|
||||
|
||||
const createMarketingHandler = async (values: CreateSalesOrderPayload) => {
|
||||
console.log(values);
|
||||
const createMarketingRes = await MarketingApi.create(values);
|
||||
if (isResponseSuccess(createMarketingRes)) {
|
||||
toast.success(createMarketingRes?.message as string);
|
||||
router.push('/marketing/sales-orders');
|
||||
}
|
||||
if (isResponseError(createMarketingRes)) {
|
||||
toast.error(createMarketingRes?.message as string);
|
||||
}
|
||||
};
|
||||
const updateMarketingHandler = async (values: CreateSalesOrderPayload) => {
|
||||
console.log(values);
|
||||
const updateMarketingRes = await MarketingApi.update(
|
||||
initialValues?.id as number,
|
||||
values
|
||||
);
|
||||
if (isResponseSuccess(updateMarketingRes)) {
|
||||
toast.success(updateMarketingRes?.message as string);
|
||||
router.push('/marketing/sales-orders');
|
||||
}
|
||||
if (isResponseError(updateMarketingRes)) {
|
||||
toast.error(updateMarketingRes?.message as string);
|
||||
}
|
||||
};
|
||||
const deleteMarketingHandler = async () => {
|
||||
setIsLoading(true);
|
||||
console.log(initialValues?.id);
|
||||
const deleteMarketingRes = await MarketingApi.delete(
|
||||
initialValues?.id as number
|
||||
);
|
||||
if (isResponseSuccess(deleteMarketingRes)) {
|
||||
console.log(deleteMarketingRes);
|
||||
}
|
||||
if (isResponseError(deleteMarketingRes)) {
|
||||
console.log(deleteMarketingRes);
|
||||
}
|
||||
toast.success('Successfully deleted Sales Order!');
|
||||
setIsLoading(false);
|
||||
deleteModal.closeModal();
|
||||
router.push('/marketing/sales-orders');
|
||||
};
|
||||
|
||||
const formikInitialValues = useMemo(() => {
|
||||
return {
|
||||
so_date: initialValues?.so_date || undefined,
|
||||
notes: initialValues?.notes || undefined,
|
||||
customer_id: initialValues?.customer?.id || undefined,
|
||||
sales_person_id: initialValues?.sales_person?.id || 1,
|
||||
customer: {
|
||||
value: initialValues?.customer?.id as number,
|
||||
label: initialValues?.customer?.name as string,
|
||||
},
|
||||
sales_order:
|
||||
initialValues?.sales_order?.map((product) =>
|
||||
MarketingProductToFieldValues(product)
|
||||
) ?? [],
|
||||
};
|
||||
}, [initialValues]);
|
||||
|
||||
const formik = useFormik<SalesOrderFormValues>({
|
||||
enableReinitialize: true,
|
||||
initialValues: formikInitialValues,
|
||||
validationSchema: SalesOrderSchema,
|
||||
validateOnMount: true,
|
||||
onSubmit: async (values) => {
|
||||
const payload = {
|
||||
customer_id: values.customer_id as number,
|
||||
sales_person_id: values.sales_person_id as number,
|
||||
date: formatDate(values.so_date as string, 'yyyy-MM-DD'),
|
||||
notes: values.notes as string,
|
||||
marketing_products: values.sales_order.map((product) => {
|
||||
return {
|
||||
vehicle_number: 'D 1234 XXXX',
|
||||
kandang_id: product.kandang_id as number,
|
||||
product_warehouse_id: product.product_warehouse_id as number,
|
||||
unit_price: parseFloat(product.unit_price as string),
|
||||
total_weight: parseFloat(product.total_weight as string),
|
||||
qty: parseFloat(product.qty as string),
|
||||
avg_weight: parseFloat(product.avg_weight as string),
|
||||
total_price: parseFloat(product.total_price as string),
|
||||
} as CreateSalesOrderProductPayload;
|
||||
}),
|
||||
} as CreateSalesOrderPayload;
|
||||
switch (formType) {
|
||||
case 'add':
|
||||
createMarketingHandler(payload);
|
||||
break;
|
||||
case 'edit':
|
||||
updateMarketingHandler(payload);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
afterSubmit?.();
|
||||
},
|
||||
});
|
||||
|
||||
const { setValues: formikSetValues } = formik;
|
||||
|
||||
useEffect(() => {
|
||||
formikSetValues(formik.initialValues);
|
||||
}, [formikSetValues, formik.initialValues]);
|
||||
|
||||
useEffect(() => {
|
||||
// Hitung Grand Total baru
|
||||
const newGrandTotal = rawMarketingProducts.reduce(
|
||||
(total, product) => total + parseFloat(product.total_price as string),
|
||||
0
|
||||
);
|
||||
|
||||
// Perbarui nilai formik.values.marketing_products
|
||||
formik.setFieldValue('marketing_products', rawMarketingProducts, false);
|
||||
// Parameter ketiga (false) untuk menghindari validasi secara langsung
|
||||
|
||||
// Perbarui state grandTotal
|
||||
setGrandTotal(newGrandTotal);
|
||||
|
||||
// Reset row selection setiap kali daftar produk berubah (opsional, tapi disarankan)
|
||||
setRowSelection({});
|
||||
}, [rawMarketingProducts]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<form
|
||||
className='flex flex-col gap-4'
|
||||
onSubmit={formik.handleSubmit}
|
||||
onReset={formik.handleReset}
|
||||
>
|
||||
<FormHeader
|
||||
title={`${formType === 'add' ? 'Tambah' : 'Edit'} Sales Order`}
|
||||
backUrl='/marketing/sales-orders'
|
||||
/>
|
||||
<Card
|
||||
title='Informasi Order'
|
||||
className={{
|
||||
wrapper: 'bg-white w-full',
|
||||
}}
|
||||
>
|
||||
<div className='grid grid-cols-2 gap-3 mt-3'>
|
||||
<SelectInput
|
||||
label='Pelanggan'
|
||||
options={customerOptions}
|
||||
isLoading={isLoadingCustomerOptions}
|
||||
value={selectedCustomer}
|
||||
onChange={handleChangeCustomer}
|
||||
isError={
|
||||
formik.touched.customer_id && Boolean(formik.errors.customer_id)
|
||||
}
|
||||
errorMessage={formik.errors.customer_id}
|
||||
isClearable
|
||||
placeholder='Pilih Pelanggan'
|
||||
/>
|
||||
<DateInput
|
||||
name='so_date'
|
||||
label='Tanggal'
|
||||
value={formik.values.so_date}
|
||||
onChange={formik.handleChange}
|
||||
isError={formik.touched.so_date && Boolean(formik.errors.so_date)}
|
||||
errorMessage={formik.errors.so_date}
|
||||
placeholder='Pilih Tanggal'
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
<Card
|
||||
title='Daftar Produk'
|
||||
className={{
|
||||
wrapper: 'bg-white w-full',
|
||||
}}
|
||||
>
|
||||
{JSON.stringify(formik.values.sales_order)}
|
||||
<div className='text-green-500'>
|
||||
{JSON.stringify(formik.values.sales_order)}
|
||||
</div>
|
||||
<span className='text-red-500'>{JSON.stringify(formik.errors)}</span>
|
||||
<SalesOrderProductTable
|
||||
data={rawMarketingProducts}
|
||||
onDelete={handleDeleteProduct}
|
||||
onBulkDelete={handleBulkDeleteProduct}
|
||||
onAddProductClick={handleAddProductClick}
|
||||
/>
|
||||
</Card>
|
||||
<div className='grid grid-cols-2 gap-3'>
|
||||
<TextArea
|
||||
required
|
||||
name='notes'
|
||||
label='Catatan'
|
||||
rows={3}
|
||||
placeholder='Masukan catatan penjualan'
|
||||
value={formik.values.notes}
|
||||
onChange={formik.handleChange}
|
||||
isError={formik.touched.notes && Boolean(formik.errors.notes)}
|
||||
errorMessage={formik.errors.notes}
|
||||
/>
|
||||
<div className='flex flex-col h-full justify-between items-end py-6'>
|
||||
<span>Total Penjualan</span>
|
||||
<span className='text-lg font-semibold'>
|
||||
{formatCurrency(grandTotal)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-row items-start justify-center gap-2 mt-4'>
|
||||
<Button type='reset' color='warning' disabled={formik.isSubmitting}>
|
||||
Reset
|
||||
</Button>
|
||||
<Button
|
||||
type='submit'
|
||||
disabled={!formik.isValid || formik.isSubmitting}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
{formType == 'edit' && (
|
||||
<div className='flex flex-row justify-start'>
|
||||
<Button type='button' color='error' onClick={handleDelete}>
|
||||
<Icon icon='mdi:trash' width={24} height={24} />
|
||||
Hapus
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<Modal
|
||||
ref={addProductModal.ref}
|
||||
closeOnBackdrop
|
||||
className={{
|
||||
modalBox: 'max-w-4/5 z-100',
|
||||
}}
|
||||
>
|
||||
<div className='flex flex-col gap-4'>
|
||||
<div className='flex flex-row items-center justify-between'>
|
||||
<h3 className='text-lg font-semibold mb-4'>Tambah Produk</h3>
|
||||
<Button
|
||||
variant='ghost'
|
||||
color='error'
|
||||
className='rounded-full'
|
||||
onClick={addProductModal.closeModal}
|
||||
>
|
||||
<Icon icon='mdi:close' width={20} height={20} />
|
||||
</Button>
|
||||
</div>
|
||||
<div>
|
||||
<SalesOrderProductForm
|
||||
onSubmitForm={handleAddSubmitProduct}
|
||||
modalRef={addProductModal.ref}
|
||||
initialValues={selectedMarketingProduct ?? undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data penjualan ini?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
onClick: deleteMarketingHandler,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default SalesForm;
|
||||
@@ -0,0 +1,56 @@
|
||||
import * as Yup from 'yup';
|
||||
|
||||
type SalesOrderProductSchemaType = {
|
||||
kandang_id?: number;
|
||||
kandang?: {
|
||||
value: number;
|
||||
label: string;
|
||||
} | null;
|
||||
product_warehouse?: {
|
||||
value: number;
|
||||
label: string;
|
||||
} | null;
|
||||
product_warehouse_id?: number;
|
||||
unit_price: string | number | undefined;
|
||||
total_weight: string | number | undefined;
|
||||
qty: string | number | undefined;
|
||||
avg_weight: string | number | undefined;
|
||||
total_price: string | number | undefined;
|
||||
};
|
||||
|
||||
export const SalesOrderProductSchema: Yup.ObjectSchema<SalesOrderProductSchemaType> =
|
||||
Yup.object({
|
||||
kandang: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).nullable(),
|
||||
kandang_id: Yup.number()
|
||||
.min(1, 'Kandang wajib diisi!')
|
||||
.required('Kandang wajib diisi!'),
|
||||
product_warehouse: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).nullable(),
|
||||
product_warehouse_id: Yup.number()
|
||||
.min(1, 'Produk wajib diisi!')
|
||||
.required('Produk wajib diisi!'),
|
||||
unit_price: Yup.number()
|
||||
.min(1, 'Harga Satuan wajib diisi!')
|
||||
.required('Harga Satuan wajib diisi!'),
|
||||
total_weight: Yup.number()
|
||||
.min(1, 'Total Bobot wajib diisi!')
|
||||
.required('Total Bobot wajib diisi!'),
|
||||
qty: Yup.number()
|
||||
.min(1, 'Kuantitas wajib diisi!')
|
||||
.required('Kuantitas wajib diisi!'),
|
||||
avg_weight: Yup.number()
|
||||
.min(0, 'Avg. Bobot wajib diisi!')
|
||||
.required('Avg. Bobot wajib diisi!'),
|
||||
total_price: Yup.number()
|
||||
.min(1, 'Total Penjualan wajib diisi!')
|
||||
.required('Total Penjualan wajib diisi!'),
|
||||
});
|
||||
|
||||
export type SalesOrderProductFormValues = Yup.InferType<
|
||||
typeof SalesOrderProductSchema
|
||||
>;
|
||||
@@ -0,0 +1,315 @@
|
||||
'use client';
|
||||
|
||||
import { useFormik } from 'formik';
|
||||
import {
|
||||
SalesOrderProductFormValues,
|
||||
SalesOrderProductSchema,
|
||||
} from './SalesOrderProduct.schema';
|
||||
import { RefObject, useEffect, useState } from 'react';
|
||||
import SelectInput, {
|
||||
OptionType,
|
||||
useSelect,
|
||||
} from '@/components/input/SelectInput';
|
||||
import { Kandang } from '@/types/api/master-data/kandang';
|
||||
import { KandangApi } from '@/services/api/master-data';
|
||||
import { ProductWarehouse } from '@/types/api/inventory/product-warehouse';
|
||||
import { ProductWarehouseApi } from '@/services/api/inventory';
|
||||
import NumberInput from '@/components/input/NumberInput';
|
||||
import Button from '@/components/Button';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
|
||||
const SalesOrderProductForm = ({
|
||||
initialValues,
|
||||
modalRef,
|
||||
onSubmitForm,
|
||||
}: {
|
||||
initialValues?: SalesOrderProductFormValues;
|
||||
modalRef?: RefObject<HTMLDialogElement | null>;
|
||||
onSubmitForm?: (value: SalesOrderProductFormValues) => Promise<void>;
|
||||
}) => {
|
||||
// State
|
||||
const [selectedOptionsKandang, setSelectedOptionsKandang] =
|
||||
useState<OptionType | null>(null);
|
||||
const [selectedOptionsWarehouse, setSelectedOptionsWarehouse] = useState<
|
||||
OptionType | null | undefined
|
||||
>(undefined);
|
||||
const [formErrorMessage, setFormErrorMessage] = useState('');
|
||||
|
||||
// Options Data
|
||||
const {
|
||||
options: kandangSourceOptions,
|
||||
rawData: kandangSourceRawData,
|
||||
isLoadingOptions: isLoadingKandangSourceOptions,
|
||||
} = useSelect<Kandang>(KandangApi.basePath, 'id', 'name');
|
||||
const {
|
||||
options: warehouseSourceOptions,
|
||||
rawData: warehouseSourceRawData,
|
||||
isLoadingOptions: isLoadingWarehouseSourceOptions,
|
||||
} = useSelect<ProductWarehouse>(
|
||||
ProductWarehouseApi.basePath,
|
||||
'id',
|
||||
'product.name',
|
||||
'search',
|
||||
{
|
||||
warehouse_id: selectedOptionsKandang?.value?.toString() ?? '',
|
||||
}
|
||||
);
|
||||
|
||||
// Handler
|
||||
const kandangChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
setSelectedOptionsKandang(val as OptionType);
|
||||
formik.setFieldValue('kandang', val as OptionType);
|
||||
formik.setFieldValue('kandang_id', (val as OptionType)?.value);
|
||||
formik.setFieldValue('product_warehouse_id', null);
|
||||
formik.setFieldValue('qty', null);
|
||||
warehouseChangeHandler(null);
|
||||
};
|
||||
|
||||
const warehouseChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
setSelectedOptionsWarehouse(val as OptionType);
|
||||
formik.setFieldValue('product_warehouse', val as OptionType);
|
||||
formik.setFieldValue('product_warehouse_id', (val as OptionType)?.value);
|
||||
if (isResponseSuccess(warehouseSourceRawData)) {
|
||||
const productWarehouse = warehouseSourceRawData?.data.find(
|
||||
(item: ProductWarehouse) => item.id === (val as OptionType)?.value
|
||||
);
|
||||
if (selectedOptionsWarehouse?.value !== null) {
|
||||
formik.setFieldValue('qty', productWarehouse?.quantity);
|
||||
handleBlurField('qty');
|
||||
} else {
|
||||
formik.setFieldValue('qty', null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Formik
|
||||
const formik = useFormik<SalesOrderProductFormValues>({
|
||||
enableReinitialize: true,
|
||||
initialValues: {
|
||||
kandang_id: initialValues?.kandang_id || undefined,
|
||||
kandang: initialValues?.kandang || undefined,
|
||||
product_warehouse: initialValues?.product_warehouse || undefined,
|
||||
product_warehouse_id: initialValues?.product_warehouse_id || undefined,
|
||||
unit_price: initialValues?.unit_price || undefined,
|
||||
total_weight: initialValues?.total_weight || undefined,
|
||||
qty: initialValues?.qty || undefined,
|
||||
avg_weight: initialValues?.avg_weight || undefined,
|
||||
total_price: initialValues?.total_price || undefined,
|
||||
},
|
||||
validationSchema: SalesOrderProductSchema,
|
||||
onSubmit: async (values) => {
|
||||
setFormErrorMessage('');
|
||||
if (
|
||||
isResponseSuccess(kandangSourceRawData) &&
|
||||
isResponseSuccess(warehouseSourceRawData)
|
||||
) {
|
||||
const productWarehouse = warehouseSourceRawData?.data.find(
|
||||
(item: ProductWarehouse) => item.id === values.product_warehouse_id
|
||||
);
|
||||
const kandang = kandangSourceRawData?.data.find(
|
||||
(item: Kandang) => item.id === values.kandang_id
|
||||
);
|
||||
|
||||
onSubmitForm?.(values);
|
||||
handleResetForm();
|
||||
}
|
||||
},
|
||||
});
|
||||
const { setValues: formikSetValues } = formik;
|
||||
|
||||
useEffect(() => {
|
||||
formikSetValues(formik.initialValues);
|
||||
}, [formikSetValues, formik.initialValues]);
|
||||
|
||||
const handleResetForm = () => {
|
||||
setSelectedOptionsKandang(null);
|
||||
setSelectedOptionsWarehouse(null);
|
||||
setFormErrorMessage('');
|
||||
formik.resetForm({
|
||||
values: {
|
||||
kandang_id: undefined,
|
||||
kandang: null,
|
||||
product_warehouse: null,
|
||||
product_warehouse_id: undefined,
|
||||
unit_price: '',
|
||||
total_weight: '',
|
||||
qty: '',
|
||||
avg_weight: '',
|
||||
total_price: '',
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleBlurField = (field: string) => {
|
||||
const { qty, unit_price, total_price, avg_weight, total_weight } =
|
||||
formik.values;
|
||||
|
||||
if (field === 'unit_price' || field === 'total_price' || field === 'qty') {
|
||||
if (qty && unit_price && field === 'unit_price') {
|
||||
formik.setFieldValue(
|
||||
'total_price',
|
||||
(qty as number) * (unit_price as number)
|
||||
);
|
||||
} else if (qty && total_price && field === 'total_price') {
|
||||
formik.setFieldValue(
|
||||
'unit_price',
|
||||
(total_price as number) / (qty as number)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (field === 'avg_weight' || field === 'total_weight' || field === 'qty') {
|
||||
if (qty && avg_weight && field === 'avg_weight') {
|
||||
formik.setFieldValue(
|
||||
'total_weight',
|
||||
(qty as number) * (avg_weight as number)
|
||||
);
|
||||
} else if (qty && total_weight && field === 'total_weight') {
|
||||
formik.setFieldValue(
|
||||
'avg_weight',
|
||||
(total_weight as number) / (qty as number)
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<form
|
||||
className='size-full'
|
||||
onSubmit={formik.handleSubmit}
|
||||
onReset={handleResetForm}
|
||||
>
|
||||
<div className='grid grid-cols-2 gap-4 z-200'>
|
||||
{/* <PatternInput
|
||||
name='vehicle_number'
|
||||
label='No. Polisi'
|
||||
format='AA #### AAA'
|
||||
mask='_'
|
||||
inputVehicleNumber
|
||||
required
|
||||
type='text'
|
||||
placeholder='B 1234 CDE'
|
||||
value={formatVechicleNumber(formik.values.vehicle_number ?? '')}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
isError={
|
||||
formik.touched.vehicle_number &&
|
||||
Boolean(formik.errors.vehicle_number)
|
||||
}
|
||||
errorMessage={formik.errors.vehicle_number}
|
||||
/> */}
|
||||
<SelectInput
|
||||
required
|
||||
label='Kandang'
|
||||
options={kandangSourceOptions}
|
||||
isLoading={isLoadingKandangSourceOptions}
|
||||
value={selectedOptionsKandang}
|
||||
onChange={kandangChangeHandler}
|
||||
isClearable
|
||||
menuPortalTarget={modalRef?.current}
|
||||
isError={
|
||||
formik.touched.kandang_id && Boolean(formik.errors.kandang_id)
|
||||
}
|
||||
errorMessage={formik.errors.kandang_id}
|
||||
placeholder='Pilih Kandang'
|
||||
/>
|
||||
<SelectInput
|
||||
required
|
||||
label='Produk'
|
||||
options={warehouseSourceOptions}
|
||||
isLoading={isLoadingWarehouseSourceOptions}
|
||||
value={selectedOptionsWarehouse}
|
||||
onChange={warehouseChangeHandler}
|
||||
isClearable
|
||||
menuPortalTarget={modalRef?.current}
|
||||
placeholder='Pilih Kandang Terlebih Dahulu'
|
||||
isDisabled={!selectedOptionsKandang?.value}
|
||||
isError={
|
||||
formik.touched.product_warehouse_id &&
|
||||
Boolean(formik.errors.product_warehouse_id)
|
||||
}
|
||||
errorMessage={formik.errors.product_warehouse_id}
|
||||
/>
|
||||
<NumberInput
|
||||
required
|
||||
label='Kuantitas'
|
||||
name='qty'
|
||||
value={formik.values.qty}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={() => handleBlurField('qty')}
|
||||
isError={formik.touched.qty && Boolean(formik.errors.qty)}
|
||||
errorMessage={formik.errors.qty}
|
||||
placeholder='Masukan Kuantitas'
|
||||
/>
|
||||
<NumberInput
|
||||
required
|
||||
label='Avg. Bobot (Kg)'
|
||||
name='avg_weight'
|
||||
value={formik.values.avg_weight}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={() => handleBlurField('avg_weight')}
|
||||
isError={
|
||||
formik.touched.avg_weight && Boolean(formik.errors.avg_weight)
|
||||
}
|
||||
errorMessage={formik.errors.avg_weight}
|
||||
placeholder='Masukan Bobot Rata-rata'
|
||||
/>
|
||||
<NumberInput
|
||||
required
|
||||
label='Harga Satuan (Rp)'
|
||||
name='unit_price'
|
||||
value={formik.values.unit_price}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={() => handleBlurField('unit_price')}
|
||||
isError={
|
||||
formik.touched.unit_price && Boolean(formik.errors.unit_price)
|
||||
}
|
||||
errorMessage={formik.errors.unit_price}
|
||||
placeholder='Masukan Harga Satuan'
|
||||
/>
|
||||
<NumberInput
|
||||
required
|
||||
label='Total Bobot (Kg)'
|
||||
name='total_weight'
|
||||
value={formik.values.total_weight}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={() => handleBlurField('total_weight')}
|
||||
isError={
|
||||
formik.touched.total_weight && Boolean(formik.errors.total_weight)
|
||||
}
|
||||
errorMessage={formik.errors.total_weight}
|
||||
placeholder='Masukan Total Bobot'
|
||||
/>
|
||||
<NumberInput
|
||||
required
|
||||
label='Total Penjualan (Rp)'
|
||||
name='total_price'
|
||||
value={formik.values.total_price}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={() => handleBlurField('total_price')}
|
||||
isError={
|
||||
formik.touched.total_price && Boolean(formik.errors.total_price)
|
||||
}
|
||||
errorMessage={formik.errors.total_price}
|
||||
placeholder='Masukan Total Penjualan'
|
||||
/>
|
||||
</div>
|
||||
<div className='flex flex-row justify-end gap-3 mt-4'>
|
||||
<Button type='reset' color='warning' onClick={handleResetForm}>
|
||||
Reset
|
||||
</Button>
|
||||
<Button
|
||||
type='submit'
|
||||
isLoading={formik.isSubmitting}
|
||||
disabled={!formik.isValid || formik.isSubmitting}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default SalesOrderProductForm;
|
||||
@@ -0,0 +1,200 @@
|
||||
'use client';
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import Table from '@/components/Table';
|
||||
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
|
||||
import { cn, formatCurrency, formatNumber } from '@/lib/helper';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import * as TanStack from '@tanstack/react-table';
|
||||
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||
|
||||
// Hapus import Modal, useModal, dan MarketingProductForm
|
||||
|
||||
// Tentukan Tipe Props baru yang diterima dari SalesForm
|
||||
type SalesOrderProductTableProps = {
|
||||
data: SalesOrderProductFormValues[];
|
||||
onDelete: (product_warehouse_id: number, kandang_id: number) => void;
|
||||
onBulkDelete: (selectedIds: number[]) => void;
|
||||
onAddProductClick: () => void; // Prop baru untuk memanggil modal di parent
|
||||
};
|
||||
|
||||
const SalesOrderProductTable = ({
|
||||
data,
|
||||
onDelete,
|
||||
onBulkDelete,
|
||||
onAddProductClick,
|
||||
}: SalesOrderProductTableProps) => {
|
||||
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||
|
||||
const selectedRowIds = Object.keys(rowSelection).map((item) =>
|
||||
parseInt(item)
|
||||
);
|
||||
|
||||
const handleBulkDeleteClick = () => {
|
||||
onBulkDelete(selectedRowIds);
|
||||
setRowSelection({});
|
||||
};
|
||||
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({
|
||||
table,
|
||||
}: {
|
||||
table: TanStack.Table<SalesOrderProductFormValues>;
|
||||
}) => (
|
||||
<div className='w-full flex flex-row justify-center'>
|
||||
<CheckboxInput
|
||||
name='allRow'
|
||||
checked={table.getIsAllRowsSelected()}
|
||||
indeterminate={table.getIsSomeRowsSelected()}
|
||||
onChange={table.getToggleAllRowsSelectedHandler()}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
cell: ({ row }: { row: TanStack.Row<SalesOrderProductFormValues> }) => (
|
||||
<div>
|
||||
<CheckboxInput
|
||||
name='row'
|
||||
checked={row.getIsSelected()}
|
||||
disabled={!row.getCanSelect()}
|
||||
indeterminate={row.getIsSomeSelected()}
|
||||
onChange={row.getToggleSelectedHandler()}
|
||||
value={`${row.original.product_warehouse_id}${row.original.kandang_id}`}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorFn: (row: SalesOrderProductFormValues) => row.kandang?.label,
|
||||
header: 'Kandang',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: SalesOrderProductFormValues) =>
|
||||
row.product_warehouse?.label,
|
||||
header: 'Produk',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: SalesOrderProductFormValues) =>
|
||||
formatCurrency(parseFloat(row.unit_price as string)),
|
||||
header: 'Harga Satuan (Rp)',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: SalesOrderProductFormValues) =>
|
||||
formatNumber(parseFloat(row.total_weight as string)),
|
||||
header: 'Total Bobot (Kg)',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: SalesOrderProductFormValues) =>
|
||||
formatNumber(parseFloat(row.qty as string)),
|
||||
header: 'Kuantitas',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: SalesOrderProductFormValues) =>
|
||||
formatNumber(parseFloat(row.avg_weight as string)),
|
||||
header: 'Avg. Bobot (Kg)',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: SalesOrderProductFormValues) =>
|
||||
formatCurrency(parseFloat(row.total_price as string)),
|
||||
header: 'Total Penjualan (Rp)',
|
||||
},
|
||||
{
|
||||
header: 'Aksi',
|
||||
cell: (
|
||||
props: TanStack.CellContext<SalesOrderProductFormValues, unknown>
|
||||
) => (
|
||||
<div className='flex flex-row gap-1 items-center justify-end h-full mt-2'>
|
||||
<Button
|
||||
color='error'
|
||||
className='p-1'
|
||||
disabled={
|
||||
!props.row.original.product_warehouse_id ||
|
||||
!props.row.original.kandang_id
|
||||
}
|
||||
onClick={() => {
|
||||
// PANGGIL CALLBACK PARENT (onDelete)
|
||||
if (
|
||||
props.row.original.product_warehouse_id &&
|
||||
props.row.original.kandang_id
|
||||
) {
|
||||
onDelete(
|
||||
props.row.original.product_warehouse_id,
|
||||
props.row.original.kandang_id
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Icon icon='mdi:trash' width={16} height={16} />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
],
|
||||
[onDelete]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Table<SalesOrderProductFormValues>
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
data={data}
|
||||
columns={columns}
|
||||
className={{
|
||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||
headerRowClassName: 'border-b border-b-gray-200',
|
||||
headerColumnClassName:
|
||||
'px-2 py-2 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end first:flex first:flex-row first:justify-start',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-2 py-2 last:flex last:flex-row last:justify-end first:flex first:flex-row first:justify-start',
|
||||
paginationClassName: 'hidden',
|
||||
}}
|
||||
emptyContent={
|
||||
<div
|
||||
className={cn(
|
||||
'w-full h-16 flex flex-col justify-center items-center gap-2'
|
||||
)}
|
||||
>
|
||||
<span className='text-gray-500'>Belum ada data penjualan</span>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<div className='flex flex-row gap-3 mt-3'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
className='justify-start w-fit py-1 text-sm'
|
||||
onClick={onAddProductClick}
|
||||
>
|
||||
<Icon icon='mdi:plus' width={16} height={16} />
|
||||
Tambah Produk
|
||||
</Button>
|
||||
{selectedRowIds.length > 0 && (
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
color='error'
|
||||
className='justify-start w-fit py-1 text-sm'
|
||||
onClick={handleBulkDeleteClick}
|
||||
>
|
||||
<Icon icon='mdi:trash' width={16} height={16} />
|
||||
Hapus
|
||||
{selectedRowIds.length > 0
|
||||
? ` (${selectedRowIds.length})`
|
||||
: ''}{' '}
|
||||
Produk
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal dan Form dihapus dari sini */}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default SalesOrderProductTable;
|
||||
Reference in New Issue
Block a user