This commit is contained in:
seb
2026-09-26 23:06:09 +02:00
parent cbb2fdeb6d
commit 69f27a2942
19 changed files with 2231 additions and 0 deletions

529
src/api/routes/printer.js Normal file
View File

@@ -0,0 +1,529 @@
import * as db from '../../db/printer.js';
import { emit } from '../sse.js';
function requireSelectedCompany(req) {
const companyId = req.user?.selectedCompanyId;
if (companyId == null) {
return { error: 'No company selected' };
}
return { companyId };
}
function parsePositiveInt(value, field) {
const id = Number(value);
if (!Number.isInteger(id) || id <= 0) {
return { error: `${field} is required` };
}
return { id };
}
function printerErrorStatus(error) {
if (error.message === 'No company selected') return 400;
if (error.message === 'Not authorized') return 403;
if (error.message === 'Company not found') return 404;
if (error.message === 'Printer not found') return 404;
if (error.message === 'Address required') return 400;
if (error.message?.startsWith('Invalid printer type')) return 400;
if (error.message === 'Invalid sort') return 400;
if (error.message === 'Invalid printer order') return 400;
return 500;
}
/**
* Registers printer routes for the authenticated user's selected company.
* @param {import('express').Application} app
* @param {string} [basePath='']
*/
export function register(app, basePath = '') {
/**
* @openapi
* /printer:
* get:
* tags: [Printer]
* summary: List printers
* description: Lists printers for the selected company, ordered by sort and id.
* security:
* - cookieAuth: []
* x-markdown: printer/list.md
* responses:
* 200:
* description: List of printers
* content:
* application/json:
* schema:
* type: object
* properties:
* printers:
* type: array
* items:
* $ref: '#/components/schemas/Printer'
* 400:
* description: 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'
*/
app.get(`${basePath}/printer`, async (req, res) => {
const selected = requireSelectedCompany(req);
if (selected.error) {
return res.status(400).json({ error: selected.error });
}
try {
const printers = await db.list(req.user.id);
res.status(200).json({ printers });
} catch (error) {
const status = printerErrorStatus(error);
if (status === 500) console.error('List printers failed:', error);
res.status(status).json({ error: error.message });
}
});
/**
* @openapi
* /printer/order:
* put:
* tags: [Printer]
* summary: Reorder printers
* description: |
* Reorders printers for the selected company.
* `printerIds` must include all existing printer IDs exactly once.
* security:
* - cookieAuth: []
* x-markdown: printer/order.md
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required: [printerIds]
* properties:
* printerIds:
* type: array
* items:
* type: integer
* responses:
* 200:
* description: Applied printer order
* content:
* application/json:
* schema:
* type: object
* properties:
* printerIds:
* type: array
* items:
* type: integer
* 400:
* description: Invalid printer order 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'
*/
app.put(`${basePath}/printer/order`, async (req, res) => {
const selected = requireSelectedCompany(req);
if (selected.error) {
return res.status(400).json({ error: selected.error });
}
const { printerIds } = req.body ?? {};
try {
const result = await db.order(req.user.id, { printerIds });
emit('printer', { companyId: selected.companyId });
res.status(200).json(result);
} catch (error) {
const status = printerErrorStatus(error);
if (status === 500) console.error('Order printers failed:', error);
res.status(status).json({ error: error.message });
}
});
/**
* @openapi
* /printer/{id}:
* get:
* tags: [Printer]
* summary: Get printer by ID
* description: Retrieves a single printer for the authenticated user's selected company.
* security:
* - cookieAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Printer ID
* x-markdown: printer/get.md
* responses:
* 200:
* description: Printer details
* content:
* application/json:
* schema:
* type: object
* properties:
* printer:
* $ref: '#/components/schemas/Printer'
* 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: Printer not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
app.get(`${basePath}/printer/:id`, 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 printer = await db.getById(req.user.id, parsedId.id);
if (!printer) {
return res.status(404).json({ error: 'Printer not found' });
}
res.status(200).json({ printer });
} catch (error) {
const status = printerErrorStatus(error);
if (status === 500) console.error('Get printer failed:', error);
res.status(status).json({ error: error.message });
}
});
/**
* @openapi
* /printer:
* post:
* tags: [Printer]
* summary: Create printer
* description: |
* Creates a new printer for the selected company.
* `type` must be `"esc/pos"` (lines) or `"zpl"` (pages).
* security:
* - cookieAuth: []
* x-markdown: printer/create.md
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/PrinterCreateInput'
* responses:
* 201:
* description: Created printer
* content:
* application/json:
* schema:
* type: object
* properties:
* printer:
* $ref: '#/components/schemas/Printer'
* 400:
* description: Invalid input or missing fields
* 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'
*/
app.post(`${basePath}/printer`, async (req, res) => {
const selected = requireSelectedCompany(req);
if (selected.error) {
return res.status(400).json({ error: selected.error });
}
const { address, type, model, serial, sort, desc } = req.body ?? {};
try {
const printer = await db.create(req.user.id, {
address,
type,
model,
serial,
sort,
desc,
});
emit('printer', { companyId: selected.companyId });
res.status(201).json({ printer });
} catch (error) {
const status = printerErrorStatus(error);
if (status === 500) console.error('Create printer failed:', error);
res.status(status).json({ error: error.message });
}
});
async function handleUpdate(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 { address, type, model, serial, sort, desc } = req.body ?? {};
try {
const printer = await db.update(req.user.id, parsedId.id, {
address,
type,
model,
serial,
sort,
desc,
});
emit('printer', { companyId: selected.companyId });
res.status(200).json({ printer });
} catch (error) {
const status = printerErrorStatus(error);
if (status === 500) console.error('Update printer failed:', error);
res.status(status).json({ error: error.message });
}
}
/**
* @openapi
* /printer/{id}:
* patch:
* tags: [Printer]
* summary: Update printer (partial)
* description: Updates specified fields of an existing printer for the selected company.
* security:
* - cookieAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Printer ID
* x-markdown: printer/update.md
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/PrinterUpdateInput'
* responses:
* 200:
* description: Updated printer
* content:
* application/json:
* schema:
* type: object
* properties:
* printer:
* $ref: '#/components/schemas/Printer'
* 400:
* description: Invalid input
* 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: Printer not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* put:
* tags: [Printer]
* summary: Update printer
* description: Updates specified fields of an existing printer for the selected company.
* security:
* - cookieAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Printer ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/PrinterUpdateInput'
* responses:
* 200:
* description: Updated printer
* content:
* application/json:
* schema:
* type: object
* properties:
* printer:
* $ref: '#/components/schemas/Printer'
* 400:
* description: Invalid input
* 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: Printer not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
app.patch(`${basePath}/printer/:id`, handleUpdate);
app.put(`${basePath}/printer/:id`, handleUpdate);
/**
* @openapi
* /printer/{id}:
* delete:
* tags: [Printer]
* summary: Delete printer
* description: Deletes a printer for the authenticated user's selected company.
* security:
* - cookieAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Printer ID
* x-markdown: printer/delete.md
* responses:
* 204:
* description: Printer deleted
* 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: Printer not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
app.delete(`${basePath}/printer/:id`, 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 {
await db.remove(req.user.id, parsedId.id);
emit('printer', { companyId: selected.companyId });
res.sendStatus(204);
} catch (error) {
const status = printerErrorStatus(error);
if (status === 500) console.error('Delete printer failed:', error);
res.status(status).json({ error: error.message });
}
});
}

118
src/api/routes/stock.js Normal file
View File

@@ -0,0 +1,118 @@
import * as db from '../../db/stock.js';
import { emit } from '../sse.js';
function requireSelectedCompany(req) {
const companyId = req.user?.selectedCompanyId;
if (companyId == null) {
return { error: 'No company selected' };
}
return { companyId };
}
function stockErrorStatus(error) {
if (error.message === 'No company selected') return 400;
if (error.message === 'Not authorized') return 403;
if (error.message === 'Company not found') return 404;
if (error.message === 'Article not found') return 404;
if (error.message === 'Warehouse not found') return 404;
if (error.message?.includes('SKU required')) return 400;
if (error.message?.includes('Warehouse required')) return 400;
if (error.message?.includes('Amount must be')) return 400;
if (error.message?.includes('Invalid amount')) return 400;
if (error.message === 'No items to adjust') return 400;
return 500;
}
function emitStockEvents(companyId, body, result) {
emit('stock', { companyId });
emit('ledger', { companyId });
emit('articles', { companyId });
if (body.sku) {
emit(`article-${body.sku}`, { companyId });
}
if (Array.isArray(body.lines)) {
for (const line of body.lines) {
if (line?.sku) {
emit(`article-${line.sku}`, { companyId });
}
}
}
}
/**
* Registers stock adjustment routes for the authenticated user's selected company.
* All operations append to the append-only ledger under an implicit "adjustment" manifest.
*
* @param {import('express').Application} app
* @param {string} [basePath='']
*/
export function register(app, basePath = '') {
/**
* @openapi
* /stock/adjust:
* post:
* tags: [Stock]
* summary: Adjust stock manually
* description: |
* Writes signed (+ or -) entries to the append-only ledger under an implicit manifest
* of type "adjustment", allocating a number from the "adjustment" number scheme.
* security:
* - cookieAuth: []
* x-markdown: stock/adjust.md
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/StockAdjustmentInput'
* responses:
* 201:
* description: Stock adjusted successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/StockAdjustmentResult'
* 400:
* description: Missing fields, invalid amount, 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: Article or warehouse not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
app.post(`${basePath}/stock/adjust`, async (req, res) => {
const selected = requireSelectedCompany(req);
if (selected.error) {
return res.status(400).json({ error: selected.error });
}
try {
const result = await db.adjust(req.user.id, req.body ?? {});
emitStockEvents(selected.companyId, req.body ?? {}, result);
res.status(201).json(result);
} catch (error) {
const status = stockErrorStatus(error);
if (status === 500) console.error('Stock adjust failed:', error);
res.status(status).json({ error: error.message });
}
});
}

136
src/api/routes/warehouse.js Normal file
View File

@@ -0,0 +1,136 @@
import * as db from '../../db/warehouse.js';
import { emit } from '../sse.js';
function requireSelectedCompany(req) {
const companyId = req.user?.selectedCompanyId;
if (companyId == null) {
return { error: 'No company selected' };
}
return { companyId };
}
function warehouseErrorStatus(error) {
if (error.message === 'No company selected') return 400;
if (error.message === 'Not authorized') return 403;
if (error.message === 'Company not found') return 404;
if (error.message === 'Warehouse not found') return 404;
if (error.message === 'Name required') return 400;
if (error.message === 'Warehouse already exists') return 409;
if (error.message === 'Warehouse in use in ledger') return 409;
return 500;
}
/**
* Registers warehouse routes for the authenticated user's selected company.
* @param {import('express').Application} app
* @param {string} [basePath='']
*/
export function register(app, basePath = '') {
app.get(`${basePath}/warehouse`, async (req, res) => {
const selected = requireSelectedCompany(req);
if (selected.error) {
return res.status(400).json({ error: selected.error });
}
try {
const warehouses = await db.list(req.user.id);
res.status(200).json({ warehouses });
} catch (error) {
const status = warehouseErrorStatus(error);
if (status === 500) console.error('List warehouses failed:', error);
res.status(status).json({ error: error.message });
}
});
app.get(`${basePath}/warehouse/:id`, 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 warehouse = await db.getById(req.user.id, id);
if (!warehouse) {
return res.status(404).json({ error: 'Warehouse not found' });
}
res.status(200).json({ warehouse });
} catch (error) {
const status = warehouseErrorStatus(error);
if (status === 500) console.error('Get warehouse failed:', error);
res.status(status).json({ error: error.message });
}
});
app.post(`${basePath}/warehouse`, async (req, res) => {
const selected = requireSelectedCompany(req);
if (selected.error) {
return res.status(400).json({ error: selected.error });
}
const { name } = req.body ?? {};
try {
const warehouse = await db.create(req.user.id, { name });
emit('warehouse', { companyId: selected.companyId });
res.status(201).json({ warehouse });
} catch (error) {
const status = warehouseErrorStatus(error);
if (status === 500) console.error('Create warehouse failed:', error);
res.status(status).json({ error: error.message });
}
});
async function handleUpdate(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 { name } = req.body ?? {};
try {
const warehouse = await db.update(req.user.id, id, { name });
emit('warehouse', { companyId: selected.companyId });
res.status(200).json({ warehouse });
} catch (error) {
const status = warehouseErrorStatus(error);
if (status === 500) console.error('Update warehouse failed:', error);
res.status(status).json({ error: error.message });
}
}
app.patch(`${basePath}/warehouse/:id`, handleUpdate);
app.put(`${basePath}/warehouse/:id`, handleUpdate);
app.delete(`${basePath}/warehouse/:id`, 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 {
await db.remove(req.user.id, id);
emit('warehouse', { companyId: selected.companyId });
res.sendStatus(204);
} catch (error) {
const status = warehouseErrorStatus(error);
if (status === 500) console.error('Delete warehouse failed:', error);
res.status(status).json({ error: error.message });
}
});
}