This commit is contained in:
seb
2026-10-14 20:50:07 +02:00
parent 9c54a8a1d3
commit d880273629
34 changed files with 4454 additions and 2695 deletions

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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
}