hotfix-add subgroup customer
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -18,6 +18,11 @@ function Field({ label, value }: { label: string; value: string | null | undefin
|
||||
export function QuotationDocumentPreview({ quotationId }: { quotationId: string }) {
|
||||
const { data } = useSuspenseQuery(quotationDocumentPreviewOptions(quotationId));
|
||||
const { documentData, template } = data.preview;
|
||||
const topicGroups: Array<{ key: 'scope' | 'exclusion' | 'payment'; title: string }> = [
|
||||
{ key: 'scope', title: 'Scope' },
|
||||
{ key: 'exclusion', title: 'Exclusions' },
|
||||
{ key: 'payment', title: 'Payment Terms' }
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='space-y-6'>
|
||||
@@ -137,12 +142,8 @@ export function QuotationDocumentPreview({ quotationId }: { quotationId: string
|
||||
<CardDescription>Scope, exclusions, and payment terms from topic records.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className='space-y-6'>
|
||||
{[
|
||||
{ key: 'scope', title: 'Scope' },
|
||||
{ key: 'exclusion', title: 'Exclusions' },
|
||||
{ key: 'payment', title: 'Payment Terms' }
|
||||
].map((group) => {
|
||||
const entries = documentData.topics[group.key as keyof typeof documentData.topics];
|
||||
{topicGroups.map((group) => {
|
||||
const entries = documentData.topics[group.key];
|
||||
return (
|
||||
<div key={group.key} className='space-y-3'>
|
||||
<div className='font-medium'>{group.title}</div>
|
||||
|
||||
204
src/features/crm/quotations/document/server/pdf-topic-engine.ts
Normal file
204
src/features/crm/quotations/document/server/pdf-topic-engine.ts
Normal file
@@ -0,0 +1,204 @@
|
||||
import type { Template } from '@pdfme/common';
|
||||
import { formatTopicItems } from './pdfme-transforms';
|
||||
import type { PdfTopic, PdfTopicEngineOptions } from './pdf-topic.type';
|
||||
|
||||
type TemplateSchema = {
|
||||
name?: string;
|
||||
position?: { x?: number; y?: number };
|
||||
width?: number;
|
||||
height?: number;
|
||||
content?: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
const DEFAULT_TOPIC_ENGINE_OPTIONS: Required<PdfTopicEngineOptions> = {
|
||||
targetPageIndex: 1,
|
||||
pageStartY: 35,
|
||||
pageBottomY: 250,
|
||||
topicSpacing: 10,
|
||||
keepTogetherNames: [
|
||||
'Please_do_not',
|
||||
'yours_faithfuly',
|
||||
'app1',
|
||||
'app1_position',
|
||||
'app2',
|
||||
'app2_position',
|
||||
'app3',
|
||||
'app3_position'
|
||||
],
|
||||
topicTemplateName: 'topic',
|
||||
topicDataTemplateName: 'data_topic',
|
||||
rowHeight: 7,
|
||||
keepTogetherMinSpace: 60
|
||||
};
|
||||
|
||||
function cloneTemplate<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value)) as T;
|
||||
}
|
||||
|
||||
function getFieldY(field: TemplateSchema) {
|
||||
return typeof field.position?.y === 'number' ? field.position.y : 0;
|
||||
}
|
||||
|
||||
function getFieldBottom(field: TemplateSchema) {
|
||||
return getFieldY(field) + (typeof field.height === 'number' ? field.height : 0);
|
||||
}
|
||||
|
||||
function setFieldY(field: TemplateSchema, y: number) {
|
||||
field.position = {
|
||||
...(field.position ?? {}),
|
||||
y
|
||||
};
|
||||
}
|
||||
|
||||
function sortTopics(topics: PdfTopic[]) {
|
||||
return [...topics].sort((left, right) => {
|
||||
const sortDelta = (left.sortOrder ?? Number.MAX_SAFE_INTEGER) - (right.sortOrder ?? Number.MAX_SAFE_INTEGER);
|
||||
|
||||
if (sortDelta !== 0) {
|
||||
return sortDelta;
|
||||
}
|
||||
|
||||
return String(left.id ?? left.topicType).localeCompare(String(right.id ?? right.topicType));
|
||||
});
|
||||
}
|
||||
|
||||
export function buildPdfTopicTemplate(
|
||||
template: Template,
|
||||
topics: PdfTopic[],
|
||||
options?: PdfTopicEngineOptions
|
||||
): {
|
||||
template: Template;
|
||||
topicInputs: Record<string, string[][]>;
|
||||
} {
|
||||
const resolvedOptions = { ...DEFAULT_TOPIC_ENGINE_OPTIONS, ...options };
|
||||
const nextTemplate = cloneTemplate(template);
|
||||
const pages = Array.isArray(nextTemplate.schemas) ? [...nextTemplate.schemas] : [];
|
||||
const targetPage = pages[resolvedOptions.targetPageIndex];
|
||||
|
||||
if (!Array.isArray(targetPage)) {
|
||||
return { template: nextTemplate, topicInputs: {} };
|
||||
}
|
||||
|
||||
const topicTemplate = targetPage.find(
|
||||
(field) => (field as TemplateSchema).name === resolvedOptions.topicTemplateName
|
||||
) as TemplateSchema | undefined;
|
||||
const topicDataTemplate = targetPage.find(
|
||||
(field) => (field as TemplateSchema).name === resolvedOptions.topicDataTemplateName
|
||||
) as TemplateSchema | undefined;
|
||||
|
||||
if (!topicTemplate || !topicDataTemplate) {
|
||||
console.warn('[pdf-topic-engine] Missing topic or data_topic schema template');
|
||||
return { template: nextTemplate, topicInputs: {} };
|
||||
}
|
||||
|
||||
const keepTogetherSet = new Set(resolvedOptions.keepTogetherNames);
|
||||
const pageWithoutDynamicFields = targetPage.filter((field) => {
|
||||
const name = (field as TemplateSchema).name;
|
||||
return (
|
||||
name !== resolvedOptions.topicTemplateName && name !== resolvedOptions.topicDataTemplateName
|
||||
);
|
||||
}) as TemplateSchema[];
|
||||
const keepTogetherFields = pageWithoutDynamicFields
|
||||
.filter((field) => keepTogetherSet.has(field.name ?? ''))
|
||||
.map((field) => cloneTemplate(field));
|
||||
const staticFields = pageWithoutDynamicFields
|
||||
.filter((field) => !keepTogetherSet.has(field.name ?? ''))
|
||||
.map((field) => cloneTemplate(field));
|
||||
const sortedTopics = sortTopics(topics);
|
||||
const topicInputs: Record<string, string[][]> = {};
|
||||
const generatedPages: Template['schemas'] = [];
|
||||
const topicToDataOffset = getFieldY(topicDataTemplate) - getFieldY(topicTemplate);
|
||||
const keepTogetherTop =
|
||||
keepTogetherFields.length > 0
|
||||
? Math.min(...keepTogetherFields.map((field) => getFieldY(field)))
|
||||
: resolvedOptions.pageBottomY;
|
||||
const keepTogetherHeight =
|
||||
keepTogetherFields.length > 0
|
||||
? Math.max(...keepTogetherFields.map((field) => getFieldBottom(field))) - keepTogetherTop
|
||||
: 0;
|
||||
|
||||
let currentPageFields = staticFields.map((field) => cloneTemplate(field));
|
||||
let currentY = Math.max(
|
||||
resolvedOptions.pageStartY,
|
||||
currentPageFields.length > 0
|
||||
? Math.max(...currentPageFields.map((field) => getFieldBottom(field)), resolvedOptions.pageStartY)
|
||||
: resolvedOptions.pageStartY
|
||||
);
|
||||
|
||||
const pushCurrentPage = () => {
|
||||
generatedPages.push(currentPageFields as Template['schemas'][number]);
|
||||
currentPageFields = [];
|
||||
currentY = resolvedOptions.pageStartY;
|
||||
};
|
||||
|
||||
for (const [topicIndex, topic] of sortedTopics.entries()) {
|
||||
const topicRows = formatTopicItems({ items: topic.items ?? [] });
|
||||
const topicKey = `topic_${resolvedOptions.targetPageIndex}_${topicIndex}`;
|
||||
const itemKey = `item_topic_${resolvedOptions.targetPageIndex}_${topicIndex}`;
|
||||
const labelHeight =
|
||||
typeof topicTemplate.height === 'number' ? topicTemplate.height : resolvedOptions.rowHeight;
|
||||
const tableHeight = Math.max(
|
||||
typeof topicDataTemplate.height === 'number' ? topicDataTemplate.height : resolvedOptions.rowHeight,
|
||||
topicRows.length * resolvedOptions.rowHeight
|
||||
);
|
||||
const blockHeight = topicToDataOffset + tableHeight;
|
||||
|
||||
if (currentY + blockHeight > resolvedOptions.pageBottomY && currentPageFields.length > 0) {
|
||||
pushCurrentPage();
|
||||
}
|
||||
|
||||
const topicField = cloneTemplate(topicTemplate);
|
||||
topicField.name = topicKey;
|
||||
topicField.content = `[[\"{${topicKey}}\"]]`;
|
||||
topicField.height = labelHeight;
|
||||
setFieldY(topicField, currentY);
|
||||
|
||||
const topicDataField = cloneTemplate(topicDataTemplate);
|
||||
topicDataField.name = itemKey;
|
||||
topicDataField.content = `[[\"{${itemKey}}\"]]`;
|
||||
topicDataField.height = tableHeight;
|
||||
setFieldY(topicDataField, currentY + topicToDataOffset);
|
||||
|
||||
topicInputs[topicKey] = [[topic.topicType?.trim() || '-']];
|
||||
topicInputs[itemKey] = topicRows;
|
||||
currentPageFields.push(topicField, topicDataField);
|
||||
currentY = getFieldY(topicDataField) + tableHeight + resolvedOptions.topicSpacing;
|
||||
}
|
||||
|
||||
if (keepTogetherFields.length > 0) {
|
||||
const remainingSpace = resolvedOptions.pageBottomY - currentY;
|
||||
|
||||
if (
|
||||
remainingSpace < resolvedOptions.keepTogetherMinSpace ||
|
||||
currentY + keepTogetherHeight > resolvedOptions.pageBottomY
|
||||
) {
|
||||
pushCurrentPage();
|
||||
}
|
||||
|
||||
const shiftDelta = currentY - keepTogetherTop;
|
||||
|
||||
for (const field of keepTogetherFields) {
|
||||
const nextField = cloneTemplate(field);
|
||||
setFieldY(nextField, getFieldY(field) + shiftDelta);
|
||||
currentPageFields.push(nextField);
|
||||
}
|
||||
}
|
||||
|
||||
if (currentPageFields.length > 0) {
|
||||
generatedPages.push(currentPageFields as Template['schemas'][number]);
|
||||
}
|
||||
|
||||
nextTemplate.schemas = [
|
||||
...pages.slice(0, resolvedOptions.targetPageIndex),
|
||||
...(generatedPages.length > 0
|
||||
? generatedPages
|
||||
: [pageWithoutDynamicFields as Template['schemas'][number]]),
|
||||
...pages.slice(resolvedOptions.targetPageIndex + 1)
|
||||
];
|
||||
|
||||
return {
|
||||
template: nextTemplate,
|
||||
topicInputs
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
export type PdfTopicItem = {
|
||||
id: string | number;
|
||||
content: string;
|
||||
sortOrder?: number | null;
|
||||
};
|
||||
|
||||
export type PdfTopic = {
|
||||
id?: string | number;
|
||||
topicType: string;
|
||||
sortOrder?: number | null;
|
||||
items?: PdfTopicItem[];
|
||||
};
|
||||
|
||||
export type PdfTopicEngineOptions = {
|
||||
targetPageIndex?: number;
|
||||
pageStartY?: number;
|
||||
pageBottomY?: number;
|
||||
topicSpacing?: number;
|
||||
keepTogetherNames?: string[];
|
||||
topicTemplateName?: string;
|
||||
topicDataTemplateName?: string;
|
||||
rowHeight?: number;
|
||||
keepTogetherMinSpace?: number;
|
||||
};
|
||||
143
src/features/crm/quotations/document/server/pdfme-transforms.ts
Normal file
143
src/features/crm/quotations/document/server/pdfme-transforms.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
const EMPTY_TABLE_FALLBACK = [['-']];
|
||||
|
||||
function normalizeNumber(
|
||||
amount: number | string | null | undefined
|
||||
): number | null {
|
||||
if (typeof amount === 'number' && Number.isFinite(amount)) {
|
||||
return amount;
|
||||
}
|
||||
|
||||
if (typeof amount === 'string') {
|
||||
const normalized = Number(amount.replaceAll(',', '').trim());
|
||||
return Number.isFinite(normalized) ? normalized : null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function formatPdfDate(
|
||||
dateString: string | Date | null | undefined,
|
||||
language: 'th' | 'en' = 'en'
|
||||
): string {
|
||||
if (!dateString) {
|
||||
return '-';
|
||||
}
|
||||
|
||||
const date = dateString instanceof Date ? dateString : new Date(dateString);
|
||||
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return '-';
|
||||
}
|
||||
|
||||
if (language === 'th') {
|
||||
return date.toLocaleDateString('th-TH', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
calendar: 'buddhist'
|
||||
});
|
||||
}
|
||||
|
||||
return date.toLocaleDateString('en-US', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric'
|
||||
});
|
||||
}
|
||||
|
||||
export function formatPdfCurrency(
|
||||
amount: number | string | null | undefined,
|
||||
currencyCode = 'THB'
|
||||
): string {
|
||||
const numericAmount = normalizeNumber(amount);
|
||||
|
||||
if (numericAmount === null) {
|
||||
return '-';
|
||||
}
|
||||
|
||||
const normalizedCode = currencyCode.toUpperCase();
|
||||
const symbols: Record<string, string> = {
|
||||
THB: 'THB ',
|
||||
USD: '$',
|
||||
EUR: 'EUR '
|
||||
};
|
||||
const symbol = symbols[normalizedCode] ?? `${normalizedCode} `;
|
||||
const formatted = new Intl.NumberFormat('en-US', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2
|
||||
}).format(numericAmount);
|
||||
|
||||
return `${symbol}${formatted}`.trim();
|
||||
}
|
||||
|
||||
export function formatTopicItems(topic?: {
|
||||
items?: Array<{ content?: string | null; sortOrder?: number | null }> | string[];
|
||||
}): string[][] {
|
||||
if (!topic?.items?.length) {
|
||||
return EMPTY_TABLE_FALLBACK;
|
||||
}
|
||||
|
||||
const rows = [...topic.items]
|
||||
.sort((left, right) => {
|
||||
if (typeof left === 'string' || typeof right === 'string') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (left.sortOrder ?? Number.MAX_SAFE_INTEGER) - (right.sortOrder ?? Number.MAX_SAFE_INTEGER);
|
||||
})
|
||||
.map((item) => {
|
||||
if (typeof item === 'string') {
|
||||
return item.trim() || '-';
|
||||
}
|
||||
|
||||
return item?.content?.trim() || '-';
|
||||
})
|
||||
.filter(Boolean)
|
||||
.map((content) => [content]);
|
||||
|
||||
return rows.length ? rows : EMPTY_TABLE_FALLBACK;
|
||||
}
|
||||
|
||||
export function normalizePdfmeTable(
|
||||
value: unknown,
|
||||
columns?: Array<{ sourceField: string; formatMask?: string | null }>
|
||||
): string[][] {
|
||||
if (!Array.isArray(value) || value.length === 0) {
|
||||
return EMPTY_TABLE_FALLBACK;
|
||||
}
|
||||
|
||||
if (value.every((row) => Array.isArray(row))) {
|
||||
const normalizedRows = value.map((row) =>
|
||||
(row as unknown[]).map((cell) => {
|
||||
const stringValue = String(cell ?? '').trim();
|
||||
return stringValue || '-';
|
||||
})
|
||||
);
|
||||
|
||||
return normalizedRows.length ? normalizedRows : EMPTY_TABLE_FALLBACK;
|
||||
}
|
||||
|
||||
if (!columns?.length) {
|
||||
return value.map((row) => [String(row ?? '').trim() || '-']) || EMPTY_TABLE_FALLBACK;
|
||||
}
|
||||
|
||||
const rows = value.map((row) => {
|
||||
const rowRecord = row as Record<string, unknown>;
|
||||
|
||||
return columns.map((column) => {
|
||||
const cell = rowRecord[column.sourceField];
|
||||
|
||||
if (typeof cell === 'number' || typeof cell === 'string') {
|
||||
return String(cell).trim() || '-';
|
||||
}
|
||||
|
||||
if (cell === null || cell === undefined) {
|
||||
return '-';
|
||||
}
|
||||
|
||||
return String(cell).trim() || '-';
|
||||
});
|
||||
});
|
||||
|
||||
return rows.length ? rows : EMPTY_TABLE_FALLBACK;
|
||||
}
|
||||
@@ -26,6 +26,15 @@ import type {
|
||||
QuotationDocumentApprovalStep,
|
||||
QuotationDocumentData
|
||||
} from '../types';
|
||||
import type { PdfTopic } from './pdf-topic.type';
|
||||
import {
|
||||
formatPdfCurrency,
|
||||
formatPdfDate,
|
||||
formatTopicItems
|
||||
} from './pdfme-transforms';
|
||||
import { buildPdfTopicTemplate } from './pdf-topic-engine';
|
||||
import { resolveQuotationTopicTypeMapping } from './topic-mapping';
|
||||
import type { Template } from '@pdfme/common';
|
||||
|
||||
const DOCUMENT_OPTION_CATEGORIES = {
|
||||
branch: 'crm_branch',
|
||||
@@ -84,6 +93,57 @@ function extractSinglePlaceholder(value: string) {
|
||||
return uniqueMatches.length === 1 ? uniqueMatches[0] : null;
|
||||
}
|
||||
|
||||
function normalizeTopicKey(value: string | null | undefined) {
|
||||
return value?.trim().toLowerCase().replaceAll(/[\s_-]+/g, '') ?? '';
|
||||
}
|
||||
|
||||
function matchesTopicAlias(actualCode: string | null | undefined, expectedCode: string) {
|
||||
const actual = normalizeTopicKey(actualCode);
|
||||
const expected = normalizeTopicKey(expectedCode);
|
||||
|
||||
if (!actual || !expected) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (actual === expected) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const aliasGroups = [
|
||||
['scope', 'scopeofwork', 'dockscopeofwork', 'solarcellscopeofwork'],
|
||||
[
|
||||
'exclusion',
|
||||
'exclusionfromscopeofsupply',
|
||||
'exclusionofsupplyinstallation',
|
||||
'solarcellexclusionofsupplyinstallation'
|
||||
],
|
||||
[
|
||||
'payment',
|
||||
'paymentconditions',
|
||||
'termsofpaymentuponprogressofeachitem',
|
||||
'solarcellpaymentconditions'
|
||||
],
|
||||
['delivery', 'deliverydate', 'solarcelldelivery'],
|
||||
['warranty', 'solarcellwarranty']
|
||||
];
|
||||
|
||||
return aliasGroups.some(
|
||||
(group) => group.includes(actual) && group.includes(expected)
|
||||
);
|
||||
}
|
||||
|
||||
function sortBySortOrder<T extends { sortOrder?: number | null }>(items: T[]) {
|
||||
return [...items].sort((left, right) => {
|
||||
const delta = (left.sortOrder ?? Number.MAX_SAFE_INTEGER) - (right.sortOrder ?? Number.MAX_SAFE_INTEGER);
|
||||
|
||||
if (delta !== 0) {
|
||||
return delta;
|
||||
}
|
||||
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
function normalizePdfmeTemplateInput(
|
||||
schemaJson: unknown,
|
||||
templateInput: Record<string, unknown>
|
||||
@@ -250,6 +310,68 @@ export async function buildQuotationDocumentData(
|
||||
const statusCode = findOptionCode(statusOptions, quotation.status);
|
||||
const statusLabel = findOptionLabel(statusOptions, quotation.status);
|
||||
const topicCodeById = new Map(topicTypeOptions.map((option) => [option.id, option.code]));
|
||||
const primaryProductType =
|
||||
items.find((item) => findOptionCode(productTypeOptions, item.productType))?.productType ?? null;
|
||||
const productTypeCode =
|
||||
findOptionCode(productTypeOptions, primaryProductType) ??
|
||||
findOptionCode(quotationTypeOptions, quotationDetail.quotationType) ??
|
||||
findOptionLabel(quotationTypeOptions, quotationDetail.quotationType) ??
|
||||
null;
|
||||
const topicTypeMapping = resolveQuotationTopicTypeMapping(productTypeCode);
|
||||
const resolvedTopics = sortBySortOrder(topics).map((item) => {
|
||||
const topicLabel =
|
||||
findOptionLabel(topicTypeOptions, item.topicType) ??
|
||||
item.title?.trim() ??
|
||||
topicCodeById.get(item.topicType) ??
|
||||
'Topic';
|
||||
|
||||
return {
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
topicType: topicLabel,
|
||||
topicCode: topicCodeById.get(item.topicType) ?? item.title,
|
||||
sortOrder: item.sortOrder,
|
||||
items: sortBySortOrder(item.items).map((child) => ({
|
||||
id: child.id,
|
||||
content: child.content,
|
||||
sortOrder: child.sortOrder
|
||||
}))
|
||||
};
|
||||
});
|
||||
const pdfTopics: PdfTopic[] = resolvedTopics.map((item) => ({
|
||||
id: item.id,
|
||||
topicType: item.topicType,
|
||||
sortOrder: item.sortOrder,
|
||||
items: item.items.map((child) => ({
|
||||
id: child.id,
|
||||
content: child.content?.trim() || '-',
|
||||
sortOrder: child.sortOrder
|
||||
}))
|
||||
}));
|
||||
const scopeTopics = resolvedTopics.filter((item) =>
|
||||
matchesTopicAlias(item.topicCode, topicTypeMapping.scope)
|
||||
);
|
||||
const exclusionTopics = resolvedTopics.filter((item) =>
|
||||
matchesTopicAlias(item.topicCode, topicTypeMapping.exclusion)
|
||||
);
|
||||
const paymentTopics = resolvedTopics.filter((item) =>
|
||||
matchesTopicAlias(item.topicCode, topicTypeMapping.payment)
|
||||
);
|
||||
const warrantyTopics = resolvedTopics.filter((item) =>
|
||||
matchesTopicAlias(item.topicCode, topicTypeMapping.warranty)
|
||||
);
|
||||
const deliveryTopics = resolvedTopics.filter((item) =>
|
||||
matchesTopicAlias(item.topicCode, topicTypeMapping.delivery)
|
||||
);
|
||||
const otherTopics = resolvedTopics.filter((item) => {
|
||||
return ![topicTypeMapping.scope, topicTypeMapping.exclusion, topicTypeMapping.payment, topicTypeMapping.warranty, topicTypeMapping.delivery].some(
|
||||
(expectedCode) => matchesTopicAlias(item.topicCode, expectedCode)
|
||||
);
|
||||
});
|
||||
const exclusionTopic = exclusionTopics[0];
|
||||
const paymentTopic = paymentTopics[0];
|
||||
const warrantyTopic = warrantyTopics[0];
|
||||
const deliveryTopic = deliveryTopics[0];
|
||||
const approvalApprovers: QuotationDocumentApprovalStep[] =
|
||||
approvalDetail?.timeline
|
||||
.filter((item) => ['approve', 'reject', 'return'].includes(item.action))
|
||||
@@ -315,6 +437,7 @@ export async function buildQuotationDocumentData(
|
||||
statusLabel,
|
||||
quotationTypeCode: findOptionCode(quotationTypeOptions, quotationDetail.quotationType),
|
||||
quotationTypeLabel: findOptionLabel(quotationTypeOptions, quotationDetail.quotationType),
|
||||
currency: findOptionCode(currencyOptions, quotationDetail.currency),
|
||||
currencyCode: findOptionCode(currencyOptions, quotationDetail.currency),
|
||||
currencyLabel: findOptionLabel(currencyOptions, quotationDetail.currency),
|
||||
exchangeRate: quotationDetail.exchangeRate,
|
||||
@@ -353,21 +476,46 @@ export async function buildQuotationDocumentData(
|
||||
isPrimary: item.isPrimary
|
||||
})),
|
||||
topics: {
|
||||
scope: topics
|
||||
.filter((item) => topicCodeById.get(item.topicType) === 'scope')
|
||||
.map((item) => ({ title: item.title, items: item.items.map((child) => child.content) })),
|
||||
exclusion: topics
|
||||
.filter((item) => topicCodeById.get(item.topicType) === 'exclusion')
|
||||
.map((item) => ({ title: item.title, items: item.items.map((child) => child.content) })),
|
||||
payment: topics
|
||||
.filter((item) => topicCodeById.get(item.topicType) === 'payment')
|
||||
.map((item) => ({ title: item.title, items: item.items.map((child) => child.content) })),
|
||||
other: topics
|
||||
.filter((item) => {
|
||||
const topicCode = topicCodeById.get(item.topicType);
|
||||
return !['scope', 'exclusion', 'payment'].includes(topicCode ?? '');
|
||||
})
|
||||
.map((item) => ({ title: item.title, items: item.items.map((child) => child.content) }))
|
||||
scope: scopeTopics.map((item) => ({
|
||||
title: item.title,
|
||||
items: item.items.map((child) => child.content ?? '-')
|
||||
})),
|
||||
exclusion: exclusionTopics.map((item) => ({
|
||||
title: item.title,
|
||||
items: item.items.map((child) => child.content ?? '-')
|
||||
})),
|
||||
payment: paymentTopics.map((item) => ({
|
||||
title: item.title,
|
||||
items: item.items.map((child) => child.content ?? '-')
|
||||
})),
|
||||
warranty: warrantyTopics.map((item) => ({
|
||||
title: item.title,
|
||||
items: item.items.map((child) => child.content ?? '-')
|
||||
})),
|
||||
delivery: deliveryTopics.map((item) => ({
|
||||
title: item.title,
|
||||
items: item.items.map((child) => child.content ?? '-')
|
||||
})),
|
||||
other: otherTopics.map((item) => ({
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
sortOrder: item.sortOrder,
|
||||
items: item.items.map((child) => child.content ?? '-')
|
||||
})),
|
||||
all: pdfTopics
|
||||
},
|
||||
pdfme: {
|
||||
quotation_date: formatPdfDate(quotationDetail.quotationDate, 'en'),
|
||||
quotation_price: formatPdfCurrency(
|
||||
quotationDetail.totalAmount,
|
||||
findOptionCode(currencyOptions, quotationDetail.currency) ?? 'THB'
|
||||
),
|
||||
exclusion_data: formatTopicItems(exclusionTopic),
|
||||
payment_data: formatTopicItems(paymentTopic),
|
||||
warranty_data: formatTopicItems(warrantyTopic),
|
||||
delivery_data: formatTopicItems(deliveryTopic),
|
||||
topics_data: formatTopicItems(scopeTopics[0] ?? exclusionTopic ?? paymentTopic),
|
||||
topic_inputs: {}
|
||||
},
|
||||
approval: {
|
||||
requestId: approvalDetail?.request.id ?? null,
|
||||
@@ -381,12 +529,16 @@ export async function buildQuotationDocumentData(
|
||||
},
|
||||
signatures: {
|
||||
preparedBy: preparer?.name ?? null,
|
||||
preparedByPosition: null,
|
||||
requestedBy: contact?.name ?? customer.name,
|
||||
salesManager:
|
||||
approvalApprovers.find((item) => item.roleCode === 'sales_manager')?.actorName ?? null,
|
||||
salesManagerPosition: null,
|
||||
departmentManager:
|
||||
approvalApprovers.find((item) => item.roleCode === 'department_manager')?.actorName ?? null,
|
||||
topManager: approvalApprovers.find((item) => item.roleCode === 'top_manager')?.actorName ?? null
|
||||
departmentManagerPosition: null,
|
||||
topManager: approvalApprovers.find((item) => item.roleCode === 'top_manager')?.actorName ?? null,
|
||||
topManagerPosition: null
|
||||
},
|
||||
watermarkStatus: statusCode && statusCode !== 'approved' ? statusLabel ?? statusCode : null
|
||||
};
|
||||
@@ -412,12 +564,28 @@ export async function getQuotationDocumentPreviewData(
|
||||
template.version.schemaJson,
|
||||
mapDocumentDataToTemplateInput(documentData as unknown as Record<string, unknown>, mappings)
|
||||
);
|
||||
const { template: renderTemplate, topicInputs } = buildPdfTopicTemplate(
|
||||
template.version.schemaJson as Template,
|
||||
documentData.topics.all
|
||||
);
|
||||
const mergedTemplateInput = {
|
||||
...templateInput,
|
||||
...topicInputs
|
||||
};
|
||||
|
||||
documentData.pdfme.topic_inputs = topicInputs;
|
||||
|
||||
return {
|
||||
documentData,
|
||||
template,
|
||||
template: {
|
||||
...template,
|
||||
version: {
|
||||
...template.version,
|
||||
schemaJson: renderTemplate
|
||||
}
|
||||
},
|
||||
mappings,
|
||||
templateInput
|
||||
templateInput: mergedTemplateInput
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
56
src/features/crm/quotations/document/server/topic-mapping.ts
Normal file
56
src/features/crm/quotations/document/server/topic-mapping.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
export const QUOTATION_TOPIC_TYPE_MAPPING = {
|
||||
crane: {
|
||||
scope: 'scope_of_work',
|
||||
exclusion: 'exclusion_from_scope_of_supply',
|
||||
payment: 'terms_of_payment_upon_progress_of_each_item',
|
||||
delivery: 'delivery_date',
|
||||
warranty: 'warranty'
|
||||
},
|
||||
dockdoor: {
|
||||
scope: 'dock_scope_of_work',
|
||||
exclusion: 'exclusion_of_supply_installation',
|
||||
payment: 'payment_conditions',
|
||||
delivery: 'delivery_date',
|
||||
warranty: 'warranty'
|
||||
},
|
||||
solarcell: {
|
||||
scope: 'solarcell_scope_of_work',
|
||||
exclusion: 'solarcell_exclusion_of_supply_installation',
|
||||
payment: 'solarcell_payment_conditions',
|
||||
delivery: 'solarcell_delivery',
|
||||
warranty: 'solarcell_warranty'
|
||||
},
|
||||
default: {
|
||||
scope: 'scope_of_work',
|
||||
exclusion: 'exclusion_from_scope_of_supply',
|
||||
payment: 'payment_conditions',
|
||||
delivery: 'delivery',
|
||||
warranty: 'warranty'
|
||||
}
|
||||
} as const;
|
||||
|
||||
function normalizeKey(value: string | null | undefined) {
|
||||
return value?.trim().toLowerCase().replaceAll(/[\s_-]+/g, '') ?? '';
|
||||
}
|
||||
|
||||
export function getQuotationTopicMapping(quotationType?: string | null) {
|
||||
const normalized = normalizeKey(quotationType);
|
||||
|
||||
if (normalized.includes('crane')) {
|
||||
return QUOTATION_TOPIC_TYPE_MAPPING.crane;
|
||||
}
|
||||
|
||||
if (normalized.includes('dock')) {
|
||||
return QUOTATION_TOPIC_TYPE_MAPPING.dockdoor;
|
||||
}
|
||||
|
||||
if (normalized.includes('solar')) {
|
||||
return QUOTATION_TOPIC_TYPE_MAPPING.solarcell;
|
||||
}
|
||||
|
||||
return QUOTATION_TOPIC_TYPE_MAPPING.default;
|
||||
}
|
||||
|
||||
export function resolveQuotationTopicTypeMapping(productType: string | null | undefined) {
|
||||
return getQuotationTopicMapping(productType);
|
||||
}
|
||||
@@ -2,9 +2,12 @@ import type {
|
||||
DocumentTemplateMappingWithColumns,
|
||||
ResolvedDocumentTemplate
|
||||
} from '@/features/foundation/document-template/types';
|
||||
import type { PdfTopic } from './server/pdf-topic.type';
|
||||
|
||||
export interface QuotationDocumentTopicGroup {
|
||||
id?: string;
|
||||
title: string;
|
||||
sortOrder?: number | null;
|
||||
items: string[];
|
||||
}
|
||||
|
||||
@@ -63,6 +66,7 @@ export interface QuotationDocumentData {
|
||||
statusLabel: string | null;
|
||||
quotationTypeCode: string | null;
|
||||
quotationTypeLabel: string | null;
|
||||
currency: string | null;
|
||||
currencyCode: string | null;
|
||||
currencyLabel: string | null;
|
||||
exchangeRate: number;
|
||||
@@ -104,7 +108,20 @@ export interface QuotationDocumentData {
|
||||
scope: QuotationDocumentTopicGroup[];
|
||||
exclusion: QuotationDocumentTopicGroup[];
|
||||
payment: QuotationDocumentTopicGroup[];
|
||||
warranty: QuotationDocumentTopicGroup[];
|
||||
delivery: QuotationDocumentTopicGroup[];
|
||||
other: QuotationDocumentTopicGroup[];
|
||||
all: PdfTopic[];
|
||||
};
|
||||
pdfme: {
|
||||
quotation_date: string;
|
||||
quotation_price: string;
|
||||
exclusion_data: string[][];
|
||||
payment_data?: string[][];
|
||||
warranty_data?: string[][];
|
||||
delivery_data?: string[][];
|
||||
topics_data?: string[][];
|
||||
topic_inputs?: Record<string, string[][]>;
|
||||
};
|
||||
approval: {
|
||||
requestId: string | null;
|
||||
@@ -117,10 +134,14 @@ export interface QuotationDocumentData {
|
||||
};
|
||||
signatures: {
|
||||
preparedBy: string | null;
|
||||
preparedByPosition?: string | null;
|
||||
requestedBy: string | null;
|
||||
salesManager: string | null;
|
||||
salesManagerPosition?: string | null;
|
||||
departmentManager: string | null;
|
||||
departmentManagerPosition?: string | null;
|
||||
topManager: string | null;
|
||||
topManagerPosition?: string | null;
|
||||
};
|
||||
watermarkStatus: string | null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user