u
This commit is contained in:
@@ -987,6 +987,11 @@
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/ManifestLine'
|
||||
* files:
|
||||
* type: array
|
||||
* description: Attached documents (e.g. quote PDF) for the quote
|
||||
* items:
|
||||
* $ref: '#/components/schemas/DeliveryFile'
|
||||
* OrderSummary:
|
||||
* type: object
|
||||
* required: [id, number, type, entityId, date]
|
||||
@@ -1293,6 +1298,11 @@
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/Shipping'
|
||||
* files:
|
||||
* type: array
|
||||
* description: Attached documents (e.g. shipment label PDF) for the shipment
|
||||
* items:
|
||||
* $ref: '#/components/schemas/DeliveryFile'
|
||||
* Package:
|
||||
* type: object
|
||||
* required: [id, shippingId, entityaddressId, number, type, state]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import multer from 'multer';
|
||||
import * as db from '../../db/delivery.js';
|
||||
import { createAndAttachManifestPdf } from '../../services/manifestPdf.js';
|
||||
import { writeErrorLog } from '../../util/errorLog.js';
|
||||
|
||||
// #region Helpers
|
||||
@@ -902,4 +903,97 @@ export function register(app, basePath = '') {
|
||||
app.get(`${basePath}/delivery/:id/files/:fileId`, handleGetDeliveryFile);
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /delivery/{id}/pdf:
|
||||
* post:
|
||||
* tags: [Delivery]
|
||||
* summary: Generate and attach delivery note PDF (goods receipt)
|
||||
* description: |
|
||||
* Generates an A4 PDF document for the goods receipt / delivery note with line items and quantities.
|
||||
* Attaches the PDF as a `manifestattachment` to the delivery.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [delivery]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Delivery ID
|
||||
* responses:
|
||||
* 201:
|
||||
* description: PDF generated and attached to delivery
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [attachment, fileUrl]
|
||||
* properties:
|
||||
* attachment:
|
||||
* $ref: '#/components/schemas/DeliveryFile'
|
||||
* fileUrl:
|
||||
* type: string
|
||||
* example: /delivery/1/file/5
|
||||
* 400:
|
||||
* description: Invalid ID or no company selected
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Delivery not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region POST /delivery/:id/pdf
|
||||
|
||||
app.post(`${basePath}/delivery/:id/pdf`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const id = Number(req.params.id);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
return res.status(400).json({ error: 'id is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const { attachment } = await createAndAttachManifestPdf(
|
||||
req.user.id,
|
||||
selected.companyId,
|
||||
id,
|
||||
'delivery'
|
||||
);
|
||||
|
||||
res.status(201).json({
|
||||
attachment,
|
||||
fileUrl: `/delivery/${id}/file/${attachment.fileId}`,
|
||||
});
|
||||
} catch (error) {
|
||||
const status = deliveryErrorStatus(error);
|
||||
if (status === 500) console.error('Create delivery PDF failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as db from '../../db/order.js';
|
||||
import { createAndAttachManifestPdf } from '../../services/manifestPdf.js';
|
||||
|
||||
// #region Helpers
|
||||
|
||||
@@ -15,6 +16,8 @@ function orderErrorStatus(error) {
|
||||
if (error.message === 'Not authorized') return 403;
|
||||
if (error.message === 'Company not found') return 404;
|
||||
if (error.message === 'Order not found') return 404;
|
||||
if (error.message === 'Manifest not found') return 404;
|
||||
if (error.message === 'Attachment not found') return 404;
|
||||
if (error.message === 'Entity not found') return 404;
|
||||
if (error.message === 'Article not found') return 404;
|
||||
if (error.message === 'Invalid entityId') return 400;
|
||||
@@ -23,6 +26,9 @@ function orderErrorStatus(error) {
|
||||
if (error.message === 'Invalid offset') return 400;
|
||||
if (error.message === 'Invalid limit') return 400;
|
||||
if (error.message === 'Invalid seekMonths') return 400;
|
||||
if (error.message === 'File name required') return 400;
|
||||
if (error.message === 'Mimetype required') return 400;
|
||||
if (error.message === 'Content required') return 400;
|
||||
if (error.message?.includes('parent article') || error.message?.includes('A parent article')) return 400;
|
||||
return 500;
|
||||
}
|
||||
@@ -567,4 +573,210 @@ export function register(app, basePath = '') {
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /order/{id}/pdf:
|
||||
* post:
|
||||
* tags: [Order]
|
||||
* summary: Generate and attach order PDF
|
||||
* description: |
|
||||
* Generates an A4 PDF document for the sales order with line items, prices, and tax breakdown.
|
||||
* Attaches the PDF as a `manifestattachment` to the order so it can be printed or archived.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [order]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Order ID
|
||||
* responses:
|
||||
* 201:
|
||||
* description: PDF generated and attached to order
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [attachment, fileUrl]
|
||||
* properties:
|
||||
* attachment:
|
||||
* $ref: '#/components/schemas/DeliveryFile'
|
||||
* fileUrl:
|
||||
* type: string
|
||||
* example: /order/1/file/5
|
||||
* 400:
|
||||
* description: Invalid ID or no company selected
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Order not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region POST /order/:id/pdf
|
||||
|
||||
app.post(`${basePath}/order/:id/pdf`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const id = Number(req.params.id);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
return res.status(400).json({ error: 'id is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const { attachment } = await createAndAttachManifestPdf(
|
||||
req.user.id,
|
||||
selected.companyId,
|
||||
id,
|
||||
'order'
|
||||
);
|
||||
|
||||
res.status(201).json({
|
||||
attachment,
|
||||
fileUrl: `/order/${id}/file/${attachment.fileId}`,
|
||||
});
|
||||
} catch (error) {
|
||||
const status = orderErrorStatus(error);
|
||||
if (status === 500) console.error('Create order PDF failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /order/{id}/file/{fileId}:
|
||||
* get:
|
||||
* tags: [Order]
|
||||
* summary: Get order attachment file content
|
||||
* description: |
|
||||
* Returns the full binary content of an attached file (e.g. order PDF)
|
||||
* for the specified order. Supports HTTP caching via ETag (SHA-256 hash) and 304 Not Modified.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Order ID
|
||||
* - in: path
|
||||
* name: fileId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: File ID or attachment ID
|
||||
* - in: query
|
||||
* name: download
|
||||
* required: false
|
||||
* schema:
|
||||
* type: boolean
|
||||
* description: When true, sets Content-Disposition to attachment instead of inline
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Binary file content
|
||||
* content:
|
||||
* application/pdf:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* application/octet-stream:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* 304:
|
||||
* description: Not modified
|
||||
* 400:
|
||||
* description: Invalid ID or no company selected
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Order or file not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region GET /order/:id/file/:fileId
|
||||
|
||||
app.get(`${basePath}/order/:id/file/:fileId`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const id = Number(req.params.id);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
return res.status(400).json({ error: 'id is required' });
|
||||
}
|
||||
|
||||
const fileId = Number(req.params.fileId);
|
||||
if (!Number.isInteger(fileId) || fileId <= 0) {
|
||||
return res.status(400).json({ error: 'fileId is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const attachment = await db.getFile(req.user.id, id, fileId);
|
||||
|
||||
if (attachment.hash) {
|
||||
const etag = `"${attachment.hash}"`;
|
||||
res.setHeader('ETag', etag);
|
||||
const ifNoneMatch = req.headers['if-none-match'];
|
||||
if (ifNoneMatch === etag || ifNoneMatch === attachment.hash) {
|
||||
return res.status(304).end();
|
||||
}
|
||||
}
|
||||
|
||||
const isDownload = req.query.download === '1' || req.query.download === 'true';
|
||||
const dispositionType = isDownload ? 'attachment' : 'inline';
|
||||
const filename = attachment.name || `file-${attachment.fileId}`;
|
||||
const asciiName = filename.replace(/["\r\n\\]/g, '_');
|
||||
const encodedName = encodeURIComponent(filename).replace(/['()]/g, escape);
|
||||
|
||||
res.setHeader('Content-Type', attachment.mimetype || 'application/octet-stream');
|
||||
res.setHeader('Content-Disposition', `${dispositionType}; filename="${asciiName}"; filename*=UTF-8''${encodedName}`);
|
||||
res.setHeader('Cache-Control', 'private, max-age=86400');
|
||||
|
||||
if (attachment.content && Buffer.isBuffer(attachment.content)) {
|
||||
res.setHeader('Content-Length', String(attachment.content.length));
|
||||
return res.status(200).send(attachment.content);
|
||||
} else {
|
||||
const buffer = Buffer.from(attachment.content || '');
|
||||
res.setHeader('Content-Length', String(buffer.length));
|
||||
return res.status(200).send(buffer);
|
||||
}
|
||||
} catch (error) {
|
||||
const status = orderErrorStatus(error);
|
||||
if (status === 500) console.error('Get order file failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as db from '../../db/quote.js';
|
||||
import { createAndAttachManifestPdf } from '../../services/manifestPdf.js';
|
||||
|
||||
// #region Helpers
|
||||
|
||||
@@ -15,11 +16,16 @@ function quoteErrorStatus(error) {
|
||||
if (error.message === 'Not authorized') return 403;
|
||||
if (error.message === 'Company not found') return 404;
|
||||
if (error.message === 'Quote not found') return 404;
|
||||
if (error.message === 'Manifest not found') return 404;
|
||||
if (error.message === 'Attachment not found') return 404;
|
||||
if (error.message === 'Entity not found') return 404;
|
||||
if (error.message === 'Article not found') return 404;
|
||||
if (error.message === 'Invalid entityId') return 400;
|
||||
if (error.message === 'Invalid quote') return 400;
|
||||
if (error.message === 'Invalid lines') return 400;
|
||||
if (error.message === 'File name required') return 400;
|
||||
if (error.message === 'Mimetype required') return 400;
|
||||
if (error.message === 'Content required') return 400;
|
||||
if (error.message?.includes('parent article') || error.message?.includes('A parent article')) return 400;
|
||||
return 500;
|
||||
}
|
||||
@@ -546,4 +552,210 @@ export function register(app, basePath = '') {
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /quote/{id}/pdf:
|
||||
* post:
|
||||
* tags: [Quote]
|
||||
* summary: Generate and attach quote PDF
|
||||
* description: |
|
||||
* Generates an A4 PDF document for the quote with prices, net sum, and tax breakdown.
|
||||
* Stores the PDF as a `manifestattachment` for printing or downloading.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [quote]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Quote ID
|
||||
* responses:
|
||||
* 201:
|
||||
* description: PDF generated and attached to quote
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [attachment, fileUrl]
|
||||
* properties:
|
||||
* attachment:
|
||||
* $ref: '#/components/schemas/DeliveryFile'
|
||||
* fileUrl:
|
||||
* type: string
|
||||
* example: /quote/1/file/5
|
||||
* 400:
|
||||
* description: Invalid ID or no company selected
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Quote not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region POST /quote/:id/pdf
|
||||
|
||||
app.post(`${basePath}/quote/:id/pdf`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const id = Number(req.params.id);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
return res.status(400).json({ error: 'id is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const { attachment } = await createAndAttachManifestPdf(
|
||||
req.user.id,
|
||||
selected.companyId,
|
||||
id,
|
||||
'quote'
|
||||
);
|
||||
|
||||
res.status(201).json({
|
||||
attachment,
|
||||
fileUrl: `/quote/${id}/file/${attachment.fileId}`,
|
||||
});
|
||||
} catch (error) {
|
||||
const status = quoteErrorStatus(error);
|
||||
if (status === 500) console.error('Create quote PDF failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /quote/{id}/file/{fileId}:
|
||||
* get:
|
||||
* tags: [Quote]
|
||||
* summary: Get quote attachment file content
|
||||
* description: |
|
||||
* Returns the full binary content of an attached file (e.g. quote PDF)
|
||||
* for the specified quote. Supports HTTP caching via ETag (SHA-256 hash) and 304 Not Modified.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Quote ID
|
||||
* - in: path
|
||||
* name: fileId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: File ID or attachment ID
|
||||
* - in: query
|
||||
* name: download
|
||||
* required: false
|
||||
* schema:
|
||||
* type: boolean
|
||||
* description: When true, sets Content-Disposition to attachment instead of inline
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Binary file content
|
||||
* content:
|
||||
* application/pdf:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* application/octet-stream:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* 304:
|
||||
* description: Not modified
|
||||
* 400:
|
||||
* description: Invalid ID or no company selected
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Quote or file not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region GET /quote/:id/file/:fileId
|
||||
|
||||
app.get(`${basePath}/quote/:id/file/:fileId`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const id = Number(req.params.id);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
return res.status(400).json({ error: 'id is required' });
|
||||
}
|
||||
|
||||
const fileId = Number(req.params.fileId);
|
||||
if (!Number.isInteger(fileId) || fileId <= 0) {
|
||||
return res.status(400).json({ error: 'fileId is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const attachment = await db.getFile(req.user.id, id, fileId);
|
||||
|
||||
if (attachment.hash) {
|
||||
const etag = `"${attachment.hash}"`;
|
||||
res.setHeader('ETag', etag);
|
||||
const ifNoneMatch = req.headers['if-none-match'];
|
||||
if (ifNoneMatch === etag || ifNoneMatch === attachment.hash) {
|
||||
return res.status(304).end();
|
||||
}
|
||||
}
|
||||
|
||||
const isDownload = req.query.download === '1' || req.query.download === 'true';
|
||||
const dispositionType = isDownload ? 'attachment' : 'inline';
|
||||
const filename = attachment.name || `file-${attachment.fileId}`;
|
||||
const asciiName = filename.replace(/["\r\n\\]/g, '_');
|
||||
const encodedName = encodeURIComponent(filename).replace(/['()]/g, escape);
|
||||
|
||||
res.setHeader('Content-Type', attachment.mimetype || 'application/octet-stream');
|
||||
res.setHeader('Content-Disposition', `${dispositionType}; filename="${asciiName}"; filename*=UTF-8''${encodedName}`);
|
||||
res.setHeader('Cache-Control', 'private, max-age=86400');
|
||||
|
||||
if (attachment.content && Buffer.isBuffer(attachment.content)) {
|
||||
res.setHeader('Content-Length', String(attachment.content.length));
|
||||
return res.status(200).send(attachment.content);
|
||||
} else {
|
||||
const buffer = Buffer.from(attachment.content || '');
|
||||
res.setHeader('Content-Length', String(buffer.length));
|
||||
return res.status(200).send(buffer);
|
||||
}
|
||||
} catch (error) {
|
||||
const status = quoteErrorStatus(error);
|
||||
if (status === 500) console.error('Get quote file failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as db from '../../db/shipment.js';
|
||||
import { createAndAttachManifestPdf } from '../../services/manifestPdf.js';
|
||||
import { emit } from '../sse.js';
|
||||
|
||||
// #region Helpers
|
||||
@@ -383,4 +384,212 @@ export function register(app, basePath = '') {
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /shipment/{id}/pdf:
|
||||
* post:
|
||||
* tags: [Shipment]
|
||||
* summary: Generate and attach shipment PDF (delivery note)
|
||||
* description: |
|
||||
* Generates an A4 delivery note PDF document for the shipment with line items and package tracking.
|
||||
* Shipping slips contain no price information.
|
||||
* Attaches the PDF as a `manifestattachment` to the shipment so it can be printed or attached to packages.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* x-signals: [shipment]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Shipment ID
|
||||
* responses:
|
||||
* 201:
|
||||
* description: PDF generated and attached to shipment
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [attachment, fileUrl]
|
||||
* properties:
|
||||
* attachment:
|
||||
* $ref: '#/components/schemas/DeliveryFile'
|
||||
* fileUrl:
|
||||
* type: string
|
||||
* example: /shipment/1/file/5
|
||||
* 400:
|
||||
* description: Invalid ID or no company selected
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 403:
|
||||
* description: Not authorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Shipment not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region POST /shipment/:id/pdf
|
||||
|
||||
app.post(`${basePath}/shipment/:id/pdf`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const parsedId = parsePositiveInt(req.params.id, 'id');
|
||||
if (parsedId.error) {
|
||||
return res.status(400).json({ error: parsedId.error });
|
||||
}
|
||||
|
||||
try {
|
||||
const { attachment } = await createAndAttachManifestPdf(
|
||||
req.user.id,
|
||||
selected.companyId,
|
||||
parsedId.id,
|
||||
'shipment'
|
||||
);
|
||||
|
||||
res.status(201).json({
|
||||
attachment,
|
||||
fileUrl: `/shipment/${parsedId.id}/file/${attachment.fileId}`,
|
||||
});
|
||||
} catch (error) {
|
||||
const status = shipmentErrorStatus(error);
|
||||
if (status === 500) console.error('Create shipment PDF failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /shipment/{id}/file/{fileId}:
|
||||
* get:
|
||||
* tags: [Shipment]
|
||||
* summary: Get shipment attachment file content
|
||||
* description: |
|
||||
* Returns the full binary content of an attached file (e.g. shipment delivery note PDF)
|
||||
* for the specified shipment. Supports HTTP caching via ETag (SHA-256 hash) and 304 Not Modified.
|
||||
* security:
|
||||
* - cookieAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Shipment ID
|
||||
* - in: path
|
||||
* name: fileId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: File ID or attachment ID
|
||||
* - in: query
|
||||
* name: download
|
||||
* required: false
|
||||
* schema:
|
||||
* type: boolean
|
||||
* description: When true, sets Content-Disposition to attachment instead of inline
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Binary file content
|
||||
* content:
|
||||
* application/pdf:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* application/octet-stream:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* 304:
|
||||
* description: Not modified
|
||||
* 400:
|
||||
* description: Invalid ID or no company selected
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
* 404:
|
||||
* description: Shipment or file not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/Error'
|
||||
*/
|
||||
// #region GET /shipment/:id/file/:fileId
|
||||
|
||||
app.get(`${basePath}/shipment/:id/file/:fileId`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const parsedId = parsePositiveInt(req.params.id, 'id');
|
||||
if (parsedId.error) {
|
||||
return res.status(400).json({ error: parsedId.error });
|
||||
}
|
||||
|
||||
const parsedFileId = parsePositiveInt(req.params.fileId, 'fileId');
|
||||
if (parsedFileId.error) {
|
||||
return res.status(400).json({ error: parsedFileId.error });
|
||||
}
|
||||
|
||||
try {
|
||||
const attachment = await db.getFile(req.user.id, parsedId.id, parsedFileId.id);
|
||||
|
||||
if (attachment.hash) {
|
||||
const etag = `"${attachment.hash}"`;
|
||||
res.setHeader('ETag', etag);
|
||||
const ifNoneMatch = req.headers['if-none-match'];
|
||||
if (ifNoneMatch === etag || ifNoneMatch === attachment.hash) {
|
||||
return res.status(304).end();
|
||||
}
|
||||
}
|
||||
|
||||
const isDownload = req.query.download === '1' || req.query.download === 'true';
|
||||
const dispositionType = isDownload ? 'attachment' : 'inline';
|
||||
const filename = attachment.name || `file-${attachment.fileId}`;
|
||||
const asciiName = filename.replace(/["\r\n\\]/g, '_');
|
||||
const encodedName = encodeURIComponent(filename).replace(/['()]/g, escape);
|
||||
|
||||
res.setHeader('Content-Type', attachment.mimetype || 'application/octet-stream');
|
||||
res.setHeader('Content-Disposition', `${dispositionType}; filename="${asciiName}"; filename*=UTF-8''${encodedName}`);
|
||||
res.setHeader('Cache-Control', 'private, max-age=86400');
|
||||
|
||||
if (attachment.content && Buffer.isBuffer(attachment.content)) {
|
||||
res.setHeader('Content-Length', String(attachment.content.length));
|
||||
return res.status(200).send(attachment.content);
|
||||
} else {
|
||||
const buffer = Buffer.from(attachment.content || '');
|
||||
res.setHeader('Content-Length', String(buffer.length));
|
||||
return res.status(200).send(buffer);
|
||||
}
|
||||
} catch (error) {
|
||||
const status = shipmentErrorStatus(error);
|
||||
if (status === 500) console.error('Get shipment file failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// #endregion
|
||||
}
|
||||
|
||||
|
||||
@@ -29,3 +29,14 @@ export async function getFile(googleAuthId, deliveryId, fileId) {
|
||||
const store = await getStore();
|
||||
return store.manifestattachment.getById(googleAuthId, deliveryId, fileId);
|
||||
}
|
||||
|
||||
export async function addAttachment(googleAuthId, deliveryId, data) {
|
||||
const store = await getStore();
|
||||
return store.manifestattachment.add(googleAuthId, deliveryId, data);
|
||||
}
|
||||
|
||||
export async function listAttachments(googleAuthId, deliveryId) {
|
||||
const store = await getStore();
|
||||
return store.manifestattachment.listByManifestId(googleAuthId, deliveryId);
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ function calculateTotalQuantity(lines = []) {
|
||||
return Math.round(qty * 1000) / 1000;
|
||||
}
|
||||
|
||||
function enrichQuote(quote) {
|
||||
function enrichQuote(quote, files = []) {
|
||||
if (!quote) return quote;
|
||||
const lines = Array.isArray(quote.lines) ? quote.lines : [];
|
||||
const positions = quote.positions !== undefined ? quote.positions : lines.length;
|
||||
@@ -38,6 +38,7 @@ function enrichQuote(quote) {
|
||||
positions,
|
||||
grossTotal,
|
||||
totalQuantity,
|
||||
files: Array.isArray(files) ? files : (quote.files || []),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -45,12 +46,12 @@ export async function list(googleAuthId, opts) {
|
||||
const store = await getStore();
|
||||
const result = await store.quote.list(googleAuthId, opts);
|
||||
if (Array.isArray(result)) {
|
||||
return result.map(enrichQuote);
|
||||
return result.map((q) => enrichQuote(q));
|
||||
}
|
||||
if (result && Array.isArray(result.quotes)) {
|
||||
return {
|
||||
...result,
|
||||
quotes: result.quotes.map(enrichQuote),
|
||||
quotes: result.quotes.map((q) => enrichQuote(q)),
|
||||
};
|
||||
}
|
||||
return result;
|
||||
@@ -58,8 +59,11 @@ export async function list(googleAuthId, opts) {
|
||||
|
||||
export async function getById(googleAuthId, id) {
|
||||
const store = await getStore();
|
||||
const quote = await store.quote.getById(googleAuthId, id);
|
||||
return enrichQuote(quote);
|
||||
const [quote, files] = await Promise.all([
|
||||
store.quote.getById(googleAuthId, id),
|
||||
store.manifestattachment.listByManifestId(googleAuthId, id).catch(() => []),
|
||||
]);
|
||||
return enrichQuote(quote, files);
|
||||
}
|
||||
|
||||
export async function create(googleAuthId, data) {
|
||||
@@ -83,3 +87,19 @@ export async function rebuildSummaries(googleAuthId) {
|
||||
const store = await getStore();
|
||||
return store.quote.rebuildSummaries(googleAuthId);
|
||||
}
|
||||
|
||||
export async function getFile(googleAuthId, quoteId, fileId) {
|
||||
const store = await getStore();
|
||||
return store.manifestattachment.getById(googleAuthId, quoteId, fileId);
|
||||
}
|
||||
|
||||
export async function addAttachment(googleAuthId, quoteId, data) {
|
||||
const store = await getStore();
|
||||
return store.manifestattachment.add(googleAuthId, quoteId, data);
|
||||
}
|
||||
|
||||
export async function listAttachments(googleAuthId, quoteId) {
|
||||
const store = await getStore();
|
||||
return store.manifestattachment.listByManifestId(googleAuthId, quoteId);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,15 @@ export async function create(googleAuthId, data) {
|
||||
|
||||
export async function getById(googleAuthId, id) {
|
||||
const store = await getStore();
|
||||
return store.shipment.getById(googleAuthId, id);
|
||||
const [shipment, files] = await Promise.all([
|
||||
store.shipment.getById(googleAuthId, id),
|
||||
store.manifestattachment.listByManifestId(googleAuthId, id).catch(() => []),
|
||||
]);
|
||||
if (!shipment) return shipment;
|
||||
return {
|
||||
...shipment,
|
||||
files: Array.isArray(files) ? files : [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function listByOrderId(googleAuthId, orderId) {
|
||||
@@ -19,3 +27,19 @@ export async function remove(googleAuthId, id) {
|
||||
const store = await getStore();
|
||||
return store.shipment.delete(googleAuthId, id);
|
||||
}
|
||||
|
||||
export async function getFile(googleAuthId, shipmentId, fileId) {
|
||||
const store = await getStore();
|
||||
return store.manifestattachment.getById(googleAuthId, shipmentId, fileId);
|
||||
}
|
||||
|
||||
export async function addAttachment(googleAuthId, shipmentId, data) {
|
||||
const store = await getStore();
|
||||
return store.manifestattachment.add(googleAuthId, shipmentId, data);
|
||||
}
|
||||
|
||||
export async function listAttachments(googleAuthId, shipmentId) {
|
||||
const store = await getStore();
|
||||
return store.manifestattachment.listByManifestId(googleAuthId, shipmentId);
|
||||
}
|
||||
|
||||
|
||||
766
src/services/manifestPdf.js
Normal file
766
src/services/manifestPdf.js
Normal file
@@ -0,0 +1,766 @@
|
||||
import PDFDocument from 'pdfkit';
|
||||
import { getStore } from '../db/store.js';
|
||||
import * as dbOrder from '../db/order.js';
|
||||
import { emit } from '../api/sse.js';
|
||||
|
||||
/**
|
||||
* Formats a Date or date string to German format DD.MM.YYYY.
|
||||
* @param {Date|string} dateVal
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatDate(dateVal) {
|
||||
if (!dateVal) return '';
|
||||
const d = new Date(dateVal);
|
||||
if (Number.isNaN(d.getTime())) return String(dateVal);
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
const month = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const year = d.getFullYear();
|
||||
return `${day}.${month}.${year}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a number as German currency string (e.g. 1.234,50 €).
|
||||
* @param {number} val
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatCurrency(val) {
|
||||
const n = Number(val) || 0;
|
||||
return (
|
||||
n.toLocaleString('de-DE', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}) + ' €'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a number with up to 3 decimal places (e.g. 1 or 2,5).
|
||||
* @param {number} val
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatQuantity(val) {
|
||||
const n = Number(val) || 0;
|
||||
return n.toLocaleString('de-DE', {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 3,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration per manifest type.
|
||||
*/
|
||||
const TYPE_CONFIG = {
|
||||
quote: {
|
||||
docTitle: 'ANGEBOT',
|
||||
numberPrefix: 'Angebots-Nr.',
|
||||
showPrices: true,
|
||||
filenamePrefix: 'angebot',
|
||||
introText: 'Wir freuen uns über Ihr Interesse und bieten Ihnen freibleibend wie folgt an:',
|
||||
closingText: 'Dieses Angebot ist freibleibend und 30 Tage ab Ausstellungsdatum gültig. Wir freuen uns auf Ihren Auftrag!',
|
||||
defaultSubject: 'Angebot',
|
||||
},
|
||||
order: {
|
||||
docTitle: 'AUFTRAG',
|
||||
numberPrefix: 'Auftrags-Nr.',
|
||||
showPrices: true,
|
||||
filenamePrefix: 'auftrag',
|
||||
introText: 'Wir bestätigen dankend die Annahme Ihres Auftrags zu folgenden Positionen:',
|
||||
closingText: 'Vielen Dank für Ihren Auftrag!',
|
||||
defaultSubject: 'Auftragsbestätigung',
|
||||
},
|
||||
shipment: {
|
||||
docTitle: 'LIEFERSCHEIN',
|
||||
numberPrefix: 'Lieferschein-Nr.',
|
||||
showPrices: false,
|
||||
filenamePrefix: 'lieferschein',
|
||||
introText: 'Mit dieser Sendung liefern wir Ihnen folgende Artikel:',
|
||||
closingText: 'Die Ware bleibt bis zur vollständigen Bezahlung unser Eigentum. Bitte prüfen Sie die Sendung sofort auf Vollständigkeit und eventuelle Transportschäden.',
|
||||
defaultSubject: 'Lieferschein',
|
||||
},
|
||||
delivery: {
|
||||
docTitle: 'WARENEINGANG',
|
||||
numberPrefix: 'Beleg-Nr.',
|
||||
showPrices: false,
|
||||
filenamePrefix: 'wareneingang',
|
||||
introText: 'Wareneingangsdokumentation zu folgenden Positionen:',
|
||||
closingText: 'Wareneingang ordnungsgemäß im Lager erfasst.',
|
||||
defaultSubject: 'Wareneingang',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Generates an A4 PDF document Buffer for any manifest document type.
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {'quote'|'order'|'shipment'|'delivery'} [params.type='order'] - Manifest document type.
|
||||
* @param {object} params.manifest - Manifest document object (order, quote, shipment, or delivery).
|
||||
* @param {object} [params.company] - Company details (name, etc.).
|
||||
* @param {Array<object>} [params.settings] - Company settings list [{ key, value }].
|
||||
* @param {object} [params.partner] - Entity (customer or supplier).
|
||||
* @param {Array<object>} [params.addresses] - Entity addresses.
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
export function generateManifestPdf({
|
||||
type = 'order',
|
||||
manifest,
|
||||
company = {},
|
||||
settings = [],
|
||||
partner = null,
|
||||
addresses = [],
|
||||
}) {
|
||||
const config = TYPE_CONFIG[type] || TYPE_CONFIG.order;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const doc = new PDFDocument({
|
||||
size: 'A4',
|
||||
margin: 45,
|
||||
bufferPages: true,
|
||||
info: {
|
||||
Title: `${config.docTitle} ${manifest.number || manifest.id}`,
|
||||
Author: company.name || 'Dash',
|
||||
Subject: `${config.defaultSubject} #${manifest.number || manifest.id}`,
|
||||
CreationDate: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
const chunks = [];
|
||||
doc.on('data', (chunk) => chunks.push(chunk));
|
||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
doc.on('error', reject);
|
||||
|
||||
// Palette
|
||||
const primaryColor = '#0f172a'; // slate-900
|
||||
const secondaryColor = '#2563eb'; // blue-600
|
||||
const textColor = '#1e293b'; // slate-800
|
||||
const mutedColor = '#64748b'; // slate-500
|
||||
const lightBorder = '#e2e8f0'; // slate-200
|
||||
const lightBg = '#f8fafc'; // slate-50
|
||||
|
||||
// Helper to lookup settings
|
||||
const settingsMap = new Map();
|
||||
if (Array.isArray(settings)) {
|
||||
for (const s of settings) {
|
||||
if (s?.key) settingsMap.set(s.key, s.value);
|
||||
}
|
||||
}
|
||||
|
||||
const companyName = company?.name || settingsMap.get('company.name') || 'Firma';
|
||||
const companyStreet = settingsMap.get('company.street') || '';
|
||||
const companyZipCity = [settingsMap.get('company.zip'), settingsMap.get('company.city')].filter(Boolean).join(' ');
|
||||
const companyEmail = settingsMap.get('company.email') || '';
|
||||
const companyPhone = settingsMap.get('company.phone') || '';
|
||||
const companyTaxId = settingsMap.get('company.taxId') || settingsMap.get('company.vatId') || '';
|
||||
|
||||
// Selected Address (for shipment prefer shipping address, for others prefer billing, fallback to first)
|
||||
let chosenAddress = null;
|
||||
if (Array.isArray(addresses) && addresses.length > 0) {
|
||||
if (type === 'shipment') {
|
||||
chosenAddress = addresses.find((a) => a.addressType === 'shipping') || addresses[0];
|
||||
} else {
|
||||
chosenAddress = addresses.find((a) => a.addressType === 'billing') || addresses[0];
|
||||
}
|
||||
}
|
||||
|
||||
const partnerName = partner
|
||||
? [partner.firstName, partner.name].filter(Boolean).join(' ')
|
||||
: '';
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 1. Header (Top bar)
|
||||
// ----------------------------------------------------
|
||||
let y = 45;
|
||||
|
||||
// Company Title (Left)
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(16)
|
||||
.fillColor(primaryColor)
|
||||
.text(companyName, 45, y);
|
||||
|
||||
// Document Title (Right)
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(20)
|
||||
.fillColor(secondaryColor)
|
||||
.text(config.docTitle, 350, y, { align: 'right', width: 200 });
|
||||
|
||||
y += 24;
|
||||
|
||||
// Company subline
|
||||
const companyAddressLine = [companyStreet, companyZipCity].filter(Boolean).join(' • ');
|
||||
if (companyAddressLine) {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8)
|
||||
.fillColor(mutedColor)
|
||||
.text(companyAddressLine, 45, y);
|
||||
}
|
||||
|
||||
// Document Number under Document Title
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(11)
|
||||
.fillColor(primaryColor)
|
||||
.text(`${config.numberPrefix} ${manifest.number || manifest.id}`, 350, y, { align: 'right', width: 200 });
|
||||
|
||||
y += 18;
|
||||
|
||||
// Separator rule
|
||||
doc.moveTo(45, y)
|
||||
.lineTo(550, y)
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(1)
|
||||
.stroke();
|
||||
|
||||
y += 20;
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 2. Partner Address & Meta Box
|
||||
// ----------------------------------------------------
|
||||
const addressBlockTop = y;
|
||||
|
||||
// Small return-address header line (DIN 5008 style)
|
||||
if (companyName || companyZipCity) {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(7)
|
||||
.fillColor(mutedColor)
|
||||
.text(`${companyName} ${companyAddressLine ? '• ' + companyAddressLine : ''}`, 45, y);
|
||||
y += 14;
|
||||
}
|
||||
|
||||
// Partner Address
|
||||
const partnerLabel = type === 'delivery' ? 'Lieferant' : (type === 'shipment' ? 'Lieferadresse' : 'Rechnungsadresse');
|
||||
if (partnerName || chosenAddress) {
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(10)
|
||||
.fillColor(textColor);
|
||||
|
||||
const displayName = chosenAddress?.name
|
||||
? [chosenAddress.firstName, chosenAddress.name].filter(Boolean).join(' ')
|
||||
: partnerName;
|
||||
|
||||
if (displayName) {
|
||||
doc.text(displayName, 45, y);
|
||||
y += 14;
|
||||
}
|
||||
|
||||
doc.font('Helvetica')
|
||||
.fontSize(9)
|
||||
.fillColor(textColor);
|
||||
|
||||
if (chosenAddress?.street) {
|
||||
const streetLine = [chosenAddress.street, chosenAddress.streetNumber].filter(Boolean).join(' ');
|
||||
doc.text(streetLine, 45, y);
|
||||
y += 13;
|
||||
}
|
||||
|
||||
if (chosenAddress?.zip || chosenAddress?.city) {
|
||||
const zipCity = [chosenAddress.zip, chosenAddress.city].filter(Boolean).join(' ');
|
||||
doc.text(zipCity, 45, y);
|
||||
y += 13;
|
||||
}
|
||||
|
||||
if (chosenAddress?.county) {
|
||||
doc.text(chosenAddress.county, 45, y);
|
||||
y += 13;
|
||||
}
|
||||
} else {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(9)
|
||||
.fillColor(mutedColor)
|
||||
.text(`Keine ${partnerLabel} hinterlegt`, 45, y);
|
||||
y += 14;
|
||||
}
|
||||
|
||||
// Right side Meta Box
|
||||
const metaBoxX = 330;
|
||||
const metaBoxWidth = 220;
|
||||
const metaBoxY = addressBlockTop;
|
||||
const metaBoxHeight = 85;
|
||||
|
||||
doc.roundedRect(metaBoxX, metaBoxY, metaBoxWidth, metaBoxHeight, 4)
|
||||
.fillColor(lightBg)
|
||||
.fill()
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(0.75)
|
||||
.stroke();
|
||||
|
||||
let metaY = metaBoxY + 10;
|
||||
const drawMetaRow = (label, val) => {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(mutedColor)
|
||||
.text(label, metaBoxX + 10, metaY, { width: 95 });
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor)
|
||||
.text(val || '–', metaBoxX + 105, metaY, { width: 105, align: 'right' });
|
||||
metaY += 15;
|
||||
};
|
||||
|
||||
drawMetaRow(`${config.docTitle.slice(0, 1) + config.docTitle.slice(1).toLowerCase()}-Nr.:`, String(manifest.number || manifest.id));
|
||||
const dateLabel = type === 'shipment' ? 'Versanddatum:' : (type === 'delivery' ? 'Eingangsdatum:' : 'Belegdatum:');
|
||||
drawMetaRow(dateLabel, formatDate(manifest.date || manifest.createdAt));
|
||||
|
||||
if (manifest.externalNumber) {
|
||||
drawMetaRow('Externe Referenz:', String(manifest.externalNumber));
|
||||
}
|
||||
if (partner?.number) {
|
||||
const numLabel = type === 'delivery' ? 'Lieferantennr.:' : 'Kundennummer:';
|
||||
drawMetaRow(numLabel, String(partner.number));
|
||||
}
|
||||
|
||||
// Ensure y is past the address & meta blocks
|
||||
y = Math.max(y + 15, metaBoxY + metaBoxHeight + 15);
|
||||
|
||||
// If shipment has package tracking info, show a compact card
|
||||
if (type === 'shipment' && Array.isArray(manifest.shippings) && manifest.shippings.length > 0) {
|
||||
const pkgBoxHeight = 16 + manifest.shippings.length * 13;
|
||||
doc.roundedRect(45, y, 505, pkgBoxHeight, 4)
|
||||
.fillColor(lightBg)
|
||||
.fill()
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(0.5)
|
||||
.stroke();
|
||||
|
||||
doc.font('Helvetica-Bold').fontSize(8.5).fillColor(primaryColor).text('Pakete & Sendungsverfolgung:', 55, y + 6);
|
||||
let pkgY = y + 20;
|
||||
manifest.shippings.forEach((pkg, pIdx) => {
|
||||
const pkgText = `Paket ${pIdx + 1}: ${pkg.carrier || 'Paketdienst'} ${pkg.number ? '#' + pkg.number : ''} ${pkg.trackingCode ? '• Tracking: ' + pkg.trackingCode : ''} (${pkg.state || 'gepackt'})`;
|
||||
doc.font('Helvetica').fontSize(8).fillColor(textColor).text(pkgText, 55, pkgY, { width: 485, ellipsis: true });
|
||||
pkgY += 13;
|
||||
});
|
||||
y += pkgBoxHeight + 15;
|
||||
}
|
||||
|
||||
// Intro text
|
||||
doc.font('Helvetica')
|
||||
.fontSize(9)
|
||||
.fillColor(textColor)
|
||||
.text(config.introText, 45, y);
|
||||
|
||||
y += 18;
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 3. Line Items Table
|
||||
// ----------------------------------------------------
|
||||
const showPrices = config.showPrices;
|
||||
|
||||
// Column setups
|
||||
const colXPrices = { pos: 45, sku: 75, name: 165, amount: 345, net: 405, tax: 465, total: 495 };
|
||||
const colWidthPrices = { pos: 25, sku: 85, name: 175, amount: 55, net: 55, tax: 25, total: 55 };
|
||||
|
||||
const colXNoPrices = { pos: 45, sku: 80, name: 185, amount: 455 };
|
||||
const colWidthNoPrices = { pos: 30, sku: 100, name: 265, amount: 95 };
|
||||
|
||||
const drawTableHeader = (atY) => {
|
||||
doc.rect(45, atY, 505, 20)
|
||||
.fillColor(primaryColor)
|
||||
.fill();
|
||||
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(8)
|
||||
.fillColor('#ffffff');
|
||||
|
||||
if (showPrices) {
|
||||
doc.text('Pos', colXPrices.pos + 3, atY + 6, { width: colWidthPrices.pos });
|
||||
doc.text('Art.-Nr.', colXPrices.sku, atY + 6, { width: colWidthPrices.sku });
|
||||
doc.text('Bezeichnung', colXPrices.name, atY + 6, { width: colWidthPrices.name });
|
||||
doc.text('Menge', colXPrices.amount, atY + 6, { width: colWidthPrices.amount, align: 'right' });
|
||||
doc.text('E-Preis Netto', colXPrices.net, atY + 6, { width: colWidthPrices.net, align: 'right' });
|
||||
doc.text('MwSt', colXPrices.tax, atY + 6, { width: colWidthPrices.tax, align: 'right' });
|
||||
doc.text('Gesamt Netto', colXPrices.total, atY + 6, { width: colWidthPrices.total, align: 'right' });
|
||||
} else {
|
||||
doc.text('Pos', colXNoPrices.pos + 3, atY + 6, { width: colWidthNoPrices.pos });
|
||||
doc.text('Art.-Nr.', colXNoPrices.sku, atY + 6, { width: colWidthNoPrices.sku });
|
||||
doc.text('Bezeichnung', colXNoPrices.name, atY + 6, { width: colWidthNoPrices.name });
|
||||
doc.text('Liefermenge', colXNoPrices.amount, atY + 6, { width: colWidthNoPrices.amount, align: 'right' });
|
||||
}
|
||||
|
||||
return atY + 22;
|
||||
};
|
||||
|
||||
y = drawTableHeader(y);
|
||||
|
||||
const lines = Array.isArray(manifest.lines) ? manifest.lines : [];
|
||||
let totalNet = 0;
|
||||
let totalQty = 0;
|
||||
const taxBreakdown = new Map();
|
||||
|
||||
lines.forEach((line, index) => {
|
||||
const amount = Number(line.amount || 0);
|
||||
const net = Number(line.net || 0);
|
||||
const rebate = Number(line.rebate || 0);
|
||||
const taxrate = Number(line.taxrate || 0);
|
||||
|
||||
totalQty += amount;
|
||||
|
||||
let lineNet = 0;
|
||||
let unitNetAfterRebate = net;
|
||||
if (showPrices) {
|
||||
unitNetAfterRebate = net * (1 - rebate / 100);
|
||||
lineNet = amount * unitNetAfterRebate;
|
||||
const lineTax = lineNet * (taxrate / 100);
|
||||
|
||||
totalNet += lineNet;
|
||||
|
||||
const currTax = taxBreakdown.get(taxrate) || { net: 0, tax: 0 };
|
||||
currTax.net += lineNet;
|
||||
currTax.tax += lineTax;
|
||||
taxBreakdown.set(taxrate, currTax);
|
||||
}
|
||||
|
||||
// Row height estimation
|
||||
const hasComment = Boolean(line.comment);
|
||||
const hasRebate = showPrices && rebate > 0;
|
||||
let extraLines = 0;
|
||||
if (hasComment) extraLines += 1;
|
||||
if (hasRebate) extraLines += 1;
|
||||
const rowHeight = 18 + extraLines * 11;
|
||||
|
||||
// Check page overflow
|
||||
if (y + rowHeight > 730) {
|
||||
doc.addPage();
|
||||
y = drawTableHeader(45);
|
||||
}
|
||||
|
||||
// Zebra striping
|
||||
if (index % 2 === 1) {
|
||||
doc.rect(45, y - 2, 505, rowHeight)
|
||||
.fillColor(lightBg)
|
||||
.fill();
|
||||
}
|
||||
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor);
|
||||
|
||||
const puSuffix = line.pu && line.pu > 1 ? ` (VPE ${line.pu})` : '';
|
||||
|
||||
if (showPrices) {
|
||||
// Pos
|
||||
doc.text(String(index + 1), colXPrices.pos + 3, y, { width: colWidthPrices.pos });
|
||||
// SKU
|
||||
doc.text(line.sku || '–', colXPrices.sku, y, { width: colWidthPrices.sku, ellipsis: true });
|
||||
// Name
|
||||
doc.text((line.name || 'Position') + puSuffix, colXPrices.name, y, {
|
||||
width: colWidthPrices.name,
|
||||
ellipsis: true,
|
||||
});
|
||||
// Amount
|
||||
doc.text(formatQuantity(amount), colXPrices.amount, y, {
|
||||
width: colWidthPrices.amount,
|
||||
align: 'right',
|
||||
});
|
||||
// Unit Price Net
|
||||
doc.text(formatCurrency(net), colXPrices.net, y, {
|
||||
width: colWidthPrices.net,
|
||||
align: 'right',
|
||||
});
|
||||
// Tax Rate
|
||||
doc.text(`${taxrate}%`, colXPrices.tax, y, {
|
||||
width: colWidthPrices.tax,
|
||||
align: 'right',
|
||||
});
|
||||
// Line Total Net
|
||||
doc.font('Helvetica-Bold')
|
||||
.text(formatCurrency(lineNet), colXPrices.total, y, {
|
||||
width: colWidthPrices.total,
|
||||
align: 'right',
|
||||
});
|
||||
|
||||
let subY = y + 12;
|
||||
if (hasRebate) {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(7.5)
|
||||
.fillColor(secondaryColor)
|
||||
.text(`Rabatt: ${rebate}% (effektiver E-Preis: ${formatCurrency(unitNetAfterRebate)})`, colXPrices.name, subY, {
|
||||
width: colWidthPrices.name,
|
||||
});
|
||||
subY += 10;
|
||||
}
|
||||
if (hasComment) {
|
||||
doc.font('Helvetica-Oblique')
|
||||
.fontSize(7.5)
|
||||
.fillColor(mutedColor)
|
||||
.text(line.comment, colXPrices.name, subY, {
|
||||
width: colWidthPrices.name,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Without Prices
|
||||
doc.text(String(index + 1), colXNoPrices.pos + 3, y, { width: colWidthNoPrices.pos });
|
||||
doc.text(line.sku || '–', colXNoPrices.sku, y, { width: colWidthNoPrices.sku, ellipsis: true });
|
||||
doc.text((line.name || 'Position') + puSuffix, colXNoPrices.name, y, {
|
||||
width: colWidthNoPrices.name,
|
||||
ellipsis: true,
|
||||
});
|
||||
doc.font('Helvetica-Bold')
|
||||
.text(formatQuantity(amount) + ' Stk', colXNoPrices.amount, y, {
|
||||
width: colWidthNoPrices.amount,
|
||||
align: 'right',
|
||||
});
|
||||
|
||||
if (hasComment) {
|
||||
doc.font('Helvetica-Oblique')
|
||||
.fontSize(7.5)
|
||||
.fillColor(mutedColor)
|
||||
.text(line.comment, colXNoPrices.name, y + 12, {
|
||||
width: colWidthNoPrices.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Bottom row separator
|
||||
doc.moveTo(45, y + rowHeight - 2)
|
||||
.lineTo(550, y + rowHeight - 2)
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(0.5)
|
||||
.stroke();
|
||||
|
||||
y += rowHeight;
|
||||
});
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 4. Summary & Totals Block
|
||||
// ----------------------------------------------------
|
||||
if (showPrices) {
|
||||
let totalTax = 0;
|
||||
for (const item of taxBreakdown.values()) {
|
||||
totalTax += item.tax;
|
||||
}
|
||||
const grandTotal = totalNet + totalTax;
|
||||
|
||||
if (y + 110 > 750) {
|
||||
doc.addPage();
|
||||
y = 50;
|
||||
} else {
|
||||
y += 15;
|
||||
}
|
||||
|
||||
const summaryX = 330;
|
||||
const summaryWidth = 220;
|
||||
|
||||
// Subtotal Net
|
||||
doc.font('Helvetica')
|
||||
.fontSize(9)
|
||||
.fillColor(mutedColor)
|
||||
.text('Summe Netto:', summaryX, y, { width: 110 });
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(9)
|
||||
.fillColor(textColor)
|
||||
.text(formatCurrency(totalNet), summaryX + 110, y, { width: 110, align: 'right' });
|
||||
y += 15;
|
||||
|
||||
// Tax Breakdown
|
||||
const sortedRates = Array.from(taxBreakdown.entries()).sort((a, b) => a[0] - b[0]);
|
||||
for (const [rate, val] of sortedRates) {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(mutedColor)
|
||||
.text(`zzgl. ${rate}% MwSt:`, summaryX, y, { width: 110 });
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor)
|
||||
.text(formatCurrency(val.tax), summaryX + 110, y, { width: 110, align: 'right' });
|
||||
y += 14;
|
||||
}
|
||||
|
||||
// Divider before Grand Total
|
||||
doc.moveTo(summaryX, y + 2)
|
||||
.lineTo(summaryX + summaryWidth, y + 2)
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(1)
|
||||
.stroke();
|
||||
y += 8;
|
||||
|
||||
// Grand Total
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(12)
|
||||
.fillColor(primaryColor)
|
||||
.text('Gesamtsumme:', summaryX, y, { width: 110 });
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(12)
|
||||
.fillColor(secondaryColor)
|
||||
.text(formatCurrency(grandTotal), summaryX + 110, y, { width: 110, align: 'right' });
|
||||
y += 24;
|
||||
|
||||
// Payments / open balance note (for orders)
|
||||
if (manifest.paidTotal !== undefined && manifest.paidTotal > 0) {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(mutedColor)
|
||||
.text('Bereits bezahlt:', summaryX, y, { width: 110 });
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor)
|
||||
.text(formatCurrency(manifest.paidTotal), summaryX + 110, y, { width: 110, align: 'right' });
|
||||
y += 14;
|
||||
|
||||
const openAmount = Math.max(0, grandTotal - Number(manifest.paidTotal || 0));
|
||||
if (openAmount > 0.01) {
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor)
|
||||
.text('Offener Betrag:', summaryX, y, { width: 110 });
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor)
|
||||
.text(formatCurrency(openAmount), summaryX + 110, y, { width: 110, align: 'right' });
|
||||
y += 16;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Non-price summary (total quantity and positions count)
|
||||
if (y + 50 > 750) {
|
||||
doc.addPage();
|
||||
y = 50;
|
||||
} else {
|
||||
y += 15;
|
||||
}
|
||||
|
||||
doc.roundedRect(45, y, 505, 30, 4)
|
||||
.fillColor(lightBg)
|
||||
.fill()
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(0.5)
|
||||
.stroke();
|
||||
|
||||
doc.font('Helvetica')
|
||||
.fontSize(9)
|
||||
.fillColor(mutedColor)
|
||||
.text('Gesamtübersicht:', 55, y + 9);
|
||||
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(9)
|
||||
.fillColor(textColor)
|
||||
.text(`${lines.length} Positionen • Gesamtmenge: ${formatQuantity(totalQty)} Stück`, 150, y + 9, {
|
||||
width: 385,
|
||||
align: 'right',
|
||||
});
|
||||
|
||||
y += 45;
|
||||
}
|
||||
|
||||
// Closing note
|
||||
if (config.closingText) {
|
||||
if (y + 40 > 750) {
|
||||
doc.addPage();
|
||||
y = 50;
|
||||
}
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(mutedColor)
|
||||
.text(config.closingText, 45, y, { width: 505 });
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 5. Footers on all pages
|
||||
// ----------------------------------------------------
|
||||
const range = doc.bufferedPageRange();
|
||||
for (let i = 0; i < range.count; i++) {
|
||||
doc.switchToPage(i);
|
||||
|
||||
// Footer rule
|
||||
doc.moveTo(45, 785)
|
||||
.lineTo(550, 785)
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(0.5)
|
||||
.stroke();
|
||||
|
||||
// Footer text left
|
||||
const footerInfo = [
|
||||
companyName,
|
||||
companyTaxId ? `USt-IdNr.: ${companyTaxId}` : null,
|
||||
companyEmail,
|
||||
companyPhone,
|
||||
].filter(Boolean).join(' • ');
|
||||
|
||||
doc.font('Helvetica')
|
||||
.fontSize(7.5)
|
||||
.fillColor(mutedColor)
|
||||
.text(footerInfo || 'Vielen Dank für Ihre Zusammenarbeit!', 45, 793, {
|
||||
width: 350,
|
||||
ellipsis: true,
|
||||
lineBreak: false,
|
||||
});
|
||||
|
||||
// Footer text right: Page X of Y
|
||||
doc.text(
|
||||
`Seite ${i + 1} von ${range.count}`,
|
||||
450,
|
||||
793,
|
||||
{ width: 100, align: 'right', lineBreak: false }
|
||||
);
|
||||
}
|
||||
|
||||
doc.end();
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and attaches a PDF to any manifest (quote, order, shipment, delivery)
|
||||
* and emits SSE updates.
|
||||
*
|
||||
* @param {number} googleAuthId - Google auth user ID.
|
||||
* @param {number} companyId - Active company ID.
|
||||
* @param {number} manifestId - Manifest ID.
|
||||
* @param {'quote'|'order'|'shipment'|'delivery'} type - Manifest type.
|
||||
* @returns {Promise<{manifest: object, attachment: object, pdfBuffer: Buffer, filename: string}>}
|
||||
*/
|
||||
export async function createAndAttachManifestPdf(googleAuthId, companyId, manifestId, type = 'order') {
|
||||
const store = await getStore();
|
||||
|
||||
let manifest;
|
||||
if (type === 'quote') {
|
||||
manifest = await store.quote.getById(googleAuthId, manifestId);
|
||||
} else if (type === 'order') {
|
||||
manifest = await dbOrder.getById(googleAuthId, manifestId);
|
||||
} else if (type === 'shipment') {
|
||||
manifest = await store.shipment.getById(googleAuthId, manifestId);
|
||||
} else if (type === 'delivery') {
|
||||
manifest = await store.delivery.getById(googleAuthId, manifestId);
|
||||
} else {
|
||||
throw new Error(`Unsupported manifest type: ${type}`);
|
||||
}
|
||||
|
||||
if (!manifest) {
|
||||
throw new Error('Manifest not found');
|
||||
}
|
||||
|
||||
const partnerId = manifest.entityId ?? manifest.supplierId ?? null;
|
||||
|
||||
const [company, settings, partner, addresses] = await Promise.all([
|
||||
store.company.getById(companyId).catch(() => null),
|
||||
store.companysetting.list(googleAuthId, { frontendOnly: false, maskWriteonly: false }).catch(() => []),
|
||||
partnerId ? store.entity.getById(googleAuthId, partnerId).catch(() => null) : null,
|
||||
partnerId ? store.entityaddress.list(googleAuthId, partnerId).catch(() => []) : [],
|
||||
]);
|
||||
|
||||
const pdfBuffer = await generateManifestPdf({
|
||||
type,
|
||||
manifest,
|
||||
company: company || {},
|
||||
settings: settings || [],
|
||||
partner: partner || null,
|
||||
addresses: addresses || [],
|
||||
});
|
||||
|
||||
const config = TYPE_CONFIG[type] || TYPE_CONFIG.order;
|
||||
const safeNumber = String(manifest.number || manifest.id).replace(/[^a-zA-Z0-9._-]/g, '_');
|
||||
const filename = `${config.filenamePrefix}-${safeNumber}.pdf`;
|
||||
|
||||
const attachment = await store.manifestattachment.add(googleAuthId, manifest.id, {
|
||||
mimetype: 'application/pdf',
|
||||
name: filename,
|
||||
content: pdfBuffer,
|
||||
meta: { type: `${type}_pdf` },
|
||||
});
|
||||
|
||||
emit(type, { companyId });
|
||||
|
||||
return { manifest, attachment, pdfBuffer, filename };
|
||||
}
|
||||
|
||||
// Re-export alias for order backwards compatibility
|
||||
export { generateManifestPdf as generateOrderPdf };
|
||||
@@ -1,555 +1,8 @@
|
||||
import PDFDocument from 'pdfkit';
|
||||
|
||||
/**
|
||||
* Formats a Date or date string to German format DD.MM.YYYY.
|
||||
* @param {Date|string} dateVal
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatDate(dateVal) {
|
||||
if (!dateVal) return '';
|
||||
const d = new Date(dateVal);
|
||||
if (Number.isNaN(d.getTime())) return String(dateVal);
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
const month = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const year = d.getFullYear();
|
||||
return `${day}.${month}.${year}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a number as German currency string (e.g. 1.234,50 €).
|
||||
* @param {number} val
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatCurrency(val) {
|
||||
const n = Number(val) || 0;
|
||||
return (
|
||||
n.toLocaleString('de-DE', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}) + ' €'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a number with up to 3 decimal places (e.g. 1 or 2,5).
|
||||
* @param {number} val
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatQuantity(val) {
|
||||
const n = Number(val) || 0;
|
||||
return n.toLocaleString('de-DE', {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 3,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates an A4 PDF document Buffer for an order.
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {object} params.order - Order object with lines, orderTotal, etc.
|
||||
* @param {object} [params.company] - Company details (name, etc.).
|
||||
* @param {Array<object>} [params.settings] - Company settings list [{ key, value }].
|
||||
* @param {object} [params.customer] - Customer entity (firstName, name, number).
|
||||
* @param {Array<object>} [params.addresses] - Customer addresses.
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
export function generateOrderPdf({ order, company = {}, settings = [], customer = null, addresses = [] }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const doc = new PDFDocument({
|
||||
size: 'A4',
|
||||
margin: 45,
|
||||
bufferPages: true,
|
||||
info: {
|
||||
Title: `Auftrag ${order.number || order.id}`,
|
||||
Author: company.name || 'Dash',
|
||||
Subject: `Auftragsbestätigung #${order.number || order.id}`,
|
||||
CreationDate: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
const chunks = [];
|
||||
doc.on('data', (chunk) => chunks.push(chunk));
|
||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
doc.on('error', reject);
|
||||
|
||||
// Palette
|
||||
const primaryColor = '#0f172a'; // slate-900
|
||||
const secondaryColor = '#2563eb'; // blue-600
|
||||
const textColor = '#1e293b'; // slate-800
|
||||
const mutedColor = '#64748b'; // slate-500
|
||||
const lightBorder = '#e2e8f0'; // slate-200
|
||||
const lightBg = '#f8fafc'; // slate-50
|
||||
|
||||
// Helper to lookup settings
|
||||
const settingsMap = new Map();
|
||||
if (Array.isArray(settings)) {
|
||||
for (const s of settings) {
|
||||
if (s?.key) settingsMap.set(s.key, s.value);
|
||||
}
|
||||
}
|
||||
|
||||
const companyName = company?.name || settingsMap.get('company.name') || 'Firma';
|
||||
const companyStreet = settingsMap.get('company.street') || '';
|
||||
const companyZipCity = [settingsMap.get('company.zip'), settingsMap.get('company.city')].filter(Boolean).join(' ');
|
||||
const companyEmail = settingsMap.get('company.email') || '';
|
||||
const companyPhone = settingsMap.get('company.phone') || '';
|
||||
const companyTaxId = settingsMap.get('company.taxId') || settingsMap.get('company.vatId') || '';
|
||||
|
||||
// Selected Address (prefer billing, then first)
|
||||
let chosenAddress = null;
|
||||
if (Array.isArray(addresses) && addresses.length > 0) {
|
||||
chosenAddress = addresses.find((a) => a.addressType === 'billing') || addresses[0];
|
||||
}
|
||||
|
||||
const customerName = customer
|
||||
? [customer.firstName, customer.name].filter(Boolean).join(' ')
|
||||
: '';
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 1. Header (Top bar)
|
||||
// ----------------------------------------------------
|
||||
let y = 45;
|
||||
|
||||
// Company Title (Left)
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(16)
|
||||
.fillColor(primaryColor)
|
||||
.text(companyName, 45, y);
|
||||
|
||||
// Document Title & Number (Right)
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(20)
|
||||
.fillColor(secondaryColor)
|
||||
.text('AUFTRAG', 350, y, { align: 'right', width: 200 });
|
||||
|
||||
y += 24;
|
||||
|
||||
// Company subline
|
||||
const companyAddressLine = [companyStreet, companyZipCity].filter(Boolean).join(' • ');
|
||||
if (companyAddressLine) {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8)
|
||||
.fillColor(mutedColor)
|
||||
.text(companyAddressLine, 45, y);
|
||||
}
|
||||
|
||||
// Order Number under Document Title
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(11)
|
||||
.fillColor(primaryColor)
|
||||
.text(`Auftrags-Nr. ${order.number || order.id}`, 350, y, { align: 'right', width: 200 });
|
||||
|
||||
y += 18;
|
||||
|
||||
// Separator rule
|
||||
doc.moveTo(45, y)
|
||||
.lineTo(550, y)
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(1)
|
||||
.stroke();
|
||||
|
||||
y += 20;
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 2. Customer Address & Order Meta Box
|
||||
// ----------------------------------------------------
|
||||
const addressBlockTop = y;
|
||||
|
||||
// Small return-address header line (standard DIN 5008 style)
|
||||
if (companyName || companyZipCity) {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(7)
|
||||
.fillColor(mutedColor)
|
||||
.text(`${companyName} ${companyAddressLine ? '• ' + companyAddressLine : ''}`, 45, y);
|
||||
y += 14;
|
||||
}
|
||||
|
||||
// Customer Address
|
||||
if (customerName || chosenAddress) {
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(10)
|
||||
.fillColor(textColor);
|
||||
|
||||
const displayName = chosenAddress?.name
|
||||
? [chosenAddress.firstName, chosenAddress.name].filter(Boolean).join(' ')
|
||||
: customerName;
|
||||
|
||||
if (displayName) {
|
||||
doc.text(displayName, 45, y);
|
||||
y += 14;
|
||||
}
|
||||
|
||||
doc.font('Helvetica')
|
||||
.fontSize(9)
|
||||
.fillColor(textColor);
|
||||
|
||||
if (chosenAddress?.street) {
|
||||
const streetLine = [chosenAddress.street, chosenAddress.streetNumber].filter(Boolean).join(' ');
|
||||
doc.text(streetLine, 45, y);
|
||||
y += 13;
|
||||
}
|
||||
|
||||
if (chosenAddress?.zip || chosenAddress?.city) {
|
||||
const zipCity = [chosenAddress.zip, chosenAddress.city].filter(Boolean).join(' ');
|
||||
doc.text(zipCity, 45, y);
|
||||
y += 13;
|
||||
}
|
||||
|
||||
if (chosenAddress?.county) {
|
||||
doc.text(chosenAddress.county, 45, y);
|
||||
y += 13;
|
||||
}
|
||||
} else {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(9)
|
||||
.fillColor(mutedColor)
|
||||
.text('Keine Kundenadresse hinterlegt', 45, y);
|
||||
y += 14;
|
||||
}
|
||||
|
||||
// Right side Meta Box (Cards)
|
||||
const metaBoxX = 330;
|
||||
const metaBoxWidth = 220;
|
||||
const metaBoxY = addressBlockTop;
|
||||
const metaBoxHeight = 85;
|
||||
|
||||
doc.roundedRect(metaBoxX, metaBoxY, metaBoxWidth, metaBoxHeight, 4)
|
||||
.fillColor(lightBg)
|
||||
.fill()
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(0.75)
|
||||
.stroke();
|
||||
|
||||
let metaY = metaBoxY + 10;
|
||||
const drawMetaRow = (label, val) => {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(mutedColor)
|
||||
.text(label, metaBoxX + 10, metaY, { width: 90 });
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor)
|
||||
.text(val || '–', metaBoxX + 105, metaY, { width: 105, align: 'right' });
|
||||
metaY += 15;
|
||||
};
|
||||
|
||||
drawMetaRow('Auftragsnummer:', String(order.number || order.id));
|
||||
drawMetaRow('Auftragsdatum:', formatDate(order.date || order.createdAt));
|
||||
if (order.externalNumber) {
|
||||
drawMetaRow('Externe Referenz:', String(order.externalNumber));
|
||||
}
|
||||
if (customer?.number) {
|
||||
drawMetaRow('Kundennummer:', String(customer.number));
|
||||
}
|
||||
|
||||
// Ensure y is past the address & meta blocks
|
||||
y = Math.max(y + 15, metaBoxY + metaBoxHeight + 20);
|
||||
|
||||
// Intro text
|
||||
doc.font('Helvetica')
|
||||
.fontSize(9)
|
||||
.fillColor(textColor)
|
||||
.text('Wir bestätigen dankend die Annahme Ihres Auftrags zu folgenden Positionen:', 45, y);
|
||||
|
||||
y += 20;
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 3. Line Items Table
|
||||
// ----------------------------------------------------
|
||||
const colX = {
|
||||
pos: 45,
|
||||
sku: 75,
|
||||
name: 165,
|
||||
amount: 345,
|
||||
net: 405,
|
||||
tax: 465,
|
||||
total: 495,
|
||||
};
|
||||
|
||||
const colWidth = {
|
||||
pos: 25,
|
||||
sku: 85,
|
||||
name: 175,
|
||||
amount: 55,
|
||||
net: 55,
|
||||
tax: 25,
|
||||
total: 55,
|
||||
};
|
||||
|
||||
const drawTableHeader = (atY) => {
|
||||
doc.rect(45, atY, 505, 20)
|
||||
.fillColor(primaryColor)
|
||||
.fill();
|
||||
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(8)
|
||||
.fillColor('#ffffff');
|
||||
|
||||
doc.text('Pos', colX.pos + 3, atY + 6, { width: colWidth.pos });
|
||||
doc.text('Art.-Nr.', colX.sku, atY + 6, { width: colWidth.sku });
|
||||
doc.text('Bezeichnung', colX.name, atY + 6, { width: colWidth.name });
|
||||
doc.text('Menge', colX.amount, atY + 6, { width: colWidth.amount, align: 'right' });
|
||||
doc.text('E-Preis Netto', colX.net, atY + 6, { width: colWidth.net, align: 'right' });
|
||||
doc.text('MwSt', colX.tax, atY + 6, { width: colWidth.tax, align: 'right' });
|
||||
doc.text('Gesamt Netto', colX.total, atY + 6, { width: colWidth.total, align: 'right' });
|
||||
|
||||
return atY + 22;
|
||||
};
|
||||
|
||||
y = drawTableHeader(y);
|
||||
|
||||
const lines = Array.isArray(order.lines) ? order.lines : [];
|
||||
let totalNet = 0;
|
||||
const taxBreakdown = new Map(); // rate -> { net, tax }
|
||||
|
||||
lines.forEach((line, index) => {
|
||||
const amount = Number(line.amount || 0);
|
||||
const net = Number(line.net || 0);
|
||||
const rebate = Number(line.rebate || 0);
|
||||
const taxrate = Number(line.taxrate || 0);
|
||||
|
||||
const unitNetAfterRebate = net * (1 - rebate / 100);
|
||||
const lineNet = amount * unitNetAfterRebate;
|
||||
const lineTax = lineNet * (taxrate / 100);
|
||||
|
||||
totalNet += lineNet;
|
||||
|
||||
const currTax = taxBreakdown.get(taxrate) || { net: 0, tax: 0 };
|
||||
currTax.net += lineNet;
|
||||
currTax.tax += lineTax;
|
||||
taxBreakdown.set(taxrate, currTax);
|
||||
|
||||
// Row height estimation
|
||||
const hasComment = Boolean(line.comment);
|
||||
const hasRebate = rebate > 0;
|
||||
let extraLines = 0;
|
||||
if (hasComment) extraLines += 1;
|
||||
if (hasRebate) extraLines += 1;
|
||||
const rowHeight = 18 + extraLines * 11;
|
||||
|
||||
// Check page overflow
|
||||
if (y + rowHeight > 730) {
|
||||
doc.addPage();
|
||||
y = drawTableHeader(45);
|
||||
}
|
||||
|
||||
// Zebra striping
|
||||
if (index % 2 === 1) {
|
||||
doc.rect(45, y - 2, 505, rowHeight)
|
||||
.fillColor(lightBg)
|
||||
.fill();
|
||||
}
|
||||
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor);
|
||||
|
||||
// Pos
|
||||
doc.text(String(index + 1), colX.pos + 3, y, { width: colWidth.pos });
|
||||
|
||||
// SKU
|
||||
doc.text(line.sku || '–', colX.sku, y, { width: colWidth.sku, ellipsis: true });
|
||||
|
||||
// Name
|
||||
const puSuffix = line.pu && line.pu > 1 ? ` (VPE ${line.pu})` : '';
|
||||
doc.text((line.name || 'Position') + puSuffix, colX.name, y, {
|
||||
width: colWidth.name,
|
||||
ellipsis: true,
|
||||
});
|
||||
|
||||
// Amount
|
||||
doc.text(formatQuantity(amount), colX.amount, y, {
|
||||
width: colWidth.amount,
|
||||
align: 'right',
|
||||
});
|
||||
|
||||
// Unit Price Net
|
||||
doc.text(formatCurrency(net), colX.net, y, {
|
||||
width: colWidth.net,
|
||||
align: 'right',
|
||||
});
|
||||
|
||||
// Tax Rate
|
||||
doc.text(`${taxrate}%`, colX.tax, y, {
|
||||
width: colWidth.tax,
|
||||
align: 'right',
|
||||
});
|
||||
|
||||
// Line Total Net
|
||||
doc.font('Helvetica-Bold')
|
||||
.text(formatCurrency(lineNet), colX.total, y, {
|
||||
width: colWidth.total,
|
||||
align: 'right',
|
||||
});
|
||||
|
||||
let subY = y + 12;
|
||||
|
||||
// Optional rebate notice
|
||||
if (hasRebate) {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(7.5)
|
||||
.fillColor(secondaryColor)
|
||||
.text(`Rabatt: ${rebate}% (effektiver E-Preis: ${formatCurrency(unitNetAfterRebate)})`, colX.name, subY, {
|
||||
width: colWidth.name,
|
||||
});
|
||||
subY += 10;
|
||||
}
|
||||
|
||||
// Optional comment
|
||||
if (hasComment) {
|
||||
doc.font('Helvetica-Oblique')
|
||||
.fontSize(7.5)
|
||||
.fillColor(mutedColor)
|
||||
.text(line.comment, colX.name, subY, {
|
||||
width: colWidth.name,
|
||||
});
|
||||
}
|
||||
|
||||
// Bottom row separator
|
||||
doc.moveTo(45, y + rowHeight - 2)
|
||||
.lineTo(550, y + rowHeight - 2)
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(0.5)
|
||||
.stroke();
|
||||
|
||||
y += rowHeight;
|
||||
});
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 4. Summary & Totals Block
|
||||
// ----------------------------------------------------
|
||||
let totalTax = 0;
|
||||
for (const item of taxBreakdown.values()) {
|
||||
totalTax += item.tax;
|
||||
}
|
||||
const grandTotal = totalNet + totalTax;
|
||||
|
||||
// Summary block fits ~90pt
|
||||
if (y + 110 > 750) {
|
||||
doc.addPage();
|
||||
y = 50;
|
||||
} else {
|
||||
y += 15;
|
||||
}
|
||||
|
||||
const summaryX = 330;
|
||||
const summaryWidth = 220;
|
||||
|
||||
// Subtotal Net
|
||||
doc.font('Helvetica')
|
||||
.fontSize(9)
|
||||
.fillColor(mutedColor)
|
||||
.text('Summe Netto:', summaryX, y, { width: 110 });
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(9)
|
||||
.fillColor(textColor)
|
||||
.text(formatCurrency(totalNet), summaryX + 110, y, { width: 110, align: 'right' });
|
||||
y += 15;
|
||||
|
||||
// Tax Breakdown
|
||||
const sortedRates = Array.from(taxBreakdown.entries()).sort((a, b) => a[0] - b[0]);
|
||||
for (const [rate, val] of sortedRates) {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(mutedColor)
|
||||
.text(`zzgl. ${rate}% MwSt:`, summaryX, y, { width: 110 });
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor)
|
||||
.text(formatCurrency(val.tax), summaryX + 110, y, { width: 110, align: 'right' });
|
||||
y += 14;
|
||||
}
|
||||
|
||||
// Divider before Grand Total
|
||||
doc.moveTo(summaryX, y + 2)
|
||||
.lineTo(summaryX + summaryWidth, y + 2)
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(1)
|
||||
.stroke();
|
||||
y += 8;
|
||||
|
||||
// Grand Total (Brutto)
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(12)
|
||||
.fillColor(primaryColor)
|
||||
.text('Gesamtsumme:', summaryX, y, { width: 110 });
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(12)
|
||||
.fillColor(secondaryColor)
|
||||
.text(formatCurrency(grandTotal), summaryX + 110, y, { width: 110, align: 'right' });
|
||||
y += 24;
|
||||
|
||||
// Payment / status note
|
||||
if (order.paidTotal !== undefined && order.paidTotal > 0) {
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(mutedColor)
|
||||
.text('Bereits bezahlt:', summaryX, y, { width: 110 });
|
||||
doc.font('Helvetica')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor)
|
||||
.text(formatCurrency(order.paidTotal), summaryX + 110, y, { width: 110, align: 'right' });
|
||||
y += 14;
|
||||
|
||||
const openAmount = Math.max(0, grandTotal - Number(order.paidTotal || 0));
|
||||
if (openAmount > 0.01) {
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor)
|
||||
.text('Offener Betrag:', summaryX, y, { width: 110 });
|
||||
doc.font('Helvetica-Bold')
|
||||
.fontSize(8.5)
|
||||
.fillColor(textColor)
|
||||
.text(formatCurrency(openAmount), summaryX + 110, y, { width: 110, align: 'right' });
|
||||
y += 16;
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 5. Footers on all pages
|
||||
// ----------------------------------------------------
|
||||
const range = doc.bufferedPageRange();
|
||||
for (let i = 0; i < range.count; i++) {
|
||||
doc.switchToPage(i);
|
||||
|
||||
// Footer rule
|
||||
doc.moveTo(45, 785)
|
||||
.lineTo(550, 785)
|
||||
.strokeColor(lightBorder)
|
||||
.lineWidth(0.5)
|
||||
.stroke();
|
||||
|
||||
// Footer text left: Company info / Thank you
|
||||
const footerInfo = [
|
||||
companyName,
|
||||
companyTaxId ? `USt-IdNr.: ${companyTaxId}` : null,
|
||||
companyEmail,
|
||||
companyPhone,
|
||||
].filter(Boolean).join(' • ');
|
||||
|
||||
doc.font('Helvetica')
|
||||
.fontSize(7.5)
|
||||
.fillColor(mutedColor)
|
||||
.text(footerInfo || 'Vielen Dank für Ihren Auftrag!', 45, 793, {
|
||||
width: 350,
|
||||
ellipsis: true,
|
||||
lineBreak: false,
|
||||
});
|
||||
|
||||
// Footer text right: Page X of Y
|
||||
doc.text(
|
||||
`Seite ${i + 1} von ${range.count}`,
|
||||
450,
|
||||
793,
|
||||
{ width: 100, align: 'right', lineBreak: false }
|
||||
);
|
||||
}
|
||||
|
||||
doc.end();
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
export {
|
||||
formatDate,
|
||||
formatCurrency,
|
||||
formatQuantity,
|
||||
generateManifestPdf,
|
||||
generateOrderPdf,
|
||||
createAndAttachManifestPdf,
|
||||
} from './manifestPdf.js';
|
||||
|
||||
Reference in New Issue
Block a user