import { defineStore } from 'pinia'; import { ref } from 'vue'; // NOTE: Import types import { QuotationPayload, EmployeeWorker } from 'src/stores/quotations/types'; // NOTE: Import stores import { useQuotationStore } from 'stores/quotations'; const DEFAULT_DATA: QuotationPayload = { productServiceList: [], urgent: false, customerBranchId: '', worker: [], workerCount: 0, payBillDate: new Date(), paySplit: [], paySplitCount: 0, payCondition: 'Full', dueDate: new Date(), documentReceivePoint: '', contactTel: '', contactName: '', workName: '', actorName: '', status: 'CREATED', }; export const useQuotationForm = defineStore('form-quotation', () => { const quotationStore = useQuotationStore(); let resetFormData = structuredClone(DEFAULT_DATA); const currentTreeData = ref(); const currentFormData = ref( structuredClone(resetFormData), ); const currentFormState = ref<{ mode: null | 'info' | 'create' | 'edit'; }>({ mode: null, }); function isFormDataDifferent() { const { ...resetData } = resetFormData; const { ...currData } = currentFormData.value; return JSON.stringify(resetData) !== JSON.stringify(currData); } function resetForm(clean = false) { if (clean) { currentFormData.value = structuredClone(DEFAULT_DATA); resetFormData = structuredClone(DEFAULT_DATA); return; } currentFormData.value = structuredClone(resetFormData); } async function assignFormData(id: string, mode: 'info' | 'edit' = 'info') { const data = await quotationStore.getQuotation(id); if (!data) return; // NOTE: Error should be handled globally by axios instance resetFormData = Object.assign(data, { dueDate: new Date(data.dueDate), payBillDate: data.payBillDate ? new Date(data.payBillDate) : undefined, worker: data.worker.map((v) => Object.assign(v.employee, { dateOfBirth: new Date(v.employee.dateOfBirth), }), ), }); currentFormData.value = structuredClone(resetFormData); currentFormState.value.mode = mode; } async function submitQuotation() { if (currentFormState.value.mode === 'create') { // await quotationStore.createQuotation(); } if (currentFormState.value.mode === 'edit' && currentFormData.value.id) { // await quotationStore.editQuotation({ // id: currentFormData.value.id, // ...currentFormData.value, // }); } currentFormState.value.mode = 'info'; } function injectNewEmployee(data: EmployeeWorker) { currentFormData.value.worker.push({ alienReferencNumber: data.alienReferencNumber, documentExpireDate: data.documentExpireDate, lastNameEN: data.lastNameEN, lastName: data.lastName, middleNameEN: data.middleNameEN, middleName: data.middleName, firstNameEN: data.firstNameEN, firstName: data.firstName, namePrefix: data.namePrefix, nationality: data.nationality, gender: data.gender, dateOfBirth: data.dateOfBirth, }); } return { currentFormData, currentFormState, injectNewEmployee, isFormDataDifferent, resetForm, assignFormData, submitQuotation, }; });