merge: resolve conflict

This commit is contained in:
rstubryan
2025-10-17 13:18:34 +07:00
11 changed files with 1023 additions and 888 deletions
+4 -1
View File
@@ -64,7 +64,10 @@ export const FormActions = <T,>({
type='reset' type='reset'
color='warning' color='warning'
className='px-4' className='px-4'
onClick={formik.handleReset} onClick={() => {
formik.handleReset();
formik.validateForm();
}}
> >
Reset Reset
</Button> </Button>
@@ -1,355 +1,56 @@
'use client'; 'use client';
import { useState, useMemo } from 'react'; import { useState } from 'react';
import useSWR from 'swr';
import { SortingState } from '@tanstack/react-table'; import { SortingState } from '@tanstack/react-table';
import { Icon } from '@iconify/react';
import Table from '@/components/Table'; import Table from '@/components/Table';
import { useModal } from '@/components/Modal'; import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal'; import ConfirmationModal from '@/components/modal/ConfirmationModal';
import { ROWS_OPTIONS } from '@/config/constant';
import { Movement } from '@/types/api/inventory/movement'; import { Movement } from '@/types/api/inventory/movement';
import { MovementApi } from '@/services/api/inventory';
import { cn } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { TableToolbar } from '@/components/table/TableToolbar'; import { TableToolbar } from '@/components/table/TableToolbar';
import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector'; import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
import { TableRowOptions } from '@/components/table/TableRowOptions';
import { OptionType } from '@/components/input/SelectInput'; import { OptionType } from '@/components/input/SelectInput';
import Button from '@/components/Button'; import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import { cn } from '@/lib/helper'; import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import { TableRowOptions } from '@/components/table/TableRowOptions';
// Dummy data
const baseMetadata = {
created_user: {
id: 1,
id_user: 1,
email: 'user@example.com',
name: 'User',
},
created_at: '2024-06-01T00:00:00Z',
updated_at: '2024-06-01T00:00:00Z',
};
const dummyMovements: Movement[] = [
{
...baseMetadata,
id: 1,
alasan_transfer: 'Restock',
tanggal_transfer: '2024-06-01',
warehouse_asal: {
...baseMetadata,
id: 1,
name: 'Warehouse A',
type: 'AREA',
area: { id: 1, name: 'Area 1' },
},
warehouse_tujuan: {
...baseMetadata,
id: 2,
name: 'Warehouse B',
type: 'AREA',
area: { id: 2, name: 'Area 2' },
},
product: [
{
product: {
...baseMetadata,
id: 1,
name: 'Product X',
brand: 'Brand X',
sku: 'SKU-X',
product_price: 10000,
selling_price: 12000,
tax: 10,
expiry_period: 365,
uom: {
...baseMetadata,
id: 1,
name: 'PCS',
},
product_category: {
...baseMetadata,
id: 1,
code: 'CAT-1',
name: 'Category 1',
},
suppliers: [],
flags: [],
},
qty_product: 10,
},
],
ekspedisi: [
{
product_id: 1,
qty: 10,
supplier: {
...baseMetadata,
id: 1,
name: 'Supplier 1',
alias: 'S1',
category: 'General',
pic: 'PIC 1',
type: 'Type 1',
hatchery: 'Hatchery 1',
phone: '08123456789',
email: 'supplier1@example.com',
address: 'Address 1',
npwp: '1234567890123456',
account_number: '1234567890',
balance: 0,
due_date: 30,
},
plat_nomor: 'B 1234 CD',
no_surat_jalan: 'SJ-001',
dokumen: 'doc1.pdf',
biaya_ekspedisi: 50000,
nama_sopir: 'Andi',
},
],
},
{
...baseMetadata,
id: 2,
alasan_transfer: 'Mutasi Stok',
tanggal_transfer: '2024-06-02',
warehouse_asal: {
...baseMetadata,
id: 2,
name: 'Warehouse B',
type: 'AREA',
area: { id: 2, name: 'Area 2' },
},
warehouse_tujuan: {
...baseMetadata,
id: 3,
name: 'Warehouse C',
type: 'AREA',
area: { id: 3, name: 'Area 3' },
},
product: [
{
product: {
...baseMetadata,
id: 2,
name: 'Product Y',
brand: 'Brand Y',
sku: 'SKU-Y',
product_price: 20000,
selling_price: 25000,
tax: 5,
expiry_period: 180,
uom: {
...baseMetadata,
id: 2,
name: 'BOX',
},
product_category: {
...baseMetadata,
id: 2,
code: 'CAT-2',
name: 'Category 2',
},
suppliers: [],
flags: [],
},
qty_product: 5,
},
],
ekspedisi: [
{
product_id: 2,
qty: 5,
supplier: {
...baseMetadata,
id: 2,
name: 'Supplier 2',
alias: 'S2',
category: 'Special',
pic: 'PIC 2',
type: 'Type 2',
hatchery: 'Hatchery 2',
phone: '08123456780',
email: 'supplier2@example.com',
address: 'Address 2',
npwp: '1234567890123457',
account_number: '1234567891',
balance: 1000,
due_date: 15,
},
plat_nomor: 'D 5678 EF',
no_surat_jalan: 'SJ-002',
dokumen: 'doc2.pdf',
biaya_ekspedisi: 60000,
nama_sopir: 'Budi',
},
],
},
{
...baseMetadata,
id: 3,
alasan_transfer: 'Pengembalian',
tanggal_transfer: '2024-06-03',
warehouse_asal: {
...baseMetadata,
id: 3,
name: 'Warehouse C',
type: 'AREA',
area: { id: 3, name: 'Area 3' },
},
warehouse_tujuan: {
...baseMetadata,
id: 1,
name: 'Warehouse A',
type: 'AREA',
area: { id: 1, name: 'Area 1' },
},
product: [
{
product: {
...baseMetadata,
id: 3,
name: 'Product Z',
brand: 'Brand Z',
sku: 'SKU-Z',
product_price: 15000,
selling_price: 18000,
tax: 8,
expiry_period: 90,
uom: {
...baseMetadata,
id: 3,
name: 'KG',
},
product_category: {
...baseMetadata,
id: 3,
code: 'CAT-3',
name: 'Category 3',
},
suppliers: [],
flags: [],
},
qty_product: 8,
},
],
ekspedisi: [
{
product_id: 3,
qty: 8,
supplier: {
...baseMetadata,
id: 3,
name: 'Supplier 3',
alias: 'S3',
category: 'Return',
pic: 'PIC 3',
type: 'Type 3',
hatchery: 'Hatchery 3',
phone: '08123456781',
email: 'supplier3@example.com',
address: 'Address 3',
npwp: '1234567890123458',
account_number: '1234567892',
balance: 500,
due_date: 10,
},
plat_nomor: 'F 9101 GH',
no_surat_jalan: 'SJ-003',
dokumen: 'doc3.pdf',
biaya_ekspedisi: 40000,
nama_sopir: 'Cici',
},
],
},
{
...baseMetadata,
id: 4,
alasan_transfer: 'Transfer Internal',
tanggal_transfer: '2024-06-04',
warehouse_asal: {
...baseMetadata,
id: 4,
name: 'Warehouse D',
type: 'AREA',
area: { id: 4, name: 'Area 4' },
},
warehouse_tujuan: {
...baseMetadata,
id: 5,
name: 'Warehouse E',
type: 'AREA',
area: { id: 5, name: 'Area 5' },
},
product: [
{
product: {
...baseMetadata,
id: 4,
name: 'Product A',
brand: 'Brand A',
sku: 'SKU-A',
product_price: 5000,
selling_price: 7000,
tax: 0,
expiry_period: 60,
uom: {
...baseMetadata,
id: 4,
name: 'LITER',
},
product_category: {
...baseMetadata,
id: 4,
code: 'CAT-4',
name: 'Category 4',
},
suppliers: [],
flags: [],
},
qty_product: 20,
},
],
ekspedisi: [
{
product_id: 4,
qty: 20,
supplier: {
...baseMetadata,
id: 4,
name: 'Supplier 4',
alias: 'S4',
category: 'Internal',
pic: 'PIC 4',
type: 'Type 4',
hatchery: 'Hatchery 4',
phone: '08123456782',
email: 'supplier4@example.com',
address: 'Address 4',
npwp: '1234567890123459',
account_number: '1234567893',
balance: 200,
due_date: 20,
},
plat_nomor: 'H 2345 IJ',
no_surat_jalan: 'SJ-004',
dokumen: 'doc4.pdf',
biaya_ekspedisi: 30000,
nama_sopir: 'Dedi',
},
],
},
];
const MovementTable = () => { const MovementTable = () => {
const [search, setSearch] = useState(''); const {
const [page, setPage] = useState(1); state: tableFilterState,
const [pageSize, setPageSize] = useState(10); updateFilter,
setPage,
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: '' },
paramMap: { page: 'page', pageSize: 'limit' },
});
const [sorting, setSorting] = useState<SortingState>([]); const [sorting, setSorting] = useState<SortingState>([]);
const [, setSelectedMovement] = useState<Movement | undefined>(undefined); const [selectedMovement, setSelectedMovement] = useState<
Movement | undefined
>(undefined);
const [isDeleteLoading, setIsDeleteLoading] = useState(false); const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const deleteModal = useModal(); const deleteModal = useModal();
const {
data: movements,
isLoading,
mutate: refreshMovements,
} = useSWR(
`${MovementApi.basePath}${getTableFilterQueryString()}`,
MovementApi.getAllFetcher
);
const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => { const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearch(e.target.value); updateFilter('search', e.target.value);
setPage(1); setPage(1);
}; };
@@ -361,17 +62,15 @@ const MovementTable = () => {
const confirmationModalDeleteClickHandler = async () => { const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true); setIsDeleteLoading(true);
setTimeout(() => { try {
setIsDeleteLoading(false); await MovementApi.delete(selectedMovement?.id as number);
refreshMovements();
deleteModal.closeModal(); deleteModal.closeModal();
}, 1000); } finally {
setIsDeleteLoading(false);
}
}; };
const paginatedData = useMemo(() => {
const start = (page - 1) * pageSize;
return dummyMovements.slice(start, start + pageSize);
}, [page, pageSize]);
return ( return (
<div className='flex flex-col gap-4'> <div className='flex flex-col gap-4'>
<div className='flex flex-col gap-2 mb-4'> <div className='flex flex-col gap-2 mb-4'>
@@ -381,81 +80,120 @@ const MovementTable = () => {
label: 'Tambah Movement', label: 'Tambah Movement',
}} }}
search={{ search={{
value: search, value: tableFilterState.search,
onChange: searchChangeHandler, onChange: searchChangeHandler,
placeholder: 'Cari Movement', placeholder: 'Cari Movement',
}} }}
/> />
<TableRowSizeSelector <TableRowSizeSelector
value={pageSize} value={tableFilterState.pageSize}
onChange={pageSizeChangeHandler} onChange={pageSizeChangeHandler}
options={ROWS_OPTIONS} options={ROWS_OPTIONS}
/> />
</div> </div>
<Table <Table<Movement>
data={paginatedData} data={isResponseSuccess(movements) ? movements?.data : []}
columns={[ columns={[
{ {
header: '#', header: '#',
cell: (props) => pageSize * (page - 1) + props.row.index + 1,
},
{
accessorKey: 'warehouse_asal',
header: 'Gudang Asal',
cell: (props) => props.row.original.warehouse_asal.name,
},
{
accessorKey: 'warehouse_tujuan',
header: 'Gudang Tujuan',
cell: (props) => props.row.original.warehouse_tujuan.name,
},
{
accessorKey: 'product',
header: 'Nama Produk',
cell: (props) => cell: (props) =>
props.row.original.product.map((p) => p.product.name), tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index +
1,
}, },
{ {
accessorKey: 'alasan_transfer', accessorFn: (row) => row.source_warehouse?.name,
header: 'Gudang Asal',
},
{
accessorFn: (row) => row.destination_warehouse?.name,
header: 'Gudang Tujuan',
},
{
accessorKey: 'transfer_reason',
header: 'Catatan', header: 'Catatan',
}, },
{ {
accessorKey: 'biaya_ekspedisi', accessorKey: 'transfer_date',
header: 'Biaya Ekspedisi', header: 'Tanggal',
cell: (props) => cell: (props) =>
props.row.original.ekspedisi.map((e) => e.biaya_ekspedisi), new Date(props.row.original.transfer_date).toLocaleDateString(
'id-ID'
),
}, },
{ {
id: 'actions', accessorFn: (row) => {
cell: (props) => ( const totalCost = row.deliveries?.reduce(
<div className='dropdown dropdown-end'> (sum, d) => sum + (d.shipping_cost_total || 0),
<Button tabIndex={0} variant='ghost' className='px-2'> 0
<Icon icon='carbon:overflow-menu-vertical' /> );
</Button> return totalCost?.toLocaleString('id-ID');
<TableRowOptions },
type='dropdown' header: 'Biaya Pengiriman',
recordId={props.row.original.id} },
basePath='/inventory/movement' {
onDelete={() => { header: 'Aksi',
setSelectedMovement(props.row.original); cell: (props) => {
deleteModal.openModal(); const currentPageSize =
}} props.table.getPaginationRowModel().rows.length;
/> const currentPageRows =
</div> props.table.getPaginationRowModel().flatRows;
), const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
const deleteClickHandler = () => {
setSelectedMovement(props.row.original);
deleteModal.openModal();
};
return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<TableRowOptions
type='dropdown'
recordId={props.row.original.id}
basePath='/inventory/movement'
queryParam='movementId'
showEdit={false}
showDelete={false}
/>
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<TableRowOptions
type='collapse'
recordId={props.row.original.id}
basePath='/inventory/movement'
queryParam='movementId'
showEdit={false}
showDelete={false}
/>
</RowCollapseOptions>
)}
</>
);
},
}, },
]} ]}
pageSize={pageSize} pageSize={tableFilterState.pageSize}
page={page} page={isResponseSuccess(movements) ? movements?.meta?.page : 0}
totalItems={dummyMovements.length} totalItems={
isResponseSuccess(movements) ? movements?.meta?.total_results : 0
}
onPageChange={setPage} onPageChange={setPage}
isLoading={false} isLoading={isLoading}
sorting={sorting} sorting={sorting}
setSorting={setSorting} setSorting={setSorting}
className={{ className={{
containerClassName: cn({ containerClassName: cn({
'mb-20': paginatedData.length === 0, 'mb-20':
isResponseSuccess(movements) && movements?.data?.length === 0,
}), }),
tableWrapperClassName: 'overflow-x-auto min-h-full!', tableWrapperClassName: 'overflow-x-auto min-h-full!',
tableClassName: 'font-inter w-full table-auto min-h-full!', tableClassName: 'font-inter w-full table-auto min-h-full!',
@@ -7,27 +7,28 @@ export type ProductSchema = {
label: string; label: string;
} | null; } | null;
product_id: number; product_id: number;
qty_product: number; product_qty: number;
}; };
export type EkspedisiSchema = { export type DeliverySchema = {
product: { delivery_cost: number;
value: number; delivery_cost_per_item?: number | undefined;
label: string; document?: File | string | null;
} | null; driver_name: string;
product_id: number; vehicle_plate: string;
qty: number;
supplier: { supplier: {
value: number; value: number;
label: string; label: string;
} | null; } | null;
supplier_id: number; supplier_id: number;
plat_nomor: string; products: {
no_surat_jalan: string; product: {
dokumen: string | File; value: number;
biaya_ekspedisi: number; label: string;
biaya_ekspedisi_per_item?: number | undefined; } | null;
nama_sopir: string; product_id: number;
product_qty: number;
}[];
}; };
const ProductObjectSchema: Yup.ObjectSchema<ProductSchema> = Yup.object({ const ProductObjectSchema: Yup.ObjectSchema<ProductSchema> = Yup.object({
@@ -36,94 +37,80 @@ const ProductObjectSchema: Yup.ObjectSchema<ProductSchema> = Yup.object({
label: Yup.string().required(), label: Yup.string().required(),
}).nullable(), }).nullable(),
product_id: Yup.number().required('Produk wajib diisi!'), product_id: Yup.number().required('Produk wajib diisi!'),
qty_product: Yup.number() product_qty: Yup.number()
.required('Qty wajib diisi!') .required('Qty wajib diisi!')
.min(1, 'Qty minimal 1!') .min(1, 'Qty minimal 1!')
.typeError('Qty harus berupa angka!'), .typeError('Qty harus berupa angka!'),
}); });
const EkspedisiObjectSchema: Yup.ObjectSchema<EkspedisiSchema> = Yup.object({ const DeliveryProductObjectSchema = Yup.object({
product: Yup.object({ product: Yup.object({
value: Yup.number().min(1).required(), value: Yup.number().min(1).required(),
label: Yup.string().required(), label: Yup.string().required(),
}).nullable(), }).nullable(),
product_id: Yup.number().required('Produk wajib diisi!'), product_id: Yup.number().required('Produk wajib diisi!'),
qty: Yup.number() product_qty: Yup.number()
.required('Qty wajib diisi!') .required('Qty wajib diisi!')
.min(1, 'Qty minimal 1!') .min(1, 'Qty minimal 1!')
.typeError('Qty harus berupa angka!') .typeError('Qty harus berupa angka!'),
.test('max-product-qty', 'Qty melebihi stok produk!', function (value) { });
const { product_id } = this.parent;
const products = (this.options.context?.product ?? []) as { const DeliveryObjectSchema: Yup.ObjectSchema<DeliverySchema> = Yup.object({
product_id: number; delivery_cost: Yup.number()
qty_product: number; .required('Biaya pengiriman wajib diisi!')
}[]; .min(1, 'Biaya minimal 1!')
const product = products.find((p) => p.product_id === product_id); .typeError('Biaya harus berupa angka!'),
if (!product) return true; delivery_cost_per_item: Yup.number()
return (value ?? 0) <= Number(product.qty_product); .transform((value) => (isNaN(value) ? undefined : value))
.min(1, 'Biaya per item minimal 1!')
.typeError('Biaya per item harus berupa angka!'),
document_index: Yup.number().optional(),
document: Yup.mixed<File | string>()
.nullable()
.test('fileSize', 'Ukuran dokumen maksimal 2 MB', (value) => {
if (!value) return true;
if (typeof value === 'string') return true;
if (value instanceof File) return value.size <= 2 * 1024 * 1024;
return false;
}), }),
driver_name: Yup.string().required('Nama sopir wajib diisi!'),
vehicle_plate: Yup.string().required('Plat nomor wajib diisi!'),
supplier: Yup.object({ supplier: Yup.object({
value: Yup.number().min(1).required(), value: Yup.number().min(1).required(),
label: Yup.string().required(), label: Yup.string().required(),
}).nullable(), }).nullable(),
supplier_id: Yup.number().required('Supplier wajib diisi!'), supplier_id: Yup.number().required('Supplier wajib diisi!'),
plat_nomor: Yup.string().required('Plat nomor wajib diisi!'), products: Yup.array()
no_surat_jalan: Yup.string().required('No surat jalan wajib diisi!'), .of(DeliveryProductObjectSchema)
dokumen: Yup.mixed<string | File>() .min(1, 'Minimal harus ada 1 produk!')
.required('Dokumen wajib diisi!') .required('Produk wajib diisi!'),
.test(
'fileType',
'Mohon upload file berformat PDF atau JPEG/JPG.',
(value) =>
typeof value === 'string' ||
(value instanceof File &&
['application/pdf', 'image/jpeg', 'image/jpg'].includes(value.type))
)
.test(
'fileSize',
'Ukuran dokumen maksimal 2 MB!',
(value) =>
typeof value === 'string' ||
(value instanceof File && value.size <= 2 * 1024 * 1024)
),
biaya_ekspedisi: Yup.number()
.required('Biaya ekspedisi wajib diisi!')
.min(0, 'Biaya minimal 0!')
.typeError('Biaya harus berupa angka!'),
biaya_ekspedisi_per_item: Yup.number()
.transform((value) => (isNaN(value) ? undefined : value))
.min(0, 'Biaya per item minimal 0!')
.typeError('Biaya per item harus berupa angka!')
.optional()
.default(undefined),
nama_sopir: Yup.string().required('Nama sopir wajib diisi!'),
}); });
export const MovementFormSchema = Yup.object({ export const MovementFormSchema = Yup.object({
alasan_transfer: Yup.string().required('Alasan transfer wajib diisi!'), transfer_reason: Yup.string().required('Alasan transfer wajib diisi!'),
tanggal_transfer: Yup.string().required('Tanggal transfer wajib diisi!'), transfer_date: Yup.string().required('Tanggal transfer wajib diisi!'),
warehouse_asal: Yup.object({ source_warehouse: Yup.object({
value: Yup.number().min(1).required(), value: Yup.number().min(1).required(),
label: Yup.string().required(), label: Yup.string().required(),
}).nullable(), }).nullable(),
warehouse_asal_id: Yup.number() source_warehouse_id: Yup.number()
.required('Gudang asal wajib diisi!') .required('Gudang asal wajib diisi!')
.typeError('Gudang asal wajib diisi!'), .typeError('Gudang asal wajib diisi!'),
warehouse_tujuan: Yup.object({ destination_warehouse: Yup.object({
value: Yup.number().min(1).required(), value: Yup.number().min(1).required(),
label: Yup.string().required(), label: Yup.string().required(),
}).nullable(), }).nullable(),
warehouse_tujuan_id: Yup.number() destination_warehouse_id: Yup.number()
.required('Gudang tujuan wajib diisi!') .required('Gudang tujuan wajib diisi!')
.typeError('Gudang tujuan wajib diisi!'), .typeError('Gudang tujuan wajib diisi!'),
product: Yup.array() products: Yup.array()
.of(ProductObjectSchema) .of(ProductObjectSchema)
.min(1, 'Minimal harus ada 1 produk!') .min(1, 'Minimal harus ada 1 produk!')
.required('Produk wajib diisi!'), .required('Produk wajib diisi!'),
ekspedisi: Yup.array() deliveries: Yup.array()
.of(EkspedisiObjectSchema) .of(DeliveryObjectSchema)
.min(1, 'Minimal harus ada 1 ekspedisi!') .min(1, 'Minimal harus ada 1 pengiriman!')
.required('Ekspedisi wajib diisi!'), .required('Pengiriman wajib diisi!'),
}); });
export const UpdateMovementFormSchema = MovementFormSchema; export const UpdateMovementFormSchema = MovementFormSchema;
@@ -132,41 +119,61 @@ export type MovementFormValues = Yup.InferType<typeof MovementFormSchema>;
export const getMovementFormInitialValues = ( export const getMovementFormInitialValues = (
initialValues?: Movement initialValues?: Movement
): MovementFormValues => ({ ): MovementFormValues => {
alasan_transfer: initialValues?.alasan_transfer ?? '', const detailIdToProductId = new Map<number, number>();
tanggal_transfer: initialValues?.tanggal_transfer ?? '', initialValues?.details?.forEach((detail) => {
warehouse_asal: initialValues?.warehouse_asal detailIdToProductId.set(detail.id, detail.product_id);
? { });
value: initialValues.warehouse_asal.id,
label: initialValues.warehouse_asal.name, return {
} transfer_reason: initialValues?.transfer_reason ?? '',
: null, transfer_date: initialValues?.transfer_date ?? '',
warehouse_asal_id: initialValues?.warehouse_asal?.id ?? 0, source_warehouse: initialValues?.source_warehouse
warehouse_tujuan: initialValues?.warehouse_tujuan ? {
? { value: initialValues.source_warehouse.id,
value: initialValues.warehouse_tujuan.id, label: initialValues.source_warehouse.name,
label: initialValues.warehouse_tujuan.name, }
} : null,
: null, source_warehouse_id: initialValues?.source_warehouse?.id ?? 0,
warehouse_tujuan_id: initialValues?.warehouse_tujuan?.id ?? 0, destination_warehouse: initialValues?.destination_warehouse
product: ? {
initialValues?.product?.map((p) => ({ value: initialValues.destination_warehouse.id,
product: { value: p.product.id, label: p.product.name }, label: initialValues.destination_warehouse.name,
product_id: p.product.id, }
qty_product: p.qty_product, : null,
})) ?? [], destination_warehouse_id: initialValues?.destination_warehouse?.id ?? 0,
ekspedisi: products:
initialValues?.ekspedisi?.map((e) => ({ initialValues?.details?.map((p) => ({
product: { value: e.product_id, label: '' }, product: { value: p.product_id, label: `Product ID: ${p.product_id}` },
product_id: e.product_id, product_id: p.product_id,
qty: e.qty, product_qty: p.quantity,
supplier: { value: e.supplier.id, label: e.supplier.name }, })) ?? [],
supplier_id: e.supplier.id, deliveries:
plat_nomor: e.plat_nomor, initialValues?.deliveries?.map((d) => {
no_surat_jalan: e.no_surat_jalan, return {
dokumen: e.dokumen, delivery_cost: d.shipping_cost_total,
biaya_ekspedisi: e.biaya_ekspedisi, delivery_cost_per_item: d.shipping_cost_item,
biaya_ekspedisi_per_item: e.biaya_ekspedisi, document_index: 0,
nama_sopir: e.nama_sopir, document: d.document_path || null,
})) ?? [], driver_name: d.driver_name,
}); vehicle_plate: d.vehicle_plate,
supplier: d.supplier
? { value: d.supplier.id, label: d.supplier.name }
: null,
supplier_id: d.supplier_id,
products: d.items.map((item) => {
const productId =
detailIdToProductId.get(item.stock_transfer_detail_id) ?? 0;
return {
product:
productId > 0
? { value: productId, label: `Product ID: ${productId}` }
: null,
product_id: productId,
product_qty: item.quantity,
};
}),
};
}) ?? [],
};
};
File diff suppressed because it is too large Load Diff
@@ -8,7 +8,6 @@ import {
UpdateMovementPayload, UpdateMovementPayload,
} from '@/types/api/inventory/movement'; } from '@/types/api/inventory/movement';
import { isResponseError } from '@/lib/api-helper'; import { isResponseError } from '@/lib/api-helper';
import { containsFile, toFormData } from '@/lib/form-data';
export const useMovementFormHandlers = (initialValuesId?: number) => { export const useMovementFormHandlers = (initialValuesId?: number) => {
const router = useRouter(); const router = useRouter();
@@ -17,12 +16,16 @@ export const useMovementFormHandlers = (initialValuesId?: number) => {
const [isDeleteLoading, setIsDeleteLoading] = useState(false); const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const createMovementHandler = useCallback( const createMovementHandler = useCallback(
async (payload: CreateMovementPayload) => { async (payload: CreateMovementPayload, documents: File[] = []) => {
const finalPayload = containsFile(payload) const formData = new FormData();
? (toFormData(payload) as unknown as CreateMovementPayload) formData.append('data', JSON.stringify(payload));
: payload; documents.forEach((file, index) => {
formData.append(`documents[${index}]`, file);
});
const res = await MovementApi.create(finalPayload); const res = await MovementApi.create(
formData as unknown as CreateMovementPayload
);
if (isResponseError(res)) { if (isResponseError(res)) {
setMovementFormErrorMessage(res.message); setMovementFormErrorMessage(res.message);
return; return;
@@ -34,10 +37,24 @@ export const useMovementFormHandlers = (initialValuesId?: number) => {
); );
const updateMovementHandler = useCallback( const updateMovementHandler = useCallback(
async (movementId: number, payload: UpdateMovementPayload) => { async (
const finalPayload = containsFile(payload) movementId: number,
? (toFormData(payload) as unknown as UpdateMovementPayload) payload: UpdateMovementPayload,
: payload; documents: File[] = []
) => {
let finalPayload: UpdateMovementPayload | FormData;
if (documents.length > 0) {
const formData = new FormData();
formData.append('data', JSON.stringify(payload));
documents.forEach((file, index) => {
formData.append(`documents[${index}]`, file);
});
finalPayload = formData as unknown as UpdateMovementPayload;
} else {
finalPayload = payload;
}
const res = await MovementApi.update(movementId, finalPayload); const res = await MovementApi.update(movementId, finalPayload);
if (res?.status === 'error') { if (res?.status === 'error') {
+21 -12
View File
@@ -7,6 +7,9 @@ interface TableRowOptionsProps {
recordId: string | number; recordId: string | number;
basePath: string; basePath: string;
onDelete?: () => void; onDelete?: () => void;
queryParam?: string;
showEdit?: boolean;
showDelete?: boolean;
} }
export const TableRowOptions = ({ export const TableRowOptions = ({
@@ -14,6 +17,9 @@ export const TableRowOptions = ({
recordId, recordId,
basePath, basePath,
onDelete, onDelete,
queryParam = 'id',
showEdit = true,
showDelete = true,
}: TableRowOptionsProps) => ( }: TableRowOptionsProps) => (
<div <div
tabIndex={type === 'dropdown' ? 0 : undefined} tabIndex={type === 'dropdown' ? 0 : undefined}
@@ -26,7 +32,7 @@ export const TableRowOptions = ({
)} )}
> >
<Button <Button
href={`${basePath}/detail/?id=${recordId}`} href={`${basePath}/detail/?${queryParam}=${recordId}`}
variant='ghost' variant='ghost'
color='primary' color='primary'
className='justify-start text-sm' className='justify-start text-sm'
@@ -34,16 +40,18 @@ export const TableRowOptions = ({
<Icon icon='mdi:eye-outline' width={16} height={16} /> <Icon icon='mdi:eye-outline' width={16} height={16} />
Detail Detail
</Button> </Button>
<Button {showEdit && (
href={`${basePath}/detail/edit/?id=${recordId}`} <Button
variant='ghost' href={`${basePath}/detail/edit/?${queryParam}=${recordId}`}
color='warning' variant='ghost'
className='justify-start text-sm' color='warning'
> className='justify-start text-sm'
<Icon icon='material-symbols:edit-outline' width={16} height={16} /> >
Edit <Icon icon='mdi:pencil-outline' width={16} height={16} />
</Button> Edit
{onDelete && ( </Button>
)}
{showDelete && onDelete && (
<Button <Button
onClick={onDelete} onClick={onDelete}
variant='ghost' variant='ghost'
@@ -51,9 +59,10 @@ export const TableRowOptions = ({
className='text-error hover:text-inherit justify-start text-sm' className='text-error hover:text-inherit justify-start text-sm'
> >
<Icon <Icon
icon='material-symbols:delete-outline-rounded' icon='mdi:delete-outline'
width={16} width={16}
height={16} height={16}
className='justify-start text-sm'
/> />
Delete Delete
</Button> </Button>
-12
View File
@@ -125,18 +125,6 @@ export const MAIN_DRAWER_LINKS: MAIN_DRAWER_MENU[] = [
}, },
], ],
}, },
{
title: 'Persediaan',
link: '/inventory',
icon: 'material-symbols:box-outline-rounded',
submenu: [
{
title: 'Penyesuaian Persediaan',
link: '/inventory/adjustment',
icon: 'material-symbols:box-edit-outline-rounded',
}
]
},
] as const; ] as const;
export const ROWS_OPTIONS = [ export const ROWS_OPTIONS = [
+13 -3
View File
@@ -1,4 +1,9 @@
import { BaseApiService } from '@/services/api/base'; import { BaseApiService } from '@/services/api/base';
import {
CreateProductWarehousePayload,
ProductWarehouse,
UpdateProductWarehousePayload,
} from '@/types/api/inventory/product-warehouse';
import { import {
CreateMovementPayload, CreateMovementPayload,
Movement, Movement,
@@ -7,17 +12,22 @@ import {
import { import {
CreateInventoryAdjustmentPayload, CreateInventoryAdjustmentPayload,
InventoryAdjustment, InventoryAdjustment,
UpdateInventoryAdjustmentPayload,
} from '@/types/api/inventory/adjustment'; } from '@/types/api/inventory/adjustment';
export const ProductWarehouseApi = new BaseApiService<
ProductWarehouse,
CreateProductWarehousePayload,
UpdateProductWarehousePayload
>('/inventory/product-warehouses');
export const MovementApi = new BaseApiService< export const MovementApi = new BaseApiService<
Movement, Movement,
CreateMovementPayload, CreateMovementPayload,
UpdateMovementPayload UpdateMovementPayload
>('/inventory/movements'); >('/inventory/transfers');
export const inventoryAdjustmentApi = new BaseApiService< export const inventoryAdjustmentApi = new BaseApiService<
InventoryAdjustment, InventoryAdjustment,
CreateInventoryAdjustmentPayload, CreateInventoryAdjustmentPayload,
UpdateInventoryAdjustmentPayload unknown
>('/inventory/adjustments'); >('/inventory/adjustments');
+4 -1
View File
@@ -14,6 +14,9 @@ export async function httpClient<T, B = unknown>(
(!opts.auth && opts.auth !== 'none' && opts.auth !== 'bearer'); (!opts.auth && opts.auth !== 'none' && opts.auth !== 'bearer');
const isBearerAuth = opts.auth === 'bearer' && !!opts.token; const isBearerAuth = opts.auth === 'bearer' && !!opts.token;
const isFormData =
typeof FormData !== 'undefined' && opts.body instanceof FormData;
const config: AxiosRequestConfig = { const config: AxiosRequestConfig = {
url: path, url: path,
method: opts.method ?? 'GET', method: opts.method ?? 'GET',
@@ -22,7 +25,7 @@ export async function httpClient<T, B = unknown>(
timeout: opts.timeoutMs ?? 10_000, timeout: opts.timeoutMs ?? 10_000,
withCredentials: isCookieAuth && !isBearerAuth, withCredentials: isCookieAuth && !isBearerAuth,
headers: { headers: {
'Content-Type': 'application/json', ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
...(opts.headers ?? {}), ...(opts.headers ?? {}),
...(isBearerAuth && !isCookieAuth ...(isBearerAuth && !isCookieAuth
? { Authorization: `Bearer ${opts.token}` } ? { Authorization: `Bearer ${opts.token}` }
+40 -31
View File
@@ -1,51 +1,60 @@
import { BaseMetadata } from '@/types/api/api-general'; import { BaseMetadata } from '@/types/api/api-general';
import { Product } from '@/types/api/master-data/product';
import { Supplier } from '@/types/api/master-data/supplier'; import { Supplier } from '@/types/api/master-data/supplier';
import { Warehouse } from '@/types/api/master-data/warehouse'; import { Warehouse } from '@/types/api/master-data/warehouse';
export type BaseMovement = { export type BaseMovement = {
id: number; id: number;
alasan_transfer: string; transfer_reason: string;
tanggal_transfer: string; transfer_date: string;
warehouse_asal: Warehouse; source_warehouse: Warehouse;
warehouse_tujuan: Warehouse; destination_warehouse: Warehouse;
product: { details: {
product: Product; id: number;
qty_product: number;
}[];
ekspedisi: {
product_id: number; product_id: number;
qty: number; quantity: number;
before_quantity: number;
after_quantity: number;
}[];
deliveries: {
id: number;
supplier_id: number;
supplier: Supplier; supplier: Supplier;
plat_nomor: string; vehicle_plate: string;
no_surat_jalan: string; driver_name: string;
dokumen: string; document_number: string;
biaya_ekspedisi: number; document_path: string;
nama_sopir: string; shipping_cost_item: number;
shipping_cost_total: number;
items: {
id: number;
stock_transfer_detail_id: number;
quantity: number;
}[];
}[]; }[];
}; };
export type Movement = BaseMetadata & BaseMovement; export type Movement = BaseMetadata & BaseMovement;
export type CreateMovementPayload = { export type CreateMovementPayload = {
alasan_transfer: string; transfer_reason: string;
tanggal_transfer: string; transfer_date: string;
warehouse_asal_id: number; source_warehouse_id: number;
warehouse_tujuan_id: number; destination_warehouse_id: number;
product: { products: {
product_id: number; product_id: number;
qty_product: number; product_qty: number;
}[]; }[];
ekspedisi: { deliveries: {
product_id: number; delivery_cost: number;
qty: number; delivery_cost_per_item: number;
document_index?: number;
driver_name: string;
vehicle_plate: string;
supplier_id: number; supplier_id: number;
plat_nomor: string; products: {
no_surat_jalan: string; product_id: number;
dokumen: string | File; product_qty: number;
biaya_ekspedisi: number; }[];
biaya_ekspedisi_per_item?: number;
nama_sopir: string;
}[]; }[];
}; };
+22
View File
@@ -0,0 +1,22 @@
import { BaseMetadata } from '@/types/api/api-general';
import { Warehouse } from '@/types/api/master-data/warehouse';
import { Product } from '@/types/api/master-data/product';
export type BaseProductWarehouse = {
id: number;
product_id: number;
warehouse_id: number;
quantity: number;
product: Product;
warehouse: Warehouse;
};
export type ProductWarehouse = BaseMetadata & BaseProductWarehouse;
export type CreateProductWarehousePayload = {
product_id: number;
warehouse_id: number;
quantity: number;
};
export type UpdateProductWarehousePayload = CreateProductWarehousePayload;