import { formatNumberDecimal } from 'src/stores/utils'; 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('
'); } }, }, } 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; }