jws-frontend/src/utils/string-template.ts

71 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-11-27 13:55:19 +07:00
import { formatNumberDecimal } from 'src/stores/utils';
const templates = {
2024-11-27 13:55:19 +07:00
'quotation-labor': {
converter: (context?: { name: string[] }) => {
return context?.name.join('<br />') || '';
},
},
2024-11-27 12:55:38 +07:00
'quotation-payment': {
converter: (context?: {
2024-11-27 13:55:19 +07:00
paymentType:
| 'Full'
| 'Split'
| 'SplitCustom'
| 'BillFull'
| 'BillSplit'
| 'BillSplitCustom';
amount?: number;
installments?: {
no: number;
2024-11-27 12:55:38 +07:00
amount: number;
}[];
}) => {
2024-11-27 13:55:19 +07:00
if (context?.paymentType === 'Full') {
return [
'**** เงื่อนไขเพิ่มเติม',
'- เงื่อนไขการชำระเงิน แบบเต็มจำนวน',
2024-11-27 13:55:19 +07:00
`&nbsp; จำนวน ${formatNumberDecimal(context?.amount || 0, 2)}`,
].join('<br/>');
} else {
return [
'**** เงื่อนไขเพิ่มเติม',
2024-11-27 13:55:19 +07:00
`- เงื่อนไขการชำระเงิน แบบแบ่งจ่าย${context?.paymentType === 'SplitCustom' ? ' กำหนดเอง ' : ' '}${context?.installments?.length} งวด`,
...(context?.installments?.map(
2024-11-27 12:55:38 +07:00
(v) =>
2024-12-03 12:57:48 +07:00
`&nbsp; งวดที่ ${v.no} จำนวน ${formatNumberDecimal(v.amount, 2)}`,
2024-11-27 13:55:19 +07:00
) || []),
].join('<br />');
}
2024-11-27 12:55:38 +07:00
},
},
} as const;
type Template = typeof templates;
type TemplateName = keyof Template;
type TemplateContext = {
2024-11-27 13:55:19 +07:00
[key in TemplateName]?: Parameters<Template[key]['converter']>[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;
2024-11-27 13:55:19 +07:00
ret = ret.replace(
new RegExp('\\#\\[' + name.replaceAll('-', '\\-') + '\\]', 'g'),
typeof template.converter === 'function'
2024-11-27 12:55:38 +07:00
? template.converter(context?.[name as TemplateName] as any)
: template.converter,
);
// console.log(ret);
}
return ret;
}