jws-frontend/src/utils/string-template.ts
puriphatt 1b4c06b182
fix/refactor: quotation installment (#121)
* refactor/feat: i18n

* chore: clean log

* refactor: type

* refactor: installment and product table state relation

* refactor: handle split custom

---------

Co-authored-by: Thanaphon Frappet <thanaphon@frappet.com>
2024-12-06 11:01:52 +07:00

70 lines
2.1 KiB
TypeScript

import { formatNumberDecimal } from 'src/stores/utils';
const templates = {
'quotation-labor': {
converter: (context?: { name: string[] }) => {
return context?.name.join('<br />') || '';
},
},
'quotation-payment': {
converter: (context?: {
paymentType:
| 'Full'
| 'Split'
| 'SplitCustom'
| 'BillFull'
| 'BillSplit'
| 'BillSplitCustom';
amount?: number;
installments?: {
no: number;
amount: number;
}[];
}) => {
if (context?.paymentType === 'Full') {
return [
'**** เงื่อนไขเพิ่มเติม',
'- เงื่อนไขการชำระเงิน แบบเต็มจำนวน',
`&nbsp; จำนวน ${formatNumberDecimal(context?.amount || 0, 2)}`,
].join('<br/>');
} else {
return [
'**** เงื่อนไขเพิ่มเติม',
`- เงื่อนไขการชำระเงิน แบบแบ่งจ่าย${context?.paymentType === 'SplitCustom' ? ' กำหนดเอง ' : ' '}${context?.installments?.length} งวด`,
...(context?.installments?.map(
(v) =>
`&nbsp; งวดที่ ${v.no} จำนวน ${formatNumberDecimal(v.amount, 2)}`,
) || []),
].join('<br />');
}
},
},
} as const;
type Template = typeof templates;
type TemplateName = keyof Template;
type TemplateContext = {
[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;
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;
}