mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-21 22:05:45 +00:00
938 lines
32 KiB
TypeScript
938 lines
32 KiB
TypeScript
'use client';
|
|
|
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
|
import { useFormik } from 'formik';
|
|
import useSWR from 'swr';
|
|
import { useRouter } from 'next/navigation';
|
|
import { Icon } from '@iconify/react';
|
|
import { toast } from 'react-hot-toast';
|
|
import Button from '@/components/Button';
|
|
import TextInput from '@/components/input/TextInput';
|
|
import SelectInput, {
|
|
OptionType,
|
|
useSelect,
|
|
} from '@/components/input/SelectInput';
|
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
|
import { useModal } from '@/components/Modal';
|
|
|
|
import {
|
|
PurchaseRequestFormSchema,
|
|
PurchaseRequestFormValues,
|
|
getPurchaseRequestFormInitialValues,
|
|
UpdatePurchaseRequestFormSchema,
|
|
} from './PurchaseRequestForm.schema';
|
|
import {
|
|
SupplierApi,
|
|
AreaApi,
|
|
LocationApi,
|
|
WarehouseApi,
|
|
} from '@/services/api/master-data';
|
|
import { ProductWarehouseApi } from '@/services/api/inventory';
|
|
import { isResponseSuccess, isResponseError } from '@/lib/api-helper';
|
|
import { PurchaseApi } from '@/services/api/purchasing';
|
|
|
|
import Card from '@/components/Card';
|
|
import {
|
|
CreatePurchaseRequestPayload,
|
|
Purchase,
|
|
} from '@/types/api/purchase/purchase';
|
|
|
|
interface PurchaseRequestFormProps {
|
|
type?: 'add' | 'edit' | 'detail';
|
|
initialValues?: Purchase;
|
|
}
|
|
|
|
const PurchaseRequestForm = ({
|
|
type = 'add',
|
|
initialValues,
|
|
}: PurchaseRequestFormProps) => {
|
|
const router = useRouter();
|
|
const deleteModal = useModal();
|
|
|
|
const [selectedPurchaseItems, setSelectedPurchaseItems] = useState<number[]>(
|
|
[]
|
|
);
|
|
const [purchaseRequestFormErrorMessage, setPurchaseRequestFormErrorMessage] =
|
|
useState('');
|
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
|
const [
|
|
productWarehouseSelectInputValue,
|
|
setProductWarehouseSelectInputValue,
|
|
] = useState('');
|
|
|
|
// ===== INTERFACES =====
|
|
interface WarehouseOptionType extends OptionType {
|
|
area?: string;
|
|
location?: string;
|
|
}
|
|
|
|
interface ProductWarehouseOptionType extends OptionType {
|
|
product_id: number;
|
|
warehouse_id: number;
|
|
warehouse_name: string;
|
|
quantity: number;
|
|
}
|
|
|
|
// ===== HELPER FUNCTIONS =====
|
|
const getPurchaseItemError = (
|
|
idx: number,
|
|
field: 'warehouse_id' | 'product_warehouse_id' | 'product_id' | 'sub_qty'
|
|
): { isError: boolean; errorMessage: string } => {
|
|
const touchedItem = formik.touched.purchase_items?.[idx];
|
|
const errorItem = formik.errors.purchase_items?.[idx] as
|
|
| Record<string, string>
|
|
| undefined;
|
|
|
|
if (!touchedItem || !errorItem) {
|
|
return { isError: false, errorMessage: '' };
|
|
}
|
|
|
|
const isTouched = (touchedItem as Record<string, boolean>)?.[field];
|
|
const errorMessage = errorItem?.[field] || '';
|
|
|
|
return {
|
|
isError: Boolean(isTouched && errorMessage),
|
|
errorMessage: isTouched && errorMessage ? errorMessage : '',
|
|
};
|
|
};
|
|
|
|
// ===== FORM HANDLERS =====
|
|
const createPurchaseRequestHandler = useCallback(
|
|
async (payload: CreatePurchaseRequestPayload) => {
|
|
const res = await PurchaseApi.create(payload);
|
|
if (isResponseError(res)) {
|
|
setPurchaseRequestFormErrorMessage(res.message);
|
|
return;
|
|
}
|
|
toast.success(res?.message as string);
|
|
router.push('/purchase');
|
|
},
|
|
[router]
|
|
);
|
|
|
|
const updatePurchaseRequestHandler = useCallback(
|
|
async (
|
|
purchaseRequestId: number,
|
|
payload: CreatePurchaseRequestPayload
|
|
) => {
|
|
const res = await PurchaseApi.update(purchaseRequestId, payload);
|
|
if (isResponseError(res)) {
|
|
setPurchaseRequestFormErrorMessage(res.message);
|
|
return;
|
|
}
|
|
toast.success(res?.message as string);
|
|
router.refresh();
|
|
router.push('/purchase');
|
|
},
|
|
[router]
|
|
);
|
|
|
|
const deletePurchaseRequestClickHandler = useCallback(() => {
|
|
deleteModal.openModal();
|
|
}, [deleteModal]);
|
|
|
|
const confirmationModalDeleteClickHandler = useCallback(async () => {
|
|
if (!initialValues?.id) return;
|
|
|
|
setIsDeleteLoading(true);
|
|
await PurchaseApi.delete(initialValues.id);
|
|
deleteModal.closeModal();
|
|
toast.success('Successfully delete Purchase Request!');
|
|
setIsDeleteLoading(false);
|
|
router.push('/purchase');
|
|
}, [deleteModal, initialValues?.id, router]);
|
|
|
|
// ===== API DATA FETCHING =====
|
|
const allProductWarehousesUrl = `${ProductWarehouseApi.basePath}`;
|
|
const { data: allProductWarehouses } = useSWR(
|
|
allProductWarehousesUrl,
|
|
ProductWarehouseApi.getAllFetcher
|
|
);
|
|
|
|
// ===== USE SELECT HOOKS =====
|
|
const {
|
|
inputValue: supplierSelectInputValue,
|
|
setInputValue: setSupplierSelectInputValue,
|
|
options: supplierOptions,
|
|
isLoadingOptions: isLoadingSuppliers,
|
|
} = useSelect(SupplierApi.basePath, 'id', 'name', 'search');
|
|
|
|
const {
|
|
inputValue: areaSelectInputValue,
|
|
setInputValue: setAreaSelectInputValue,
|
|
options: areaOptions,
|
|
isLoadingOptions: isLoadingAreas,
|
|
} = useSelect(AreaApi.basePath, 'id', 'name', 'search');
|
|
|
|
const [locationSelectInputValue, setLocationSelectInputValue] = useState('');
|
|
|
|
const {
|
|
inputValue: warehouseSelectInputValue,
|
|
setInputValue: setWarehouseSelectInputValue,
|
|
isLoadingOptions: isLoadingWarehouses,
|
|
} = useSelect(WarehouseApi.basePath, 'id', 'name', 'search');
|
|
|
|
// ===== PRODUCT WAREHOUSE FETCHING =====
|
|
const getProductWarehousesUrl = useCallback(() => {
|
|
const productWarehouseParams = new URLSearchParams({
|
|
search: productWarehouseSelectInputValue,
|
|
});
|
|
|
|
return `${ProductWarehouseApi.basePath}?${productWarehouseParams.toString()}`;
|
|
}, [productWarehouseSelectInputValue]);
|
|
|
|
const productWarehousesUrl = getProductWarehousesUrl();
|
|
const { data: productWarehouses, isLoading: isLoadingProductWarehouses } =
|
|
useSWR(productWarehousesUrl, ProductWarehouseApi.getAllFetcher);
|
|
|
|
// Filter product warehouses per item based on selected warehouse
|
|
const getProductWarehouseOptionsForItem = useCallback(
|
|
(warehouseId: number | string) => {
|
|
if (!isResponseSuccess(productWarehouses)) return [];
|
|
|
|
const warehouseIdNum =
|
|
typeof warehouseId === 'string'
|
|
? parseInt(warehouseId) || 0
|
|
: warehouseId;
|
|
if (warehouseIdNum === 0) return [];
|
|
|
|
return (
|
|
productWarehouses?.data
|
|
.filter((pw) => pw.warehouse.id === warehouseIdNum)
|
|
.map((pw) => ({
|
|
value: pw.product.id,
|
|
label: pw.product.name,
|
|
product_id: pw.product.id,
|
|
warehouse_id: pw.warehouse.id,
|
|
warehouse_name: pw.warehouse.name,
|
|
quantity: pw.quantity,
|
|
})) || []
|
|
);
|
|
},
|
|
[productWarehouses]
|
|
);
|
|
|
|
const productWarehouseOptions = isResponseSuccess(productWarehouses)
|
|
? productWarehouses?.data.map((pw) => ({
|
|
value: pw.product.id,
|
|
label: pw.product.name,
|
|
product_id: pw.product.id,
|
|
warehouse_id: pw.warehouse.id,
|
|
warehouse_name: pw.warehouse.name,
|
|
quantity: pw.quantity,
|
|
}))
|
|
: [];
|
|
|
|
const formikInitialValues = useMemo<PurchaseRequestFormValues>(
|
|
() => getPurchaseRequestFormInitialValues(initialValues),
|
|
[initialValues]
|
|
);
|
|
|
|
const formik = useFormik<PurchaseRequestFormValues>({
|
|
initialValues: formikInitialValues,
|
|
validationSchema:
|
|
type === 'edit'
|
|
? UpdatePurchaseRequestFormSchema
|
|
: PurchaseRequestFormSchema,
|
|
validateOnChange: true,
|
|
validateOnBlur: true,
|
|
onSubmit: async (values) => {
|
|
const payload: CreatePurchaseRequestPayload = {
|
|
supplier_id:
|
|
typeof values.supplier_id === 'string'
|
|
? parseInt(values.supplier_id) || 0
|
|
: values.supplier_id || 0,
|
|
credit_term:
|
|
typeof values.credit_term === 'string'
|
|
? parseInt(values.credit_term) || 0
|
|
: values.credit_term || 0,
|
|
notes: values.notes || '',
|
|
purchase_items: (values.purchase_items || []).map((item) => ({
|
|
warehouse_id:
|
|
typeof item.warehouse_id === 'string'
|
|
? parseInt(item.warehouse_id) || 0
|
|
: item.warehouse_id || 0,
|
|
product_id:
|
|
typeof item.product_id === 'string'
|
|
? parseInt(item.product_id) || 0
|
|
: item.product_id || 0,
|
|
product_warehouse_id:
|
|
typeof item.product_warehouse_id === 'string'
|
|
? parseInt(item.product_warehouse_id) || 0
|
|
: item.product_warehouse_id || 0,
|
|
sub_qty:
|
|
typeof item.sub_qty === 'string'
|
|
? parseFloat(item.sub_qty) || 0
|
|
: item.sub_qty || 0,
|
|
})),
|
|
};
|
|
|
|
switch (type) {
|
|
case 'add':
|
|
await createPurchaseRequestHandler(payload);
|
|
break;
|
|
case 'edit':
|
|
await updatePurchaseRequestHandler(
|
|
initialValues?.id as number,
|
|
payload
|
|
);
|
|
break;
|
|
}
|
|
},
|
|
});
|
|
|
|
// ===== API DATA FETCHING =====
|
|
const locationsUrl = useMemo(() => {
|
|
const params = new URLSearchParams({
|
|
search: locationSelectInputValue,
|
|
...(formik.values.area_id && formik.values.area_id > 0
|
|
? { area_id: formik.values.area_id.toString() }
|
|
: {}),
|
|
});
|
|
return `${LocationApi.basePath}?${params.toString()}`;
|
|
}, [locationSelectInputValue, formik.values.area_id]);
|
|
|
|
const { data: locations, isLoading: isLoadingLocations } = useSWR(
|
|
locationsUrl,
|
|
LocationApi.getAllFetcher
|
|
);
|
|
|
|
const locationOptions = useMemo(() => {
|
|
if (!isResponseSuccess(locations)) return [];
|
|
return (
|
|
locations?.data.map((location) => ({
|
|
value: location.id,
|
|
label: location.name,
|
|
})) || []
|
|
);
|
|
}, [locations]);
|
|
|
|
const warehousesUrl = useMemo(() => {
|
|
const params = new URLSearchParams({ search: warehouseSelectInputValue });
|
|
|
|
if (formik.values.area_id && formik.values.area_id > 0) {
|
|
params.append('area_id', formik.values.area_id.toString());
|
|
}
|
|
|
|
if (formik.values.location_id && formik.values.location_id > 0) {
|
|
params.append('location_id', formik.values.location_id.toString());
|
|
}
|
|
|
|
return `${WarehouseApi.basePath}?${params.toString()}`;
|
|
}, [
|
|
warehouseSelectInputValue,
|
|
formik.values.area_id,
|
|
formik.values.location_id,
|
|
]);
|
|
|
|
const { data: warehouses } = useSWR(
|
|
warehousesUrl,
|
|
WarehouseApi.getAllFetcher
|
|
);
|
|
|
|
const warehouseOptions = useMemo(() => {
|
|
if (!isResponseSuccess(warehouses)) return [];
|
|
|
|
return (
|
|
warehouses?.data.map((w) => ({
|
|
value: w.id,
|
|
label: w.name,
|
|
area: w.area?.name,
|
|
location:
|
|
'type' in w && (w.type === 'LOKASI' || w.type === 'KANDANG')
|
|
? w.location?.name
|
|
: undefined,
|
|
})) || []
|
|
);
|
|
}, [warehouses]);
|
|
|
|
// ===== EVENT HANDLERS =====
|
|
const supplierChangeHandler = (val: OptionType | OptionType[] | null) => {
|
|
const supplier = val as OptionType | null;
|
|
formik.setFieldTouched('supplier', true);
|
|
formik.setFieldValue('supplier', supplier);
|
|
formik.setFieldTouched('supplier_id', true);
|
|
formik.setFieldValue('supplier_id', (supplier as OptionType)?.value || 0);
|
|
};
|
|
|
|
const areaChangeHandler = (val: OptionType | OptionType[] | null) => {
|
|
const area = val as OptionType | null;
|
|
formik.setFieldTouched('area', true);
|
|
formik.setFieldValue('area', area);
|
|
formik.setFieldTouched('area_id', true);
|
|
formik.setFieldValue('area_id', (area as OptionType)?.value || 0);
|
|
|
|
// Reset area dependent fields
|
|
formik.setFieldValue('location', null);
|
|
formik.setFieldValue('location_id', 0);
|
|
setLocationSelectInputValue('');
|
|
|
|
// Reset area dependent fields in all purchase items
|
|
if (formik.values.purchase_items) {
|
|
formik.values.purchase_items.forEach((_, idx) => {
|
|
formik.setFieldValue(`purchase_items.${idx}.warehouse`, null);
|
|
formik.setFieldValue(`purchase_items.${idx}.warehouse_id`, '');
|
|
formik.setFieldValue(`purchase_items.${idx}.product_warehouse`, null);
|
|
formik.setFieldValue(
|
|
`purchase_items.${idx}.product_warehouse_id`,
|
|
null
|
|
);
|
|
formik.setFieldValue(`purchase_items.${idx}.product_id`, '');
|
|
});
|
|
}
|
|
};
|
|
|
|
const locationChangeHandler = (val: OptionType | OptionType[] | null) => {
|
|
const location = val as OptionType | null;
|
|
formik.setFieldTouched('location', true);
|
|
formik.setFieldValue('location', location);
|
|
formik.setFieldTouched('location_id', true);
|
|
formik.setFieldValue('location_id', (location as OptionType)?.value || 0);
|
|
|
|
// Reset location dependent fields in all purchase items
|
|
if (formik.values.purchase_items) {
|
|
formik.values.purchase_items.forEach((_, idx) => {
|
|
formik.setFieldValue(`purchase_items.${idx}.warehouse`, null);
|
|
formik.setFieldValue(`purchase_items.${idx}.warehouse_id`, '');
|
|
formik.setFieldValue(`purchase_items.${idx}.product_warehouse`, null);
|
|
formik.setFieldValue(
|
|
`purchase_items.${idx}.product_warehouse_id`,
|
|
null
|
|
);
|
|
formik.setFieldValue(`purchase_items.${idx}.product_id`, '');
|
|
});
|
|
}
|
|
};
|
|
|
|
// Purchase Items Handlers
|
|
const addPurchaseItem = () => {
|
|
const newPurchaseItems = [
|
|
...(formik.values.purchase_items || []),
|
|
{
|
|
warehouse: null,
|
|
warehouse_id: '',
|
|
product: null,
|
|
product_id: '',
|
|
product_warehouse: null,
|
|
product_warehouse_id: null,
|
|
sub_qty: '',
|
|
},
|
|
];
|
|
formik.setFieldValue('purchase_items', newPurchaseItems);
|
|
};
|
|
|
|
const removePurchaseItem = (idx: number) => {
|
|
const updatedPurchaseItems = formik.values.purchase_items?.filter(
|
|
(_, i) => i !== idx
|
|
);
|
|
formik.setFieldValue('purchase_items', updatedPurchaseItems);
|
|
};
|
|
|
|
const removeSelectedPurchaseItems = () => {
|
|
const updatedPurchaseItems = formik.values.purchase_items?.filter(
|
|
(_, idx) => !selectedPurchaseItems.includes(idx)
|
|
);
|
|
formik.setFieldValue('purchase_items', updatedPurchaseItems);
|
|
setSelectedPurchaseItems([]);
|
|
};
|
|
|
|
const handlePurchaseItemChange = (
|
|
idx: number,
|
|
field: string,
|
|
value: string | number
|
|
) => {
|
|
const integerFields = [
|
|
'warehouse_id',
|
|
'product_id',
|
|
'product_warehouse_id',
|
|
'total_qty',
|
|
];
|
|
const floatFields = ['price', 'sub_qty'];
|
|
|
|
if (integerFields.includes(field)) {
|
|
const numValue = typeof value === 'string' ? parseInt(value) || 0 : value;
|
|
formik.setFieldValue(`purchase_items.${idx}.${field}`, numValue);
|
|
} else if (floatFields.includes(field)) {
|
|
const numValue =
|
|
typeof value === 'string' ? parseFloat(value) || 0 : value;
|
|
formik.setFieldValue(`purchase_items.${idx}.${field}`, numValue);
|
|
} else {
|
|
formik.setFieldValue(`purchase_items.${idx}.${field}`, value);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<section className='w-full'>
|
|
<header className='flex flex-col gap-4'>
|
|
<Button
|
|
href='/purchase'
|
|
variant='link'
|
|
className='w-fit p-0 text-primary'
|
|
>
|
|
<Icon icon='uil:arrow-left' width={24} height={24} />
|
|
Kembali
|
|
</Button>
|
|
<h1 className='text-2xl font-bold text-center'>
|
|
{type === 'add' && 'Tambah Purchase Request'}
|
|
{type === 'edit' && 'Edit Purchase Request'}
|
|
{type === 'detail' && 'Detail Purchase Request'}
|
|
</h1>
|
|
</header>
|
|
<form
|
|
onSubmit={formik.handleSubmit}
|
|
onReset={formik.handleReset}
|
|
className='w-full mt-8 flex flex-col gap-6'
|
|
>
|
|
{/* Basic Info Card */}
|
|
<Card
|
|
title='Informasi Purchase Request'
|
|
className={{
|
|
wrapper: 'w-full mb-4 shadow',
|
|
body: 'flex flex-col gap-6',
|
|
}}
|
|
>
|
|
<div
|
|
className={
|
|
type === 'detail'
|
|
? 'flex flex-col gap-6'
|
|
: 'grid grid-cols-1 md:grid-cols-2 gap-6'
|
|
}
|
|
>
|
|
<SelectInput
|
|
required
|
|
label='Vendor'
|
|
placeholder='Pilih Vendor...'
|
|
value={formik.values.supplier}
|
|
onChange={supplierChangeHandler}
|
|
options={supplierOptions}
|
|
onInputChange={setSupplierSelectInputValue}
|
|
isLoading={isLoadingSuppliers}
|
|
isError={
|
|
formik.touched.supplier_id &&
|
|
Boolean(formik.errors.supplier_id)
|
|
}
|
|
errorMessage={formik.errors.supplier_id as string}
|
|
isDisabled={type === 'detail'}
|
|
isClearable
|
|
/>
|
|
<TextInput
|
|
required
|
|
label='Jatuh tempo (hari)'
|
|
name='credit_term'
|
|
value={formik.values.credit_term || ''}
|
|
onChange={formik.handleChange}
|
|
onBlur={formik.handleBlur}
|
|
isError={
|
|
formik.touched.credit_term &&
|
|
Boolean(formik.errors.credit_term)
|
|
}
|
|
errorMessage={formik.errors.credit_term as string}
|
|
readOnly={type === 'detail'}
|
|
type='number'
|
|
placeholder='Masukkan Credit Term'
|
|
/>
|
|
|
|
<SelectInput
|
|
required
|
|
label='Area'
|
|
placeholder='Pilih Area...'
|
|
value={formik.values.area}
|
|
onChange={areaChangeHandler}
|
|
options={areaOptions}
|
|
onInputChange={setAreaSelectInputValue}
|
|
isLoading={isLoadingAreas}
|
|
isError={
|
|
formik.touched.area && Boolean(formik.errors.area_id)
|
|
}
|
|
errorMessage={formik.errors.area_id as string}
|
|
isDisabled={type === 'detail'}
|
|
isClearable
|
|
/>
|
|
|
|
<SelectInput
|
|
required
|
|
label='Lokasi'
|
|
placeholder={
|
|
!formik.values.area_id
|
|
? 'Pilih Area terlebih dahulu'
|
|
: 'Pilih Lokasi...'
|
|
}
|
|
value={formik.values.location}
|
|
onChange={locationChangeHandler}
|
|
options={locationOptions}
|
|
onInputChange={setLocationSelectInputValue}
|
|
isLoading={isLoadingLocations}
|
|
isError={
|
|
formik.touched.location && Boolean(formik.errors.location_id)
|
|
}
|
|
errorMessage={formik.errors.location_id as string}
|
|
isDisabled={type === 'detail' || !formik.values.area_id}
|
|
isClearable={type !== 'detail' && !!formik.values.area_id}
|
|
/>
|
|
|
|
<div className={type === 'detail' ? 'col-span-1' : 'col-span-2'}>
|
|
<TextInput
|
|
label='Notes'
|
|
name='notes'
|
|
value={formik.values.notes || ''}
|
|
onChange={formik.handleChange}
|
|
onBlur={formik.handleBlur}
|
|
isError={formik.touched.notes && Boolean(formik.errors.notes)}
|
|
errorMessage={formik.errors.notes as string}
|
|
readOnly={type === 'detail'}
|
|
placeholder='Masukkan catatan'
|
|
/>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
|
|
{/* Purchase Items Table */}
|
|
<Card
|
|
title='Item Pembelian'
|
|
className={{
|
|
wrapper: 'w-full mb-4 shadow',
|
|
title: 'mb-4',
|
|
}}
|
|
>
|
|
<div className='overflow-x-auto'>
|
|
<table className='table'>
|
|
<thead>
|
|
<tr>
|
|
{type !== 'detail' && (
|
|
<th>
|
|
<input
|
|
type='checkbox'
|
|
className='checkbox checkbox-sm'
|
|
checked={
|
|
formik.values.purchase_items?.length ===
|
|
selectedPurchaseItems.length &&
|
|
formik.values.purchase_items?.length > 0
|
|
}
|
|
onChange={(e) => {
|
|
if (e.target.checked) {
|
|
setSelectedPurchaseItems(
|
|
formik.values.purchase_items?.map(
|
|
(_, idx) => idx
|
|
) ?? []
|
|
);
|
|
} else {
|
|
setSelectedPurchaseItems([]);
|
|
}
|
|
}}
|
|
/>
|
|
</th>
|
|
)}
|
|
<th>
|
|
Gudang
|
|
<span className='text-error'>*</span>
|
|
</th>
|
|
<th>
|
|
Item
|
|
<span className='text-error'>*</span>
|
|
</th>
|
|
<th>
|
|
Jumlah
|
|
<span className='text-error'>*</span>
|
|
</th>
|
|
<th>Estimasi Harga</th>
|
|
<th>Satuan</th>
|
|
{type !== 'detail' && <th>Action</th>}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{formik.values.purchase_items?.map((item, idx) => (
|
|
<tr key={`purchase-item-${idx}`}>
|
|
{type !== 'detail' && (
|
|
<td className='!align-middle'>
|
|
<input
|
|
type='checkbox'
|
|
className='checkbox checkbox-sm'
|
|
checked={selectedPurchaseItems.includes(idx)}
|
|
onChange={(e) => {
|
|
if (e.target.checked) {
|
|
setSelectedPurchaseItems([
|
|
...selectedPurchaseItems,
|
|
idx,
|
|
]);
|
|
} else {
|
|
setSelectedPurchaseItems(
|
|
selectedPurchaseItems.filter((i) => i !== idx)
|
|
);
|
|
}
|
|
}}
|
|
/>
|
|
</td>
|
|
)}
|
|
<td>
|
|
<SelectInput
|
|
required
|
|
value={item.warehouse}
|
|
onChange={(val) => {
|
|
const warehouse = val as OptionType | null;
|
|
formik.setFieldValue(
|
|
`purchase_items.${idx}.warehouse`,
|
|
warehouse
|
|
);
|
|
formik.setFieldValue(
|
|
`purchase_items.${idx}.warehouse_id`,
|
|
(warehouse as OptionType)?.value || 0
|
|
);
|
|
formik.setFieldValue(
|
|
`purchase_items.${idx}.product_warehouse`,
|
|
null
|
|
);
|
|
formik.setFieldValue(
|
|
`purchase_items.${idx}.product_warehouse_id`,
|
|
null
|
|
);
|
|
formik.setFieldValue(
|
|
`purchase_items.${idx}.product_id`,
|
|
''
|
|
);
|
|
}}
|
|
options={warehouseOptions}
|
|
onInputChange={setWarehouseSelectInputValue}
|
|
isLoading={isLoadingWarehouses}
|
|
isError={
|
|
getPurchaseItemError(idx, 'warehouse_id').isError
|
|
}
|
|
errorMessage={
|
|
getPurchaseItemError(idx, 'warehouse_id')
|
|
.errorMessage
|
|
}
|
|
isDisabled={type === 'detail'}
|
|
isClearable
|
|
placeholder='Pilih Gudang'
|
|
className={{
|
|
wrapper: 'min-w-32',
|
|
}}
|
|
/>
|
|
</td>
|
|
<td>
|
|
<SelectInput
|
|
required
|
|
value={item.product_warehouse}
|
|
onChange={(val) => {
|
|
const productWarehouse =
|
|
val as ProductWarehouseOptionType | null;
|
|
formik.setFieldValue(
|
|
`purchase_items.${idx}.product_warehouse`,
|
|
productWarehouse
|
|
);
|
|
formik.setFieldValue(
|
|
`purchase_items.${idx}.product_warehouse_id`,
|
|
(productWarehouse as ProductWarehouseOptionType)
|
|
?.value || 0
|
|
);
|
|
formik.setFieldValue(
|
|
`purchase_items.${idx}.product_id`,
|
|
(productWarehouse as ProductWarehouseOptionType)
|
|
?.product_id || 0
|
|
);
|
|
}}
|
|
options={getProductWarehouseOptionsForItem(
|
|
item.warehouse_id
|
|
)}
|
|
onInputChange={setProductWarehouseSelectInputValue}
|
|
isLoading={isLoadingProductWarehouses}
|
|
isError={
|
|
getPurchaseItemError(idx, 'product_warehouse_id')
|
|
.isError
|
|
}
|
|
errorMessage={
|
|
getPurchaseItemError(idx, 'product_warehouse_id')
|
|
.errorMessage
|
|
}
|
|
isDisabled={type === 'detail' || !item.warehouse_id}
|
|
isClearable={type !== 'detail' && !!item.warehouse_id}
|
|
placeholder={
|
|
!item.warehouse_id
|
|
? 'Pilih Gudang terlebih dahulu'
|
|
: 'Pilih Produk'
|
|
}
|
|
className={{
|
|
wrapper: 'min-w-32',
|
|
}}
|
|
/>
|
|
</td>
|
|
<td>
|
|
<TextInput
|
|
required
|
|
name={`purchase_items.${idx}.sub_qty`}
|
|
value={item.sub_qty || ''}
|
|
onChange={(e) =>
|
|
handlePurchaseItemChange(
|
|
idx,
|
|
'sub_qty',
|
|
e.target.value
|
|
)
|
|
}
|
|
onBlur={formik.handleBlur}
|
|
type='number'
|
|
placeholder='Masukkan kuantitas'
|
|
readOnly={type === 'detail'}
|
|
className={{
|
|
wrapper: 'min-w-24',
|
|
}}
|
|
/>
|
|
</td>
|
|
<td>
|
|
<TextInput
|
|
required
|
|
name={`purchase_items.${idx}.price`}
|
|
onChange={(e) =>
|
|
handlePurchaseItemChange(
|
|
idx,
|
|
'price',
|
|
e.target.value
|
|
)
|
|
}
|
|
onBlur={formik.handleBlur}
|
|
type='number'
|
|
className={{
|
|
wrapper: 'min-w-24',
|
|
}}
|
|
disabled={true}
|
|
readOnly={true}
|
|
inputPrefix={'Rp'}
|
|
/>
|
|
</td>
|
|
<td>
|
|
<TextInput
|
|
required
|
|
name={`purchase_items.${idx}.uom`}
|
|
onBlur={formik.handleBlur}
|
|
type='number'
|
|
readOnly={true}
|
|
disabled={true}
|
|
className={{
|
|
wrapper: 'min-w-24',
|
|
}}
|
|
/>
|
|
</td>
|
|
{type !== 'detail' && (
|
|
<td>
|
|
<div className='flex justify-center'>
|
|
<Button
|
|
type='button'
|
|
color='error'
|
|
onClick={() => removePurchaseItem(idx)}
|
|
>
|
|
<Icon
|
|
icon='mdi:trash-can'
|
|
width={24}
|
|
height={24}
|
|
/>
|
|
</Button>
|
|
</div>
|
|
</td>
|
|
)}
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
{type !== 'detail' && (
|
|
<div className='flex justify-center items-center mt-4 gap-4'>
|
|
{selectedPurchaseItems.length > 0 && (
|
|
<Button
|
|
type='button'
|
|
color='error'
|
|
onClick={removeSelectedPurchaseItems}
|
|
disabled={selectedPurchaseItems.length === 0}
|
|
className='w-fit'
|
|
>
|
|
<Icon icon='mdi:trash-can' width={24} height={24} />
|
|
Hapus Terpilih ({selectedPurchaseItems.length})
|
|
</Button>
|
|
)}
|
|
<Button
|
|
type='button'
|
|
color='success'
|
|
onClick={addPurchaseItem}
|
|
className='w-fit'
|
|
>
|
|
<Icon icon='ic:round-plus' width={24} height={24} />
|
|
Tambah Item
|
|
</Button>
|
|
</div>
|
|
)}
|
|
</Card>
|
|
|
|
{/* Action buttons */}
|
|
<div className='flex flex-row justify-between gap-2 flex-wrap'>
|
|
{type !== 'detail' && (
|
|
<div className='flex flex-row justify-end gap-2 w-full'>
|
|
<Button type='reset' color='warning' className='px-4'>
|
|
Reset
|
|
</Button>
|
|
|
|
<Button
|
|
type='submit'
|
|
color='primary'
|
|
className='px-4'
|
|
isLoading={formik.isSubmitting}
|
|
disabled={!formik.isValid || formik.isSubmitting}
|
|
>
|
|
Submit
|
|
</Button>
|
|
</div>
|
|
)}
|
|
{type === 'detail' && (
|
|
<div className='flex flex-row justify-end gap-2 w-full'>
|
|
<Button
|
|
href={`/purchase/detail/edit/?purchaseId=${initialValues?.id}`}
|
|
color='primary'
|
|
className='px-4'
|
|
>
|
|
Edit
|
|
</Button>
|
|
|
|
<Button
|
|
type='button'
|
|
color='error'
|
|
onClick={deletePurchaseRequestClickHandler}
|
|
className='px-4'
|
|
>
|
|
Delete
|
|
</Button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{purchaseRequestFormErrorMessage && (
|
|
<div role='alert' className='alert alert-error'>
|
|
<Icon
|
|
icon='material-symbols:error-outline'
|
|
width={24}
|
|
height={24}
|
|
/>
|
|
<span>{purchaseRequestFormErrorMessage}</span>
|
|
</div>
|
|
)}
|
|
</form>
|
|
</section>
|
|
|
|
{type !== 'add' && (
|
|
<ConfirmationModal
|
|
ref={deleteModal.ref}
|
|
type='error'
|
|
text='Apakah anda yakin ingin menghapus data Purchase Request ini?'
|
|
secondaryButton={{
|
|
text: 'Tidak',
|
|
}}
|
|
primaryButton={{
|
|
text: 'Ya',
|
|
color: 'error',
|
|
isLoading: isDeleteLoading,
|
|
onClick: confirmationModalDeleteClickHandler,
|
|
}}
|
|
/>
|
|
)}
|
|
</>
|
|
);
|
|
};
|
|
|
|
export default PurchaseRequestForm;
|