import { RequestWork } from 'src/stores/request-list';
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('
');
}
},
},
'order-detail': {
converter: (context?: {
items: {
product: RequestWork['productService']['product'];
list: RequestWork[];
}[];
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}. ` +
`${employee.namePrefix}. ${employee.firstNameEN} ${employee.lastNameEN} `.toUpperCase() +
`(${branch.customer.customerType === 'PERS' ? `นายจ้าง ${branch.namePrefix}. ${branch.firstNameEN} ${branch.lastNameEN} `.toUpperCase() : branch.registerName})`
);
});
return [`- ${item.product.name} ราคา ${price} บาท`, '', ...list].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;
}