mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-20 13:32:00 +00:00
Merge branch 'fix/marketing' into 'development'
[FIX/FE] Refactor UI Sales Order & Delivery Order See merge request mbugroup/lti-web-client!299
This commit is contained in:
@@ -1,9 +1,14 @@
|
||||
import DeliveryOrderFormModal from '@/components/pages/marketing/DeliveryOrderFormModal';
|
||||
import MarketingTable from '@/components/pages/marketing/MarketingTable';
|
||||
import SalesOrderFormModal from '@/components/pages/marketing/SalesOrderFormModal';
|
||||
|
||||
const Marketing = () => {
|
||||
return (
|
||||
<div className='w-full p-4'>
|
||||
<div className='w-full'>
|
||||
<MarketingTable />
|
||||
|
||||
<SalesOrderFormModal />
|
||||
<DeliveryOrderFormModal />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Alert from '@/components/Alert';
|
||||
import Button from '@/components/Button';
|
||||
import { cn } from '@/lib/helper';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useState } from 'react';
|
||||
|
||||
@@ -10,34 +11,68 @@ import { useState } from 'react';
|
||||
*/
|
||||
const AlertErrorList = ({
|
||||
formErrorList,
|
||||
className,
|
||||
onClose,
|
||||
title,
|
||||
}: {
|
||||
formErrorList: string[];
|
||||
className?: {
|
||||
alert?: string;
|
||||
button?: string;
|
||||
headerWrapper?: string;
|
||||
headerIcon?: string;
|
||||
headerText?: string;
|
||||
titleWrapper?: string;
|
||||
ul?: string;
|
||||
li?: string;
|
||||
};
|
||||
onClose: () => void;
|
||||
title?: string;
|
||||
}) => {
|
||||
if (formErrorList.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Alert color='error' className='w-full flex flex-col gap-2 px-4'>
|
||||
<div className='flex justify-between items-center gap-2 w-full'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon icon='material-symbols:error-outline' width={24} height={24} />
|
||||
<span className='font-semibold'>
|
||||
Terdapat {formErrorList.length} error pada form:
|
||||
<Alert
|
||||
color='error'
|
||||
className={cn(
|
||||
'w-full flex flex-col gap-2 px-3 rounded-lg',
|
||||
className?.alert
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'flex justify-between items-center gap-2 w-full',
|
||||
className?.headerWrapper
|
||||
)}
|
||||
>
|
||||
<div className={cn('flex items-center gap-2', className?.titleWrapper)}>
|
||||
<Icon
|
||||
icon='material-symbols:error-outline'
|
||||
className={cn(className?.headerIcon)}
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
<span className={cn('font-semibold text-sm', className?.headerText)}>
|
||||
{title || `Terdapat ${formErrorList.length} error pada form:`}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
onClick={onClose}
|
||||
variant='link'
|
||||
className='ml-auto p-0 w-fit text-white'
|
||||
className={cn('ml-auto p-0 w-fit text-white', className?.button)}
|
||||
color='none'
|
||||
>
|
||||
<Icon icon='material-symbols:close' width={24} height={24} />
|
||||
<Icon icon='material-symbols:close' width={20} height={20} />
|
||||
</Button>
|
||||
</div>
|
||||
<ul className='list-disc list-inside pl-8 space-y-1 w-full'>
|
||||
<ul
|
||||
className={cn(
|
||||
'list-disc list-inside pl-4 space-y-1.5 w-full',
|
||||
className?.ul
|
||||
)}
|
||||
>
|
||||
{formErrorList.map((error, index) => (
|
||||
<li key={index} className='text-sm'>
|
||||
<li key={index} className={cn('text-sm', className?.li)}>
|
||||
{error}
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -7,6 +7,7 @@ import TextArea, { TextAreaProps } from '@/components/input/TextArea';
|
||||
|
||||
interface DebouncedTextAreaProps extends TextAreaProps {
|
||||
delay?: number;
|
||||
ref?: React.RefObject<HTMLTextAreaElement | null>;
|
||||
}
|
||||
|
||||
const DebouncedTextArea = (props: DebouncedTextAreaProps) => {
|
||||
@@ -19,6 +20,11 @@ const DebouncedTextArea = (props: DebouncedTextAreaProps) => {
|
||||
const [debouncedChangeEvent] = useDebounce(internalChangeEvent, delay ?? 300);
|
||||
const [debouncedValue] = useDebounce(internalValue, delay ?? 300);
|
||||
|
||||
// Sync internal value with external props.value when it changes (e.g., form reset)
|
||||
useEffect(() => {
|
||||
setInternalValue(props.value);
|
||||
}, [props.value]);
|
||||
|
||||
const internalChangeHandler: ChangeEventHandler<HTMLTextAreaElement> = (
|
||||
e
|
||||
) => {
|
||||
@@ -35,6 +41,7 @@ const DebouncedTextArea = (props: DebouncedTextAreaProps) => {
|
||||
return (
|
||||
<TextArea
|
||||
{...props}
|
||||
ref={props.ref}
|
||||
value={internalValue}
|
||||
onChange={internalChangeHandler}
|
||||
/>
|
||||
|
||||
@@ -28,6 +28,7 @@ export interface TextAreaProps {
|
||||
onChange?: ChangeEventHandler<HTMLTextAreaElement>;
|
||||
onBlur?: FocusEventHandler<HTMLTextAreaElement>;
|
||||
rows?: number;
|
||||
ref?: React.RefObject<HTMLTextAreaElement | null>;
|
||||
}
|
||||
|
||||
const TextArea = ({
|
||||
@@ -49,6 +50,7 @@ const TextArea = ({
|
||||
readOnly = false,
|
||||
isLoading = false,
|
||||
rows = 3,
|
||||
ref,
|
||||
}: TextAreaProps) => {
|
||||
return (
|
||||
<div
|
||||
@@ -99,6 +101,7 @@ const TextArea = ({
|
||||
onBlur={onBlur}
|
||||
disabled={disabled}
|
||||
readOnly={readOnly}
|
||||
ref={ref}
|
||||
/>
|
||||
|
||||
{(isLoading || endAdornment) && (
|
||||
|
||||
@@ -309,9 +309,10 @@ const useApprovalSteps = ({
|
||||
moduleId: string;
|
||||
params?: {
|
||||
page?: number;
|
||||
limit: number | string;
|
||||
limit?: number | string;
|
||||
search?: string;
|
||||
group_step_number?: boolean;
|
||||
order_by_date?: 'ASC' | 'DESC';
|
||||
};
|
||||
}) => {
|
||||
// Membuat URL Parameters
|
||||
@@ -319,6 +320,8 @@ const useApprovalSteps = ({
|
||||
page: params?.page?.toString() || '',
|
||||
limit: params?.limit?.toString() || '',
|
||||
search: params?.search || '',
|
||||
group_step_number: params?.group_step_number?.toString() || '',
|
||||
order_by_date: params?.order_by_date || '',
|
||||
}).toString();
|
||||
|
||||
// fetching data approvals
|
||||
|
||||
@@ -0,0 +1,809 @@
|
||||
'use client';
|
||||
|
||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||
import { useSelect, OptionType } from '@/components/input/SelectInput';
|
||||
import Modal, { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import {
|
||||
mergeSOwithDO,
|
||||
SalesProductToFieldValues,
|
||||
DeliveryProductToFieldValues,
|
||||
} from '@/components/pages/marketing/form/MarketingForm';
|
||||
import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
|
||||
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
|
||||
import { isResponseSuccess, isResponseError } from '@/lib/api-helper';
|
||||
import { formatCurrency, formatDate, formatTitleCase } from '@/lib/helper';
|
||||
import {
|
||||
DeliveryOrderApi,
|
||||
MarketingApi,
|
||||
SalesOrderApi,
|
||||
} from '@/services/api/marketing/marketing';
|
||||
import { CustomerApi } from '@/services/api/master-data';
|
||||
import { UserApi } from '@/services/api/user';
|
||||
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||
import { BaseApproval, CreatedUser } from '@/types/api/api-general';
|
||||
import {
|
||||
CreateDeliveryOrderPayload,
|
||||
Marketing,
|
||||
UpdateDeliveryOrderPayload,
|
||||
} from '@/types/api/marketing/marketing';
|
||||
import { Customer } from '@/types/api/master-data/customer';
|
||||
import { useFormik } from 'formik';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useState, useRef, useMemo, useCallback, useEffect } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import useSWR, { useSWRConfig } from 'swr';
|
||||
import Button from '@/components/Button';
|
||||
import { memo } from 'react';
|
||||
import SalesOrderExport from '@/components/pages/marketing/pdf/SalesOrderExport';
|
||||
import ApprovalStepsV2 from '@/components/helper/ApprovalStepsV2';
|
||||
import { useApprovalSteps } from '@/components/pages/ApprovalSteps';
|
||||
import { MARKETING_APPROVAL_LINE } from '@/config/approval-line';
|
||||
import DeliveryOrderProductForm from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct';
|
||||
import DeliveryOrderProductTable from '@/components/pages/marketing/form/table-view/DeliveryOrderProductTable';
|
||||
import {
|
||||
DeliveryOrderFormValues,
|
||||
DeliveryOrderSchema,
|
||||
getFilledMarketingFormInitialValues,
|
||||
SalesOrderFormValues,
|
||||
} from '@/components/pages/marketing/form/MarketingForm.schema';
|
||||
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
|
||||
import RequirePermission from '@/components/helper/RequirePermission';
|
||||
|
||||
const MemoizedDeliveryOrderProductTable = memo(DeliveryOrderProductTable);
|
||||
const MemoizedDeliveryOrderProductForm = memo(DeliveryOrderProductForm);
|
||||
|
||||
const DeliveryOrderFormModal = ({
|
||||
initialValues,
|
||||
}: {
|
||||
initialValues?: Marketing;
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const modalAction = searchParams.get('action');
|
||||
const marketingId = searchParams.get('id');
|
||||
|
||||
const isModalActionForForm =
|
||||
modalAction === 'add_delivery' ||
|
||||
modalAction === 'edit_delivery' ||
|
||||
modalAction === 'detail';
|
||||
|
||||
const { mutate } = useSWRConfig();
|
||||
|
||||
const refreshMarketing = () => {
|
||||
mutate(
|
||||
(key) => typeof key === 'string' && key.includes(MarketingApi.basePath)
|
||||
);
|
||||
};
|
||||
|
||||
const { data: marketing, isLoading: isLoadingMarketing } = useSWR(
|
||||
isModalActionForForm && marketingId
|
||||
? `detail-marketing-${marketingId}`
|
||||
: undefined,
|
||||
() => MarketingApi.getSingle(Number(marketingId))
|
||||
);
|
||||
|
||||
const {
|
||||
approvals,
|
||||
rawDataApprovals,
|
||||
isLoading: isLoadingApproval,
|
||||
refresh: refreshApproval,
|
||||
} = useApprovalSteps({
|
||||
latestApproval: isResponseSuccess(marketing)
|
||||
? marketing?.data.latest_approval
|
||||
: undefined,
|
||||
approvalLines: MARKETING_APPROVAL_LINE,
|
||||
moduleName: 'MARKETINGS',
|
||||
moduleId: marketingId as string,
|
||||
params: {
|
||||
group_step_number: false,
|
||||
order_by_date: 'ASC',
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Step 1: View Details
|
||||
* Step 2: Edit Delivery
|
||||
*/
|
||||
const [step, setStep] = useState(1);
|
||||
|
||||
const formModal = useModal();
|
||||
const successModal = useModal();
|
||||
const rejectModal = useModal();
|
||||
const deleteModal = useModal();
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
const [grandTotal, setGrandTotal] = useState(
|
||||
isResponseSuccess(marketing) &&
|
||||
marketing?.data.sales_order
|
||||
?.map((item) => item.total_price)
|
||||
.reduce((a, b) => a + b, 0)
|
||||
);
|
||||
|
||||
const [formErrorMessage, setFormErrorMessage] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedDeliveryProduct, setSelectedDeliveryProduct] =
|
||||
useState<DeliveryOrderProductFormValues | null>(null);
|
||||
const [deliveryOrderValues, setDeliveryOrderValues] = useState<
|
||||
DeliveryOrderProductFormValues[]
|
||||
>(
|
||||
isResponseSuccess(marketing)
|
||||
? mergeSOwithDO(
|
||||
marketing?.data.sales_order?.map(SalesProductToFieldValues) ?? [],
|
||||
marketing?.data.delivery_order?.flatMap((delivery) =>
|
||||
DeliveryProductToFieldValues(marketing.data.sales_order, delivery)
|
||||
) ?? [],
|
||||
true
|
||||
)
|
||||
: []
|
||||
);
|
||||
|
||||
// ================== SETUP FORMIK ==================
|
||||
const formikInitialValues = useMemo<
|
||||
SalesOrderFormValues & DeliveryOrderFormValues
|
||||
>(() => {
|
||||
if (!isResponseSuccess(marketing))
|
||||
return {} as SalesOrderFormValues & DeliveryOrderFormValues;
|
||||
const deliveryValues = mergeSOwithDO(
|
||||
marketing?.data.sales_order?.map(SalesProductToFieldValues) ?? [],
|
||||
marketing?.data.delivery_order?.flatMap((delivery) =>
|
||||
DeliveryProductToFieldValues(marketing.data.sales_order, delivery)
|
||||
) ?? [],
|
||||
true
|
||||
);
|
||||
|
||||
setDeliveryOrderValues(deliveryValues);
|
||||
|
||||
return {
|
||||
so_date: marketing?.data?.so_date || undefined,
|
||||
notes: marketing?.data?.notes || undefined,
|
||||
customer_id: marketing?.data?.customer?.id || undefined,
|
||||
sales_person_id: marketing?.data?.sales_person?.id || undefined,
|
||||
sales_person: marketing?.data?.sales_person
|
||||
? {
|
||||
value: marketing?.data.sales_person.id,
|
||||
label: marketing?.data.sales_person.name,
|
||||
}
|
||||
: null,
|
||||
customer: marketing?.data?.customer
|
||||
? {
|
||||
value: marketing?.data.customer.id,
|
||||
label: marketing?.data.customer.name,
|
||||
}
|
||||
: null,
|
||||
sales_order:
|
||||
marketing?.data?.sales_order?.map((product) =>
|
||||
SalesProductToFieldValues(product)
|
||||
) ?? [],
|
||||
delivery_order: deliveryValues,
|
||||
};
|
||||
}, [marketing]);
|
||||
|
||||
const formik = useFormik<SalesOrderFormValues & DeliveryOrderFormValues>({
|
||||
enableReinitialize: true,
|
||||
initialValues: formikInitialValues,
|
||||
validationSchema: DeliveryOrderSchema,
|
||||
validateOnMount: true,
|
||||
onSubmit: async (values) => {
|
||||
const payload = {
|
||||
marketing_id: Number(marketingId),
|
||||
delivery_products: values.delivery_order
|
||||
.map((product) => {
|
||||
if (Boolean(product.delivery_date)) {
|
||||
return {
|
||||
marketing_product_id: product.marketing_product_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),
|
||||
delivery_date: formatDate(
|
||||
product.delivery_date as string,
|
||||
'yyyy-MM-DD'
|
||||
),
|
||||
vehicle_number: product.vehicle_number,
|
||||
};
|
||||
}
|
||||
})
|
||||
.filter((item) => Boolean(item)),
|
||||
} as UpdateDeliveryOrderPayload;
|
||||
switch (modalAction) {
|
||||
case 'add_delivery':
|
||||
await createDeliveryHandler(payload as CreateDeliveryOrderPayload);
|
||||
break;
|
||||
case 'edit_delivery':
|
||||
await updateDeliveryHandler(payload as UpdateDeliveryOrderPayload);
|
||||
break;
|
||||
case 'detail':
|
||||
const dataMarketing = isResponseSuccess(marketing)
|
||||
? marketing.data
|
||||
: null;
|
||||
if (!dataMarketing) break;
|
||||
if (
|
||||
dataMarketing.delivery_order &&
|
||||
dataMarketing.delivery_order.length > 0
|
||||
) {
|
||||
await updateDeliveryHandler(payload as UpdateDeliveryOrderPayload);
|
||||
break;
|
||||
} else {
|
||||
await createDeliveryHandler(payload as CreateDeliveryOrderPayload);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// ===== Formik Error List =====
|
||||
const { formErrorList, setFormErrorList, close, handleFormSubmit } =
|
||||
useFormikErrorList(formik);
|
||||
|
||||
// ================== FORM HANDLER ==================
|
||||
const createDeliveryHandler = async (values: CreateDeliveryOrderPayload) => {
|
||||
setIsLoading(true);
|
||||
const createDeliveryRes = await DeliveryOrderApi.create(values);
|
||||
if (isResponseSuccess(createDeliveryRes)) {
|
||||
toast.success(createDeliveryRes?.message as string);
|
||||
setDeliveryOrderValues(
|
||||
createDeliveryRes.data?.delivery_order?.flatMap((delivery) =>
|
||||
DeliveryProductToFieldValues(
|
||||
createDeliveryRes.data?.sales_order,
|
||||
delivery
|
||||
)
|
||||
) ?? []
|
||||
);
|
||||
closeModalHandler(false);
|
||||
successModal.openModal();
|
||||
}
|
||||
if (isResponseError(createDeliveryRes)) {
|
||||
setFormErrorMessage(createDeliveryRes?.message as string);
|
||||
}
|
||||
setIsLoading(false);
|
||||
};
|
||||
const updateDeliveryHandler = async (values: UpdateDeliveryOrderPayload) => {
|
||||
setIsLoading(true);
|
||||
const updateDeliveryRes = await DeliveryOrderApi.update(
|
||||
Number(marketingId),
|
||||
values
|
||||
);
|
||||
if (isResponseSuccess(updateDeliveryRes)) {
|
||||
toast.success(updateDeliveryRes?.message as string);
|
||||
setDeliveryOrderValues(
|
||||
mergeSOwithDO(
|
||||
formik.values.sales_order,
|
||||
updateDeliveryRes.data?.delivery_order?.flatMap((delivery) =>
|
||||
DeliveryProductToFieldValues(
|
||||
updateDeliveryRes.data?.sales_order,
|
||||
delivery
|
||||
)
|
||||
) ?? []
|
||||
)
|
||||
);
|
||||
closeModalHandler(false);
|
||||
successModal.openModal();
|
||||
}
|
||||
if (isResponseError(updateDeliveryRes)) {
|
||||
setFormErrorMessage(updateDeliveryRes?.message as string);
|
||||
}
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
const memoSalesOrder = formik.values.sales_order;
|
||||
|
||||
// ================== HANDLER ==================
|
||||
const nextButtonHandler = () => {
|
||||
setStep(step + 1);
|
||||
};
|
||||
const prevButtonHandler = () => {
|
||||
setStep(step - 1);
|
||||
};
|
||||
const handleChangeCustomer = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldValue('customer_id', (val as OptionType)?.value);
|
||||
formik.setFieldValue('customer', val as OptionType);
|
||||
},
|
||||
[]
|
||||
);
|
||||
const handleChangeSalesPerson = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldValue('sales_person_id', (val as OptionType)?.value);
|
||||
formik.setFieldValue('sales_person', val as OptionType);
|
||||
},
|
||||
[]
|
||||
);
|
||||
const rejectMarketingHandler = async (notes: string) => {
|
||||
if (!marketingId) {
|
||||
toast.error(`Tidak ada data yang valid untuk di reject.`);
|
||||
rejectModal.closeModal();
|
||||
return;
|
||||
}
|
||||
|
||||
const rejectMarketingRes = await SalesOrderApi.singleApproval(
|
||||
Number(marketingId),
|
||||
'REJECTED',
|
||||
notes
|
||||
);
|
||||
|
||||
if (isResponseSuccess(rejectMarketingRes)) {
|
||||
rejectModal.closeModal();
|
||||
toast.success(rejectMarketingRes?.message as string);
|
||||
closeModalHandler();
|
||||
router.push('/marketing');
|
||||
}
|
||||
if (isResponseError(rejectMarketingRes)) {
|
||||
rejectModal.closeModal();
|
||||
toast.error(rejectMarketingRes?.message as string);
|
||||
}
|
||||
refreshMarketing();
|
||||
refreshApproval();
|
||||
};
|
||||
|
||||
const deleteClickHandler = () => {
|
||||
deleteModal.openModal();
|
||||
};
|
||||
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
if (!marketingId) {
|
||||
toast.error(`Tidak ada data yang valid untuk di hapus.`);
|
||||
deleteModal.closeModal();
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
const res = await MarketingApi.delete(Number(marketingId));
|
||||
deleteModal.closeModal();
|
||||
toast.success(res?.message as string);
|
||||
setIsLoading(false);
|
||||
router.replace('/marketing');
|
||||
};
|
||||
|
||||
// ================== DELIVERY ORDER HANDLER ==================
|
||||
const handleEditDO = useCallback(
|
||||
(id: number, values?: DeliveryOrderProductFormValues) => {
|
||||
const currentProducts = deliveryOrderValues?.find(
|
||||
(product) => product.id == id
|
||||
);
|
||||
setSelectedDeliveryProduct(values ?? currentProducts ?? null);
|
||||
if (id) {
|
||||
setStep(2);
|
||||
}
|
||||
},
|
||||
[deliveryOrderValues, setSelectedDeliveryProduct, setStep]
|
||||
);
|
||||
const handleAddDOClick = useCallback(() => {
|
||||
setSelectedDeliveryProduct(null);
|
||||
}, []);
|
||||
const handleAddSubmitDO = useCallback(
|
||||
async (values: DeliveryOrderProductFormValues) => {
|
||||
const newValues = {
|
||||
...values,
|
||||
id: values.id ?? Date.now(),
|
||||
};
|
||||
|
||||
setDeliveryOrderValues((prev) => [...prev, newValues]);
|
||||
setSelectedDeliveryProduct(null);
|
||||
prevButtonHandler();
|
||||
},
|
||||
[prevButtonHandler]
|
||||
);
|
||||
const handleUpdateDO = useCallback(
|
||||
async (id: number, values: DeliveryOrderProductFormValues) => {
|
||||
setDeliveryOrderValues((prev) =>
|
||||
prev.map((product) =>
|
||||
product.id === id ? { ...product, ...values } : product
|
||||
)
|
||||
);
|
||||
setSelectedDeliveryProduct(null);
|
||||
prevButtonHandler();
|
||||
},
|
||||
[prevButtonHandler]
|
||||
);
|
||||
const handleDeleteDO = useCallback(async (id: number) => {
|
||||
setDeliveryOrderValues((prev) =>
|
||||
prev.map((product) =>
|
||||
product.id === id
|
||||
? {
|
||||
...product,
|
||||
...{
|
||||
delivery_date: '',
|
||||
},
|
||||
}
|
||||
: product
|
||||
)
|
||||
);
|
||||
setSelectedDeliveryProduct(null);
|
||||
}, []);
|
||||
|
||||
// ================== MEMOIZED ==================
|
||||
const isNextButtonDisabled = useMemo(() => {
|
||||
if (step === 1) {
|
||||
return Boolean(
|
||||
!formik.values.customer_id ||
|
||||
!formik.values.sales_person_id ||
|
||||
!formik.values.so_date ||
|
||||
!formik.values.notes
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}, [step, formik.values]);
|
||||
const deliveryRejected = useMemo(() => {
|
||||
return (
|
||||
isResponseSuccess(marketing) &&
|
||||
((marketing.data.latest_approval.step_number === 3 &&
|
||||
marketing.data.latest_approval.action === 'REJECTED') ||
|
||||
(marketing.data.latest_approval.step_number === 2 &&
|
||||
marketing.data.latest_approval.action === 'REJECTED'))
|
||||
);
|
||||
}, [marketing]);
|
||||
|
||||
const isPending = useMemo(() => {
|
||||
return (
|
||||
isResponseSuccess(marketing) &&
|
||||
marketing.data.latest_approval.step_number === 1
|
||||
);
|
||||
}, [marketing]);
|
||||
|
||||
// ================== EFFECT ==================
|
||||
useEffect(() => {
|
||||
if (
|
||||
modalAction === 'add_delivery' ||
|
||||
modalAction === 'edit_delivery' ||
|
||||
modalAction === 'detail'
|
||||
) {
|
||||
formModal.openModal();
|
||||
}
|
||||
}, [modalAction]);
|
||||
|
||||
const closeModalHandler = (shouldPushToRoute: boolean = true) => {
|
||||
refreshMarketing();
|
||||
|
||||
if (shouldPushToRoute) {
|
||||
formik.resetForm();
|
||||
textareaRef.current?.setAttribute('value', '');
|
||||
successModal.closeModal();
|
||||
router.push('/marketing');
|
||||
}
|
||||
|
||||
setStep(1);
|
||||
setFormErrorMessage('');
|
||||
formModal.closeModal();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const getFilledInitialValues = async () => {
|
||||
if (marketingId && isResponseSuccess(marketing)) {
|
||||
const filledInitialValues = await getFilledMarketingFormInitialValues(
|
||||
marketing.data
|
||||
);
|
||||
|
||||
formik.setValues(filledInitialValues);
|
||||
setStep(1);
|
||||
}
|
||||
|
||||
if (isResponseError(marketing)) {
|
||||
router.push('/marketing');
|
||||
closeModalHandler();
|
||||
toast.error(marketing.message);
|
||||
}
|
||||
};
|
||||
|
||||
getFilledInitialValues();
|
||||
}, [marketingId, marketing]);
|
||||
|
||||
// Reset error message when step changes
|
||||
useEffect(() => {
|
||||
setFormErrorList([]);
|
||||
setFormErrorMessage('');
|
||||
}, [step]);
|
||||
|
||||
// sync delivery order values to formik
|
||||
useEffect(() => {
|
||||
formik.setFieldValue('delivery_order', deliveryOrderValues);
|
||||
}, [deliveryOrderValues]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
ref={formModal.ref}
|
||||
position='end'
|
||||
className={{
|
||||
modalBox: 'w-full sm:w-fit p-3 rounded-xl bg-transparent shadow-none',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
}}
|
||||
className='w-full min-h-full flex flex-col sm:flex-row items-stretch bg-base-100 rounded-xl overflow-y-auto'
|
||||
>
|
||||
{step <= 2 && isResponseSuccess(marketing) && (
|
||||
<>
|
||||
<div className='w-full sm:w-[446px]'>
|
||||
<div className='w-full p-4 flex flex-row items-stretch gap-3 border-b border-base-content/10'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={() => closeModalHandler()}
|
||||
className='p-0 text-black hover:text-base-content'
|
||||
>
|
||||
<Icon icon='heroicons:x-mark' width={20} height={20} />
|
||||
</Button>
|
||||
|
||||
<div className='w-px border-none bg-base-content/10' />
|
||||
|
||||
<h4 className='text-sm font-medium text-base-content/50'>
|
||||
View Details
|
||||
</h4>
|
||||
</div>
|
||||
<form
|
||||
className='w-full p-4 gap-3 flex flex-col border-b border-base-content/10'
|
||||
ref={formRef}
|
||||
onSubmit={handleFormSubmit}
|
||||
>
|
||||
<h4 className='text-base font-medium text-base-content/50 font-roboto'>
|
||||
Informasi Penjualan
|
||||
</h4>
|
||||
<div className='rounded-lg border border-tools-table-outline border-base-content/5'>
|
||||
<table
|
||||
style={{
|
||||
borderRadius: '0.5rem',
|
||||
}}
|
||||
className='border-none w-full'
|
||||
>
|
||||
<tbody className='w-full'>
|
||||
<tr className='border-b border-tools-table-outline border-base-content/5'>
|
||||
<th className='w-1/3 text-start not-first:font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||
Label
|
||||
</th>
|
||||
<th className='text-start font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||
<div className='flex w-full flex-row gap-1 items-center justify-between h-full mt-2'>
|
||||
<div>Value</div>
|
||||
</div>
|
||||
</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>No. Sales Order</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{marketing.data.so_number}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Nama Pelanggan</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{marketing.data.customer.name}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Status</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{formatTitleCase(
|
||||
marketing.data.latest_approval.step_name
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
Tanggal Penjualan
|
||||
</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{formatDate(marketing.data.so_date, 'DD MMM yyyy')}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Total Penjualan</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{formatCurrency(grandTotal || 0)}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
Dokumen Penjualan
|
||||
</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
<SalesOrderExport data={marketing.data} />
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div className='w-full min-h-full flex flex-col sm:w-[446px] border-l border-base-content/10'>
|
||||
<div className='w-full p-4 flex flex-row items-center justify-between gap-3 border-b border-base-content/10'>
|
||||
<div className='w-full flex flex-row items-stretch gap-3'>
|
||||
{step === 2 && (
|
||||
<>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={() => {
|
||||
setStep(1);
|
||||
}}
|
||||
className='p-0 text-black hover:text-base-content'
|
||||
>
|
||||
<Icon
|
||||
icon='heroicons:chevron-left'
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
</Button>
|
||||
|
||||
<div className='w-px border-none bg-base-content/10' />
|
||||
</>
|
||||
)}
|
||||
<h4 className='text-sm font-medium text-base-content/50'>
|
||||
Informasi
|
||||
</h4>
|
||||
</div>
|
||||
{step === 1 && (
|
||||
<RequirePermission permissions='lti.marketing.sales_order.delete'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={() => {
|
||||
deleteClickHandler();
|
||||
}}
|
||||
className='p-0 text-error hover:text-base-content'
|
||||
>
|
||||
<Icon icon='heroicons:trash' width={20} height={20} />
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
)}
|
||||
</div>
|
||||
{step === 1 && (
|
||||
<ApprovalStepsV2
|
||||
approvals={rawDataApprovals as BaseApproval[]}
|
||||
steps={MARKETING_APPROVAL_LINE}
|
||||
/>
|
||||
)}
|
||||
<div className='w-full p-4 gap-3 flex flex-col'>
|
||||
<h4 className='text-base font-medium text-base-content/50 font-roboto'>
|
||||
{step == 2 && 'Ubah '} Informasi{' '}
|
||||
{step == 2 ? 'Delivery' : 'Produk'}
|
||||
</h4>
|
||||
{step === 1 && (
|
||||
<MemoizedDeliveryOrderProductTable
|
||||
marketing={marketing.data}
|
||||
formType={
|
||||
deliveryRejected
|
||||
? 'rejected'
|
||||
: isPending
|
||||
? 'pending'
|
||||
: modalAction
|
||||
}
|
||||
data={deliveryOrderValues}
|
||||
onEdit={handleEditDO}
|
||||
onDelete={handleDeleteDO}
|
||||
onAddProductClick={handleAddDOClick}
|
||||
/>
|
||||
)}
|
||||
{step === 2 && (
|
||||
<MemoizedDeliveryOrderProductForm
|
||||
formState={'edit'}
|
||||
salesOrders={marketing?.data?.sales_order ?? []}
|
||||
exisitingValues={deliveryOrderValues}
|
||||
onSubmitForm={handleAddSubmitDO}
|
||||
initialValues={selectedDeliveryProduct ?? undefined}
|
||||
onUpdateForm={handleUpdateDO}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{formErrorMessage && (
|
||||
<div className='px-4 pb-4'>
|
||||
<AlertErrorList
|
||||
className={{
|
||||
alert: 'w-full',
|
||||
}}
|
||||
formErrorList={[formErrorMessage]}
|
||||
onClose={() => setFormErrorMessage('')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{formErrorList && (
|
||||
<div className='px-4 pb-4 '>
|
||||
<AlertErrorList
|
||||
className={{
|
||||
alert: 'w-full',
|
||||
}}
|
||||
formErrorList={formErrorList}
|
||||
onClose={close}
|
||||
title={`Terdapat ${formErrorList.length} error pada ${formErrorMessage ? 'server' : 'form'}:`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{step === 1 && (
|
||||
<div className='w-full px-4 py-3 grid grid-cols-2 items-center justify-between gap-3 border-t border-base-content/10'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
color='none'
|
||||
onClick={() => rejectModal.openModal()}
|
||||
disabled={deliveryRejected || isPending}
|
||||
className='p-3 border-base-content/10 shadow-button-soft rounded-lg text-sm text-base-content/50 font-semibold'
|
||||
>
|
||||
Reject
|
||||
</Button>
|
||||
<Button
|
||||
type='button'
|
||||
color='primary'
|
||||
onClick={() => {
|
||||
formRef.current?.requestSubmit();
|
||||
}}
|
||||
className='p-3 shadow-button-soft text-base-100 rounded-lg text-sm font-semibold'
|
||||
disabled={deliveryRejected || isPending}
|
||||
>
|
||||
Approve
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
<ConfirmationModal
|
||||
ref={successModal.ref}
|
||||
iconPosition='left'
|
||||
type='success'
|
||||
text={`${modalAction === 'add' ? 'Data Berhasil Disimpan' : 'Data Berhasil Diubah'}`}
|
||||
subtitleText={`${modalAction === 'add' ? 'Data delivery order telah berhasil disimpan.' : 'Data delivery order telah berhasil diubah.'}`}
|
||||
primaryButton={{
|
||||
text: 'Oke',
|
||||
color: 'primary',
|
||||
className: 'rounded-lg',
|
||||
onClick: (e) => {
|
||||
closeModalHandler();
|
||||
},
|
||||
}}
|
||||
>
|
||||
<MemoizedDeliveryOrderProductTable
|
||||
marketing={isResponseSuccess(marketing) ? marketing.data : undefined}
|
||||
formType={'success'}
|
||||
data={deliveryOrderValues}
|
||||
onDelete={handleDeleteDO}
|
||||
onEdit={handleEditDO}
|
||||
onAddProductClick={handleAddDOClick}
|
||||
/>
|
||||
</ConfirmationModal>
|
||||
|
||||
<ConfirmationModalWithNotes
|
||||
ref={rejectModal.ref}
|
||||
type={'error'}
|
||||
text={`Apakah anda yakin ingin reject data penjualan?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
onClick: rejectModal.closeModal,
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
onClick: rejectMarketingHandler,
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data penjualan ini?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isLoading,
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default DeliveryOrderFormModal;
|
||||
@@ -0,0 +1,572 @@
|
||||
'use client';
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import Card from '@/components/Card';
|
||||
import { FormHeader } from '@/components/helper/form/FormHeader';
|
||||
import { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
|
||||
import ApprovalSteps, {
|
||||
useApprovalSteps,
|
||||
} from '@/components/pages/ApprovalSteps';
|
||||
import Table from '@/components/Table';
|
||||
import { MARKETING_APPROVAL_LINE } from '@/config/approval-line';
|
||||
import {
|
||||
cn,
|
||||
formatCurrency,
|
||||
formatDate,
|
||||
formatNumber,
|
||||
formatTitleCase,
|
||||
formatVechicleNumber,
|
||||
} from '@/lib/helper';
|
||||
import {
|
||||
MarketingApi,
|
||||
SalesOrderApi,
|
||||
} from '@/services/api/marketing/marketing';
|
||||
import {
|
||||
BaseDelivery,
|
||||
BaseSalesOrder,
|
||||
Marketing,
|
||||
} from '@/types/api/marketing/marketing';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import SalesOrderExport from '@/components/pages/marketing/pdf/SalesOrderExport';
|
||||
import DeliveryOrderExport from '@/components/pages/marketing/pdf/DeliveryOrderExport';
|
||||
import RequirePermission from '@/components/helper/RequirePermission';
|
||||
import Badge from '@/components/Badge';
|
||||
|
||||
const MarketingDetail = ({
|
||||
initialValues,
|
||||
refresh,
|
||||
}: {
|
||||
initialValues?: Marketing;
|
||||
refresh?: () => void;
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
const [approvalAction, setApprovalAction] = useState<'APPROVED' | 'REJECTED'>(
|
||||
'APPROVED'
|
||||
);
|
||||
const [grandTotal, setGrandTotal] = useState(
|
||||
initialValues?.sales_order
|
||||
?.map((item) => item.total_price)
|
||||
.reduce((a, b) => a + b, 0)
|
||||
);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const deleteModal = useModal();
|
||||
const confirmationModal = useModal();
|
||||
const deliveryModal = useModal();
|
||||
const {
|
||||
approvals,
|
||||
isLoading: isLoadingApproval,
|
||||
refresh: refreshApproval,
|
||||
} = useApprovalSteps({
|
||||
latestApproval: initialValues?.latest_approval,
|
||||
approvalLines: MARKETING_APPROVAL_LINE,
|
||||
moduleName: 'MARKETINGS',
|
||||
moduleId: initialValues?.id as number as unknown as string,
|
||||
});
|
||||
|
||||
const approveClickHandler = () => {
|
||||
setApprovalAction('APPROVED');
|
||||
confirmationModal.openModal();
|
||||
};
|
||||
|
||||
const rejectClickHandler = () => {
|
||||
setApprovalAction('REJECTED');
|
||||
confirmationModal.openModal();
|
||||
};
|
||||
|
||||
const deleteClickHandler = () => {
|
||||
deleteModal.openModal();
|
||||
};
|
||||
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
setIsLoading(true);
|
||||
const res = await MarketingApi.delete(initialValues?.id as number);
|
||||
deleteModal.closeModal();
|
||||
router.push('/marketing');
|
||||
toast.success(res?.message as string);
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
const confirmationModalApproveClickHandler = async (notes: string) => {
|
||||
setIsLoading(true);
|
||||
const res = await SalesOrderApi.singleApproval(
|
||||
initialValues?.id as number,
|
||||
approvalAction,
|
||||
notes
|
||||
);
|
||||
setIsLoading(false);
|
||||
confirmationModal.closeModal();
|
||||
toast.success(res?.message as string);
|
||||
refresh?.();
|
||||
refreshApproval?.();
|
||||
};
|
||||
|
||||
const confirmationModalDeliveryClickHandler = async (notes: string) => {
|
||||
setIsLoading(true);
|
||||
const res = await SalesOrderApi.delivery(
|
||||
initialValues?.id as number,
|
||||
notes
|
||||
);
|
||||
setIsLoading(false);
|
||||
deliveryModal.closeModal();
|
||||
toast.success(res?.message as string);
|
||||
refresh?.();
|
||||
refreshApproval?.();
|
||||
router.push(
|
||||
`/marketing/detail/delivery-orders/edit?marketingId=${initialValues?.id}`
|
||||
);
|
||||
};
|
||||
|
||||
const approval = initialValues?.latest_approval;
|
||||
const isRejected = approval?.action == 'REJECTED';
|
||||
const isApproved = approval?.action == 'APPROVED';
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='flex flex-col w-full gap-4'>
|
||||
<FormHeader
|
||||
title={`Detail ${Number(initialValues?.latest_approval?.step_number) > 2 ? 'Delivery Order' : 'Sales Order'}`}
|
||||
backUrl='/marketing'
|
||||
/>
|
||||
{!isLoadingApproval && approvals && (
|
||||
<ApprovalSteps approvals={approvals} />
|
||||
)}
|
||||
<div className='flex-row flex gap-3'>
|
||||
{initialValues?.latest_approval?.step_number == 1 && (
|
||||
<>
|
||||
<RequirePermission permissions='lti.marketing.sales_order.approve'>
|
||||
<Button
|
||||
color='success'
|
||||
onClick={approveClickHandler}
|
||||
disabled={
|
||||
initialValues?.latest_approval?.step_number == 1 &&
|
||||
initialValues?.latest_approval?.action == 'REJECTED'
|
||||
}
|
||||
>
|
||||
<Icon icon='mdi:check' width={24} height={24} />
|
||||
Approve
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
|
||||
<RequirePermission permissions='lti.marketing.sales_order.approve'>
|
||||
<Button
|
||||
color='error'
|
||||
onClick={rejectClickHandler}
|
||||
disabled={
|
||||
initialValues?.latest_approval?.step_number == 1 &&
|
||||
initialValues?.latest_approval?.action == 'REJECTED'
|
||||
}
|
||||
>
|
||||
<Icon icon='mdi:close' width={24} height={24} />
|
||||
Reject
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
</>
|
||||
)}
|
||||
{initialValues?.latest_approval?.step_number != 1 && (
|
||||
<>
|
||||
<RequirePermission
|
||||
permissions={
|
||||
initialValues?.latest_approval?.step_number == 3
|
||||
? 'lti.marketing.delivery_order.update'
|
||||
: 'lti.marketing.delivery_order.create'
|
||||
}
|
||||
>
|
||||
<Button
|
||||
color='success'
|
||||
href={
|
||||
initialValues?.latest_approval?.step_number == 3
|
||||
? `/marketing/detail/delivery-orders/edit?marketingId=${initialValues?.id}`
|
||||
: `/marketing/add/delivery-orders?marketingId=${initialValues?.id}`
|
||||
}
|
||||
>
|
||||
<Icon icon='mdi:truck' width={24} height={24} />
|
||||
{initialValues?.latest_approval?.step_number == 3
|
||||
? 'Edit '
|
||||
: 'Tambah '}
|
||||
Delivery Order
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Card
|
||||
title='Informasi Penjualan'
|
||||
className={{
|
||||
wrapper: 'w-full bg-white',
|
||||
}}
|
||||
>
|
||||
<div className='overflow-x-auto rounded-box border border-base-content/5 bg-base-100 mt-3'>
|
||||
<table className='table'>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td width='45%' className='font-semibold'>
|
||||
No. Sales Order
|
||||
</td>
|
||||
<td>:</td>
|
||||
<td width='50%' className='font-mono'>
|
||||
{initialValues?.so_number}
|
||||
</td>
|
||||
</tr>
|
||||
{Number(initialValues?.latest_approval?.step_number) > 2 && (
|
||||
<tr>
|
||||
<td width='45%' className='font-semibold'>
|
||||
No. Delivery Order
|
||||
</td>
|
||||
<td>:</td>
|
||||
<td width='50%' className='font-mono'>
|
||||
{initialValues?.delivery_order
|
||||
?.map((item) => item.do_number)
|
||||
.join(', ')}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
<tr>
|
||||
<td className='font-semibold'>Nama Pelanggan</td>
|
||||
<td>:</td>
|
||||
<td>{initialValues?.customer?.name}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='font-semibold'>Status</td>
|
||||
<td>:</td>
|
||||
<td>
|
||||
<Badge
|
||||
variant='soft'
|
||||
className={{
|
||||
badge:
|
||||
'rounded-lg px-2 w-fit flex flex-row justify-start whitespace-nowrap',
|
||||
}}
|
||||
color={
|
||||
isRejected
|
||||
? 'error'
|
||||
: isApproved
|
||||
? approval?.step_number == 1
|
||||
? 'neutral'
|
||||
: approval?.step_number == 2
|
||||
? 'primary'
|
||||
: approval?.step_number == 3
|
||||
? 'success'
|
||||
: 'neutral'
|
||||
: 'neutral'
|
||||
}
|
||||
>
|
||||
<Icon
|
||||
icon='mdi:circle'
|
||||
width={12}
|
||||
height={12}
|
||||
color={
|
||||
approval?.step_number == 1
|
||||
? 'neutral'
|
||||
: approval?.step_number == 2
|
||||
? 'primary'
|
||||
: approval?.step_number == 3
|
||||
? 'success'
|
||||
: 'neutral'
|
||||
}
|
||||
/>
|
||||
{isRejected
|
||||
? 'Ditolak'
|
||||
: formatTitleCase(approval?.step_name || '')}
|
||||
</Badge>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='font-semibold'>Tanggal Penjualan</td>
|
||||
<td>:</td>
|
||||
<td>{formatDate(initialValues?.so_date, 'DD MMM yyyy')}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='font-semibold'>Total Penjualan</td>
|
||||
<td>:</td>
|
||||
<td>{formatCurrency(grandTotal as number)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='font-semibold'>Catatan</td>
|
||||
<td>:</td>
|
||||
<td>{initialValues?.notes ?? '-'}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='font-semibold'>Dokumen Penjualan</td>
|
||||
<td>:</td>
|
||||
<td>
|
||||
<SalesOrderExport data={initialValues} />
|
||||
</td>
|
||||
</tr>
|
||||
{Number(initialValues?.latest_approval?.step_number) > 2 && (
|
||||
<tr>
|
||||
<td className='font-semibold'>Dokumen Pengiriman</td>
|
||||
<td>:</td>
|
||||
<td className='flex flex-wrap gap-2'>
|
||||
{initialValues?.delivery_order?.map((item, index) => (
|
||||
<DeliveryOrderExport
|
||||
key={index}
|
||||
data={initialValues}
|
||||
deliveryOrder={item}
|
||||
/>
|
||||
))}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Card>
|
||||
{initialValues?.sales_order && (
|
||||
<Card
|
||||
title='Informasi Produk'
|
||||
className={{
|
||||
wrapper: 'w-full bg-white',
|
||||
}}
|
||||
>
|
||||
<Table<BaseSalesOrder>
|
||||
data={initialValues?.sales_order}
|
||||
columns={[
|
||||
{
|
||||
header: 'Kandang',
|
||||
accessorFn(row) {
|
||||
return row.product_warehouse.warehouse.name;
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Produk',
|
||||
accessorFn(row) {
|
||||
return row.product_warehouse.product.name;
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Harga Satuan (Rp)',
|
||||
accessorFn(row) {
|
||||
return formatCurrency(row.unit_price);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Total Bobot (Kg)',
|
||||
accessorFn(row) {
|
||||
return formatNumber(row.total_weight);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Kuantitas',
|
||||
accessorFn(row) {
|
||||
return formatNumber(row.qty);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Avg. Bobot (Kg)',
|
||||
accessorFn(row) {
|
||||
return formatNumber(row.avg_weight);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Total Penjualan (Rp)',
|
||||
accessorFn(row) {
|
||||
return formatCurrency(row.total_price);
|
||||
},
|
||||
},
|
||||
]}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20':
|
||||
initialValues?.sales_order &&
|
||||
initialValues?.sales_order?.length === 0,
|
||||
}),
|
||||
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-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
paginationClassName: 'hidden',
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
{initialValues?.delivery_order && (
|
||||
<Card
|
||||
title='Informasi Pengiriman'
|
||||
className={{
|
||||
wrapper: 'w-full bg-white',
|
||||
}}
|
||||
>
|
||||
{initialValues?.delivery_order.map((delivery, index) => {
|
||||
return (
|
||||
<div key={index}>
|
||||
<Card
|
||||
className={{
|
||||
wrapper: 'w-full',
|
||||
}}
|
||||
>
|
||||
<div className='flex flex-row gap-3'>
|
||||
<div className='font-semibold'>
|
||||
Nomor DO : {delivery.do_number}
|
||||
</div>
|
||||
</div>
|
||||
<Table<BaseDelivery>
|
||||
data={delivery.deliveries}
|
||||
columns={[
|
||||
{
|
||||
header: 'Tanggal Pengiriman',
|
||||
accessorFn() {
|
||||
return formatDate(
|
||||
delivery.delivery_date,
|
||||
'DD MMM yyyy'
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'No. Polisi',
|
||||
accessorFn(row) {
|
||||
return formatVechicleNumber(row.vehicle_number);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Kandang',
|
||||
accessorFn(row) {
|
||||
return row.product_warehouse.warehouse.name;
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Produk',
|
||||
accessorFn(row) {
|
||||
return row.product_warehouse.product.name;
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Harga Satuan (Rp)',
|
||||
accessorFn(row) {
|
||||
return formatCurrency(row.unit_price);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Total Bobot (Kg)',
|
||||
accessorFn(row) {
|
||||
return formatNumber(row.total_weight);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Kuantitas',
|
||||
accessorFn(row) {
|
||||
return formatNumber(row.qty);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Avg. Bobot (Kg)',
|
||||
accessorFn(row) {
|
||||
return formatNumber(row.avg_weight);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Total Penjualan (Rp)',
|
||||
accessorFn(row) {
|
||||
return formatCurrency(row.total_price);
|
||||
},
|
||||
},
|
||||
]}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20':
|
||||
initialValues?.sales_order &&
|
||||
initialValues?.sales_order?.length === 0,
|
||||
}),
|
||||
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-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
paginationClassName: 'hidden',
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
<div className='flex flex-row gap-3 my-3'>
|
||||
<DeliveryOrderExport
|
||||
data={initialValues}
|
||||
deliveryOrder={delivery}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Card>
|
||||
)}
|
||||
<div className='flex flex-row gap-3'>
|
||||
{initialValues?.latest_approval?.step_number != 3 && (
|
||||
<>
|
||||
<RequirePermission permissions='lti.marketing.sales_order.update'>
|
||||
<Button
|
||||
color='warning'
|
||||
type='button'
|
||||
href={`/marketing/detail/${initialValues?.latest_approval?.step_number == 3 ? 'delivery-orders' : 'sales-orders'}/edit?marketingId=${initialValues?.id}`}
|
||||
>
|
||||
<Icon icon='mdi:pencil' width={24} height={24} />
|
||||
Edit
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
</>
|
||||
)}
|
||||
<RequirePermission permissions='lti.marketing.sales_order.delete'>
|
||||
<Button color='error' onClick={deleteClickHandler}>
|
||||
<Icon icon='mdi:delete' width={24} height={24} />
|
||||
Hapus
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
</div>
|
||||
</div>
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data penjualan ini?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isLoading,
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
}}
|
||||
/>
|
||||
<ConfirmationModalWithNotes
|
||||
ref={confirmationModal.ref}
|
||||
type={approvalAction === 'APPROVED' ? 'success' : 'error'}
|
||||
text={`Apakah anda yakin ingin ${approvalAction == 'APPROVED' ? 'approve' : 'reject'} data penjualan ini?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: approvalAction === 'APPROVED' ? 'success' : 'error',
|
||||
isLoading: isLoading,
|
||||
onClick: confirmationModalApproveClickHandler,
|
||||
}}
|
||||
/>
|
||||
<ConfirmationModalWithNotes
|
||||
ref={deliveryModal.ref}
|
||||
type={'success'}
|
||||
text={`Apakah anda yakin ingin deliver penjualan ini?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'success',
|
||||
isLoading: isLoading,
|
||||
onClick: confirmationModalDeliveryClickHandler,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default MarketingDetail;
|
||||
@@ -0,0 +1,186 @@
|
||||
'use client';
|
||||
|
||||
import { RefObject } from 'react';
|
||||
import { useFormik } from 'formik';
|
||||
import { Icon } from '@iconify/react';
|
||||
import Modal from '@/components/Modal';
|
||||
import Button from '@/components/Button';
|
||||
import SelectInput, {
|
||||
OptionType,
|
||||
useSelect,
|
||||
} from '@/components/input/SelectInput';
|
||||
import { CustomerApi, ProductApi } from '@/services/api/master-data';
|
||||
import { MARKETING_APPROVAL_LINE } from '@/config/approval-line';
|
||||
import { MarketingFilter } from '@/types/api/marketing/marketing';
|
||||
import SelectInputCheckbox from '@/components/input/SelectInputCheckbox';
|
||||
|
||||
interface MarketingFilterModal {
|
||||
ref: RefObject<HTMLDialogElement | null>;
|
||||
onSubmit?: (values: MarketingFilter) => void;
|
||||
onReset?: () => void;
|
||||
}
|
||||
|
||||
const MarketingFilterModal = ({
|
||||
ref,
|
||||
onSubmit,
|
||||
onReset,
|
||||
}: MarketingFilterModal) => {
|
||||
const closeModalHandler = () => {
|
||||
ref.current?.close();
|
||||
};
|
||||
|
||||
// ===== OPTIONS =====
|
||||
const {
|
||||
options: productsOptions,
|
||||
isLoadingOptions: isLoadingProductsOptions,
|
||||
setInputValue: setProductsInputValue,
|
||||
loadMore: loadMoreProducts,
|
||||
} = useSelect(ProductApi.basePath, 'id', 'name', '', {
|
||||
limit: 'limit',
|
||||
});
|
||||
const {
|
||||
options: customersOptions,
|
||||
isLoadingOptions: isLoadingCustomersOptions,
|
||||
setInputValue: setCustomersInputValue,
|
||||
loadMore: loadMoreCustomers,
|
||||
} = useSelect(CustomerApi.basePath, 'id', 'name', '', {
|
||||
limit: 'limit',
|
||||
});
|
||||
const statusOptions = MARKETING_APPROVAL_LINE.map((item) => ({
|
||||
value: item.step_name.split(' ').join('_').toUpperCase(),
|
||||
label: item.step_name,
|
||||
}));
|
||||
|
||||
const formik = useFormik<{
|
||||
product_ids: OptionType[];
|
||||
status: OptionType | null;
|
||||
customer_id: OptionType | null;
|
||||
}>({
|
||||
initialValues: {
|
||||
product_ids: [],
|
||||
status: null,
|
||||
customer_id: null,
|
||||
},
|
||||
|
||||
onSubmit: async (values) => {
|
||||
const formattedValues = {
|
||||
...values,
|
||||
product_ids: values.product_ids.map((item) => Number(item.value)),
|
||||
status: values.status?.value.toString() || '',
|
||||
customer_id: Number(values.customer_id?.value),
|
||||
};
|
||||
|
||||
onSubmit?.(formattedValues);
|
||||
closeModalHandler();
|
||||
},
|
||||
|
||||
onReset: () => {
|
||||
onReset?.();
|
||||
closeModalHandler();
|
||||
},
|
||||
});
|
||||
|
||||
const productChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldValue('product_ids', val as OptionType[]);
|
||||
};
|
||||
|
||||
const customerChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldValue('customer_id', val as OptionType);
|
||||
};
|
||||
|
||||
const statusChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldValue('status', val as OptionType);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
ref={ref}
|
||||
className={{
|
||||
modalBox: 'p-0 rounded-xl',
|
||||
}}
|
||||
>
|
||||
<form
|
||||
onSubmit={formik.handleSubmit}
|
||||
onReset={formik.handleReset}
|
||||
className='w-full flex flex-col'
|
||||
>
|
||||
{/* Modal Header */}
|
||||
<div className='p-4 flex items-center justify-between gap-2 border-b border-gray-300'>
|
||||
<div className='flex items-center gap-2 text-primary'>
|
||||
<Icon icon='heroicons:funnel' width={20} height={20} />
|
||||
<h3 className='text-sm font-medium'>Filter Data</h3>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={closeModalHandler}
|
||||
className='p-0 text-base-content/50 hover:text-base-content'
|
||||
>
|
||||
<Icon icon='heroicons:x-mark' width={20} height={20} />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Modal Body */}
|
||||
<div className='p-4 flex flex-col gap-1.5'>
|
||||
{/* select multiple product */}
|
||||
<SelectInputCheckbox
|
||||
label='Product'
|
||||
isClearable
|
||||
placeholder='Pilih product'
|
||||
options={productsOptions}
|
||||
isLoading={isLoadingProductsOptions}
|
||||
value={formik.values.product_ids}
|
||||
onChange={productChangeHandler}
|
||||
onInputChange={setProductsInputValue}
|
||||
onMenuScrollToBottom={loadMoreProducts}
|
||||
isMulti
|
||||
/>
|
||||
{/* select status */}
|
||||
<SelectInput
|
||||
label='Status'
|
||||
isClearable
|
||||
placeholder='Pilih status'
|
||||
options={statusOptions}
|
||||
value={formik.values.status}
|
||||
onChange={statusChangeHandler}
|
||||
/>
|
||||
{/* select customer */}
|
||||
<SelectInput
|
||||
label='Customer'
|
||||
isClearable
|
||||
placeholder='Pilih customer'
|
||||
options={customersOptions}
|
||||
isLoading={isLoadingCustomersOptions}
|
||||
value={formik.values.customer_id}
|
||||
onChange={customerChangeHandler}
|
||||
onInputChange={setCustomersInputValue}
|
||||
onMenuScrollToBottom={loadMoreCustomers}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Modal Footer */}
|
||||
<div className='p-4 flex justify-between gap-4 border-t border-gray-300 bg-gray-100'>
|
||||
<Button
|
||||
type='reset'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
className='p-3 rounded-lg text-base-content/65'
|
||||
>
|
||||
Reset Filter
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type='submit'
|
||||
className='p-3 rounded-lg w-fit sm:w-full max-w-40 text-base-100 text-sm'
|
||||
>
|
||||
Apply Filter
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default MarketingFilterModal;
|
||||
@@ -2,19 +2,10 @@
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||
import SelectInput, {
|
||||
OptionType,
|
||||
useSelect,
|
||||
} from '@/components/input/SelectInput';
|
||||
import Modal, { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
|
||||
import Table from '@/components/Table';
|
||||
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
||||
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
||||
import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
|
||||
import { TableToolbar } from '@/components/table/TableToolbar';
|
||||
import { ROWS_OPTIONS } from '@/config/constant';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
import { cn, formatCurrency, formatDate, formatTitleCase } from '@/lib/helper';
|
||||
import {
|
||||
@@ -22,54 +13,76 @@ import {
|
||||
SalesOrderApi,
|
||||
} from '@/services/api/marketing/marketing';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import { BaseSalesOrder, Marketing } from '@/types/api/marketing/marketing';
|
||||
import {
|
||||
BaseSalesOrder,
|
||||
Marketing,
|
||||
MarketingFilter,
|
||||
} from '@/types/api/marketing/marketing';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { CellContext, Row } from '@tanstack/react-table';
|
||||
import { CellContext, ColumnDef, Row } from '@tanstack/react-table';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import useSWR from 'swr';
|
||||
import RequirePermission from '@/components/helper/RequirePermission';
|
||||
import { useAuth } from '@/services/hooks/useAuth';
|
||||
import { CustomerApi, ProductApi } from '@/services/api/master-data';
|
||||
import { MARKETING_APPROVAL_LINE } from '@/config/approval-line';
|
||||
import Badge from '@/components/Badge';
|
||||
import ButtonFilter from '@/components/helper/ButtonFilter';
|
||||
import Dropdown from '@/components/Dropdown';
|
||||
import PopoverButton from '@/components/popover/PopoverButton';
|
||||
import PopoverContent from '@/components/popover/PopoverContent';
|
||||
import StatusBadge from '@/components/helper/StatusBadge';
|
||||
import MarketingFilterModal from '@/components/pages/marketing/MarketingFilter';
|
||||
|
||||
const RowsOptionsMenu = ({
|
||||
type = 'dropdown',
|
||||
props,
|
||||
deleteClickHandler,
|
||||
deliveryClickHandler,
|
||||
popoverPosition,
|
||||
}: {
|
||||
type: 'dropdown' | 'collapse';
|
||||
props: CellContext<Marketing, unknown>;
|
||||
deleteClickHandler: () => void;
|
||||
deliveryClickHandler?: () => void;
|
||||
popoverPosition?: 'top' | 'bottom';
|
||||
}) => {
|
||||
const popoverId = `marketing#${props.row.original.id}`;
|
||||
const popoverAnchorName = `--anchor-marketing#${props.row.original.id}`;
|
||||
|
||||
const isDeliveryRejected =
|
||||
props.row.original.latest_approval.action === 'REJECTED' &&
|
||||
props.row.original.latest_approval.step_number === 3;
|
||||
|
||||
return (
|
||||
<div
|
||||
tabIndex={type === 'dropdown' ? 0 : undefined}
|
||||
className={cn(
|
||||
{
|
||||
'dropdown-content': type === 'dropdown',
|
||||
'mt-2': type === 'collapse',
|
||||
},
|
||||
'p-2.5 mr-2 bg-base-100 rounded-box z-10 border border-black/10 shadow'
|
||||
)}
|
||||
<div className='relative'>
|
||||
<PopoverButton
|
||||
tabIndex={0}
|
||||
variant='ghost'
|
||||
color='none'
|
||||
popoverTarget={popoverId}
|
||||
anchorName={popoverAnchorName}
|
||||
>
|
||||
<div className='flex flex-col gap-1'>
|
||||
<Icon icon='material-symbols:more-vert' width={16} height={16} />
|
||||
</PopoverButton>
|
||||
<PopoverContent
|
||||
id={popoverId}
|
||||
anchorName={popoverAnchorName}
|
||||
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
|
||||
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
|
||||
>
|
||||
<div className='flex flex-col bg-base-100 rounded-xl'>
|
||||
<RequirePermission permissions='lti.marketing.delivery_order.detail'>
|
||||
<Button
|
||||
href={`/marketing/detail?marketingId=${props.row.original.id}`}
|
||||
href={`/marketing?action=detail&id=${props.row.original.id}`}
|
||||
variant='ghost'
|
||||
color='primary'
|
||||
className='justify-start text-sm'
|
||||
color='none'
|
||||
className='p-3 justify-start text-sm font-semibold w-full'
|
||||
>
|
||||
<Icon icon='mdi:eye-outline' width={16} height={16} />
|
||||
Detail
|
||||
<Icon icon='heroicons:eye' width={20} height={20} />
|
||||
View Details
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
{props.row.original.latest_approval.step_number != 1 && (
|
||||
{props.row.original.latest_approval.step_number != 1 &&
|
||||
!isDeliveryRejected && (
|
||||
<>
|
||||
<RequirePermission
|
||||
permissions={
|
||||
@@ -81,9 +94,9 @@ const RowsOptionsMenu = ({
|
||||
<Button
|
||||
href={
|
||||
props.row.original.latest_approval.step_number == 3
|
||||
? `/marketing/detail/delivery-orders/edit?marketingId=${props.row.original.id}`
|
||||
? `/marketing?action=edit_delivery&id=${props.row.original.id}`
|
||||
: props.row.original.latest_approval.step_number == 2
|
||||
? `/marketing/add/delivery-orders?marketingId=${props.row.original.id}`
|
||||
? `/marketing?action=add_delivery&id=${props.row.original.id}`
|
||||
: undefined
|
||||
}
|
||||
onClick={() => {
|
||||
@@ -92,11 +105,11 @@ const RowsOptionsMenu = ({
|
||||
}
|
||||
}}
|
||||
variant='ghost'
|
||||
color='success'
|
||||
className='justify-start text-sm'
|
||||
color='none'
|
||||
className='p-3 justify-start text-sm font-semibold w-full'
|
||||
>
|
||||
<Icon icon='mdi:truck' width={16} height={16} />
|
||||
Deliver
|
||||
<Icon icon='heroicons:truck' width={20} height={20} />
|
||||
Deliver Item
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
</>
|
||||
@@ -105,13 +118,13 @@ const RowsOptionsMenu = ({
|
||||
<>
|
||||
<RequirePermission permissions='lti.marketing.sales_order.update'>
|
||||
<Button
|
||||
href={`/marketing/detail/sales-orders/edit?marketingId=${props.row.original.id}`}
|
||||
href={`/marketing?action=edit&id=${props.row.original.id}`}
|
||||
variant='ghost'
|
||||
color='warning'
|
||||
className='justify-start text-sm'
|
||||
color='none'
|
||||
className='p-3 justify-start text-sm font-semibold w-full'
|
||||
>
|
||||
<Icon icon='mdi:pencil-outline' width={16} height={16} />
|
||||
Edit
|
||||
<Icon icon='heroicons:pencil-square' width={20} height={20} />
|
||||
Edit Item
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
</>
|
||||
@@ -120,14 +133,15 @@ const RowsOptionsMenu = ({
|
||||
<Button
|
||||
onClick={deleteClickHandler}
|
||||
variant='ghost'
|
||||
color='error'
|
||||
className='text-error hover:text-inherit justify-start text-sm'
|
||||
color='none'
|
||||
className='relative p-3 overflow-hidden justify-start text-sm font-semibold w-full text-error before:content-[""] before:absolute before:h-0.25 before:p-3 before:top-0 before:left-0 before:right-0 before:border-t before:border-base-content/5'
|
||||
>
|
||||
<Icon icon='mdi:delete-outline' width={16} height={16} />
|
||||
Delete
|
||||
<Icon icon='heroicons:trash' width={20} height={20} />
|
||||
Delete Item
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -147,6 +161,8 @@ const MarketingTable = () => {
|
||||
const confirmationModal = useModal();
|
||||
const productsModal = useModal();
|
||||
const deliveryModal = useModal();
|
||||
const filterModal = useModal();
|
||||
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
@@ -159,8 +175,6 @@ const MarketingTable = () => {
|
||||
product_ids: '',
|
||||
status: '',
|
||||
customer_id: '',
|
||||
page: 1,
|
||||
limit: 10,
|
||||
},
|
||||
paramMap: {
|
||||
page: 'page',
|
||||
@@ -181,46 +195,27 @@ const MarketingTable = () => {
|
||||
MarketingApi.getAllFetcher
|
||||
);
|
||||
|
||||
// ===== OPTIONS =====
|
||||
const {
|
||||
options: productsOptions,
|
||||
isLoadingOptions: isLoadingProductsOptions,
|
||||
setInputValue: setProductsInputValue,
|
||||
loadMore: loadMoreProducts,
|
||||
} = useSelect(ProductApi.basePath, 'id', 'name', '', {
|
||||
limit: 'limit',
|
||||
});
|
||||
const {
|
||||
options: customersOptions,
|
||||
isLoadingOptions: isLoadingCustomersOptions,
|
||||
setInputValue: setCustomersInputValue,
|
||||
loadMore: loadMoreCustomers,
|
||||
} = useSelect(CustomerApi.basePath, 'id', 'name', '', {
|
||||
limit: 'limit',
|
||||
});
|
||||
const statusOptions = MARKETING_APPROVAL_LINE.map((item) => ({
|
||||
value: item.step_number,
|
||||
label: item.step_name,
|
||||
}));
|
||||
|
||||
// ===== HANDLER =====
|
||||
const searchChangeHandler = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setSearch(e.target.value);
|
||||
updateFilter('page', 1);
|
||||
updateFilter('search', e.target.value);
|
||||
},
|
||||
[]
|
||||
const filterSubmitHandler = (values: MarketingFilter) => {
|
||||
updateFilter(
|
||||
'product_ids',
|
||||
values.product_ids?.map((item) => item.toString()).join(',')
|
||||
);
|
||||
const pageSizeChangeHandler = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
const newVal = val as OptionType;
|
||||
setPageSize(newVal.value as number);
|
||||
updateFilter('page', 1);
|
||||
updateFilter('limit', newVal.value as number);
|
||||
},
|
||||
[]
|
||||
updateFilter('status', values.status ? values.status.toString() : '');
|
||||
updateFilter(
|
||||
'customer_id',
|
||||
values.customer_id ? values.customer_id.toString() : ''
|
||||
);
|
||||
};
|
||||
|
||||
const [isLoadingExportingToExcel, setIsLoadingExportingToExcel] =
|
||||
useState(false);
|
||||
|
||||
const filterResetHandler = () => {
|
||||
updateFilter('product_ids', '');
|
||||
updateFilter('status', '');
|
||||
updateFilter('customer_id', '');
|
||||
};
|
||||
|
||||
const approveClickHandler = () => {
|
||||
setApproveAction('APPROVED');
|
||||
@@ -318,7 +313,7 @@ const MarketingTable = () => {
|
||||
toast.success(res?.message as string);
|
||||
refreshMarketing?.();
|
||||
router.push(
|
||||
`/marketing/detail/delivery-orders/edit?marketingId=${selectedItem?.id}`
|
||||
`/marketing/detail/delivery-orders/edit?id=${selectedItem?.id}`
|
||||
);
|
||||
};
|
||||
|
||||
@@ -327,142 +322,19 @@ const MarketingTable = () => {
|
||||
return approval?.step_number === 1 && approval?.action !== 'REJECTED';
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='flex flex-col gap-4'>
|
||||
<div className='flex flex-col gap-2 mb-4'>
|
||||
<TableToolbar
|
||||
addButton={
|
||||
permissionCheck('lti.marketing.sales_order.create')
|
||||
? {
|
||||
href: '/marketing/add/sales-orders',
|
||||
label: 'Tambah Sales Order',
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
search={{
|
||||
value: search,
|
||||
onChange: searchChangeHandler,
|
||||
placeholder: 'Cari Sales Order',
|
||||
}}
|
||||
/>
|
||||
<div className='flex flex-row gap-2'>
|
||||
<RequirePermission permissions='lti.marketing.sales_order.approve'>
|
||||
<Button
|
||||
color='success'
|
||||
onClick={approveClickHandler}
|
||||
className='justify-start text-sm'
|
||||
disabled={disableApprove}
|
||||
>
|
||||
<Icon icon='material-symbols:check' width={24} height={24} />
|
||||
Approve
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
const exportToExcelHandler = async () => {
|
||||
setIsLoadingExportingToExcel(true);
|
||||
|
||||
<RequirePermission permissions='lti.marketing.sales_order.approve'>
|
||||
<Button
|
||||
color='error'
|
||||
onClick={rejectClickHandler}
|
||||
className='justify-start text-sm'
|
||||
disabled={disableReject}
|
||||
>
|
||||
<Icon icon='material-symbols:close' width={24} height={24} />
|
||||
Reject
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
</div>
|
||||
<TableRowSizeSelector
|
||||
value={tableFilterState.pageSize}
|
||||
onChange={pageSizeChangeHandler}
|
||||
options={ROWS_OPTIONS}
|
||||
className='flex sm:flex-row flex-col gap-3 items-end justify-end'
|
||||
>
|
||||
{/* select multiple product */}
|
||||
<SelectInput
|
||||
label='Product'
|
||||
isClearable
|
||||
placeholder='Pilih product'
|
||||
options={productsOptions}
|
||||
isLoading={isLoadingProductsOptions}
|
||||
value={
|
||||
tableFilterState.product_ids
|
||||
?.split(',')
|
||||
.map((id) =>
|
||||
productsOptions.find(
|
||||
(option) => option.value === Number(id)
|
||||
)
|
||||
)
|
||||
.filter(
|
||||
(option): option is { value: number; label: string } =>
|
||||
option !== undefined
|
||||
) ?? null
|
||||
}
|
||||
onChange={(value: OptionType | OptionType[] | null) =>
|
||||
updateFilter(
|
||||
'product_ids',
|
||||
(value as OptionType[])
|
||||
?.map((item: OptionType) => item.value.toString())
|
||||
.join(',') || ''
|
||||
)
|
||||
}
|
||||
onInputChange={setProductsInputValue}
|
||||
onMenuScrollToBottom={loadMoreProducts}
|
||||
isMulti
|
||||
/>
|
||||
{/* select status */}
|
||||
<SelectInput
|
||||
label='Status'
|
||||
isClearable
|
||||
placeholder='Pilih status'
|
||||
options={statusOptions}
|
||||
value={
|
||||
tableFilterState.status
|
||||
? statusOptions.find(
|
||||
(option) =>
|
||||
option.value === Number(tableFilterState.status)
|
||||
)
|
||||
: null
|
||||
}
|
||||
onChange={(value: OptionType | OptionType[] | null) =>
|
||||
updateFilter(
|
||||
'status',
|
||||
(value as OptionType)?.value.toString() || ''
|
||||
)
|
||||
}
|
||||
/>
|
||||
{/* select customer */}
|
||||
<SelectInput
|
||||
label='Customer'
|
||||
isClearable
|
||||
placeholder='Pilih customer'
|
||||
options={customersOptions}
|
||||
isLoading={isLoadingCustomersOptions}
|
||||
value={
|
||||
tableFilterState.customer_id
|
||||
? customersOptions.find(
|
||||
(option) =>
|
||||
option.value === Number(tableFilterState.customer_id)
|
||||
)
|
||||
: null
|
||||
}
|
||||
onChange={(value: OptionType | OptionType[] | null) =>
|
||||
updateFilter(
|
||||
'customer_id',
|
||||
(value as OptionType)?.value.toString() || ''
|
||||
)
|
||||
}
|
||||
onInputChange={setCustomersInputValue}
|
||||
onMenuScrollToBottom={loadMoreCustomers}
|
||||
/>
|
||||
</TableRowSizeSelector>
|
||||
</div>
|
||||
<Table
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
data={allData}
|
||||
columns={[
|
||||
await MarketingApi.exportToExcel(getTableFilterToQueryString());
|
||||
|
||||
setIsLoadingExportingToExcel(false);
|
||||
};
|
||||
|
||||
const columns = useMemo<ColumnDef<Marketing>[]>(() => {
|
||||
return [
|
||||
{
|
||||
id: 'select',
|
||||
size: 1,
|
||||
header: ({ table }) => {
|
||||
const allRows = table.getRowModel().rows;
|
||||
const selectableRows = allRows.filter(getRowCanSelect);
|
||||
@@ -472,18 +344,15 @@ const MarketingTable = () => {
|
||||
selectableRows.every((row) => row.getIsSelected());
|
||||
|
||||
const someSelected =
|
||||
selectableRows.some((row) => row.getIsSelected()) &&
|
||||
!allSelected;
|
||||
selectableRows.some((row) => row.getIsSelected()) && !allSelected;
|
||||
|
||||
const toggleSelectableRows = () => {
|
||||
const shouldSelect = !allSelected;
|
||||
selectableRows.forEach((row) =>
|
||||
row.toggleSelected(shouldSelect)
|
||||
);
|
||||
selectableRows.forEach((row) => row.toggleSelected(shouldSelect));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center'>
|
||||
<div className='w-fit flex flex-row justify-start'>
|
||||
<CheckboxInput
|
||||
name='allRow'
|
||||
checked={allSelected}
|
||||
@@ -497,7 +366,7 @@ const MarketingTable = () => {
|
||||
cell: ({ row }) => {
|
||||
const canSelect = getRowCanSelect(row);
|
||||
return (
|
||||
<div>
|
||||
<div className='w-fit flex flex-row justify-start'>
|
||||
<CheckboxInput
|
||||
name='row'
|
||||
checked={row.getIsSelected()}
|
||||
@@ -527,45 +396,31 @@ const MarketingTable = () => {
|
||||
const approval = props.row.original.latest_approval;
|
||||
const isRejected = approval?.action == 'REJECTED';
|
||||
const isApproved = approval?.action == 'APPROVED';
|
||||
const isUpdated = approval?.action == 'UPDATED';
|
||||
return (
|
||||
<Badge
|
||||
variant='soft'
|
||||
className={{
|
||||
badge:
|
||||
'rounded-lg px-2 w-full flex flex-row justify-start whitespace-nowrap',
|
||||
}}
|
||||
<StatusBadge
|
||||
color={
|
||||
isRejected
|
||||
? 'error'
|
||||
: isApproved
|
||||
: isApproved || isUpdated
|
||||
? approval?.step_number == 1
|
||||
? 'neutral'
|
||||
: approval?.step_number == 2
|
||||
? 'primary'
|
||||
? 'info'
|
||||
: approval?.step_number == 3
|
||||
? 'success'
|
||||
? 'warning'
|
||||
: 'neutral'
|
||||
: 'neutral'
|
||||
}
|
||||
>
|
||||
<Icon
|
||||
icon='mdi:circle'
|
||||
width={12}
|
||||
height={12}
|
||||
color={
|
||||
approval?.step_number == 1
|
||||
? 'neutral'
|
||||
: approval?.step_number == 2
|
||||
? 'primary'
|
||||
: approval?.step_number == 3
|
||||
? 'success'
|
||||
: 'neutral'
|
||||
}
|
||||
/>
|
||||
{isRejected
|
||||
text={
|
||||
isRejected
|
||||
? 'Ditolak'
|
||||
: formatTitleCase(approval?.step_name || '')}
|
||||
</Badge>
|
||||
: formatTitleCase(approval?.step_name || '')
|
||||
}
|
||||
className={{
|
||||
badge: 'whitespace-nowrap',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
@@ -596,8 +451,7 @@ const MarketingTable = () => {
|
||||
return (
|
||||
<Button
|
||||
variant='link'
|
||||
color='success'
|
||||
className='p-0 text-none'
|
||||
className='p-0 text-none text-sm'
|
||||
onClick={() => {
|
||||
productsClickHandler(props?.row?.original);
|
||||
}}
|
||||
@@ -613,17 +467,16 @@ const MarketingTable = () => {
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Aksi',
|
||||
id: 'actions',
|
||||
maxSize: 80,
|
||||
cell: (props) => {
|
||||
const currentPageSize =
|
||||
props.table.getPaginationRowModel().rows.length;
|
||||
const currentPageRows =
|
||||
props.table.getPaginationRowModel().flatRows;
|
||||
const currentPageRows = props.table.getPaginationRowModel().flatRows;
|
||||
const currentRowRelativeIndex =
|
||||
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
|
||||
|
||||
const isLast2Rows =
|
||||
currentRowRelativeIndex > currentPageSize - 2;
|
||||
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
|
||||
|
||||
const deleteClickHandler = () => {
|
||||
setSelectedItem(props.row.original);
|
||||
@@ -636,45 +489,149 @@ const MarketingTable = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{currentPageSize > 2 && (
|
||||
<RowDropdownOptions isLast2Rows={isLast2Rows}>
|
||||
<RowsOptionsMenu
|
||||
type='dropdown'
|
||||
props={props}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
deliveryClickHandler={deliveryClickHandler}
|
||||
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
|
||||
/>
|
||||
</RowDropdownOptions>
|
||||
)}
|
||||
|
||||
{currentPageSize <= 2 && (
|
||||
<RowCollapseOptions>
|
||||
<RowsOptionsMenu
|
||||
type='collapse'
|
||||
props={props}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
deliveryClickHandler={deliveryClickHandler}
|
||||
/>
|
||||
</RowCollapseOptions>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
];
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='flex flex-col'>
|
||||
<div className='flex flex-row justify-between p-3 border-b border-base-content/10'>
|
||||
<div className='flex flex-row gap-3'>
|
||||
<RequirePermission permissions='lti.marketing.sales_order.create'>
|
||||
<Button
|
||||
href={{
|
||||
pathname: '/marketing',
|
||||
query: {
|
||||
action: 'add',
|
||||
},
|
||||
}}
|
||||
className='font-semibold text-base-100 text-sm rounded-lg shadow-button-soft px-3 py-2.5'
|
||||
>
|
||||
<Icon icon='heroicons:plus' width={20} height={20} />
|
||||
Add Sales Order
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
{idsToProcess.length > 0 && (
|
||||
<>
|
||||
<div className='divider divider-horizontal w-0.25 p-0 m-0 bg-base-content/10 text-base-content/10 before:bg-base-content/10 before:w-0.25 after:bg-base-content/10 after:w-0.25'></div>
|
||||
<RequirePermission permissions='lti.marketing.sales_order.approve'>
|
||||
<Button
|
||||
color='error'
|
||||
onClick={rejectClickHandler}
|
||||
className='justify-start text-sm shadow-button-soft rounded-lg bg-base-100 text-base-content/50 px-3 py-2.5 border border-base-content/10'
|
||||
disabled={disableReject}
|
||||
>
|
||||
<Icon
|
||||
icon='heroicons:x-mark'
|
||||
className='text-error'
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
Reject
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
<RequirePermission permissions='lti.marketing.sales_order.approve'>
|
||||
<Button
|
||||
color='none'
|
||||
onClick={approveClickHandler}
|
||||
className='justify-start text-sm shadow-button-soft rounded-lg bg-base-100 text-base-content/50 px-3 py-2.5 border border-base-content/10'
|
||||
disabled={disableApprove}
|
||||
>
|
||||
<Icon
|
||||
icon='heroicons:check'
|
||||
className='text-success'
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
Approve
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className='flex flex-row gap-3'>
|
||||
<ButtonFilter
|
||||
values={(() => {
|
||||
const { page, pageSize, ...rest } = tableFilterState;
|
||||
return rest;
|
||||
})()}
|
||||
onClick={() => {
|
||||
filterModal.openModal();
|
||||
}}
|
||||
className='rounded-lg px-3 py-2.5'
|
||||
/>
|
||||
<Dropdown
|
||||
align='end'
|
||||
direction='bottom'
|
||||
trigger={
|
||||
<Button
|
||||
variant='outline'
|
||||
color='none'
|
||||
className={cn(
|
||||
'px-3 py-2.5 rounded-lg font-semibold text-sm gap-1.5',
|
||||
'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft'
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
width={20}
|
||||
height={20}
|
||||
icon='heroicons:cloud-arrow-down'
|
||||
/>
|
||||
Export
|
||||
<div className='w-6.5 h-5 flex items-center justify-center border-l border-base-content/10'>
|
||||
<Icon
|
||||
width={14}
|
||||
height={14}
|
||||
icon='heroicons:chevron-down'
|
||||
/>
|
||||
</div>
|
||||
</Button>
|
||||
}
|
||||
className={{
|
||||
content:
|
||||
'mt-1 rounded-xl border border-base-content/5 shadow-sm overflow-hidden',
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={exportToExcelHandler}
|
||||
isLoading={isLoadingExportingToExcel}
|
||||
className='w-full p-3 justify-start text-sm text-base-content/50 font-semibold text-nowrap'
|
||||
>
|
||||
<Icon icon='heroicons:table-cells' width={20} height={20} />
|
||||
Export to Excel
|
||||
</Button>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</div>
|
||||
<Table
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={setPageSize}
|
||||
data={allData}
|
||||
columns={columns}
|
||||
pageSize={tableFilterState.pageSize}
|
||||
page={tableFilterState.page}
|
||||
onPageChange={setPage}
|
||||
isLoading={isLoadingMarketing}
|
||||
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-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
containerClassName: cn('p-3', {
|
||||
'w-full mb-20':
|
||||
isResponseSuccess(marketing) && marketing?.data?.length === 0,
|
||||
}),
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
'last:text-end last:w-17 first:text-start first:w-5',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -736,19 +693,23 @@ const MarketingTable = () => {
|
||||
<Modal
|
||||
ref={productsModal.ref}
|
||||
className={{
|
||||
modalBox: 'xs:max-w-2/5 z-100',
|
||||
modalBox: 'xs:max-w-2/5 z-100 rounded-lg p-0 flex flex-col',
|
||||
modal: 'rounded-lg',
|
||||
}}
|
||||
closeOnBackdrop
|
||||
>
|
||||
<div className='flex flex-row justify-between items-center mb-3'>
|
||||
<h4 className='text-xl font-semibold'>Daftar Produk</h4>
|
||||
<div className='flex flex-row justify-between items-center border-b border-base-content/10 p-4'>
|
||||
<h4 className='flex items-center justify-center gap-2 text-sm font-medium text-base-content'>
|
||||
<Icon icon='heroicons:information-circle' width={20} height={20} />{' '}
|
||||
Daftar Produk
|
||||
</h4>
|
||||
<Button
|
||||
variant='ghost'
|
||||
color='error'
|
||||
color='none'
|
||||
onClick={productsModal.closeModal}
|
||||
className='justify-start text-sm rounded-full'
|
||||
className='justify-start text-sm p-1'
|
||||
>
|
||||
<Icon icon='mdi:close' width={16} height={16} />
|
||||
<Icon icon='mdi:close' width={20} height={20} />
|
||||
</Button>
|
||||
</div>
|
||||
<Table<BaseSalesOrder>
|
||||
@@ -778,20 +739,19 @@ const MarketingTable = () => {
|
||||
},
|
||||
]}
|
||||
className={{
|
||||
containerClassName: 'p-6',
|
||||
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-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
containerClassName: 'p-4',
|
||||
headerColumnClassName: 'whitespace-nowrap',
|
||||
bodyColumnClassName: 'last:flex last:flex-row last:justify-end',
|
||||
paginationClassName: 'hidden',
|
||||
}}
|
||||
isLoading={isLoadingMarketing}
|
||||
/>
|
||||
</Modal>
|
||||
<MarketingFilterModal
|
||||
ref={filterModal.ref}
|
||||
onSubmit={filterSubmitHandler}
|
||||
onReset={filterResetHandler}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,748 @@
|
||||
'use client';
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||
import RequirePermission from '@/components/helper/RequirePermission';
|
||||
import DateInput from '@/components/input/DateInput';
|
||||
import DebouncedTextArea from '@/components/input/DebouncedTextArea';
|
||||
import NumberInput from '@/components/input/NumberInput';
|
||||
import { OptionType, useSelect } from '@/components/input/SelectInput';
|
||||
import SelectInputRadio from '@/components/input/SelectInputRadio';
|
||||
import Modal, { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import {
|
||||
DeliveryProductToFieldValues,
|
||||
mergeSOwithDO,
|
||||
SalesProductToFieldValues,
|
||||
} from '@/components/pages/marketing/form/MarketingForm';
|
||||
import {
|
||||
DeliveryOrderFormValues,
|
||||
DeliveryOrderSchema,
|
||||
getFilledMarketingFormInitialValues,
|
||||
SalesOrderFormValues,
|
||||
SalesOrderSchema,
|
||||
} from '@/components/pages/marketing/form/MarketingForm.schema';
|
||||
import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
|
||||
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
|
||||
import SalesOrderProductForm from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProductForm';
|
||||
import SalesOrderProductTable from '@/components/pages/marketing/form/table-view/SalesOrderProductTable';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
import { formatDate } from '@/lib/helper';
|
||||
import {
|
||||
MarketingApi,
|
||||
SalesOrderApi,
|
||||
} from '@/services/api/marketing/marketing';
|
||||
import { CustomerApi } from '@/services/api/master-data';
|
||||
import { UserApi } from '@/services/api/user';
|
||||
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||
import { CreatedUser } from '@/types/api/api-general';
|
||||
import {
|
||||
CreateSalesOrderPayload,
|
||||
CreateSalesOrderProductPayload,
|
||||
Marketing,
|
||||
UpdateDeliveryOrderPayload,
|
||||
UpdateSalesOrderPayload,
|
||||
} from '@/types/api/marketing/marketing';
|
||||
import { Customer } from '@/types/api/master-data/customer';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useFormik } from 'formik';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import useSWR, { useSWRConfig } from 'swr';
|
||||
|
||||
const MemoizedSalesOrderProductTable = memo(SalesOrderProductTable);
|
||||
const MemoizedSalesOrderProductForm = memo(SalesOrderProductForm);
|
||||
|
||||
const SalesOrderFormModal = ({
|
||||
initialValues,
|
||||
}: {
|
||||
initialValues?: Marketing;
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const modalAction = searchParams.get('action');
|
||||
const marketingId = searchParams.get('id');
|
||||
|
||||
const isModalActionForForm =
|
||||
modalAction === 'add' ||
|
||||
modalAction === 'edit' ||
|
||||
modalAction === 'add_delivery' ||
|
||||
modalAction === 'edit_delivery';
|
||||
|
||||
const { mutate } = useSWRConfig();
|
||||
|
||||
const refreshMarketing = () => {
|
||||
mutate(
|
||||
(key) => typeof key === 'string' && key.includes(MarketingApi.basePath)
|
||||
);
|
||||
};
|
||||
|
||||
const { data: marketing, isLoading: isLoadingMarketing } = useSWR(
|
||||
isModalActionForForm && marketingId
|
||||
? `detail-marketing-${marketingId}`
|
||||
: undefined,
|
||||
() => MarketingApi.getSingle(Number(marketingId))
|
||||
);
|
||||
|
||||
// ================== FETCH OPTIONS ==================
|
||||
const {
|
||||
options: customerOptions,
|
||||
isLoadingOptions: isLoadingCustomerOptions,
|
||||
setInputValue: setInputCustomerValue,
|
||||
loadMore: loadMoreCustomer,
|
||||
} = useSelect<Customer>(CustomerApi.basePath, 'id', 'name');
|
||||
const {
|
||||
options: salesOptions,
|
||||
isLoadingOptions: isLoadingSalesOptions,
|
||||
setInputValue: setInputSalesValue,
|
||||
loadMore: loadMoreSales,
|
||||
} = useSelect<CreatedUser>(UserApi.basePath, 'id', 'name');
|
||||
|
||||
/**
|
||||
* Step 1: General Information
|
||||
* Step 2: Repeater Add Product
|
||||
* Step 3: Submit
|
||||
*/
|
||||
const [step, setStep] = useState(1);
|
||||
|
||||
const formModal = useModal();
|
||||
const successModal = useModal();
|
||||
const deleteModal = useModal();
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
const [formikLastValues, setFormikLastValues] = useState<
|
||||
SalesOrderFormValues | undefined
|
||||
>(undefined);
|
||||
const [formErrorMessage, setFormErrorMessage] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedMarketingProduct, setSelectedMarketingProduct] =
|
||||
useState<SalesOrderProductFormValues | null>(null);
|
||||
const [selectedDeliveryProduct, setSelectedDeliveryProduct] =
|
||||
useState<DeliveryOrderProductFormValues | null>(null);
|
||||
const [deliveryFormState, setDeliveryFormState] = useState<'add' | 'edit'>(
|
||||
'add'
|
||||
);
|
||||
const [deliveryOrderValues, setDeliveryOrderValues] = useState<
|
||||
DeliveryOrderProductFormValues[]
|
||||
>(
|
||||
mergeSOwithDO(
|
||||
initialValues?.sales_order?.map(SalesProductToFieldValues) ?? [],
|
||||
initialValues?.delivery_order?.flatMap((delivery) =>
|
||||
DeliveryProductToFieldValues(initialValues.sales_order, delivery)
|
||||
) ?? []
|
||||
)
|
||||
);
|
||||
|
||||
// ================== SETUP FORMIK ==================
|
||||
const formikInitialValues = useMemo<
|
||||
SalesOrderFormValues & DeliveryOrderFormValues
|
||||
>(() => {
|
||||
return {
|
||||
so_date: initialValues?.so_date || undefined,
|
||||
notes: initialValues?.notes || undefined,
|
||||
customer_id: initialValues?.customer?.id || undefined,
|
||||
sales_person_id: initialValues?.sales_person?.id || undefined,
|
||||
sales_person: initialValues?.sales_person
|
||||
? {
|
||||
value: initialValues.sales_person.id,
|
||||
label: initialValues.sales_person.name,
|
||||
}
|
||||
: null,
|
||||
customer: initialValues?.customer
|
||||
? {
|
||||
value: initialValues.customer.id,
|
||||
label: initialValues.customer.name,
|
||||
}
|
||||
: null,
|
||||
sales_order:
|
||||
initialValues?.sales_order?.map((product) =>
|
||||
SalesProductToFieldValues(product)
|
||||
) ?? [],
|
||||
delivery_order: mergeSOwithDO(
|
||||
initialValues?.sales_order?.map(SalesProductToFieldValues) ?? [],
|
||||
initialValues?.delivery_order?.flatMap((delivery) =>
|
||||
DeliveryProductToFieldValues(initialValues.sales_order, delivery)
|
||||
) ?? []
|
||||
),
|
||||
};
|
||||
}, [initialValues]);
|
||||
const formik = useFormik<SalesOrderFormValues & DeliveryOrderFormValues>({
|
||||
enableReinitialize: true,
|
||||
initialValues: formikInitialValues,
|
||||
validationSchema:
|
||||
modalAction == 'add_deliver' || modalAction == 'edit_deliver'
|
||||
? DeliveryOrderSchema
|
||||
: SalesOrderSchema,
|
||||
validateOnMount: true,
|
||||
onSubmit: async (values) => {
|
||||
const payload =
|
||||
modalAction != 'add_deliver' && modalAction != 'edit_deliver'
|
||||
? ({
|
||||
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: product.vehicle_number as string,
|
||||
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)
|
||||
: ({
|
||||
marketing_id: initialValues?.id as number,
|
||||
delivery_products: values.delivery_order
|
||||
.map((product) => {
|
||||
if (Boolean(product.delivery_date)) {
|
||||
return {
|
||||
marketing_product_id:
|
||||
product.marketing_product_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),
|
||||
delivery_date: formatDate(
|
||||
product.delivery_date as string,
|
||||
'yyyy-MM-DD'
|
||||
),
|
||||
vehicle_number: product.vehicle_number,
|
||||
};
|
||||
}
|
||||
})
|
||||
.filter((item) => Boolean(item)),
|
||||
} as UpdateDeliveryOrderPayload);
|
||||
switch (modalAction) {
|
||||
case 'add':
|
||||
await createMarketingHandler(payload as CreateSalesOrderPayload);
|
||||
break;
|
||||
case 'edit':
|
||||
await updateMarketingHandler(payload as UpdateSalesOrderPayload);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// ===== Formik Error List =====
|
||||
const { formErrorList, setFormErrorList, close, handleFormSubmit } =
|
||||
useFormikErrorList(formik, {
|
||||
onAfterSubmit: () => {
|
||||
router.push('/marketing');
|
||||
},
|
||||
});
|
||||
|
||||
// ================== FORM REPEATER HANDLER ==================
|
||||
const createMarketingHandler = async (values: CreateSalesOrderPayload) => {
|
||||
setIsLoading(true);
|
||||
const createMarketingRes = await SalesOrderApi.create(values);
|
||||
if (isResponseSuccess(createMarketingRes)) {
|
||||
closeModalHandler(false);
|
||||
successModal.openModal();
|
||||
refreshMarketing();
|
||||
}
|
||||
if (isResponseError(createMarketingRes)) {
|
||||
toast.error(createMarketingRes?.message as string);
|
||||
}
|
||||
setIsLoading(false);
|
||||
};
|
||||
const updateMarketingHandler = async (values: UpdateSalesOrderPayload) => {
|
||||
setIsLoading(true);
|
||||
if (!marketingId) {
|
||||
toast.error('Marketing ID is required');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
const updateMarketingRes = await SalesOrderApi.update(
|
||||
Number(marketingId),
|
||||
values
|
||||
);
|
||||
if (isResponseSuccess(updateMarketingRes)) {
|
||||
closeModalHandler(false);
|
||||
successModal.openModal();
|
||||
refreshMarketing();
|
||||
}
|
||||
if (isResponseError(updateMarketingRes)) {
|
||||
toast.error(updateMarketingRes?.message as string);
|
||||
}
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
const memoSalesOrder = formik.values.sales_order;
|
||||
|
||||
// ================== HANDLER ==================
|
||||
const nextButtonHandler = () => {
|
||||
setStep(step + 1);
|
||||
};
|
||||
const prevButtonHandler = () => {
|
||||
setStep(step - 1);
|
||||
};
|
||||
const handleChangeCustomer = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldValue('customer_id', (val as OptionType)?.value);
|
||||
formik.setFieldValue('customer', val as OptionType);
|
||||
},
|
||||
[]
|
||||
);
|
||||
const handleChangeSalesPerson = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldValue('sales_person_id', (val as OptionType)?.value);
|
||||
formik.setFieldValue('sales_person', val as OptionType);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const deleteClickHandler = () => {
|
||||
deleteModal.openModal();
|
||||
};
|
||||
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
if (!marketingId) {
|
||||
toast.error(`Tidak ada data yang valid untuk di hapus.`);
|
||||
deleteModal.closeModal();
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
const res = await MarketingApi.delete(Number(marketingId));
|
||||
deleteModal.closeModal();
|
||||
toast.success(res?.message as string);
|
||||
setIsLoading(false);
|
||||
refreshMarketing();
|
||||
closeModalHandler();
|
||||
router.replace('/marketing');
|
||||
};
|
||||
|
||||
// ================== SALES ORDER HANDLER ==================
|
||||
const handleDeleteSO = useCallback(
|
||||
(id: number) => {
|
||||
const currentProducts = formik.values.sales_order;
|
||||
formik.setFieldValue(
|
||||
'sales_order',
|
||||
currentProducts.filter((p) => p.id != id)
|
||||
);
|
||||
},
|
||||
[memoSalesOrder]
|
||||
);
|
||||
const handleDeleteAllSO = useCallback(() => {
|
||||
formik.setFieldValue('sales_order', []);
|
||||
}, [memoSalesOrder]);
|
||||
const handleEditSO = useCallback(
|
||||
(id: number) => {
|
||||
const currentProducts = formik.values.sales_order;
|
||||
const selectedProduct = currentProducts.find((p) => p.id == id);
|
||||
setSelectedMarketingProduct(selectedProduct ?? null);
|
||||
setStep(2);
|
||||
},
|
||||
[memoSalesOrder]
|
||||
);
|
||||
const handleAddSOClick = useCallback(() => {
|
||||
setSelectedMarketingProduct(null);
|
||||
if (step === 3) {
|
||||
setStep(2);
|
||||
} else {
|
||||
prevButtonHandler();
|
||||
}
|
||||
}, [step]);
|
||||
const handleAddSubmitSO = useCallback(
|
||||
async (values: SalesOrderProductFormValues, id?: number) => {
|
||||
const currentProducts = formik.values.sales_order;
|
||||
|
||||
const newValues = {
|
||||
...values,
|
||||
id: values.id ?? Date.now(),
|
||||
};
|
||||
|
||||
let updatedProducts = [];
|
||||
|
||||
if (id) {
|
||||
// Overwrite
|
||||
updatedProducts = currentProducts.map((item) =>
|
||||
item.id === id ? newValues : item
|
||||
);
|
||||
} else {
|
||||
// Add new item
|
||||
updatedProducts = [...currentProducts, newValues];
|
||||
}
|
||||
|
||||
formik.setFieldValue('sales_order', updatedProducts);
|
||||
nextButtonHandler();
|
||||
},
|
||||
[memoSalesOrder, nextButtonHandler]
|
||||
);
|
||||
|
||||
const isNextButtonDisabled = useMemo(() => {
|
||||
if (step === 1) {
|
||||
return Boolean(
|
||||
!formik.values.customer_id ||
|
||||
!formik.values.sales_person_id ||
|
||||
!formik.values.so_date ||
|
||||
!formik.values.notes
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}, [step, formik.values]);
|
||||
|
||||
// ================== EFFECT ==================
|
||||
useEffect(() => {
|
||||
if (modalAction === 'add' || modalAction === 'edit') {
|
||||
formModal.openModal();
|
||||
}
|
||||
}, [modalAction]);
|
||||
|
||||
const closeModalHandler = (shouldPushToRoute: boolean = true) => {
|
||||
refreshMarketing();
|
||||
if (shouldPushToRoute) {
|
||||
formik.resetForm();
|
||||
textareaRef.current?.setAttribute('value', '');
|
||||
successModal.closeModal();
|
||||
router.push('/marketing');
|
||||
}
|
||||
|
||||
setStep(1);
|
||||
setFormErrorMessage('');
|
||||
formModal.closeModal();
|
||||
};
|
||||
|
||||
const grandTotal = useMemo(() => {
|
||||
return memoSalesOrder.reduce(
|
||||
(total, product) =>
|
||||
total + parseFloat((product.total_price as string) || '0'),
|
||||
0
|
||||
);
|
||||
}, [memoSalesOrder]);
|
||||
|
||||
useEffect(() => {
|
||||
const getFilledInitialValues = async () => {
|
||||
if (marketingId && isResponseSuccess(marketing)) {
|
||||
const filledInitialValues = await getFilledMarketingFormInitialValues(
|
||||
marketing.data
|
||||
);
|
||||
|
||||
formik.setValues(filledInitialValues);
|
||||
setStep(3);
|
||||
}
|
||||
|
||||
if (isResponseError(marketing)) {
|
||||
router.push('/marketing');
|
||||
closeModalHandler();
|
||||
toast.error(marketing.message);
|
||||
}
|
||||
};
|
||||
|
||||
getFilledInitialValues();
|
||||
}, [marketingId, marketing]);
|
||||
|
||||
// Reset error message when step changes
|
||||
useEffect(() => {
|
||||
setFormErrorList([]);
|
||||
setFormErrorMessage('');
|
||||
}, [step]);
|
||||
|
||||
useEffect(() => {
|
||||
if (memoSalesOrder.length === 0) {
|
||||
setStep(1);
|
||||
}
|
||||
}, [memoSalesOrder]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
ref={formModal.ref}
|
||||
position='end'
|
||||
className={{
|
||||
modalBox: 'w-full sm:w-fit p-3 rounded-xl bg-transparent shadow-none',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
}}
|
||||
className='w-full min-h-full flex flex-col sm:flex-row items-stretch bg-base-100 rounded-xl overflow-y-auto'
|
||||
>
|
||||
{step <= 3 && (
|
||||
<div className='w-full sm:w-[446px]'>
|
||||
<div className='w-full p-4 flex flex-row items-stretch gap-3 border-b border-base-content/10'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={() => closeModalHandler()}
|
||||
className='p-0 text-black hover:text-base-content'
|
||||
>
|
||||
<Icon icon='heroicons:x-mark' width={20} height={20} />
|
||||
</Button>
|
||||
|
||||
<div className='w-px border-none bg-base-content/10' />
|
||||
|
||||
<h4 className='text-sm font-medium text-base-content/50'>
|
||||
{modalAction === 'add' ? 'Add' : 'Edit'} Sales Order
|
||||
</h4>
|
||||
</div>
|
||||
<form
|
||||
className='w-full p-4 flex flex-col border-b border-base-content/10'
|
||||
ref={formRef}
|
||||
onSubmit={handleFormSubmit}
|
||||
>
|
||||
<h4 className='text-base font-medium text-base-content/50 font-roboto'>
|
||||
Informasi Order
|
||||
</h4>
|
||||
|
||||
<SelectInputRadio
|
||||
required
|
||||
label='Pelanggan'
|
||||
options={customerOptions}
|
||||
isLoading={isLoadingCustomerOptions}
|
||||
value={formik.values.customer}
|
||||
onChange={handleChangeCustomer}
|
||||
onInputChange={setInputCustomerValue}
|
||||
onMenuScrollToBottom={loadMoreCustomer}
|
||||
isError={
|
||||
formik.touched.customer_id &&
|
||||
Boolean(formik.errors.customer_id)
|
||||
}
|
||||
errorMessage={formik.errors.customer_id}
|
||||
isClearable
|
||||
placeholder='Pilih Pelanggan'
|
||||
isDisabled={
|
||||
modalAction === 'add_deliver' ||
|
||||
modalAction === 'edit_deliver' ||
|
||||
modalAction === 'edit'
|
||||
}
|
||||
/>
|
||||
<DateInput
|
||||
required
|
||||
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'
|
||||
readOnly={
|
||||
modalAction == 'add_deliver' ||
|
||||
modalAction == 'edit_deliver'
|
||||
}
|
||||
/>
|
||||
<SelectInputRadio
|
||||
required
|
||||
label='Sales'
|
||||
options={salesOptions}
|
||||
isLoading={isLoadingSalesOptions}
|
||||
value={formik.values.sales_person}
|
||||
onChange={handleChangeSalesPerson}
|
||||
onInputChange={setInputSalesValue}
|
||||
onMenuScrollToBottom={loadMoreSales}
|
||||
isError={
|
||||
formik.touched.sales_person_id &&
|
||||
Boolean(formik.errors.sales_person_id)
|
||||
}
|
||||
errorMessage={formik.errors.sales_person_id}
|
||||
isClearable
|
||||
placeholder='Pilih Sales'
|
||||
isDisabled={
|
||||
modalAction === 'add_deliver' ||
|
||||
modalAction === 'edit_deliver'
|
||||
}
|
||||
/>
|
||||
<DebouncedTextArea
|
||||
ref={textareaRef}
|
||||
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}
|
||||
disabled={
|
||||
modalAction === 'add_deliver' ||
|
||||
modalAction === 'edit_deliver'
|
||||
}
|
||||
/>
|
||||
<NumberInput
|
||||
name='total_price'
|
||||
label='Total Penjualan'
|
||||
value={grandTotal}
|
||||
disabled={
|
||||
grandTotal === 0 && formik.values.sales_order.length === 0
|
||||
}
|
||||
readOnly
|
||||
startAdornment={
|
||||
<span className='font-semibold py-1 text-xs'>Rp</span>
|
||||
}
|
||||
/>
|
||||
<AlertErrorList
|
||||
className={{
|
||||
alert: 'w-full mt-4',
|
||||
}}
|
||||
formErrorList={formErrorList}
|
||||
onClose={close}
|
||||
/>
|
||||
</form>
|
||||
|
||||
<div className='w-full p-4'>
|
||||
{step === 1 && (
|
||||
<Button
|
||||
type='button'
|
||||
onClick={nextButtonHandler}
|
||||
disabled={isNextButtonDisabled}
|
||||
className='w-full rounded-lg text-sm text-base-100'
|
||||
>
|
||||
Tambah Produk
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{step === 2 && (
|
||||
<div className='w-full min-h-full flex flex-col sm:w-[446px] border-l border-base-content/10'>
|
||||
<div className='w-full p-4 flex flex-row items-center justify-between gap-3 border-b border-base-content/10'>
|
||||
<div className='w-full flex flex-row items-stretch gap-3'>
|
||||
{memoSalesOrder.length > 0 && (
|
||||
<>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={() => {
|
||||
setStep(3);
|
||||
}}
|
||||
className='p-0 text-black hover:text-base-content'
|
||||
>
|
||||
<Icon
|
||||
icon='heroicons:chevron-left'
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
</Button>
|
||||
|
||||
<div className='w-px border-none bg-base-content/10' />
|
||||
</>
|
||||
)}
|
||||
|
||||
<h4 className='text-sm font-medium text-base-content/50'>
|
||||
{selectedMarketingProduct?.id ? 'Ubah' : 'Tambah'} Produk
|
||||
</h4>
|
||||
</div>
|
||||
<RequirePermission permissions='lti.marketing.sales_order.delete'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={deleteClickHandler}
|
||||
className='p-0 text-error hover:text-base-content'
|
||||
>
|
||||
<Icon icon='heroicons:trash' width={20} height={20} />
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
</div>
|
||||
<div className='flex flex-1 flex-col p-4'>
|
||||
<MemoizedSalesOrderProductForm
|
||||
onSubmitForm={handleAddSubmitSO}
|
||||
initialValues={selectedMarketingProduct ?? undefined}
|
||||
exisitingValues={memoSalesOrder}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{step === 3 && (
|
||||
<div className='w-full min-h-full flex flex-col sm:w-[446px] border-l border-base-content/10 relative'>
|
||||
<div className='w-full p-4 flex flex-row items-center justify-between gap-3 border-b border-base-content/10'>
|
||||
<h4 className='text-sm font-medium text-base-content/50'>
|
||||
Informasi Produk
|
||||
</h4>
|
||||
<RequirePermission permissions='lti.marketing.sales_order.delete'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={deleteClickHandler}
|
||||
className='p-0 text-error hover:text-base-content'
|
||||
>
|
||||
<Icon icon='heroicons:trash' width={20} height={20} />
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
</div>
|
||||
<div className='flex flex-1 flex-col'>
|
||||
{memoSalesOrder.length > 0 && (
|
||||
<div className='px-4 pt-4'>
|
||||
<MemoizedSalesOrderProductTable
|
||||
formType={(modalAction || 'add') as 'add' | 'edit'}
|
||||
data={memoSalesOrder}
|
||||
onDelete={handleDeleteSO}
|
||||
onEdit={handleEditSO}
|
||||
onAddProductClick={handleAddSOClick}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className='p-4 w-full'>
|
||||
<Button
|
||||
type='button'
|
||||
className='justify-center w-full p-3 rounded-lg text-center text-sm text-base-100'
|
||||
onClick={() => formRef.current?.requestSubmit()}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
<ConfirmationModal
|
||||
ref={successModal.ref}
|
||||
iconPosition='left'
|
||||
type='success'
|
||||
text={`${modalAction === 'add' ? 'Data Berhasil Ditambahkan' : 'Data Berhasil Diubah'}`}
|
||||
subtitleText={`${modalAction === 'add' ? 'Data sales order telah berhasil disimpan.' : 'Data sales order telah berhasil diubah.'}`}
|
||||
primaryButton={{
|
||||
text: 'Oke',
|
||||
color: 'primary',
|
||||
className: 'rounded-lg',
|
||||
onClick: (e) => {
|
||||
closeModalHandler();
|
||||
},
|
||||
}}
|
||||
>
|
||||
<MemoizedSalesOrderProductTable
|
||||
formType={'success'}
|
||||
data={memoSalesOrder}
|
||||
onDelete={handleDeleteSO}
|
||||
onEdit={handleEditSO}
|
||||
onAddProductClick={handleAddSOClick}
|
||||
/>
|
||||
</ConfirmationModal>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data penjualan ini?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isLoading,
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default SalesOrderFormModal;
|
||||
@@ -7,6 +7,12 @@ import {
|
||||
DeliveryOrderProductFormValues,
|
||||
DeliveryOrderProductSchema,
|
||||
} from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
|
||||
import {
|
||||
BaseDeliveryOrder,
|
||||
BaseSalesOrder,
|
||||
Marketing,
|
||||
} from '@/types/api/marketing/marketing';
|
||||
import { formatDate } from '@/lib/helper';
|
||||
|
||||
type MarketingSchemaType = {
|
||||
customer_id: number | undefined;
|
||||
@@ -64,7 +70,7 @@ export const DeliveryOrderSchema: Yup.ObjectSchema<DeliveryOrderSchemaType> =
|
||||
.required('Pengiriman wajib diisi!')
|
||||
.test(
|
||||
'at-least-one-valid-row',
|
||||
'Minimal ada satu baris pengiriman yang valid!',
|
||||
'Minimal harus ada satu baris pengiriman yang lengkap diisi!',
|
||||
function (items) {
|
||||
if (!items || items.length === 0) return false;
|
||||
|
||||
@@ -86,3 +92,124 @@ export const UpdateSalesOrderSchema = SalesOrderSchema;
|
||||
export type SalesOrderFormValues = Yup.InferType<typeof SalesOrderSchema>;
|
||||
|
||||
export type DeliveryOrderFormValues = Yup.InferType<typeof DeliveryOrderSchema>;
|
||||
|
||||
// ================ Helper Function ================
|
||||
const SalesProductToFieldValues = (
|
||||
product: BaseSalesOrder
|
||||
): SalesOrderProductFormValues => {
|
||||
return {
|
||||
id: product.id,
|
||||
vehicle_number: product.vehicle_number,
|
||||
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 DeliveryProductToFieldValues = (
|
||||
salesOrders: BaseSalesOrder[],
|
||||
delivery: BaseDeliveryOrder
|
||||
): DeliveryOrderProductFormValues[] => {
|
||||
const data = delivery.deliveries.map((item) => {
|
||||
const soId = salesOrders.find(
|
||||
(so) => so.product_warehouse.id === item.product_warehouse.id
|
||||
)?.id;
|
||||
return {
|
||||
id: soId,
|
||||
unit_price: item.unit_price,
|
||||
total_weight: item.total_weight,
|
||||
qty: item.qty,
|
||||
avg_weight: item.avg_weight,
|
||||
total_price: item.total_price,
|
||||
vehicle_number: item.vehicle_number,
|
||||
delivery_date: formatDate(delivery.delivery_date, 'yyyy-MM-DD'),
|
||||
do_number: delivery.do_number,
|
||||
marketing_product_id: soId,
|
||||
marketing_product: {
|
||||
id: soId,
|
||||
vehicle_number: item.vehicle_number,
|
||||
kandang_id: item.product_warehouse.warehouse.id,
|
||||
kandang: {
|
||||
value: item.product_warehouse.warehouse.id,
|
||||
label: item.product_warehouse.warehouse.name,
|
||||
},
|
||||
product_warehouse: {
|
||||
value: item.product_warehouse.id,
|
||||
label: item.product_warehouse.product.name,
|
||||
},
|
||||
product_warehouse_id: item.product_warehouse.id,
|
||||
unit_price: item.unit_price,
|
||||
total_weight: item.total_weight,
|
||||
qty: item.qty,
|
||||
avg_weight: item.avg_weight,
|
||||
total_price: item.total_price,
|
||||
},
|
||||
} as DeliveryOrderProductFormValues;
|
||||
});
|
||||
return data;
|
||||
};
|
||||
export const mergeSOwithDO = (
|
||||
salesOrders: SalesOrderProductFormValues[],
|
||||
deliveryOrders: DeliveryOrderProductFormValues[],
|
||||
autofill?: boolean
|
||||
): DeliveryOrderProductFormValues[] => {
|
||||
return salesOrders.map((so) => {
|
||||
const delivery = deliveryOrders.find(
|
||||
(d) => d?.marketing_product_id === so.id
|
||||
);
|
||||
|
||||
return {
|
||||
...so, // nilai dasar dari sales order
|
||||
marketing_product_id: so.id,
|
||||
delivery_date: delivery?.delivery_date || undefined,
|
||||
do_number: delivery?.do_number || undefined,
|
||||
vehicle_number: delivery?.vehicle_number || so.vehicle_number,
|
||||
unit_price: autofill ? so.unit_price : delivery?.unit_price,
|
||||
total_weight: autofill ? so.total_weight : delivery?.total_weight,
|
||||
qty: autofill ? so.qty : delivery?.qty,
|
||||
avg_weight: autofill ? so.avg_weight : delivery?.avg_weight,
|
||||
total_price: autofill ? so.total_price : delivery?.total_price,
|
||||
marketing_product: so, // jika ada, override
|
||||
} as DeliveryOrderProductFormValues;
|
||||
});
|
||||
};
|
||||
|
||||
export const getFilledMarketingFormInitialValues = (
|
||||
marketing: Marketing
|
||||
): SalesOrderFormValues & DeliveryOrderFormValues => {
|
||||
return {
|
||||
customer_id: marketing.customer.id,
|
||||
sales_person_id: marketing.sales_person.id,
|
||||
sales_person: {
|
||||
value: marketing.sales_person.id,
|
||||
label: marketing.sales_person.name,
|
||||
},
|
||||
customer: {
|
||||
value: marketing.customer.id,
|
||||
label: marketing.customer.name,
|
||||
},
|
||||
so_date: formatDate(marketing.so_date, 'yyyy-MM-DD'),
|
||||
notes: marketing.notes,
|
||||
sales_order: marketing.sales_order.map((so) =>
|
||||
SalesProductToFieldValues(so)
|
||||
),
|
||||
delivery_order: mergeSOwithDO(
|
||||
marketing.sales_order?.map(SalesProductToFieldValues) ?? [],
|
||||
marketing.delivery_order?.flatMap((delivery) =>
|
||||
DeliveryProductToFieldValues(marketing.sales_order, delivery)
|
||||
) ?? [],
|
||||
marketing.latest_approval.step_number > 1
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -41,7 +41,6 @@ import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import DebouncedTextArea from '@/components/input/DebouncedTextArea';
|
||||
import SalesOrderProductTable from '@/components/pages/marketing/form/table-view/SalesOrderProductTable';
|
||||
import SalesOrderProductForm from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProductForm';
|
||||
import DeliveryOrderProductTable from '@/components/pages/marketing/form/table-view/DeliveryOrderProductTable';
|
||||
import DeliveryOrderProductForm from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct';
|
||||
@@ -53,7 +52,6 @@ import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||
import { CreatedUser } from '@/types/api/api-general';
|
||||
import { UserApi } from '@/services/api/user';
|
||||
|
||||
const MemoizedSalesOrderProductTable = memo(SalesOrderProductTable);
|
||||
const MemoizedSalesOrderProductForm = memo(SalesOrderProductForm);
|
||||
const MemoizedDeliveryOrderProductTable = memo(DeliveryOrderProductTable);
|
||||
const MemoizedDeliveryOrderProductForm = memo(DeliveryOrderProductForm);
|
||||
@@ -134,7 +132,8 @@ export const DeliveryProductToFieldValues = (
|
||||
};
|
||||
export const mergeSOwithDO = (
|
||||
salesOrders: SalesOrderProductFormValues[],
|
||||
deliveryOrders: DeliveryOrderProductFormValues[]
|
||||
deliveryOrders: DeliveryOrderProductFormValues[],
|
||||
autofill?: boolean
|
||||
): DeliveryOrderProductFormValues[] => {
|
||||
return salesOrders.map((so) => {
|
||||
const delivery = deliveryOrders.find(
|
||||
@@ -147,11 +146,11 @@ export const mergeSOwithDO = (
|
||||
delivery_date: delivery?.delivery_date || undefined,
|
||||
do_number: delivery?.do_number || undefined,
|
||||
vehicle_number: delivery?.vehicle_number || so.vehicle_number,
|
||||
unit_price: delivery?.unit_price,
|
||||
total_weight: delivery?.total_weight,
|
||||
qty: delivery?.qty,
|
||||
avg_weight: delivery?.avg_weight,
|
||||
total_price: delivery?.total_price,
|
||||
unit_price: autofill ? so.unit_price : delivery?.unit_price,
|
||||
total_weight: autofill ? so.total_weight : delivery?.total_weight,
|
||||
qty: autofill ? so.qty : delivery?.qty,
|
||||
avg_weight: autofill ? so.avg_weight : delivery?.avg_weight,
|
||||
total_price: autofill ? so.total_price : delivery?.total_price,
|
||||
marketing_product: so, // jika ada, override
|
||||
} as DeliveryOrderProductFormValues;
|
||||
});
|
||||
@@ -677,7 +676,7 @@ const MarketingForm = ({
|
||||
}}
|
||||
variant='bordered'
|
||||
>
|
||||
<MemoizedSalesOrderProductTable
|
||||
{/* <MemoizedSalesOrderProductTable
|
||||
formType={formType}
|
||||
data={memoSalesOrder}
|
||||
rowSelection={rowSOSelection}
|
||||
@@ -687,7 +686,7 @@ const MarketingForm = ({
|
||||
onEdit={handleEditSO}
|
||||
onBulkDelete={handleBulkDeleteSO}
|
||||
onAddProductClick={handleAddSOClick}
|
||||
/>
|
||||
/> */}
|
||||
</Card>
|
||||
|
||||
{/* Input Table Repeater Delivery Order */}
|
||||
@@ -701,6 +700,7 @@ const MarketingForm = ({
|
||||
}}
|
||||
>
|
||||
<MemoizedDeliveryOrderProductTable
|
||||
marketing={initialValues}
|
||||
formType={formType}
|
||||
data={deliveryOrderValues}
|
||||
onEdit={handleEditDO}
|
||||
|
||||
+42
-45
@@ -10,9 +10,7 @@ import NumberInput from '@/components/input/NumberInput';
|
||||
import PatternInput from '@/components/input/PatternInput';
|
||||
import { formatVechicleNumber } from '@/lib/helper';
|
||||
import DateInput from '@/components/input/DateInput';
|
||||
import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
||||
import { BaseSalesOrder } from '@/types/api/marketing/marketing';
|
||||
import Badge from '@/components/Badge';
|
||||
import { SalesProductToFieldValues } from '@/components/pages/marketing/form/MarketingForm';
|
||||
import * as Yup from 'yup';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
@@ -20,6 +18,9 @@ import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||
import useSWR from 'swr';
|
||||
import { ProductApi } from '@/services/api/master-data';
|
||||
import StatusBadge from '@/components/helper/StatusBadge';
|
||||
import SelectInputRadio from '@/components/input/SelectInputRadio';
|
||||
import { OptionType } from '@/components/input/SelectInput';
|
||||
|
||||
const roundWeight = (value: number) => Number(value.toFixed(2));
|
||||
const roundPrice = (value: number) => Math.round(value);
|
||||
@@ -247,7 +248,7 @@ const DeliveryOrderProductForm = ({
|
||||
return (
|
||||
<>
|
||||
<form
|
||||
className='size-full'
|
||||
className='size-full flex flex-col relative gap-1.5'
|
||||
onSubmit={handleFormSubmit}
|
||||
onReset={handleResetForm}
|
||||
>
|
||||
@@ -256,13 +257,27 @@ const DeliveryOrderProductForm = ({
|
||||
<Alert color='error'>{formikErrorMessage}</Alert>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className='grid sm:grid-cols-3 gap-4'>
|
||||
<SelectInput
|
||||
<DateInput
|
||||
name='delivery_date'
|
||||
label='Tanggal'
|
||||
value={formik.values.delivery_date ?? undefined}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
isError={
|
||||
formik.touched.delivery_date && Boolean(formik.errors.delivery_date)
|
||||
}
|
||||
errorMessage={formik.errors.delivery_date}
|
||||
placeholder='Pilih Tanggal'
|
||||
className={{
|
||||
inputWrapper: 'bg-white',
|
||||
}}
|
||||
required
|
||||
/>
|
||||
<SelectInputRadio
|
||||
options={options}
|
||||
label='Produk'
|
||||
placeholder='Pilih Produk'
|
||||
isDisabled={formState == 'edit'}
|
||||
readOnly={formState == 'edit'}
|
||||
value={
|
||||
selectedProduct
|
||||
? ({
|
||||
@@ -277,9 +292,7 @@ const DeliveryOrderProductForm = ({
|
||||
const selected = value as OptionType;
|
||||
setSelectedProduct(selected);
|
||||
|
||||
const so = salesOrders?.find(
|
||||
(item) => item.id === selected?.value
|
||||
);
|
||||
const so = salesOrders?.find((item) => item.id === selected?.value);
|
||||
if (!so) {
|
||||
formik.setValues({
|
||||
...formik.values,
|
||||
@@ -309,18 +322,17 @@ const DeliveryOrderProductForm = ({
|
||||
}}
|
||||
startAdornment={
|
||||
selectedProduct && (
|
||||
<Badge
|
||||
variant='soft'
|
||||
color='success'
|
||||
size='sm'
|
||||
className={{ badge: 'whitespace-nowrap font-semibold' }}
|
||||
>
|
||||
{
|
||||
<StatusBadge
|
||||
text={
|
||||
exisitingValues?.find(
|
||||
(item) => item.id === selectedProduct?.value
|
||||
)?.marketing_product?.kandang?.label
|
||||
)?.marketing_product?.kandang?.label ?? ''
|
||||
}
|
||||
</Badge>
|
||||
color='success'
|
||||
className={{
|
||||
badge: 'whitespace-nowrap w-fit font-semibold',
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
isClearable
|
||||
@@ -328,23 +340,6 @@ const DeliveryOrderProductForm = ({
|
||||
errorMessage={formik.errors.marketing_product_id}
|
||||
required
|
||||
/>
|
||||
<DateInput
|
||||
name='delivery_date'
|
||||
label='Tanggal'
|
||||
value={formik.values.delivery_date ?? undefined}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
isError={
|
||||
formik.touched.delivery_date &&
|
||||
Boolean(formik.errors.delivery_date)
|
||||
}
|
||||
errorMessage={formik.errors.delivery_date}
|
||||
placeholder='Pilih Tanggal'
|
||||
className={{
|
||||
inputWrapper: 'bg-white',
|
||||
}}
|
||||
required
|
||||
/>
|
||||
|
||||
<PatternInput
|
||||
name='vehicle_number'
|
||||
@@ -361,9 +356,6 @@ const DeliveryOrderProductForm = ({
|
||||
isError={Boolean(formik.errors.vehicle_number)}
|
||||
errorMessage={formik.errors.vehicle_number}
|
||||
/>
|
||||
</div>
|
||||
<div className='divider my-6'></div>
|
||||
<div className='grid sm:grid-cols-3 gap-4'>
|
||||
<NumberInput
|
||||
required
|
||||
label='Kuantitas'
|
||||
@@ -456,18 +448,23 @@ const DeliveryOrderProductForm = ({
|
||||
errorMessage={formik.errors.total_price}
|
||||
placeholder='Masukan Total Penjualan'
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||
<AlertErrorList
|
||||
className={{
|
||||
alert: 'w-full my-4',
|
||||
}}
|
||||
formErrorList={formErrorList}
|
||||
onClose={close}
|
||||
/>
|
||||
|
||||
<div className='flex flex-row justify-end gap-3 mt-4'>
|
||||
<Button type='reset' color='warning'>
|
||||
Reset
|
||||
</Button>
|
||||
<div className='h-18' />
|
||||
|
||||
<div className='absolute sm:w-full bottom-0 right-0'>
|
||||
<Button
|
||||
type='submit'
|
||||
isLoading={formik.isSubmitting}
|
||||
disabled={formik.isSubmitting}
|
||||
className='w-full p-3 rounded-lg text-base-100 text-sm font-semibold'
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
|
||||
+11
-23
@@ -6,27 +6,20 @@ import {
|
||||
SalesOrderProductSchema,
|
||||
} from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
|
||||
import { RefObject, useMemo, useState } from 'react';
|
||||
import SelectInput, {
|
||||
OptionType,
|
||||
useSelect,
|
||||
} from '@/components/input/SelectInput';
|
||||
import { OptionType, useSelect } from '@/components/input/SelectInput';
|
||||
import { Kandang } from '@/types/api/master-data/kandang';
|
||||
import { ProductApi, UomApi, WarehouseApi } from '@/services/api/master-data';
|
||||
import { WarehouseApi } 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';
|
||||
import {
|
||||
formatCurrency,
|
||||
formatNumber,
|
||||
formatVechicleNumber,
|
||||
} from '@/lib/helper';
|
||||
import { formatNumber, formatVechicleNumber } from '@/lib/helper';
|
||||
import PatternInput from '@/components/input/PatternInput';
|
||||
import Alert from '@/components/Alert';
|
||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||
import useSWR from 'swr';
|
||||
import SelectInputRadio from '@/components/input/SelectInputRadio';
|
||||
|
||||
const roundWeight = (value: number) => Number(value.toFixed(2));
|
||||
const roundPrice = (value: number) => Math.round(value);
|
||||
@@ -282,7 +275,7 @@ const SalesOrderProductForm = ({
|
||||
return (
|
||||
<>
|
||||
<form
|
||||
className='size-full'
|
||||
className='size-full flex flex-col gap-1.5 relative'
|
||||
onSubmit={handleFormSubmit}
|
||||
onReset={handleResetForm}
|
||||
>
|
||||
@@ -293,7 +286,6 @@ const SalesOrderProductForm = ({
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
<div className='grid sm:grid-cols-3 gap-4 z-200'>
|
||||
<PatternInput
|
||||
name='vehicle_number'
|
||||
label='No. Polisi'
|
||||
@@ -312,7 +304,7 @@ const SalesOrderProductForm = ({
|
||||
}
|
||||
errorMessage={formik.errors.vehicle_number}
|
||||
/>
|
||||
<SelectInput
|
||||
<SelectInputRadio
|
||||
required
|
||||
label='Kandang'
|
||||
options={kandangSourceOptions}
|
||||
@@ -328,7 +320,7 @@ const SalesOrderProductForm = ({
|
||||
errorMessage={formik.errors.kandang_id}
|
||||
placeholder='Pilih Kandang'
|
||||
/>
|
||||
<SelectInput
|
||||
<SelectInputRadio
|
||||
required
|
||||
label='Produk'
|
||||
options={productOptionsFiltered}
|
||||
@@ -352,9 +344,6 @@ const SalesOrderProductForm = ({
|
||||
}
|
||||
errorMessage={formik.errors.product_warehouse_id}
|
||||
/>
|
||||
</div>
|
||||
<div className='divider my-6'></div>
|
||||
<div className='grid sm:grid-cols-3 gap-4 z-200'>
|
||||
<NumberInput
|
||||
required
|
||||
label='Kuantitas'
|
||||
@@ -450,20 +439,19 @@ const SalesOrderProductForm = ({
|
||||
errorMessage={formik.errors.total_price}
|
||||
placeholder='Masukan Total Penjualan'
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='mt-4'>
|
||||
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||
</div>
|
||||
|
||||
<div className='flex flex-row justify-end gap-3 mt-4'>
|
||||
<Button type='reset' color='warning' onClick={handleResetForm}>
|
||||
Reset
|
||||
</Button>
|
||||
<div className='h-18' />
|
||||
|
||||
<div className='absolute w-full bottom-0 right-0'>
|
||||
<Button
|
||||
type='submit'
|
||||
isLoading={formik.isSubmitting}
|
||||
disabled={formik.isSubmitting}
|
||||
className='w-full p-3 rounded-lg text-base-100'
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
|
||||
@@ -1,21 +1,27 @@
|
||||
import Table from '@/components/Table';
|
||||
import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
|
||||
import Button from '@/components/Button';
|
||||
import { Icon } from '@iconify/react';
|
||||
import * as TanStack from '@tanstack/react-table';
|
||||
import { useMemo, useRef } from 'react';
|
||||
import {
|
||||
cn,
|
||||
formatCurrency,
|
||||
formatDate,
|
||||
formatNumber,
|
||||
formatVechicleNumber,
|
||||
} from '@/lib/helper';
|
||||
import { useRef } from 'react';
|
||||
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
|
||||
import DeliveryOrderExport from '@/components/pages/marketing/pdf/DeliveryOrderExport';
|
||||
import { Marketing } from '@/types/api/marketing/marketing';
|
||||
|
||||
type DeliveryOrderProductTableProps = {
|
||||
data: DeliveryOrderProductFormValues[];
|
||||
formType?: 'add' | 'edit' | 'add_deliver' | 'edit_deliver';
|
||||
onEdit: (id: number) => void;
|
||||
formType?:
|
||||
| 'add'
|
||||
| 'edit'
|
||||
| 'add_deliver'
|
||||
| 'edit_deliver'
|
||||
| 'add_delivery'
|
||||
| 'edit_delivery'
|
||||
| 'detail'
|
||||
| 'rejected'
|
||||
| 'pending'
|
||||
| string
|
||||
| null;
|
||||
marketing?: Marketing;
|
||||
onEdit: (id: number, values: DeliveryOrderProductFormValues) => void;
|
||||
onDelete: (id: number) => void;
|
||||
onAddProductClick: () => void;
|
||||
};
|
||||
@@ -26,201 +32,168 @@ const DeliveryOrderProductTable = ({
|
||||
onEdit,
|
||||
onDelete,
|
||||
onAddProductClick,
|
||||
marketing,
|
||||
}: DeliveryOrderProductTableProps) => {
|
||||
const onEditRef = useRef(onEdit);
|
||||
onEditRef.current = onEdit;
|
||||
const onDeleteRef = useRef(onDelete);
|
||||
onDeleteRef.current = onDelete;
|
||||
|
||||
const canAddData = data.filter((item) => !Boolean(item.qty));
|
||||
|
||||
const columns = useMemo(() => {
|
||||
const cols = [
|
||||
{
|
||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.do_number,
|
||||
header: 'No. Pengiriman',
|
||||
cell: (
|
||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
||||
) => (
|
||||
<>
|
||||
{props.row.original.do_number ? props.row.original.do_number : '-'}
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.vehicle_number,
|
||||
header: 'No. Polisi',
|
||||
cell: (
|
||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
||||
) =>
|
||||
props.row.original.vehicle_number
|
||||
? formatVechicleNumber(props.row.original.vehicle_number as string)
|
||||
: '-',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: DeliveryOrderProductFormValues) =>
|
||||
row.marketing_product?.kandang?.label,
|
||||
header: 'Kandang',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: DeliveryOrderProductFormValues) =>
|
||||
row.marketing_product?.product_warehouse?.label,
|
||||
header: 'Produk',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: DeliveryOrderProductFormValues) =>
|
||||
row.delivery_date
|
||||
? formatDate(row.delivery_date as string, 'DD MMM YYYY')
|
||||
: '-',
|
||||
header: 'Tanggal Delivery',
|
||||
cell: (
|
||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
||||
) =>
|
||||
props.row.original.delivery_date
|
||||
? formatDate(
|
||||
props.row.original.delivery_date as string,
|
||||
'DD MMM YYYY'
|
||||
)
|
||||
: '-',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.unit_price,
|
||||
header: 'Harga Satuan (Rp)',
|
||||
cell: (
|
||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
||||
) =>
|
||||
props.row.original.unit_price
|
||||
? formatCurrency(
|
||||
parseFloat(props.row.original.unit_price as string)
|
||||
)
|
||||
: '-',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.total_weight,
|
||||
header: 'Total Bobot (Kg)',
|
||||
cell: (
|
||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
||||
) =>
|
||||
props.row.original.total_weight
|
||||
? formatNumber(
|
||||
parseFloat(props.row.original.total_weight as string)
|
||||
)
|
||||
: '-',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.qty,
|
||||
header: 'Kuantitas',
|
||||
cell: (
|
||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
||||
) =>
|
||||
props.row.original.qty
|
||||
? formatNumber(parseFloat(props.row.original.qty as string))
|
||||
: '-',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.avg_weight,
|
||||
header: 'Avg. Bobot (Kg)',
|
||||
cell: (
|
||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
||||
) =>
|
||||
props.row.original.avg_weight
|
||||
? formatNumber(parseFloat(props.row.original.avg_weight as string))
|
||||
: '-',
|
||||
},
|
||||
{
|
||||
accessorFn: (row: DeliveryOrderProductFormValues) => row.total_price,
|
||||
header: 'Total Penjualan (Rp)',
|
||||
cell: (
|
||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
||||
) =>
|
||||
props.row.original.total_price
|
||||
? formatCurrency(
|
||||
parseFloat(props.row.original.total_price as string)
|
||||
)
|
||||
: '-',
|
||||
},
|
||||
|
||||
{
|
||||
header: 'Aksi',
|
||||
cell: (
|
||||
props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
|
||||
) => (
|
||||
<div className='flex flex-row gap-1 items-center justify-end h-full mt-2'>
|
||||
<>
|
||||
{props.row.original.qty && (
|
||||
<>
|
||||
<Button
|
||||
color='warning'
|
||||
className='px-2 py-1 text-sm'
|
||||
onClick={() =>
|
||||
onEditRef.current(props.row.original.id as number)
|
||||
}
|
||||
type='button'
|
||||
>
|
||||
<Icon icon='mdi:edit' width={16} height={16} /> Edit
|
||||
</Button>
|
||||
<Button
|
||||
color='error'
|
||||
className='px-2 py-1 text-sm'
|
||||
onClick={() =>
|
||||
onDeleteRef.current(props.row.original.id as number)
|
||||
}
|
||||
type='button'
|
||||
disabled={!!props.row.original.do_number}
|
||||
>
|
||||
<Icon icon='mdi:delete' width={16} height={16} /> Hapus
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{!props.row.original.qty && '-'}
|
||||
</>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
if (formType == 'add_deliver') {
|
||||
return cols.filter((col) => col.header != 'No. Pengiriman');
|
||||
}
|
||||
return cols;
|
||||
}, [formType, onEditRef]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Table<DeliveryOrderProductFormValues>
|
||||
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',
|
||||
paginationClassName: 'hidden',
|
||||
}}
|
||||
emptyContent={
|
||||
<div className='size-full flex flex-col relative overflow-x-hidden gap-3'>
|
||||
{data.map((item) => {
|
||||
const doItem = marketing?.delivery_order?.find(
|
||||
(doItem) => doItem.do_number === item.do_number
|
||||
);
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full h-16 flex flex-col justify-center items-center gap-2'
|
||||
)}
|
||||
className='rounded-lg border border-tools-table-outline border-base-content/5'
|
||||
key={`table-${item.id}`}
|
||||
>
|
||||
<span className='text-gray-500'>Belum ada data pengiriman</span>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<div className='flex flex-row gap-3 mt-3'>
|
||||
<table
|
||||
style={{
|
||||
borderRadius: '0.5rem',
|
||||
}}
|
||||
className='border-none w-full'
|
||||
>
|
||||
<tbody className='w-full'>
|
||||
<tr className='border-b border-tools-table-outline border-base-content/5'>
|
||||
<th className='w-1/3 text-start not-first:font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||
Label
|
||||
</th>
|
||||
<th className='text-start font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||
<div className='flex w-full flex-row gap-1 items-center justify-between h-full mt-2'>
|
||||
<div>Value</div>
|
||||
{(formType === 'add_delivery' ||
|
||||
formType === 'edit_delivery' ||
|
||||
formType === 'detail') && (
|
||||
<div className='flex flex-row gap-1.5 items-center'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
className='justify-start w-fit py-1 text-sm'
|
||||
onClick={onAddProductClick}
|
||||
disabled={!canAddData}
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={() => {
|
||||
onEditRef.current(item.id as number, item);
|
||||
}}
|
||||
className='p-0 hover:text-base-content'
|
||||
>
|
||||
<Icon icon='mdi:plus' width={16} height={16} />
|
||||
Tambah Pengiriman
|
||||
<Icon
|
||||
icon='heroicons:pencil'
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
</Button>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={() => {
|
||||
onDeleteRef.current(item.id as number);
|
||||
}}
|
||||
className='p-0 text-error hover:text-base-content'
|
||||
>
|
||||
<Icon
|
||||
icon='heroicons:trash'
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</th>
|
||||
</tr>
|
||||
<>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Tanggal Pengiriman</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{item.delivery_date ? (
|
||||
formatDate(item.delivery_date, 'DD MMM YYYY')
|
||||
) : (
|
||||
<span className='text-error'>Belum diisi</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
{item.do_number && (
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>No. Pengiriman</td>
|
||||
<td className='text-sm px-4 py-3'>{item.do_number}</td>
|
||||
</tr>
|
||||
)}
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>No. Polisi</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{item.vehicle_number}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Gudang</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{item.marketing_product?.product_warehouse?.label}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Produk</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{item.marketing_product?.product_warehouse?.label}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Qty</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{item.qty
|
||||
? `${formatNumber(parseFloat(item.qty as string))} ${item.marketing_product?.uom ?? ''}`
|
||||
: '-'}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Avg Bobot</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{item.avg_weight
|
||||
? formatNumber(
|
||||
parseFloat(item.avg_weight as string)
|
||||
) + ' Kg'
|
||||
: '-'}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Total Bobot</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{formatNumber(parseFloat(item.total_weight as string))}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Total Harga Satuan</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{formatCurrency(parseFloat(item.unit_price as string))}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Total Penjualan</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{formatCurrency(parseFloat(item.total_price as string))}
|
||||
</td>
|
||||
</tr>
|
||||
{doItem && (
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
Dokumen Pengiriman
|
||||
</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
<DeliveryOrderExport
|
||||
data={marketing}
|
||||
deliveryOrder={doItem}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,42 +1,30 @@
|
||||
'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,
|
||||
formatVechicleNumber,
|
||||
} from '@/lib/helper';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
import { useMemo, useRef } from 'react';
|
||||
import * as TanStack from '@tanstack/react-table';
|
||||
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||
|
||||
type SalesOrderProductTableProps = {
|
||||
data: SalesOrderProductFormValues[];
|
||||
formType: 'add' | 'edit' | 'add_deliver' | 'edit_deliver';
|
||||
rowSelection: Record<string, boolean>;
|
||||
setRowSelection: React.Dispatch<
|
||||
React.SetStateAction<Record<string, boolean>>
|
||||
>;
|
||||
selectedRowIds: number[];
|
||||
formType: 'add' | 'edit' | 'add_deliver' | 'edit_deliver' | 'success';
|
||||
onDelete: (id: number) => void;
|
||||
onEdit: (id: number) => void;
|
||||
onBulkDelete: () => void;
|
||||
onAddProductClick: () => void;
|
||||
};
|
||||
|
||||
const SalesOrderProductTable = ({
|
||||
data,
|
||||
formType,
|
||||
rowSelection,
|
||||
setRowSelection,
|
||||
selectedRowIds,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onBulkDelete,
|
||||
onAddProductClick,
|
||||
}: SalesOrderProductTableProps) => {
|
||||
const onDeleteRef = useRef(onDelete);
|
||||
@@ -156,67 +144,135 @@ const SalesOrderProductTable = ({
|
||||
|
||||
return (
|
||||
<>
|
||||
<Table<SalesOrderProductFormValues>
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
data={data}
|
||||
columns={
|
||||
formType == 'add_deliver' || formType == 'edit_deliver'
|
||||
? columns.filter(
|
||||
(col) => col.header != 'Aksi' && col.id != 'select'
|
||||
)
|
||||
: 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='size-full flex flex-col relative overflow-x-hidden gap-3'>
|
||||
{data.map((item) => (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full h-16 flex flex-col justify-center items-center gap-2'
|
||||
)}
|
||||
className='rounded-lg border border-tools-table-outline border-base-content/5'
|
||||
key={`table-${item.id}`}
|
||||
>
|
||||
<span className='text-gray-500'>Belum ada data penjualan</span>
|
||||
</div>
|
||||
}
|
||||
<table
|
||||
style={{
|
||||
borderRadius: '0.5rem',
|
||||
}}
|
||||
className='border-none w-full'
|
||||
>
|
||||
<tbody className='w-full'>
|
||||
<tr className='border-b border-tools-table-outline border-base-content/5'>
|
||||
<th className='w-1/3 text-start not-first:font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||
Label
|
||||
</th>
|
||||
<th className='text-start font-medium text-base-content/50 text-sm px-4 py-3'>
|
||||
<div className='flex w-full flex-row gap-1 items-center justify-between h-full mt-2'>
|
||||
<div>Value</div>
|
||||
{formType !== 'success' && (
|
||||
<div className='flex flex-row gap-1.5 items-center'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={() => {
|
||||
onEditRef.current(item.id as number);
|
||||
}}
|
||||
className='p-0 hover:text-base-content'
|
||||
>
|
||||
<Icon
|
||||
icon='heroicons:pencil'
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
{formType != 'add_deliver' && formType != 'edit_deliver' && (
|
||||
<div className='flex flex-row gap-3 mt-3'>
|
||||
</Button>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={() => {
|
||||
onDeleteRef.current(item.id as number);
|
||||
}}
|
||||
className='p-0 text-error hover:text-base-content'
|
||||
>
|
||||
<Icon
|
||||
icon='heroicons:trash'
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</th>
|
||||
</tr>
|
||||
<>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>No. Polisi</td>
|
||||
<td className='text-sm px-4 py-3'>{item.vehicle_number}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Gudang</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{item.product_warehouse?.label}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Produk</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{item.product_warehouse?.label}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Total Bobot</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{item.total_weight
|
||||
? formatNumber(
|
||||
parseFloat(item.total_weight as string)
|
||||
) + ' Kg'
|
||||
: '-'}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Avg Bobot</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{item.avg_weight
|
||||
? formatNumber(parseFloat(item.avg_weight as string)) +
|
||||
' Kg'
|
||||
: '-'}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Qty</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{`${formatNumber(parseFloat(item.qty as string))} ${item.uom || ''}`}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Total Harga Satuan</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{formatCurrency(parseFloat(item.unit_price as string))}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='text-sm px-4 py-3'>Total Penjualan</td>
|
||||
<td className='text-sm px-4 py-3'>
|
||||
{formatCurrency(parseFloat(item.total_price as string))}
|
||||
</td>
|
||||
</tr>
|
||||
</>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
))}
|
||||
{formType != 'add_deliver' &&
|
||||
formType != 'edit_deliver' &&
|
||||
formType != 'success' && (
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
className='justify-start w-fit py-1 text-sm'
|
||||
className='justify-center p-3 w-full rounded-lg text-center text-sm mt-3'
|
||||
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={onBulkDelete}
|
||||
>
|
||||
<Icon icon='mdi:trash' width={16} height={16} />
|
||||
Hapus
|
||||
{selectedRowIds.length > 0
|
||||
? ` (${selectedRowIds.length})`
|
||||
: ''}{' '}
|
||||
Produk
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -4,10 +4,9 @@ import { Icon } from '@iconify/react';
|
||||
import { Document, Image, Page, pdf, Text, View } from '@react-pdf/renderer';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { formatDate, formatNumber, formatVechicleNumber } from '@/lib/helper';
|
||||
import { format } from 'path';
|
||||
import { date } from 'yup';
|
||||
import pdfStyles from '@/components/pages/marketing/pdf/styles/MarketingPDFStyles';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
interface DeliveryOrderExportProps {
|
||||
data?: Marketing;
|
||||
@@ -21,6 +20,9 @@ const DeliveryOrderExport = ({
|
||||
}: DeliveryOrderExportProps) => {
|
||||
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
|
||||
const salesData = data;
|
||||
const searchParams = useSearchParams();
|
||||
const action = searchParams.get('action');
|
||||
const id = searchParams.get('id');
|
||||
|
||||
const handleDownloadPDF = async () => {
|
||||
if (!salesData) {
|
||||
@@ -32,37 +34,47 @@ const DeliveryOrderExport = ({
|
||||
const blob = await pdf(
|
||||
<PDFDocument data={salesData} deliveryOrder={deliveryOrder} />
|
||||
).toBlob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.style.display = 'none';
|
||||
link.href = url;
|
||||
link.download = `${deliveryOrder?.do_number || 'delivery-order'}.pdf`;
|
||||
link.setAttribute('target', '_blank');
|
||||
link.setAttribute('rel', 'noopener noreferrer');
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
|
||||
// Delay cleanup to ensure download starts
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
window.URL.revokeObjectURL(url);
|
||||
}, 150);
|
||||
} catch (error) {
|
||||
toast.error('Failed to generate PDF. Please try again.');
|
||||
} finally {
|
||||
setIsGeneratingPDF(false);
|
||||
window.location.href = `/marketing?action=${action}&id=${id}`;
|
||||
}
|
||||
};
|
||||
|
||||
if (!salesData) {
|
||||
return (
|
||||
<div className='flex items-center justify-center min-h-screen'>
|
||||
<div className='flex items-start justify-start'>
|
||||
<div className='text-gray-500'>No sales order data available</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return salesData?.so_number && salesData.so_number !== 'Belum dibuat' ? (
|
||||
return deliveryOrder?.do_number ? (
|
||||
<Button
|
||||
color='primary'
|
||||
className='w-fit min-w-32 flex items-center justify-start gap-1 px-2 py-1 text-sm font-mono'
|
||||
variant='outline'
|
||||
color='none'
|
||||
className='w-fit text-sm px-3 py-2.5 rounded-lg border-base-content/10 text-base-content/50'
|
||||
onClick={handleDownloadPDF}
|
||||
isLoading={isGeneratingPDF}
|
||||
type='button'
|
||||
>
|
||||
<Icon icon='material-symbols:file-open-outline' width={16} height={16} />
|
||||
<Icon icon='heroicons:document-text' width={20} height={20} />
|
||||
{deliveryOrder.do_number}
|
||||
</Button>
|
||||
) : null;
|
||||
@@ -87,11 +99,6 @@ const PDFDocument = ({
|
||||
<Page size='A4' style={pdfStyles.page}>
|
||||
{/* Header Section */}
|
||||
<View style={pdfStyles.header}>
|
||||
<Image
|
||||
src={'https://placehold.co/120x30/png'}
|
||||
style={pdfStyles.logo}
|
||||
id={'mbu-logo'}
|
||||
/>
|
||||
<Text style={pdfStyles.companyInfo}>PT LUMBUNG TELUR INDONESIA</Text>
|
||||
<Text style={pdfStyles.address}>
|
||||
SOHO Building Lt.3 (Paris Van Java), Jalan Karang Tinggal, Kel.
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useMemo, useState } from 'react';
|
||||
import { formatDate, formatNumber } from '@/lib/helper';
|
||||
import pdfStyles from '@/components/pages/marketing/pdf/styles/MarketingPDFStyles';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
|
||||
interface SalesOrderExportProps {
|
||||
data?: Marketing;
|
||||
@@ -15,6 +16,9 @@ interface SalesOrderExportProps {
|
||||
const SalesOrderExport = ({ data }: SalesOrderExportProps) => {
|
||||
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
|
||||
const salesData = data;
|
||||
const searchParams = useSearchParams();
|
||||
const action = searchParams.get('action');
|
||||
const id = searchParams.get('id');
|
||||
|
||||
const handleDownloadPDF = async () => {
|
||||
if (!salesData) {
|
||||
@@ -24,24 +28,32 @@ const SalesOrderExport = ({ data }: SalesOrderExportProps) => {
|
||||
setIsGeneratingPDF(true);
|
||||
try {
|
||||
const blob = await pdf(<PDFDocument data={salesData} />).toBlob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.style.display = 'none';
|
||||
link.href = url;
|
||||
link.download = `${salesData?.so_number || 'sales-order'}.pdf`;
|
||||
link.setAttribute('target', '_blank');
|
||||
link.setAttribute('rel', 'noopener noreferrer');
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
|
||||
// Delay cleanup to ensure download starts
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
window.URL.revokeObjectURL(url);
|
||||
}, 150);
|
||||
} catch (error) {
|
||||
toast.error('Failed to generate PDF. Please try again.');
|
||||
} finally {
|
||||
setIsGeneratingPDF(false);
|
||||
window.location.href = `/marketing?action=${action}&id=${id}`;
|
||||
}
|
||||
};
|
||||
|
||||
if (!salesData) {
|
||||
return (
|
||||
<div className='flex items-center justify-center min-h-screen'>
|
||||
<div className='flex items-start justify-start'>
|
||||
<div className='text-gray-500'>No sales order data available</div>
|
||||
</div>
|
||||
);
|
||||
@@ -49,12 +61,14 @@ const SalesOrderExport = ({ data }: SalesOrderExportProps) => {
|
||||
|
||||
return salesData?.so_number && salesData.so_number !== 'Belum dibuat' ? (
|
||||
<Button
|
||||
color='primary'
|
||||
className='w-fit min-w-32 flex items-center justify-start gap-1 px-2 py-1 text-sm font-mono'
|
||||
variant='outline'
|
||||
color='none'
|
||||
className='w-fit text-sm px-3 py-2.5 rounded-lg border-base-content/10 text-base-content/50'
|
||||
onClick={handleDownloadPDF}
|
||||
isLoading={isGeneratingPDF}
|
||||
type='button'
|
||||
>
|
||||
<Icon icon='material-symbols:file-open-outline' width={16} height={16} />
|
||||
<Icon icon='heroicons:document-text' width={20} height={20} />
|
||||
{salesData.so_number}
|
||||
</Button>
|
||||
) : null;
|
||||
@@ -71,11 +85,6 @@ const PDFDocument = ({ data }: { data: Marketing }) => {
|
||||
<Page size='A4' style={pdfStyles.page}>
|
||||
{/* Header Section */}
|
||||
<View style={pdfStyles.header}>
|
||||
<Image
|
||||
src={'https://placehold.co/120x30/png'}
|
||||
style={pdfStyles.logo}
|
||||
id={'mbu-logo'}
|
||||
/>
|
||||
<Text style={pdfStyles.companyInfo}>PT LUMBUNG TELUR INDONESIA</Text>
|
||||
<Text style={pdfStyles.address}>
|
||||
SOHO Building Lt.3 (Paris Van Java), Jalan Karang Tinggal, Kel.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { isResponseError } from '@/lib/api-helper';
|
||||
import { BaseApiService } from '@/services/api/base';
|
||||
import { httpClient } from '@/services/http/client';
|
||||
import { httpClient, httpClientFetcher } from '@/services/http/client';
|
||||
import { BaseApiResponse } from '@/types/api/api-general';
|
||||
import {
|
||||
Marketing,
|
||||
@@ -8,6 +9,9 @@ import {
|
||||
CreateDeliveryOrderPayload,
|
||||
UpdateDeliveryOrderPayload,
|
||||
} from '@/types/api/marketing/marketing';
|
||||
import toast from 'react-hot-toast';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { formatCurrency, formatDate, formatTitleCase } from '@/lib/helper';
|
||||
|
||||
/**
|
||||
* 💡 Helper untuk membuat respons dummy
|
||||
@@ -97,6 +101,78 @@ export class SalesOrderService extends BaseApiService<
|
||||
}
|
||||
}
|
||||
}
|
||||
class MarketingExportService extends BaseApiService<
|
||||
Marketing,
|
||||
unknown,
|
||||
unknown
|
||||
> {
|
||||
constructor(basePath: string = '/marketing') {
|
||||
super(basePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export to Excel
|
||||
*/
|
||||
async exportToExcel(initialQueryString: string) {
|
||||
const params = new URLSearchParams(initialQueryString);
|
||||
const queryString = `?${params.toString()}`;
|
||||
|
||||
try {
|
||||
const marketingData = await httpClientFetcher<
|
||||
BaseApiResponse<Marketing[]>
|
||||
>(`${this.basePath}${queryString}`);
|
||||
|
||||
if (isResponseError(marketingData)) {
|
||||
toast.error('Gagal melakukan export marketing! Coba lagi.');
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = marketingData.data;
|
||||
|
||||
const formattedRows = [];
|
||||
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
const row = rows[i];
|
||||
const approval = row.latest_approval;
|
||||
const isRejected = approval?.action === 'REJECTED';
|
||||
|
||||
// Calculate grand total from sales_order products
|
||||
const grandTotal =
|
||||
row.sales_order
|
||||
?.map((product) => product.total_price)
|
||||
.reduce((a, b) => a + b, 0) ?? 0;
|
||||
|
||||
// Get product names
|
||||
const products =
|
||||
row.sales_order
|
||||
?.map((product) => product.product_warehouse?.product?.name)
|
||||
.filter(Boolean)
|
||||
.join(', ') ?? '';
|
||||
|
||||
formattedRows.push({
|
||||
'No. Order': row.so_number,
|
||||
Tanggal: formatDate(row.so_date, 'DD-MM-YYYY'),
|
||||
Status: isRejected
|
||||
? 'Ditolak'
|
||||
: formatTitleCase(approval?.step_name || ''),
|
||||
Customer: row.customer?.name || '',
|
||||
'Grand Total': formatCurrency(grandTotal),
|
||||
Products: products,
|
||||
Notes: row.notes || '',
|
||||
});
|
||||
}
|
||||
|
||||
const ws = XLSX.utils.json_to_sheet(formattedRows);
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'marketing');
|
||||
|
||||
// triggers download in browser
|
||||
XLSX.writeFile(wb, 'marketing.xlsx');
|
||||
} catch (error) {
|
||||
toast.error('Gagal melakukan export marketing! Coba lagi.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const SalesOrderApi = new SalesOrderService('/marketing/sales-orders');
|
||||
export const DeliveryOrderApi = new BaseApiService<
|
||||
@@ -104,6 +180,4 @@ export const DeliveryOrderApi = new BaseApiService<
|
||||
CreateDeliveryOrderPayload,
|
||||
UpdateDeliveryOrderPayload
|
||||
>('/marketing/delivery-orders');
|
||||
export const MarketingApi = new BaseApiService<Marketing, unknown, unknown>(
|
||||
'/marketing'
|
||||
);
|
||||
export const MarketingApi = new MarketingExportService('/marketing');
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useState } from 'react';
|
||||
interface UseFormikErrorListOptions {
|
||||
onBeforeSubmit?: (e: React.FormEvent<HTMLFormElement>) => boolean | void;
|
||||
onAfterValidation?: () => void | Promise<void>;
|
||||
onAfterSubmit?: () => void | Promise<void>;
|
||||
}
|
||||
|
||||
export const useFormikErrorList = <T>(
|
||||
@@ -49,6 +50,11 @@ export const useFormikErrorList = <T>(
|
||||
|
||||
// Submit form
|
||||
formik.handleSubmit();
|
||||
|
||||
// Call onAfterSubmit callback if validation passed
|
||||
if (options?.onAfterSubmit) {
|
||||
await options.onAfterSubmit();
|
||||
}
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
|
||||
+9
@@ -82,6 +82,15 @@ export type MarketingDeliveryProducts = {
|
||||
|
||||
export type Marketing = BaseMetadata & BaseMarketing;
|
||||
|
||||
/**
|
||||
* Filter Data Types
|
||||
*/
|
||||
export type MarketingFilter = {
|
||||
product_ids: number[];
|
||||
status: string;
|
||||
customer_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Base Data Payload
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user