import { RequestWork } from 'src/stores/request-list'; import { TaskStatus } from 'src/stores/task-order/types'; import { formatNumberDecimal } from 'src/stores/utils'; import { i18n } from 'src/boot/i18n'; const templates = { 'quotation-labor': { converter: (context?: { name: string[] }) => { return context?.name.join('
') || ''; }, }, 'quotation-payment': { converter: (context?: { paymentType: | 'Full' | 'Split' | 'SplitCustom' | 'BillFull' | 'BillSplit' | 'BillSplitCustom'; amount?: number; installments?: { no: number; amount: number; }[]; }) => { if (context?.paymentType === 'Full') { return [ '**** เงื่อนไขเพิ่มเติม', '- เงื่อนไขการชำระเงิน แบบเต็มจำนวน', `  จำนวน ${formatNumberDecimal(context?.amount || 0, 2)}`, ].join('
'); } else { return [ '**** เงื่อนไขเพิ่มเติม', `- เงื่อนไขการชำระเงิน แบบแบ่งจ่าย${context?.paymentType === 'SplitCustom' ? ' กำหนดเอง ' : ' '}${context?.installments?.length} งวด`, ...(context?.installments?.map( (v) => `  งวดที่ ${v.no} จำนวน ${formatNumberDecimal(v.amount, 2)}`, ) || []), ].join('
'); } }, }, 'order-detail': { converter: (context?: { items?: { product: RequestWork['productService']['product']; list: (RequestWork & { taskStatus?: TaskStatus; failedComment?: string; failedType?: string; codeRequest?: string; })[]; }[]; itemsDiscount?: { productId: string; discount?: number; }[]; }) => { return ( context?.items?.flatMap((item) => { const price = formatNumberDecimal( item.product.serviceCharge - (context.itemsDiscount?.find( (v) => v.productId === item.product.id, )?.discount || 0), ); const list = item.list.map((v, i) => { const employee = v.request.employee; const branch = v.request.quotation.customerBranch; return ( `${i + 1}. ` + ` ${v.request.code}_${branch.customer.customerType === 'PERS' ? `${branch.namePrefix}. ${branch.firstNameEN} ${branch.lastNameEN} `.toUpperCase() : branch.registerName}_` + `${employee.namePrefix}. ${employee.firstNameEN} ${employee.lastNameEN} `.toUpperCase() + `${!!v.failedType && v.failedType !== 'other' ? `${i18n.global.t(`taskOrder.${v.failedType}`)}` : !!v.failedComment ? v.failedComment : ''}` ); }); return [ `- ${item.product.name} ราคา ${price} บาท`, '', ...list, '', ].join('
'); }) || [] ).join('
'); }, }, } as const; type Template = typeof templates; type TemplateName = keyof Template; type TemplateContext = { [key in TemplateName]?: Parameters[0]; }; export function convertTemplate( text: string, context?: TemplateContext, templateUse?: TemplateName[], ) { let ret = text; for (const [name, template] of Object.entries(templates)) { if (templateUse && !templateUse.includes(name as TemplateName)) continue; ret = ret.replace( new RegExp('\\#\\[' + name.replaceAll('-', '\\-') + '\\]', 'g'), typeof template.converter === 'function' ? template.converter(context?.[name as TemplateName] as any) : template.converter, ); // console.log(ret); } return ret; }