task-g
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { mutationOptions } from '@tanstack/react-query';
|
||||
import { getQueryClient } from '@/lib/query-client';
|
||||
import { quotationDocumentKeys } from '@/features/crm/quotations/document/queries';
|
||||
import {
|
||||
createQuotation,
|
||||
createQuotationAttachment,
|
||||
@@ -31,6 +32,11 @@ import type {
|
||||
QuotationTopicMutationPayload
|
||||
} from './types';
|
||||
|
||||
function invalidateQuotationDocumentQueries(quotationId: string) {
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationDocumentKeys.data(quotationId) });
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationDocumentKeys.preview(quotationId) });
|
||||
}
|
||||
|
||||
export const createQuotationMutation = mutationOptions({
|
||||
mutationFn: (data: QuotationMutationPayload) => createQuotation(data),
|
||||
onSuccess: () => {
|
||||
@@ -44,6 +50,7 @@ export const updateQuotationMutation = mutationOptions({
|
||||
onSuccess: (_data, variables) => {
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.all });
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.detail(variables.id) });
|
||||
invalidateQuotationDocumentQueries(variables.id);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -61,6 +68,7 @@ export const createQuotationItemMutation = mutationOptions({
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.items(variables.quotationId) });
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.detail(variables.quotationId) });
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.all });
|
||||
invalidateQuotationDocumentQueries(variables.quotationId);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -78,6 +86,7 @@ export const updateQuotationItemMutation = mutationOptions({
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.items(variables.quotationId) });
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.detail(variables.quotationId) });
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.all });
|
||||
invalidateQuotationDocumentQueries(variables.quotationId);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -88,6 +97,7 @@ export const deleteQuotationItemMutation = mutationOptions({
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.items(variables.quotationId) });
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.detail(variables.quotationId) });
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.all });
|
||||
invalidateQuotationDocumentQueries(variables.quotationId);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -104,6 +114,7 @@ export const createQuotationCustomerMutation = mutationOptions({
|
||||
queryKey: quotationKeys.customers(variables.quotationId)
|
||||
});
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.detail(variables.quotationId) });
|
||||
invalidateQuotationDocumentQueries(variables.quotationId);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -122,6 +133,7 @@ export const updateQuotationCustomerMutation = mutationOptions({
|
||||
queryKey: quotationKeys.customers(variables.quotationId)
|
||||
});
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.detail(variables.quotationId) });
|
||||
invalidateQuotationDocumentQueries(variables.quotationId);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -133,6 +145,7 @@ export const deleteQuotationCustomerMutation = mutationOptions({
|
||||
queryKey: quotationKeys.customers(variables.quotationId)
|
||||
});
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.detail(variables.quotationId) });
|
||||
invalidateQuotationDocumentQueries(variables.quotationId);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -141,6 +154,7 @@ export const createQuotationTopicMutation = mutationOptions({
|
||||
createQuotationTopic(quotationId, values),
|
||||
onSuccess: (_data, variables) => {
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.topics(variables.quotationId) });
|
||||
invalidateQuotationDocumentQueries(variables.quotationId);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -149,6 +163,7 @@ export const updateQuotationTopicMutation = mutationOptions({
|
||||
updateQuotationTopic(quotationId, values),
|
||||
onSuccess: (_data, variables) => {
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.topics(variables.quotationId) });
|
||||
invalidateQuotationDocumentQueries(variables.quotationId);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -157,6 +172,7 @@ export const deleteQuotationTopicMutation = mutationOptions({
|
||||
deleteQuotationTopic(quotationId, topicId),
|
||||
onSuccess: (_data, variables) => {
|
||||
getQueryClient().invalidateQueries({ queryKey: quotationKeys.topics(variables.quotationId) });
|
||||
invalidateQuotationDocumentQueries(variables.quotationId);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -69,6 +69,7 @@ import type {
|
||||
QuotationTopicRecord
|
||||
} from '../api/types';
|
||||
import { submitQuotationApprovalMutation } from '@/features/foundation/approval/mutations';
|
||||
import { QuotationDocumentPreview } from './quotation-document-preview';
|
||||
import { QuotationFormSheet } from './quotation-form-sheet';
|
||||
import { QuotationApprovalTab } from './quotation-approval-tab';
|
||||
import { QuotationStatusBadge } from './quotation-status-badge';
|
||||
@@ -481,7 +482,8 @@ export function QuotationDetail({
|
||||
canReturnApproval,
|
||||
activeBusinessRole,
|
||||
isOrgAdmin,
|
||||
currentUserId
|
||||
currentUserId,
|
||||
canPreviewDocument
|
||||
}: {
|
||||
quotationId: string;
|
||||
referenceData: QuotationReferenceData;
|
||||
@@ -499,6 +501,7 @@ export function QuotationDetail({
|
||||
activeBusinessRole: string | null;
|
||||
isOrgAdmin: boolean;
|
||||
currentUserId: string;
|
||||
canPreviewDocument: boolean;
|
||||
}) {
|
||||
const { data } = useSuspenseQuery(quotationByIdOptions(quotationId));
|
||||
const { data: itemsData } = useSuspenseQuery(quotationItemsOptions(quotationId));
|
||||
@@ -1188,15 +1191,19 @@ export function QuotationDetail({
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='preview'>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Document Preview Placeholder</CardTitle>
|
||||
<CardDescription>PDF and rendered output are intentionally postponed.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState message='Production preview and PDF generation are outside Task E scope.' />
|
||||
</CardContent>
|
||||
</Card>
|
||||
{canPreviewDocument ? (
|
||||
<QuotationDocumentPreview quotationId={quotationId} />
|
||||
) : (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Document Preview</CardTitle>
|
||||
<CardDescription>Preview permission is required to load document data.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState message='You do not have access to quotation document preview.' />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</CardContent>
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
'use client';
|
||||
|
||||
import { useSuspenseQuery } from '@tanstack/react-query';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { quotationDocumentPreviewOptions } from '@/features/crm/quotations/document/queries';
|
||||
|
||||
function Field({ label, value }: { label: string; value: string | null | undefined }) {
|
||||
return (
|
||||
<div className='space-y-1'>
|
||||
<div className='text-muted-foreground text-xs'>{label}</div>
|
||||
<div className='text-sm'>{value || '-'}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function QuotationDocumentPreview({ quotationId }: { quotationId: string }) {
|
||||
const { data } = useSuspenseQuery(quotationDocumentPreviewOptions(quotationId));
|
||||
const { documentData, template } = data.preview;
|
||||
|
||||
return (
|
||||
<div className='space-y-6'>
|
||||
<Card className='overflow-hidden'>
|
||||
<CardHeader className='border-b bg-muted/20'>
|
||||
<div className='flex flex-wrap items-start justify-between gap-4'>
|
||||
<div className='space-y-1'>
|
||||
<CardTitle className='text-2xl'>{documentData.company.name}</CardTitle>
|
||||
<CardDescription>
|
||||
Quotation Preview using {template.template.templateName} v{template.version.version}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className='flex flex-wrap gap-2'>
|
||||
{documentData.watermarkStatus ? (
|
||||
<Badge variant='destructive'>{documentData.watermarkStatus}</Badge>
|
||||
) : (
|
||||
<Badge>Approved Ready</Badge>
|
||||
)}
|
||||
<Badge variant='outline'>{template.template.fileType}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className='space-y-8 p-6'>
|
||||
<div className='grid gap-6 lg:grid-cols-2'>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Quotation Header</CardTitle>
|
||||
<CardDescription>Commercial identity and issue information.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className='grid gap-4 md:grid-cols-2'>
|
||||
<Field label='Quotation Code' value={documentData.quotation.code} />
|
||||
<Field label='Revision' value={documentData.quotation.revisionLabel} />
|
||||
<Field
|
||||
label='Quotation Date'
|
||||
value={new Date(documentData.quotation.quotationDate).toLocaleDateString()}
|
||||
/>
|
||||
<Field
|
||||
label='Valid Until'
|
||||
value={
|
||||
documentData.quotation.validUntil
|
||||
? new Date(documentData.quotation.validUntil).toLocaleDateString()
|
||||
: null
|
||||
}
|
||||
/>
|
||||
<Field label='Type' value={documentData.quotation.quotationTypeLabel} />
|
||||
<Field label='Branch' value={documentData.branch?.label} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Customer Block</CardTitle>
|
||||
<CardDescription>Bill-to and attention context for the document.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className='grid gap-4 md:grid-cols-2'>
|
||||
<Field label='Customer' value={documentData.customer.name} />
|
||||
<Field label='Contact' value={documentData.contact?.name} />
|
||||
<Field label='Phone' value={documentData.customer.phone} />
|
||||
<Field label='Email' value={documentData.customer.email} />
|
||||
<div className='md:col-span-2'>
|
||||
<Field label='Address' value={documentData.customer.address} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Project Information</CardTitle>
|
||||
<CardDescription>Scope summary and reference data for the customer.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className='grid gap-4 md:grid-cols-2 xl:grid-cols-4'>
|
||||
<Field label='Project Name' value={documentData.quotation.projectName} />
|
||||
<Field label='Site Location' value={documentData.quotation.projectLocation} />
|
||||
<Field label='Attention' value={documentData.quotation.attention} />
|
||||
<Field label='Reference' value={documentData.quotation.reference} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Items Table</CardTitle>
|
||||
<CardDescription>Normalized line items prepared for template mapping.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className='space-y-3'>
|
||||
<div className='grid grid-cols-[1.2fr_4fr_1fr_1.2fr_1.4fr_1.4fr] gap-3 rounded-lg border bg-muted/20 px-4 py-3 text-xs font-medium uppercase tracking-wide'>
|
||||
<div>Item</div>
|
||||
<div>Description</div>
|
||||
<div>Qty</div>
|
||||
<div>Unit</div>
|
||||
<div>Unit Price</div>
|
||||
<div>Total</div>
|
||||
</div>
|
||||
{documentData.items.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className='grid grid-cols-[1.2fr_4fr_1fr_1.2fr_1.4fr_1.4fr] gap-3 rounded-lg border px-4 py-3 text-sm'
|
||||
>
|
||||
<div>{item.itemNumber}</div>
|
||||
<div className='space-y-1'>
|
||||
<div>{item.description}</div>
|
||||
<div className='text-muted-foreground text-xs'>{item.productTypeLabel || '-'}</div>
|
||||
</div>
|
||||
<div>{item.quantity}</div>
|
||||
<div>{item.unitLabel || '-'}</div>
|
||||
<div>{item.unitPrice.toLocaleString()}</div>
|
||||
<div>{item.totalPrice.toLocaleString()}</div>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className='grid gap-6 lg:grid-cols-[2fr_1fr]'>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Topics</CardTitle>
|
||||
<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];
|
||||
return (
|
||||
<div key={group.key} className='space-y-3'>
|
||||
<div className='font-medium'>{group.title}</div>
|
||||
{!entries.length ? (
|
||||
<div className='text-muted-foreground text-sm'>No entries</div>
|
||||
) : (
|
||||
entries.map((entry) => (
|
||||
<div key={`${group.key}-${entry.title}`} className='rounded-lg border p-4'>
|
||||
<div className='mb-2 text-sm font-medium'>{entry.title}</div>
|
||||
<ul className='list-disc space-y-1 pl-5 text-sm'>
|
||||
{entry.items.map((item) => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className='space-y-6'>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Price Summary</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className='space-y-3 text-sm'>
|
||||
<div className='flex items-center justify-between'>
|
||||
<span className='text-muted-foreground'>Subtotal</span>
|
||||
<span>{documentData.quotation.subtotal.toLocaleString()}</span>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<span className='text-muted-foreground'>Tax</span>
|
||||
<span>{documentData.quotation.taxAmount.toLocaleString()}</span>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<span className='text-muted-foreground'>Total</span>
|
||||
<span className='font-semibold'>{documentData.quotation.totalAmount.toLocaleString()}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Approval Block</CardTitle>
|
||||
<CardDescription>Prepared for watermark and approval snapshot flows.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className='space-y-4'>
|
||||
<Field label='Status' value={documentData.approval.status} />
|
||||
<Field label='Workflow' value={documentData.approval.workflowName} />
|
||||
<Field label='Approved At' value={documentData.approval.approvedAt} />
|
||||
<Separator />
|
||||
{!documentData.approval.approvers.length ? (
|
||||
<div className='text-muted-foreground text-sm'>No approval actions recorded.</div>
|
||||
) : (
|
||||
documentData.approval.approvers.map((item) => (
|
||||
<div key={`${item.stepNumber}-${item.roleCode}`} className='rounded-lg border p-3 text-sm'>
|
||||
<div className='font-medium'>
|
||||
Step {item.stepNumber} - {item.roleName}
|
||||
</div>
|
||||
<div className='text-muted-foreground'>
|
||||
{item.actorName || '-'} {item.actedAt ? `on ${new Date(item.actedAt).toLocaleString()}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Signature Placeholders</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className='space-y-3 text-sm'>
|
||||
<Field label='Prepared By' value={documentData.signatures.preparedBy} />
|
||||
<Field label='Requested By' value={documentData.signatures.requestedBy} />
|
||||
<Field label='Sales Manager' value={documentData.signatures.salesManager} />
|
||||
<Field
|
||||
label='Department Manager'
|
||||
value={documentData.signatures.departmentManager}
|
||||
/>
|
||||
<Field label='Top Manager' value={documentData.signatures.topManager} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
20
src/features/crm/quotations/document/queries.ts
Normal file
20
src/features/crm/quotations/document/queries.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { queryOptions } from '@tanstack/react-query';
|
||||
import { getQuotationDocumentData, getQuotationDocumentPreview } from './service';
|
||||
|
||||
export const quotationDocumentKeys = {
|
||||
all: ['crm-quotation-document'] as const,
|
||||
data: (id: string) => [...quotationDocumentKeys.all, 'data', id] as const,
|
||||
preview: (id: string) => [...quotationDocumentKeys.all, 'preview', id] as const
|
||||
};
|
||||
|
||||
export const quotationDocumentDataOptions = (id: string) =>
|
||||
queryOptions({
|
||||
queryKey: quotationDocumentKeys.data(id),
|
||||
queryFn: () => getQuotationDocumentData(id)
|
||||
});
|
||||
|
||||
export const quotationDocumentPreviewOptions = (id: string) =>
|
||||
queryOptions({
|
||||
queryKey: quotationDocumentKeys.preview(id),
|
||||
queryFn: () => getQuotationDocumentPreview(id)
|
||||
});
|
||||
359
src/features/crm/quotations/document/server/service.ts
Normal file
359
src/features/crm/quotations/document/server/service.ts
Normal file
@@ -0,0 +1,359 @@
|
||||
import { and, eq, inArray, isNull } from 'drizzle-orm';
|
||||
import {
|
||||
crmCustomerContacts,
|
||||
crmCustomers,
|
||||
crmQuotations,
|
||||
organizations,
|
||||
users
|
||||
} from '@/db/schema';
|
||||
import { db } from '@/lib/db';
|
||||
import { AuthError } from '@/lib/auth/session';
|
||||
import { listApprovalRequests, getApprovalRequest } from '@/features/foundation/approval/server/service';
|
||||
import {
|
||||
mapDocumentDataToTemplateInput,
|
||||
resolveTemplateForDocument,
|
||||
resolveTemplateMappings
|
||||
} from '@/features/foundation/document-template/server/service';
|
||||
import { getActiveOptionsByCategory } from '@/features/foundation/master-options/service';
|
||||
import {
|
||||
getQuotationDetail,
|
||||
listQuotationCustomers,
|
||||
listQuotationItems,
|
||||
listQuotationTopics
|
||||
} from '@/features/crm/quotations/server/service';
|
||||
import type {
|
||||
ApprovedQuotationSnapshot,
|
||||
QuotationDocumentApprovalStep,
|
||||
QuotationDocumentData
|
||||
} from '../types';
|
||||
|
||||
const DOCUMENT_OPTION_CATEGORIES = {
|
||||
branch: 'crm_branch',
|
||||
status: 'crm_quotation_status',
|
||||
quotationType: 'crm_quotation_type',
|
||||
currency: 'crm_currency',
|
||||
discountType: 'crm_discount_type',
|
||||
unit: 'crm_unit',
|
||||
customerRole: 'crm_quotation_customer_role',
|
||||
productType: 'crm_product_type'
|
||||
} as const;
|
||||
|
||||
function toRevisionLabel(revision: number) {
|
||||
return `R${String(revision).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
async function assertQuotationDocumentAccess(quotationId: string, organizationId: string) {
|
||||
const [quotation] = await db
|
||||
.select()
|
||||
.from(crmQuotations)
|
||||
.where(
|
||||
and(
|
||||
eq(crmQuotations.id, quotationId),
|
||||
eq(crmQuotations.organizationId, organizationId),
|
||||
isNull(crmQuotations.deletedAt)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!quotation) {
|
||||
throw new AuthError('Quotation not found', 404);
|
||||
}
|
||||
|
||||
return quotation;
|
||||
}
|
||||
|
||||
function findOptionLabel(
|
||||
options: Array<{ id: string; code: string; label: string }>,
|
||||
id: string | null | undefined
|
||||
) {
|
||||
return id ? options.find((option) => option.id === id)?.label ?? null : null;
|
||||
}
|
||||
|
||||
function findOptionCode(
|
||||
options: Array<{ id: string; code: string; label: string }>,
|
||||
id: string | null | undefined
|
||||
) {
|
||||
return id ? options.find((option) => option.id === id)?.code ?? null : null;
|
||||
}
|
||||
|
||||
export async function buildQuotationDocumentData(
|
||||
quotationId: string,
|
||||
organizationId: string
|
||||
): Promise<QuotationDocumentData> {
|
||||
const quotation = await assertQuotationDocumentAccess(quotationId, organizationId);
|
||||
const [
|
||||
company,
|
||||
quotationDetail,
|
||||
items,
|
||||
quotationCustomers,
|
||||
topics,
|
||||
branchOptions,
|
||||
statusOptions,
|
||||
quotationTypeOptions,
|
||||
currencyOptions,
|
||||
discountTypeOptions,
|
||||
unitOptions,
|
||||
customerRoleOptions,
|
||||
productTypeOptions,
|
||||
approvalRequests
|
||||
] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(organizations)
|
||||
.where(eq(organizations.id, organizationId))
|
||||
.then((rows) => rows[0] ?? null),
|
||||
getQuotationDetail(quotationId, organizationId),
|
||||
listQuotationItems(quotationId, organizationId),
|
||||
listQuotationCustomers(quotationId, organizationId),
|
||||
listQuotationTopics(quotationId, organizationId),
|
||||
getActiveOptionsByCategory(DOCUMENT_OPTION_CATEGORIES.branch, { organizationId }),
|
||||
getActiveOptionsByCategory(DOCUMENT_OPTION_CATEGORIES.status, { organizationId }),
|
||||
getActiveOptionsByCategory(DOCUMENT_OPTION_CATEGORIES.quotationType, { organizationId }),
|
||||
getActiveOptionsByCategory(DOCUMENT_OPTION_CATEGORIES.currency, { organizationId }),
|
||||
getActiveOptionsByCategory(DOCUMENT_OPTION_CATEGORIES.discountType, { organizationId }),
|
||||
getActiveOptionsByCategory(DOCUMENT_OPTION_CATEGORIES.unit, { organizationId }),
|
||||
getActiveOptionsByCategory(DOCUMENT_OPTION_CATEGORIES.customerRole, { organizationId }),
|
||||
getActiveOptionsByCategory(DOCUMENT_OPTION_CATEGORIES.productType, { organizationId }),
|
||||
listApprovalRequests(organizationId, { entityType: 'quotation', entityId: quotationId, limit: 20 })
|
||||
]);
|
||||
|
||||
if (!company) {
|
||||
throw new AuthError('Organization not found', 404);
|
||||
}
|
||||
|
||||
const [customer, contact, relatedCustomers, preparer] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(crmCustomers)
|
||||
.where(
|
||||
and(
|
||||
eq(crmCustomers.id, quotation.customerId),
|
||||
eq(crmCustomers.organizationId, organizationId),
|
||||
isNull(crmCustomers.deletedAt)
|
||||
)
|
||||
)
|
||||
.then((rows) => rows[0] ?? null),
|
||||
quotation.contactId
|
||||
? db
|
||||
.select()
|
||||
.from(crmCustomerContacts)
|
||||
.where(
|
||||
and(
|
||||
eq(crmCustomerContacts.id, quotation.contactId),
|
||||
eq(crmCustomerContacts.organizationId, organizationId),
|
||||
isNull(crmCustomerContacts.deletedAt)
|
||||
)
|
||||
)
|
||||
.then((rows) => rows[0] ?? null)
|
||||
: Promise.resolve(null),
|
||||
quotationCustomers.length
|
||||
? db
|
||||
.select({ id: crmCustomers.id, code: crmCustomers.code, name: crmCustomers.name })
|
||||
.from(crmCustomers)
|
||||
.where(
|
||||
and(
|
||||
eq(crmCustomers.organizationId, organizationId),
|
||||
inArray(
|
||||
crmCustomers.id,
|
||||
quotationCustomers.map((item) => item.customerId)
|
||||
),
|
||||
isNull(crmCustomers.deletedAt)
|
||||
)
|
||||
)
|
||||
: Promise.resolve([]),
|
||||
db
|
||||
.select({ id: users.id, name: users.name })
|
||||
.from(users)
|
||||
.where(eq(users.id, quotation.createdBy))
|
||||
.then((rows) => rows[0] ?? null)
|
||||
]);
|
||||
|
||||
if (!customer) {
|
||||
throw new AuthError('Customer not found', 404);
|
||||
}
|
||||
|
||||
const approvalRequest = approvalRequests.items.find((item) => item.status === 'approved') ?? approvalRequests.items[0] ?? null;
|
||||
const approvalDetail = approvalRequest
|
||||
? await getApprovalRequest(approvalRequest.id, organizationId)
|
||||
: null;
|
||||
const branch = branchOptions.find((option) => option.id === quotation.branchId) ?? null;
|
||||
const relatedCustomerMap = new Map(relatedCustomers.map((item) => [item.id, item]));
|
||||
const statusCode = findOptionCode(statusOptions, quotation.status);
|
||||
const statusLabel = findOptionLabel(statusOptions, quotation.status);
|
||||
const approvalApprovers: QuotationDocumentApprovalStep[] =
|
||||
approvalDetail?.timeline
|
||||
.filter((item) => ['approve', 'reject', 'return'].includes(item.action))
|
||||
.map((item) => {
|
||||
const step = approvalDetail.steps.find((candidate) => candidate.stepNumber === item.stepNumber);
|
||||
return {
|
||||
stepNumber: item.stepNumber,
|
||||
roleCode: step?.roleCode ?? '',
|
||||
roleName: step?.roleName ?? `Step ${item.stepNumber}`,
|
||||
action: item.action,
|
||||
actorName: item.actorName,
|
||||
actedAt: item.actedAt,
|
||||
remark: item.remark
|
||||
};
|
||||
}) ?? [];
|
||||
|
||||
return {
|
||||
company: {
|
||||
id: company.id,
|
||||
name: company.name,
|
||||
slug: company.slug,
|
||||
imageUrl: company.imageUrl,
|
||||
plan: company.plan
|
||||
},
|
||||
branch: branch
|
||||
? {
|
||||
id: branch.id,
|
||||
code: branch.code,
|
||||
label: branch.label,
|
||||
value: branch.value
|
||||
}
|
||||
: null,
|
||||
customer: {
|
||||
id: customer.id,
|
||||
code: customer.code,
|
||||
name: customer.name,
|
||||
address: customer.address,
|
||||
phone: customer.phone,
|
||||
email: customer.email,
|
||||
taxId: customer.taxId
|
||||
},
|
||||
contact: contact
|
||||
? {
|
||||
id: contact.id,
|
||||
name: contact.name,
|
||||
email: contact.email,
|
||||
mobile: contact.mobile,
|
||||
position: contact.position
|
||||
}
|
||||
: null,
|
||||
quotation: {
|
||||
id: quotationDetail.id,
|
||||
code: quotationDetail.code,
|
||||
quotationDate: quotationDetail.quotationDate,
|
||||
validUntil: quotationDetail.validUntil,
|
||||
projectName: quotationDetail.projectName,
|
||||
projectLocation: quotationDetail.projectLocation,
|
||||
attention: quotationDetail.attention,
|
||||
reference: quotationDetail.reference,
|
||||
revision: quotationDetail.revision,
|
||||
revisionLabel: toRevisionLabel(quotationDetail.revision),
|
||||
statusCode,
|
||||
statusLabel,
|
||||
quotationTypeCode: findOptionCode(quotationTypeOptions, quotationDetail.quotationType),
|
||||
quotationTypeLabel: findOptionLabel(quotationTypeOptions, quotationDetail.quotationType),
|
||||
currencyCode: findOptionCode(currencyOptions, quotationDetail.currency),
|
||||
currencyLabel: findOptionLabel(currencyOptions, quotationDetail.currency),
|
||||
exchangeRate: quotationDetail.exchangeRate,
|
||||
subtotal: quotationDetail.subtotal,
|
||||
discount: quotationDetail.discount,
|
||||
discountTypeCode: findOptionCode(discountTypeOptions, quotationDetail.discountType),
|
||||
discountTypeLabel: findOptionLabel(discountTypeOptions, quotationDetail.discountType),
|
||||
taxRate: quotationDetail.taxRate,
|
||||
taxAmount: quotationDetail.taxAmount,
|
||||
totalAmount: quotationDetail.totalAmount,
|
||||
notes: quotationDetail.notes
|
||||
},
|
||||
items: items.map((item) => ({
|
||||
id: item.id,
|
||||
itemNumber: item.itemNumber,
|
||||
productTypeCode: findOptionCode(productTypeOptions, item.productType),
|
||||
productTypeLabel: findOptionLabel(productTypeOptions, item.productType),
|
||||
description: item.description,
|
||||
quantity: item.quantity,
|
||||
unitCode: findOptionCode(unitOptions, item.unit),
|
||||
unitLabel: findOptionLabel(unitOptions, item.unit),
|
||||
unitPrice: item.unitPrice,
|
||||
discount: item.discount,
|
||||
discountTypeCode: findOptionCode(discountTypeOptions, item.discountType),
|
||||
taxRate: item.taxRate,
|
||||
totalPrice: item.totalPrice,
|
||||
notes: item.notes
|
||||
})),
|
||||
quotationCustomers: quotationCustomers.map((item) => ({
|
||||
id: item.id,
|
||||
customerId: item.customerId,
|
||||
customerName: relatedCustomerMap.get(item.customerId)?.name ?? item.customerName,
|
||||
customerCode: relatedCustomerMap.get(item.customerId)?.code ?? item.customerCode,
|
||||
roleCode: item.role,
|
||||
roleLabel: findOptionLabel(customerRoleOptions, item.role),
|
||||
isPrimary: item.isPrimary
|
||||
})),
|
||||
topics: {
|
||||
scope: topics
|
||||
.filter((item) => item.topicType === 'scope')
|
||||
.map((item) => ({ title: item.title, items: item.items.map((child) => child.content) })),
|
||||
exclusion: topics
|
||||
.filter((item) => item.topicType === 'exclusion')
|
||||
.map((item) => ({ title: item.title, items: item.items.map((child) => child.content) })),
|
||||
payment: topics
|
||||
.filter((item) => item.topicType === 'payment')
|
||||
.map((item) => ({ title: item.title, items: item.items.map((child) => child.content) })),
|
||||
other: topics
|
||||
.filter((item) => !['scope', 'exclusion', 'payment'].includes(item.topicType))
|
||||
.map((item) => ({ title: item.title, items: item.items.map((child) => child.content) }))
|
||||
},
|
||||
approval: {
|
||||
requestId: approvalDetail?.request.id ?? null,
|
||||
workflowName: approvalDetail?.workflow.name ?? null,
|
||||
status: approvalDetail?.request.status ?? null,
|
||||
approvedAt:
|
||||
approvalDetail?.request.status === 'approved' ? approvalDetail.request.completedAt : null,
|
||||
currentStep: approvalDetail?.request.currentStep ?? null,
|
||||
currentStepRoleName: approvalDetail?.currentStep?.roleName ?? null,
|
||||
approvers: approvalApprovers
|
||||
},
|
||||
signatures: {
|
||||
preparedBy: preparer?.name ?? null,
|
||||
requestedBy: contact?.name ?? customer.name,
|
||||
salesManager:
|
||||
approvalApprovers.find((item) => item.roleCode === 'sales_manager')?.actorName ?? null,
|
||||
departmentManager:
|
||||
approvalApprovers.find((item) => item.roleCode === 'department_manager')?.actorName ?? null,
|
||||
topManager: approvalApprovers.find((item) => item.roleCode === 'top_manager')?.actorName ?? null
|
||||
},
|
||||
watermarkStatus: statusCode && statusCode !== 'approved' ? statusLabel ?? statusCode : null
|
||||
};
|
||||
}
|
||||
|
||||
export async function getQuotationDocumentPreviewData(
|
||||
quotationId: string,
|
||||
organizationId: string
|
||||
) {
|
||||
const documentData = await buildQuotationDocumentData(quotationId, organizationId);
|
||||
const template = await resolveTemplateForDocument(organizationId, {
|
||||
documentType: 'quotation',
|
||||
productType: 'default',
|
||||
fileType: 'pdfme'
|
||||
});
|
||||
const mappings = await resolveTemplateMappings(template.version.id, organizationId);
|
||||
const templateInput = mapDocumentDataToTemplateInput(
|
||||
documentData as unknown as Record<string, unknown>,
|
||||
mappings
|
||||
);
|
||||
|
||||
return {
|
||||
documentData,
|
||||
template,
|
||||
mappings,
|
||||
templateInput
|
||||
};
|
||||
}
|
||||
|
||||
export async function prepareApprovedQuotationSnapshot(
|
||||
quotationId: string,
|
||||
organizationId: string
|
||||
): Promise<ApprovedQuotationSnapshot> {
|
||||
const preview = await getQuotationDocumentPreviewData(quotationId, organizationId);
|
||||
|
||||
return {
|
||||
quotationId,
|
||||
approvedAt: preview.documentData.approval.approvedAt,
|
||||
documentData: preview.documentData,
|
||||
templateVersionId: preview.template.version.id,
|
||||
templateInput: preview.templateInput
|
||||
};
|
||||
}
|
||||
13
src/features/crm/quotations/document/service.ts
Normal file
13
src/features/crm/quotations/document/service.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import type {
|
||||
QuotationDocumentDataResponse,
|
||||
QuotationDocumentPreviewResponse
|
||||
} from './types';
|
||||
|
||||
export async function getQuotationDocumentData(id: string) {
|
||||
return apiClient<QuotationDocumentDataResponse>(`/crm/quotations/${id}/document-data`);
|
||||
}
|
||||
|
||||
export async function getQuotationDocumentPreview(id: string) {
|
||||
return apiClient<QuotationDocumentPreviewResponse>(`/crm/quotations/${id}/document-preview`);
|
||||
}
|
||||
153
src/features/crm/quotations/document/types.ts
Normal file
153
src/features/crm/quotations/document/types.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
import type {
|
||||
DocumentTemplateMappingWithColumns,
|
||||
ResolvedDocumentTemplate
|
||||
} from '@/features/foundation/document-template/types';
|
||||
|
||||
export interface QuotationDocumentTopicGroup {
|
||||
title: string;
|
||||
items: string[];
|
||||
}
|
||||
|
||||
export interface QuotationDocumentApprovalStep {
|
||||
stepNumber: number;
|
||||
roleCode: string;
|
||||
roleName: string;
|
||||
action: string;
|
||||
actorName: string | null;
|
||||
actedAt: string | null;
|
||||
remark: string | null;
|
||||
}
|
||||
|
||||
export interface QuotationDocumentData {
|
||||
company: {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
imageUrl: string | null;
|
||||
plan: string;
|
||||
};
|
||||
branch: {
|
||||
id: string;
|
||||
code: string;
|
||||
label: string;
|
||||
value: string | null;
|
||||
} | null;
|
||||
customer: {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
address: string | null;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
taxId: string | null;
|
||||
};
|
||||
contact: {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
mobile: string | null;
|
||||
position: string | null;
|
||||
} | null;
|
||||
quotation: {
|
||||
id: string;
|
||||
code: string;
|
||||
quotationDate: string;
|
||||
validUntil: string | null;
|
||||
projectName: string | null;
|
||||
projectLocation: string | null;
|
||||
attention: string | null;
|
||||
reference: string | null;
|
||||
revision: number;
|
||||
revisionLabel: string;
|
||||
statusCode: string | null;
|
||||
statusLabel: string | null;
|
||||
quotationTypeCode: string | null;
|
||||
quotationTypeLabel: string | null;
|
||||
currencyCode: string | null;
|
||||
currencyLabel: string | null;
|
||||
exchangeRate: number;
|
||||
subtotal: number;
|
||||
discount: number;
|
||||
discountTypeCode: string | null;
|
||||
discountTypeLabel: string | null;
|
||||
taxRate: number;
|
||||
taxAmount: number;
|
||||
totalAmount: number;
|
||||
notes: string | null;
|
||||
};
|
||||
items: Array<{
|
||||
id: string;
|
||||
itemNumber: number;
|
||||
productTypeCode: string | null;
|
||||
productTypeLabel: string | null;
|
||||
description: string;
|
||||
quantity: number;
|
||||
unitCode: string | null;
|
||||
unitLabel: string | null;
|
||||
unitPrice: number;
|
||||
discount: number;
|
||||
discountTypeCode: string | null;
|
||||
taxRate: number;
|
||||
totalPrice: number;
|
||||
notes: string | null;
|
||||
}>;
|
||||
quotationCustomers: Array<{
|
||||
id: string;
|
||||
customerId: string;
|
||||
customerName: string;
|
||||
customerCode: string;
|
||||
roleCode: string;
|
||||
roleLabel: string | null;
|
||||
isPrimary: boolean;
|
||||
}>;
|
||||
topics: {
|
||||
scope: QuotationDocumentTopicGroup[];
|
||||
exclusion: QuotationDocumentTopicGroup[];
|
||||
payment: QuotationDocumentTopicGroup[];
|
||||
other: QuotationDocumentTopicGroup[];
|
||||
};
|
||||
approval: {
|
||||
requestId: string | null;
|
||||
workflowName: string | null;
|
||||
status: string | null;
|
||||
approvedAt: string | null;
|
||||
currentStep: number | null;
|
||||
currentStepRoleName: string | null;
|
||||
approvers: QuotationDocumentApprovalStep[];
|
||||
};
|
||||
signatures: {
|
||||
preparedBy: string | null;
|
||||
requestedBy: string | null;
|
||||
salesManager: string | null;
|
||||
departmentManager: string | null;
|
||||
topManager: string | null;
|
||||
};
|
||||
watermarkStatus: string | null;
|
||||
}
|
||||
|
||||
export interface QuotationDocumentDataResponse {
|
||||
success: boolean;
|
||||
time: string;
|
||||
message: string;
|
||||
documentData: QuotationDocumentData;
|
||||
}
|
||||
|
||||
export interface QuotationDocumentPreviewResponse {
|
||||
success: boolean;
|
||||
time: string;
|
||||
message: string;
|
||||
preview: {
|
||||
documentData: QuotationDocumentData;
|
||||
template: ResolvedDocumentTemplate;
|
||||
mappings: DocumentTemplateMappingWithColumns[];
|
||||
templateInput: Record<string, unknown>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ApprovedQuotationSnapshot {
|
||||
quotationId: string;
|
||||
approvedAt: string | null;
|
||||
documentData: QuotationDocumentData;
|
||||
templateVersionId: string;
|
||||
templateInput: Record<string, unknown>;
|
||||
}
|
||||
Reference in New Issue
Block a user