1130 lines
57 KiB
TypeScript
1130 lines
57 KiB
TypeScript
import type { FastifyInstance, FastifySchema } from 'fastify';
|
|
import type pg from 'pg';
|
|
import type { CurrentUser, Role } from '../../../shared/auth.js';
|
|
import { AppError } from '../../../shared/errors.js';
|
|
import { parseJson } from '../../../shared/http-input.js';
|
|
import { errorSchema } from '../../../shared/swagger.js';
|
|
import { requireRole, requireAnyRole } from '../../../shared/auth.js';
|
|
import { z } from 'zod';
|
|
import { ListStoresUseCase } from '../application/list-stores.js';
|
|
import { ListTerminalsUseCase } from '../application/list-terminals.js';
|
|
import { GetPosConfigUseCase } from '../application/get-pos-config.js';
|
|
import { OpenCashSessionUseCase } from '../application/open-cash-session.js';
|
|
import { CloseCashSessionUseCase } from '../application/close-cash-session.js';
|
|
import { CreatePosSaleUseCase } from '../application/create-pos-sale.js';
|
|
import { PgStoreRepository } from '../infrastructure/pg-store-repository.js';
|
|
import { PgTerminalRepository } from '../infrastructure/pg-terminal-repository.js';
|
|
import { PgPaymentMethodRepository } from '../infrastructure/pg-payment-method-repository.js';
|
|
import { PgCashSessionRepository } from '../infrastructure/pg-cash-session-repository.js';
|
|
|
|
export interface PosRouteDeps {
|
|
pool: pg.Pool;
|
|
authenticate: (request: import('fastify').FastifyRequest) => Promise<CurrentUser>;
|
|
}
|
|
|
|
const idParamSchema = z.object({ id: z.string().uuid() });
|
|
|
|
export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps) {
|
|
const { pool, authenticate } = deps;
|
|
|
|
const storeRepo = new PgStoreRepository(pool);
|
|
const terminalRepo = new PgTerminalRepository(pool);
|
|
const paymentMethodRepo = new PgPaymentMethodRepository(pool);
|
|
const sessionRepo = new PgCashSessionRepository(pool);
|
|
const createPosSale = new CreatePosSaleUseCase(pool);
|
|
|
|
const listStores = new ListStoresUseCase(storeRepo);
|
|
const listTerminals = new ListTerminalsUseCase(terminalRepo);
|
|
const getConfig = new GetPosConfigUseCase(storeRepo, terminalRepo, paymentMethodRepo, sessionRepo);
|
|
const openSession = new OpenCashSessionUseCase(sessionRepo, terminalRepo);
|
|
const closeSession = new CloseCashSessionUseCase(sessionRepo);
|
|
|
|
// ── Admin: stores ─────────────────────────────────────────────────────────
|
|
|
|
app.get('/pos/admin/stores', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'List POS stores',
|
|
querystring: { type: 'object', properties: { active: { type: 'boolean' } } },
|
|
response: { 401: errorSchema, 403: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { active } = request.query as { active?: boolean };
|
|
const result = await listStores.execute({ active });
|
|
return reply.send(result);
|
|
});
|
|
|
|
app.post('/pos/admin/stores', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'Create POS store',
|
|
body: {
|
|
type: 'object',
|
|
required: ['name', 'slug'],
|
|
properties: {
|
|
name: { type: 'string', minLength: 1, maxLength: 200 },
|
|
slug: { type: 'string', pattern: '^[a-z0-9]+(?:-[a-z0-9]+)*$' },
|
|
address: { type: 'string' },
|
|
taxId: { type: 'string' },
|
|
contactEmail: { type: 'string' },
|
|
contactPhone: { type: 'string' },
|
|
receiptHeader: { type: 'string' },
|
|
receiptFooter: { type: 'string' },
|
|
},
|
|
},
|
|
response: { 400: errorSchema, 401: errorSchema, 403: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const body = parseJson(
|
|
z.object({
|
|
name: z.string().min(1).max(200),
|
|
slug: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
|
|
address: z.string().optional(),
|
|
taxId: z.string().optional(),
|
|
contactEmail: z.string().optional(),
|
|
contactPhone: z.string().optional(),
|
|
receiptHeader: z.string().optional(),
|
|
receiptFooter: z.string().optional(),
|
|
}),
|
|
request.body ?? {},
|
|
);
|
|
const result = await pool.query<{ id: string; name: string; slug: string; active: boolean }>(
|
|
`INSERT INTO pos_stores (name, slug, address, tax_id, contact_email, contact_phone, receipt_header, receipt_footer)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
RETURNING id, name, slug, active`,
|
|
[body.name, body.slug, body.address, body.taxId, body.contactEmail, body.contactPhone, body.receiptHeader, body.receiptFooter],
|
|
);
|
|
return reply.code(201).send(result.rows[0]);
|
|
});
|
|
|
|
// ── Admin: terminals ─────────────────────────────────────────────────────
|
|
|
|
app.get('/pos/admin/terminals', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'List POS terminals',
|
|
querystring: {
|
|
type: 'object',
|
|
properties: {
|
|
storeId: { type: 'string', format: 'uuid' },
|
|
status: { type: 'string', enum: ['active', 'disabled', 'decommissioned'] },
|
|
},
|
|
},
|
|
response: { 401: errorSchema, 403: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { storeId, status } = request.query as { storeId?: string; status?: string };
|
|
const result = await listTerminals.execute({ storeId, status: status as 'active' | 'disabled' | 'decommissioned' | undefined });
|
|
return reply.send(result);
|
|
});
|
|
|
|
app.post('/pos/admin/terminals', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'Create POS terminal',
|
|
body: {
|
|
type: 'object',
|
|
required: ['storeId', 'name'],
|
|
properties: {
|
|
storeId: { type: 'string', format: 'uuid' },
|
|
name: { type: 'string', minLength: 1, maxLength: 100 },
|
|
},
|
|
},
|
|
response: { 400: errorSchema, 401: errorSchema, 403: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const body = parseJson(
|
|
z.object({ storeId: z.string().uuid(), name: z.string().min(1).max(100) }),
|
|
request.body ?? {},
|
|
);
|
|
// Generate a short binding code (8 hex chars)
|
|
const bindingCode = Math.random().toString(16).slice(2, 10).toUpperCase();
|
|
const result = await pool.query<{ id: string; name: string; bindingCode: string; storeId: string }>(
|
|
`INSERT INTO pos_terminals (store_id, name, binding_code)
|
|
VALUES ($1, $2, $3)
|
|
RETURNING id, name, binding_code as "bindingCode", store_id as "storeId"`,
|
|
[body.storeId, body.name, bindingCode],
|
|
);
|
|
return reply.code(201).send(result.rows[0]);
|
|
});
|
|
|
|
app.get<{ Params: { id: string } }>('/pos/admin/terminals/:id', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'Get terminal',
|
|
params: idParamSchema,
|
|
response: { 401: errorSchema, 403: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { id } = parseJson(idParamSchema, request.params);
|
|
const terminal = await terminalRepo.findById(id);
|
|
if (!terminal) throw new AppError(404, 'TERMINAL_NOT_FOUND', 'Terminal not found');
|
|
return reply.send(terminal);
|
|
});
|
|
|
|
app.delete<{ Params: { id: string } }>('/pos/admin/terminals/:id', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'Decommission terminal',
|
|
params: idParamSchema,
|
|
response: { 401: errorSchema, 403: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { id } = parseJson(idParamSchema, request.params);
|
|
await pool.query(`UPDATE pos_terminals SET status = 'decommissioned' WHERE id = $1`, [id]);
|
|
return reply.send({ ok: true });
|
|
});
|
|
|
|
// ── Terminal: me + bind + config ───────────────────────────────────────
|
|
|
|
app.get('/pos/terminals/me', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Get current terminal info',
|
|
headers: { type: 'object', properties: { 'x-terminal-id': { type: 'string', format: 'uuid' } } },
|
|
response: { 401: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const terminalId = request.headers['x-terminal-id'] as string | undefined;
|
|
if (!terminalId) throw new AppError(400, 'MISSING_TERMINAL_ID', 'x-terminal-id header required');
|
|
const terminal = await terminalRepo.findById(terminalId);
|
|
if (!terminal) throw new AppError(404, 'TERMINAL_NOT_FOUND', 'Terminal not found');
|
|
return reply.send(terminal);
|
|
});
|
|
|
|
app.post('/pos/terminals/bind', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Bind terminal with code',
|
|
body: {
|
|
type: 'object',
|
|
required: ['bindingCode'],
|
|
properties: { bindingCode: { type: 'string', minLength: 8, maxLength: 8 } },
|
|
},
|
|
response: { 400: errorSchema, 401: errorSchema, 404: errorSchema, 409: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const body = parseJson(z.object({ bindingCode: z.string().length(8) }), request.body ?? {});
|
|
const terminal = await terminalRepo.findByBindingCode(body.bindingCode.toUpperCase());
|
|
if (!terminal) throw new AppError(404, 'TERMINAL_NOT_FOUND', 'Terminal not found');
|
|
if (terminal.status !== 'active') throw new AppError(409, 'TERMINAL_NOT_ACTIVE', 'Terminal is not active');
|
|
const bound = await terminalRepo.bind(terminal.id, body.bindingCode.toUpperCase());
|
|
return reply.send({ terminalId: bound.id, storeId: bound.storeId });
|
|
});
|
|
|
|
app.get('/pos/config', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Get POS terminal config',
|
|
headers: { type: 'object', properties: { 'x-terminal-id': { type: 'string', format: 'uuid' } } },
|
|
response: { 401: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const terminalId = request.headers['x-terminal-id'] as string | undefined;
|
|
if (!terminalId) throw new AppError(400, 'MISSING_TERMINAL_ID', 'x-terminal-id header required');
|
|
const config = await getConfig.execute(terminalId);
|
|
return reply.send(config);
|
|
});
|
|
|
|
// ── Cash sessions ───────────────────────────────────────────────────────
|
|
|
|
app.get('/pos/sessions/me', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Get current open session',
|
|
headers: { type: 'object', properties: { 'x-terminal-id': { type: 'string', format: 'uuid' } } },
|
|
response: { 401: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const terminalId = request.headers['x-terminal-id'] as string | undefined;
|
|
if (!terminalId) throw new AppError(400, 'MISSING_TERMINAL_ID', 'x-terminal-id header required');
|
|
const session = await sessionRepo.findOpenByTerminal(terminalId);
|
|
if (!session) throw new AppError(404, 'SESSION_NOT_FOUND', 'No open session');
|
|
return reply.send(session);
|
|
});
|
|
|
|
app.post('/pos/sessions', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Open cash session',
|
|
headers: { type: 'object', properties: { 'x-terminal-id': { type: 'string', format: 'uuid' } } },
|
|
body: {
|
|
type: 'object',
|
|
required: ['openingCashCents'],
|
|
properties: { openingCashCents: { type: 'integer', minimum: 0 } },
|
|
},
|
|
response: { 400: errorSchema, 401: errorSchema, 404: errorSchema, 409: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const terminalId = request.headers['x-terminal-id'] as string | undefined;
|
|
if (!terminalId) throw new AppError(400, 'MISSING_TERMINAL_ID', 'x-terminal-id header required');
|
|
const body = parseJson(z.object({ openingCashCents: z.number().int().min(0) }), request.body ?? {});
|
|
try {
|
|
const session = await openSession.execute({ terminalId, userId: user.id, openingCashCents: body.openingCashCents });
|
|
return reply.code(201).send(session);
|
|
} catch (err) {
|
|
if (err instanceof AppError) throw err;
|
|
throw new AppError(409, 'SESSION_ERROR', String(err));
|
|
}
|
|
});
|
|
|
|
app.post<{ Params: { id: string } }>('/pos/sessions/:id/close', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Close cash session',
|
|
params: idParamSchema,
|
|
body: {
|
|
type: 'object',
|
|
required: ['closingCashCents', 'actualCashCents'],
|
|
properties: {
|
|
closingCashCents: { type: 'integer', minimum: 0 },
|
|
actualCashCents: { type: 'integer', minimum: 0 },
|
|
notes: { type: 'string' },
|
|
},
|
|
},
|
|
response: { 400: errorSchema, 401: errorSchema, 404: errorSchema, 409: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { id } = parseJson(idParamSchema, request.params);
|
|
const body = parseJson(
|
|
z.object({
|
|
closingCashCents: z.number().int().min(0),
|
|
actualCashCents: z.number().int().min(0),
|
|
notes: z.string().optional(),
|
|
}),
|
|
request.body ?? {},
|
|
);
|
|
try {
|
|
const session = await closeSession.execute({ sessionId: id, ...body });
|
|
return reply.send(session);
|
|
} catch (err) {
|
|
if (err instanceof AppError) throw err;
|
|
throw new AppError(409, 'CLOSE_ERROR', String(err));
|
|
}
|
|
});
|
|
|
|
// ── POS-005: Product search ───────────────────────────────────────────────
|
|
|
|
app.get('/pos/products/search', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Search products for POS',
|
|
querystring: {
|
|
type: 'object',
|
|
properties: {
|
|
q: { type: 'string', minLength: 1 },
|
|
storeId: { type: 'string', format: 'uuid' },
|
|
limit: { type: 'integer', minimum: 1, maximum: 50, default: 20 },
|
|
},
|
|
},
|
|
response: { 401: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { q, storeId, limit = 20 } = request.query as { q?: string; storeId?: string; limit?: number };
|
|
if (!q || q.trim().length < 2) throw new AppError(400, 'INVALID_QUERY', 'Query must be at least 2 characters');
|
|
const result = await pool.query(
|
|
`SELECT v.id AS variant_id, v.product_id, v.name, v.sku, v.ean,
|
|
COALESCE(s.quantity, 0) AS stock, pp.price_cents, c.name AS category, b.name AS brand
|
|
FROM catalog_product_variants v
|
|
JOIN catalog_products p ON p.id = v.product_id
|
|
LEFT JOIN LATERAL (SELECT quantity FROM inventory_stock WHERE variant_id = v.id AND store_id = $3 LIMIT 1) s ON true
|
|
LEFT JOIN pricing_variant_prices pp ON pp.variant_id = v.id AND pp.currency = 'EUR'
|
|
LEFT JOIN catalog_product_categories pc ON pc.variant_id = v.id AND pc.is_primary = true
|
|
LEFT JOIN categories_categories c ON c.id = pc.category_id
|
|
LEFT JOIN brands_brands b ON b.id = p.brand_id
|
|
WHERE (v.name ILIKE $1 OR v.sku ILIKE $1 OR v.ean = $1) AND v.active = true AND p.active = true
|
|
ORDER BY v.name LIMIT $2`,
|
|
[`%${q.trim()}%`, limit, storeId ?? null],
|
|
);
|
|
return reply.send({ items: result.rows.map(r => ({
|
|
variantId: r.variant_id, productId: r.product_id, name: r.name, sku: r.sku, ean: r.ean,
|
|
stock: r.stock, priceCents: r.price_cents, category: r.category, brand: r.brand,
|
|
})) });
|
|
});
|
|
|
|
app.get<{ Params: { ean: string } }>('/pos/products/by-ean/:ean', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Get product by EAN',
|
|
params: { type: 'object', properties: { ean: { type: 'string' } } },
|
|
response: { 401: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { ean } = request.params;
|
|
const result = await pool.query(
|
|
`SELECT v.id AS variant_id, v.product_id, v.name, v.sku, v.ean, COALESCE(s.quantity, 0) AS stock, pp.price_cents
|
|
FROM catalog_product_variants v
|
|
JOIN catalog_products p ON p.id = v.product_id
|
|
LEFT JOIN LATERAL (SELECT quantity FROM inventory_stock WHERE variant_id = v.id LIMIT 1) s ON true
|
|
LEFT JOIN pricing_variant_prices pp ON pp.variant_id = v.id AND pp.currency = 'EUR'
|
|
WHERE v.ean = $1 AND v.active = true AND p.active = true LIMIT 1`,
|
|
[ean],
|
|
);
|
|
if (!result.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Product not found');
|
|
const r = result.rows[0];
|
|
return reply.send({ variantId: r.variant_id, productId: r.product_id, name: r.name, sku: r.sku, ean: r.ean, stock: r.stock, priceCents: r.price_cents });
|
|
});
|
|
|
|
app.get<{ Params: { sku: string } }>('/pos/products/by-sku/:sku', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Get product by SKU',
|
|
params: { type: 'object', properties: { sku: { type: 'string' } } },
|
|
response: { 401: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { sku } = request.params;
|
|
const result = await pool.query(
|
|
`SELECT v.id AS variant_id, v.product_id, v.name, v.sku, v.ean, COALESCE(s.quantity, 0) AS stock, pp.price_cents
|
|
FROM catalog_product_variants v
|
|
JOIN catalog_products p ON p.id = v.product_id
|
|
LEFT JOIN LATERAL (SELECT quantity FROM inventory_stock WHERE variant_id = v.id LIMIT 1) s ON true
|
|
LEFT JOIN pricing_variant_prices pp ON pp.variant_id = v.id AND pp.currency = 'EUR'
|
|
WHERE v.sku = $1 AND v.active = true AND p.active = true LIMIT 1`,
|
|
[sku],
|
|
);
|
|
if (!result.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Product not found');
|
|
const r = result.rows[0];
|
|
return reply.send({ variantId: r.variant_id, productId: r.product_id, name: r.name, sku: r.sku, ean: r.ean, stock: r.stock, priceCents: r.price_cents });
|
|
});
|
|
|
|
// ── POS-005: Admin payment methods ───────────────────────────────────────
|
|
|
|
app.get<{ Params: { storeId: string } }>('/pos/admin/payment-methods', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'List payment methods',
|
|
querystring: { type: 'object', properties: { storeId: { type: 'string', format: 'uuid' } } },
|
|
response: { 401: errorSchema, 403: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { storeId } = request.query as { storeId: string };
|
|
const methods = await paymentMethodRepo.listByStore(storeId);
|
|
return reply.send({ items: methods });
|
|
});
|
|
|
|
app.post('/pos/admin/payment-methods', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'Create payment method',
|
|
body: {
|
|
type: 'object',
|
|
required: ['storeId', 'code', 'label', 'kind'],
|
|
properties: {
|
|
storeId: { type: 'string', format: 'uuid' },
|
|
code: { type: 'string', minLength: 1, maxLength: 32 },
|
|
label: { type: 'string', minLength: 1, maxLength: 64 },
|
|
kind: { type: 'string', enum: ['cash', 'card', 'other'] },
|
|
active: { type: 'boolean', default: true },
|
|
sortOrder: { type: 'integer', default: 0 },
|
|
},
|
|
},
|
|
response: { 400: errorSchema, 401: errorSchema, 403: errorSchema, 409: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const body = parseJson(
|
|
z.object({
|
|
storeId: z.string().uuid(),
|
|
code: z.string().min(1).max(32),
|
|
label: z.string().min(1).max(64),
|
|
kind: z.enum(['cash', 'card', 'other']),
|
|
active: z.boolean().default(true),
|
|
sortOrder: z.number().int().default(0),
|
|
}),
|
|
request.body ?? {},
|
|
);
|
|
try {
|
|
const result = await pool.query(
|
|
`INSERT INTO pos_payment_methods (store_id, code, label, kind, active, sort_order)
|
|
VALUES ($1, $2, $3, $4, $5, $6)
|
|
RETURNING id, store_id AS "storeId", code, label, kind, active, sort_order AS "sortOrder"`,
|
|
[body.storeId, body.code, body.label, body.kind, body.active, body.sortOrder],
|
|
);
|
|
return reply.code(201).send(result.rows[0]);
|
|
} catch (err: unknown) {
|
|
if ((err as Record<string, unknown>).code === '23505') throw new AppError(409, 'DUPLICATE', 'Code already exists');
|
|
throw err;
|
|
}
|
|
});
|
|
|
|
app.patch<{ Params: { id: string } }>('/pos/admin/payment-methods/:id', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'Update payment method',
|
|
params: { type: 'object', properties: { id: { type: 'string', format: 'uuid' } } },
|
|
body: {
|
|
type: 'object',
|
|
properties: { label: { type: 'string' }, active: { type: 'boolean' }, sortOrder: { type: 'integer' } },
|
|
},
|
|
response: { 401: errorSchema, 403: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { id } = request.params;
|
|
const body = (request.body ?? {}) as Record<string, unknown>;
|
|
const sets: string[] = [];
|
|
const vals: unknown[] = [];
|
|
if (body.label !== undefined) { vals.push(body.label); sets.push(`label = $${vals.length}`); }
|
|
if (body.active !== undefined) { vals.push(body.active); sets.push(`active = $${vals.length}`); }
|
|
if (body.sortOrder !== undefined) { vals.push(body.sortOrder); sets.push(`sort_order = $${vals.length}`); }
|
|
if (sets.length === 0) return reply.send({ ok: true });
|
|
vals.push(id);
|
|
const result = await pool.query(
|
|
`UPDATE pos_payment_methods SET ${sets.join(', ')}, updated_at = now() WHERE id = $${vals.length} RETURNING *`,
|
|
vals,
|
|
);
|
|
if (!result.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Payment method not found');
|
|
return reply.send(result.rows[0]);
|
|
});
|
|
|
|
|
|
// ── POS-008: POST /pos/sales idempotent ───────────────────────────────────
|
|
|
|
app.post('/pos/sales', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Record a POS sale (idempotent)',
|
|
body: {
|
|
type: 'object',
|
|
required: ['idempotencyKey', 'cashSessionId', 'terminalId', 'items', 'payments'],
|
|
properties: {
|
|
idempotencyKey: { type: 'string', minLength: 1, maxLength: 128 },
|
|
cashSessionId: { type: 'string', format: 'uuid' },
|
|
terminalId: { type: 'string', format: 'uuid' },
|
|
items: {
|
|
type: 'array',
|
|
items: {
|
|
type: 'object',
|
|
required: ['variantId', 'productId', 'sku', 'name', 'unitPriceCents', 'discountCents', 'taxCents', 'quantity'],
|
|
properties: {
|
|
variantId: { type: 'string', format: 'uuid' },
|
|
productId: { type: 'string', format: 'uuid' },
|
|
sku: { type: 'string' },
|
|
ean: { type: ['string', 'null'] },
|
|
name: { type: 'string' },
|
|
unitPriceCents: { type: 'integer', minimum: 0 },
|
|
discountCents: { type: 'integer', minimum: 0 },
|
|
taxCents: { type: 'integer', minimum: 0 },
|
|
quantity: { type: 'integer', minimum: 1 },
|
|
},
|
|
},
|
|
},
|
|
payments: {
|
|
type: 'array',
|
|
minItems: 1,
|
|
items: {
|
|
type: 'object',
|
|
required: ['kind', 'amountCents'],
|
|
properties: {
|
|
kind: { type: 'string', enum: ['cash', 'card', 'other'] },
|
|
amountCents: { type: 'integer', minimum: 1 },
|
|
tenderedCents: { type: 'integer', minimum: 0 },
|
|
last4: { type: 'string', maxLength: 4 },
|
|
},
|
|
},
|
|
},
|
|
customerId: { type: 'string', format: 'uuid' },
|
|
},
|
|
},
|
|
response: { 400: errorSchema, 401: errorSchema, 404: errorSchema, 409: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const body = parseJson(
|
|
z.object({
|
|
idempotencyKey: z.string().min(1).max(128),
|
|
cashSessionId: z.string().uuid(),
|
|
terminalId: z.string().uuid(),
|
|
items: z.array(z.object({
|
|
variantId: z.string().uuid(), productId: z.string().uuid(), sku: z.string(),
|
|
ean: z.string().nullable(), name: z.string(),
|
|
unitPriceCents: z.number().int().min(0), discountCents: z.number().int().min(0),
|
|
taxCents: z.number().int().min(0), quantity: z.number().int().min(1),
|
|
})),
|
|
payments: z.array(z.object({
|
|
kind: z.enum(['cash', 'card', 'other']), amountCents: z.number().int().min(1),
|
|
tenderedCents: z.number().int().min(0).optional(), last4: z.string().max(4).optional(),
|
|
})),
|
|
customerId: z.string().uuid().optional(),
|
|
}),
|
|
request.body ?? {},
|
|
);
|
|
const result = await createPosSale.execute({ ...body, userId: user.id });
|
|
return reply.code(201).send(result);
|
|
});
|
|
|
|
|
|
// ── POS-009: Customer search for POS ──────────────────────────────────────
|
|
|
|
app.get('/pos/customers/search', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Search customers for POS association',
|
|
querystring: {
|
|
type: 'object',
|
|
properties: { q: { type: 'string', minLength: 2 }, limit: { type: 'integer', minimum: 1, maximum: 20, default: 10 } },
|
|
},
|
|
response: { 401: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { q, limit = 10 } = request.query as { q?: string; limit?: number };
|
|
if (!q || q.trim().length < 2) return reply.send({ items: [] });
|
|
const result = await pool.query(
|
|
`SELECT u.id, u.email, p.first_name AS "firstName", p.last_name AS "lastName", p.phone
|
|
FROM identity_users u
|
|
LEFT JOIN users_profiles p ON p.user_id = u.id
|
|
WHERE u.email ILIKE $1 OR p.first_name ILIKE $1 OR p.last_name ILIKE $1 OR p.phone ILIKE $1
|
|
ORDER BY p.last_name LIMIT $2`,
|
|
[`%${q.trim()}%`, limit],
|
|
);
|
|
return reply.send({ items: result.rows });
|
|
});
|
|
|
|
app.get<{ Params: { id: string } }>('/pos/customers/:id', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Get customer details for POS',
|
|
params: { type: 'object', properties: { id: { type: 'string', format: 'uuid' } } },
|
|
response: { 401: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { id } = request.params;
|
|
const result = await pool.query(
|
|
`SELECT u.id, u.email, p.first_name AS "firstName", p.last_name AS "lastName", p.phone
|
|
FROM identity_users u
|
|
LEFT JOIN users_profiles p ON p.user_id = u.id
|
|
WHERE u.id = $1 LIMIT 1`,
|
|
[id],
|
|
);
|
|
if (!result.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Customer not found');
|
|
return reply.send(result.rows[0]);
|
|
});
|
|
|
|
|
|
// ── POS-010: Discount validation ──────────────────────────────────────────
|
|
|
|
app.post('/pos/discounts/validate', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Validate discount before applying',
|
|
body: {
|
|
type: 'object',
|
|
required: ['unitPriceCents', 'discountCents'],
|
|
properties: {
|
|
unitPriceCents: { type: 'integer', minimum: 0 },
|
|
discountCents: { type: 'integer', minimum: 0 },
|
|
discountPercent: { type: 'number', minimum: 0, maximum: 100 },
|
|
role: { type: 'string', enum: ['admin', 'pos_manager', 'pos_cashier'] },
|
|
},
|
|
},
|
|
response: { 401: errorSchema, 403: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const body = (request.body ?? {}) as { unitPriceCents?: number; discountCents?: number; discountPercent?: number; role?: string };
|
|
const unitPriceCents = body.unitPriceCents ?? 0;
|
|
const discountCents = body.discountCents ?? 0;
|
|
const discountPercent = body.discountPercent ?? (unitPriceCents > 0 ? (discountCents / unitPriceCents) * 100 : 0);
|
|
|
|
// Cashiers capped at 50% per item
|
|
const maxPercent = user.role === 'pos_manager' || user.role === 'admin' ? 100 : 50;
|
|
if (discountPercent > maxPercent) {
|
|
throw new AppError(403, 'DISCOUNT_EXCEEDED', `Discount ${discountPercent.toFixed(0)}% exceeds max ${maxPercent}% for role`);
|
|
}
|
|
if (discountCents > unitPriceCents) {
|
|
throw new AppError(400, 'INVALID_DISCOUNT', 'Discount cannot exceed unit price');
|
|
}
|
|
return reply.send({
|
|
valid: true,
|
|
maxPercent,
|
|
appliedPercent: discountPercent,
|
|
appliedCents: discountCents,
|
|
finalPriceCents: unitPriceCents - discountCents,
|
|
});
|
|
});
|
|
|
|
|
|
// ── POS-011: List sales, void, receipts, session history ──────────────────
|
|
|
|
app.get('/pos/sales', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'List recent POS sales',
|
|
querystring: {
|
|
type: 'object',
|
|
properties: {
|
|
sessionId: { type: 'string', format: 'uuid' },
|
|
limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
|
|
},
|
|
},
|
|
response: { 401: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { sessionId, limit = 20 } = request.query as { sessionId?: string; limit?: number };
|
|
let query = `SELECT o.id, o.total_cents AS "totalCents", o.subtotal_cents AS "subtotalCents",
|
|
o.discount_cents AS "discountCents", o.created_at AS "createdAt",
|
|
u.email AS "userEmail"
|
|
FROM orders_orders o
|
|
LEFT JOIN identity_users u ON u.id = o.user_id
|
|
WHERE o.idempotency_key IS NOT NULL`;
|
|
const params: unknown[] = [];
|
|
if (sessionId) { params.push(sessionId); query += ` AND o.id IN (SELECT order_id FROM pos_cash_sessions WHERE id = $${params.length})`; }
|
|
params.push(limit);
|
|
query += ` ORDER BY o.created_at DESC LIMIT $${params.length}`;
|
|
const result = await pool.query(query, params);
|
|
return reply.send({ items: result.rows });
|
|
});
|
|
|
|
app.post<{ Params: { id: string } }>('/pos/sales/:id/void', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'Void a POS sale',
|
|
params: { type: 'object', properties: { id: { type: 'string', format: 'uuid' } } },
|
|
body: {
|
|
type: 'object',
|
|
required: ['reason'],
|
|
properties: { reason: { type: 'string', minLength: 1 } },
|
|
},
|
|
response: { 401: errorSchema, 403: errorSchema, 404: errorSchema, 409: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin'); // Only admins can void
|
|
const { id } = request.params;
|
|
const { reason } = (request.body ?? {}) as { reason?: string };
|
|
const order = await pool.query<{ id: string }>('SELECT id FROM orders_orders WHERE id = $1', [id]);
|
|
if (!order.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Order not found');
|
|
await pool.query(
|
|
`INSERT INTO orders_order_events (order_id, event, actor_id, metadata)
|
|
VALUES ($1, 'VOIDED', $2, $3)`,
|
|
[id, user.id, JSON.stringify({ reason })],
|
|
);
|
|
return reply.send({ ok: true, voidedAt: new Date().toISOString() });
|
|
});
|
|
|
|
app.get<{ Params: { id: string } }>('/pos/sales/:id/receipt', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Get receipt for a sale',
|
|
params: { type: 'object', properties: { id: { type: 'string', format: 'uuid' } } },
|
|
response: { 401: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { id } = request.params;
|
|
const order = await pool.query(
|
|
`SELECT o.*, u.email FROM orders_orders o LEFT JOIN identity_users u ON u.id = o.user_id WHERE o.id = $1`,
|
|
[id],
|
|
);
|
|
if (!order.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Order not found');
|
|
const items = await pool.query('SELECT * FROM orders_items WHERE order_id = $1', [id]);
|
|
const payments = await pool.query<{ amount_cents: number; provider: string }>(
|
|
'SELECT amount_cents, provider FROM payments_transactions WHERE order_id = $1',
|
|
[id],
|
|
);
|
|
return reply.send({
|
|
order: order.rows[0],
|
|
items: items.rows,
|
|
payments: payments.rows,
|
|
});
|
|
});
|
|
|
|
app.get('/pos/sessions', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'List cash sessions',
|
|
querystring: {
|
|
type: 'object',
|
|
properties: { storeId: { type: 'string', format: 'uuid' }, status: { type: 'string', enum: ['OPEN', 'CLOSED'] }, limit: { type: 'integer', minimum: 1, maximum: 50, default: 20 } },
|
|
},
|
|
response: { 401: errorSchema, 403: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { storeId, status, limit = 20 } = request.query as { storeId?: string; status?: string; limit?: number };
|
|
const conditions: string[] = [];
|
|
const params: unknown[] = [];
|
|
if (storeId) { params.push(storeId); conditions.push(`store_id = $${params.length}`); }
|
|
if (status) { params.push(status); conditions.push(`status = $${params.length}`); }
|
|
params.push(limit);
|
|
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')} AND ` : 'WHERE ';
|
|
const result = await pool.query(
|
|
`SELECT s.*, t.name AS "terminalName", u.email AS "userEmail"
|
|
FROM pos_cash_sessions s
|
|
LEFT JOIN pos_terminals t ON t.id = s.terminal_id
|
|
LEFT JOIN identity_users u ON u.id = s.user_id
|
|
${where} 1=1 ORDER BY s.created_at DESC LIMIT $${params.length}`,
|
|
params,
|
|
);
|
|
return reply.send({ items: result.rows });
|
|
});
|
|
|
|
|
|
|
|
// ── POS-012: Refund + receipt print + analytics ────────────────────────────
|
|
|
|
app.post<{ Params: { id: string } }>('/pos/sales/:id/refund', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Refund a POS sale',
|
|
params: { type: 'object', properties: { id: { type: 'string', format: 'uuid' } } },
|
|
body: {
|
|
type: 'object',
|
|
required: ['refundAmountCents', 'reason'],
|
|
properties: { refundAmountCents: { type: 'integer', minimum: 1 }, reason: { type: 'string', minLength: 1 } },
|
|
},
|
|
response: { 400: errorSchema, 401: errorSchema, 403: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { id } = request.params;
|
|
const body = (request.body ?? {}) as { refundAmountCents?: number; reason?: string };
|
|
const order = await pool.query<{ id: string; total_cents: number }>('SELECT id, total_cents FROM orders_orders WHERE id = $1', [id]);
|
|
if (!order.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Order not found');
|
|
if ((body.refundAmountCents ?? 0) > (order.rows[0].total_cents ?? 0)) throw new AppError(400, 'REFUND_EXCEEDS', 'Refund exceeds amount');
|
|
await pool.query(`INSERT INTO payments_transactions (provider, provider_event_id, provider_payment_id, order_id, amount_cents, currency, status, raw) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, ['pos_refund', `ref-${id}`, `ref-${Date.now()}`, id, body.refundAmountCents, 'EUR', 'COMPLETED', JSON.stringify({ reason: body.reason, by: user.id })]);
|
|
await pool.query(`INSERT INTO orders_order_events (order_id, event, actor_id, metadata) VALUES ($1, 'REFUNDED', $2, $3)`, [id, user.id, JSON.stringify({ amt: body.refundAmountCents, reason: body.reason })]);
|
|
return reply.send({ ok: true, refundedCents: body.refundAmountCents });
|
|
});
|
|
|
|
app.get<{ Params: { id: string } }>('/pos/sales/:id/print', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Get printable receipt',
|
|
params: { type: 'object', properties: { id: { type: 'string', format: 'uuid' } } },
|
|
response: { 401: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { id } = request.params;
|
|
const order = await pool.query('SELECT * FROM orders_orders WHERE id = $1', [id]);
|
|
if (!order.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Sale not found');
|
|
const items = await pool.query('SELECT name, quantity, unit_price_cents, discount_cents, tax_cents FROM orders_items WHERE order_id = $1', [id]);
|
|
const payments = await pool.query<{ amount_cents: number; provider: string }>('SELECT amount_cents, provider FROM payments_transactions WHERE order_id = $1', [id]);
|
|
return reply.send({ receipt: { orderId: id, storeName: 'Mercado de Vida', terminalName: 'TPV', totalCents: order.rows[0].total_cents, createdAt: order.rows[0].created_at, items: items.rows.map(i => ({ name: i.name, qty: i.quantity, unitPrice: i.unit_price_cents, discount: i.discount_cents, tax: i.tax_cents, line: (i.unit_price_cents - i.discount_cents + i.tax_cents) * i.quantity })), payments: payments.rows.map(p => ({ amountCents: p.amount_cents, kind: p.provider })) } });
|
|
});
|
|
|
|
app.get('/pos/analytics/summary', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'POS sales analytics',
|
|
querystring: { type: 'object', properties: { storeId: { type: 'string', format: 'uuid' }, from: { type: 'string' }, to: { type: 'string' } } },
|
|
response: { 401: errorSchema, 403: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { storeId, from, to } = request.query as { storeId?: string; from?: string; to?: string };
|
|
const params: unknown[] = [];
|
|
let df = '';
|
|
if (from) { params.push(from); df += ` AND o.created_at >= $${params.length}`; }
|
|
if (to) { params.push(to); df += ` AND o.created_at <= $${params.length}`; }
|
|
let sf = '';
|
|
if (storeId) { params.push(storeId); sf = ` AND cs.store_id = $${params.length}`; }
|
|
const sum = await pool.query(`SELECT COUNT(*) AS cnt, COALESCE(SUM(o.total_cents),0) AS total, COALESCE(SUM(o.discount_cents),0) AS disc FROM orders_orders o LEFT JOIN pos_cash_sessions cs ON cs.id = o.cash_session_id WHERE o.idempotency_key IS NOT NULL${df}${sf}`, params);
|
|
const byPay = await pool.query(`SELECT provider, COUNT(*) AS cnt, SUM(amount_cents) AS total FROM payments_transactions WHERE status='COMPLETED'${df} GROUP BY provider`, params);
|
|
return reply.send({ summary: sum.rows[0], byPayment: byPay.rows });
|
|
});
|
|
|
|
|
|
|
|
// ── POS-013: Low stock alerts + loyalty + settings + shortcuts ────────────
|
|
|
|
app.get('/pos/inventory/low-stock', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'List low-stock variants for a store',
|
|
querystring: { type: 'object', required: ['storeId'], properties: { storeId: { type: 'string', format: 'uuid' }, threshold: { type: 'integer', minimum: 1, default: 10 } } },
|
|
response: { 401: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { storeId, threshold = 10 } = request.query as { storeId?: string; threshold?: number };
|
|
const result = await pool.query(
|
|
`SELECT v.id AS "variantId", v.name, v.sku, s.quantity AS stock
|
|
FROM catalog_product_variants v
|
|
LEFT JOIN LATERAL (SELECT quantity FROM inventory_stock WHERE variant_id = v.id AND store_id = $1 LIMIT 1) s ON true
|
|
WHERE v.active = true AND (s.quantity IS NULL OR s.quantity <= $2)
|
|
ORDER BY s.quantity ASC NULLS FIRST LIMIT 50`,
|
|
[storeId, threshold],
|
|
);
|
|
return reply.send({ items: result.rows });
|
|
});
|
|
|
|
app.get<{ Params: { customerId: string } }>('/pos/loyalty/:customerId', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Get loyalty info for a customer',
|
|
params: { type: 'object', properties: { customerId: { type: 'string', format: 'uuid' } } },
|
|
response: { 401: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { customerId } = request.params;
|
|
const profile = await pool.query('SELECT user_id, loyalty_points AS "loyaltyPoints", loyalty_tier AS "loyaltyTier" FROM users_profiles WHERE user_id = $1', [customerId]);
|
|
if (!profile.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Customer not found');
|
|
return reply.send({ customerId, points: profile.rows[0].loyaltyPoints ?? 0, tier: profile.rows[0].loyaltyTier ?? 'bronze' });
|
|
});
|
|
|
|
app.post<{ Params: { customerId: string } }>('/pos/loyalty/:customerId/points', {
|
|
schema: {
|
|
tags: ['POS Terminal'],
|
|
summary: 'Award or redeem loyalty points',
|
|
params: { type: 'object', properties: { customerId: { type: 'string', format: 'uuid' } } },
|
|
body: { type: 'object', required: ['delta', 'reason'], properties: { delta: { type: 'integer' }, reason: { type: 'string' } } },
|
|
response: { 400: errorSchema, 401: errorSchema, 404: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager'] as ReadonlyArray<Role>);
|
|
const { customerId } = request.params;
|
|
const { delta, reason } = (request.body ?? {}) as { delta?: number; reason?: string };
|
|
const current = await pool.query<{ loyalty_points: number }>('SELECT loyalty_points FROM users_profiles WHERE user_id = $1', [customerId]);
|
|
if (!current.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Customer not found');
|
|
const newPoints = Math.max(0, (current.rows[0].loyalty_points ?? 0) + (delta ?? 0));
|
|
await pool.query('UPDATE users_profiles SET loyalty_points = $1, updated_at = now() WHERE user_id = $2', [newPoints, customerId]);
|
|
return reply.send({ customerId, points: newPoints, delta: delta ?? 0, reason });
|
|
});
|
|
|
|
app.get('/pos/settings', {
|
|
schema: { tags: ['POS Admin'], summary: 'Get POS store settings', querystring: { type: 'object', properties: { storeId: { type: 'string', format: 'uuid' } } }, response: { 401: errorSchema, 403: errorSchema } } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { storeId } = request.query as { storeId?: string };
|
|
const result = storeId
|
|
? await pool.query('SELECT store_id AS "storeId", receipt_footer AS "receiptFooter", receipt_vat AS "receiptVat", default_payment_method AS "defaultPaymentMethod" FROM pos_store_settings WHERE store_id = $1', [storeId])
|
|
: await pool.query('SELECT store_id AS "storeId", receipt_footer AS "receiptFooter", receipt_vat AS "receiptVat", default_payment_method AS "defaultPaymentMethod" FROM pos_store_settings LIMIT 1');
|
|
return reply.send(result.rows[0] ?? { receiptFooter: 'Gracias por su compra', receiptVat: 'ES00000000', defaultPaymentMethod: 'cash' });
|
|
});
|
|
|
|
app.patch('/pos/settings', {
|
|
schema: {
|
|
tags: ['POS Admin'],
|
|
summary: 'Update POS store settings',
|
|
body: { type: 'object', properties: { storeId: { type: 'string', format: 'uuid' }, receiptFooter: { type: 'string' }, receiptVat: { type: 'string' }, defaultPaymentMethod: { type: 'string', enum: ['cash', 'card', 'other'] } } },
|
|
response: { 401: errorSchema, 403: errorSchema },
|
|
} as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const body = (request.body ?? {}) as Record<string, unknown>;
|
|
if (!body.storeId) throw new AppError(400, 'MISSING_STORE_ID', 'storeId required');
|
|
const sets: string[] = [];
|
|
const vals: unknown[] = [];
|
|
if (body.receiptFooter !== undefined) { vals.push(body.receiptFooter); sets.push(`receipt_footer = $${vals.length}`); }
|
|
if (body.receiptVat !== undefined) { vals.push(body.receiptVat); sets.push(`receipt_vat = $${vals.length}`); }
|
|
if (body.defaultPaymentMethod !== undefined) { vals.push(body.defaultPaymentMethod); sets.push(`default_payment_method = $${vals.length}`); }
|
|
vals.push(body.storeId);
|
|
if (sets.length === 0) return reply.send({ ok: true });
|
|
await pool.query(`INSERT INTO pos_store_settings (store_id, receipt_footer, receipt_vat, default_payment_method) VALUES ($${vals.length}, $1, $2, $3) ON CONFLICT (store_id) DO UPDATE SET ${sets.join(', ')}, updated_at = now()`, vals);
|
|
return reply.send({ ok: true });
|
|
});
|
|
|
|
app.get('/pos/shortcuts', {
|
|
schema: { tags: ['POS Terminal'], summary: 'Get keyboard shortcuts' } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
await authenticate(request);
|
|
return reply.send({ shortcuts: [
|
|
{ key: 'F1', action: 'search', description: 'Focus product search' },
|
|
{ key: 'F2', action: 'pay-cash', description: 'Pay with cash' },
|
|
{ key: 'F3', action: 'pay-card', description: 'Pay with card' },
|
|
{ key: 'F4', action: 'discount', description: 'Apply discount' },
|
|
{ key: 'F5', action: 'customer', description: 'Associate customer' },
|
|
{ key: 'F6', action: 'clear', description: 'Clear cart' },
|
|
{ key: 'F7', action: 'receipt', description: 'Print last receipt' },
|
|
]});
|
|
});
|
|
|
|
|
|
|
|
// ── POS-014: Shifts + tax rates + daily/end-of-day reports ───────────────
|
|
|
|
app.get('/pos/shifts', {
|
|
schema: { tags: ['POS Admin'], summary: 'List POS user shifts', querystring: { type: 'object', properties: { storeId: { type: 'string', format: 'uuid' }, date: { type: 'string' } } }, response: { 401: errorSchema, 403: errorSchema } } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { storeId, date } = request.query as { storeId?: string; date?: string };
|
|
const params: unknown[] = [];
|
|
let filter = '';
|
|
if (storeId) { params.push(storeId); filter += ` AND cs.store_id = $${params.length}`; }
|
|
if (date) { params.push(date); filter += ` AND DATE(cs.created_at) = $${params.length}`; }
|
|
const result = await pool.query(`SELECT cs.id, cs.store_id AS "storeId", cs.user_id AS "userId", u.email AS "userEmail", cs.status, cs.opening_cash_cents AS "openingCash", cs.expected_cash_cents AS "expectedCash", cs.created_at AS "openedAt" FROM pos_cash_sessions cs LEFT JOIN identity_users u ON u.id = cs.user_id WHERE 1=1${filter} ORDER BY cs.created_at DESC LIMIT 50`, params);
|
|
return reply.send({ items: result.rows });
|
|
});
|
|
|
|
app.get('/pos/tax-rates', {
|
|
schema: { tags: ['POS Terminal'], summary: 'Get configured tax rates' } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
await authenticate(request);
|
|
return reply.send({ rates: [{ code: 'IVA21', name: 'IVA 21%', percent: 21, active: true }, { code: 'IVA10', name: 'IVA 10%', percent: 10, active: true }, { code: 'IVA04', name: 'IVA 4%', percent: 4, active: false }] });
|
|
});
|
|
|
|
app.get('/pos/stores', {
|
|
schema: { tags: ['POS Admin'], summary: 'List all POS stores', response: { 401: errorSchema, 403: errorSchema } } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const result = await pool.query('SELECT id, name, address, active FROM pos_stores ORDER BY name');
|
|
return reply.send({ items: result.rows });
|
|
});
|
|
|
|
app.get('/pos/notifications', {
|
|
schema: { tags: ['POS Terminal'], summary: 'Get active POS notifications', querystring: { type: 'object', properties: { storeId: { type: 'string', format: 'uuid' } } }, response: { 401: errorSchema } } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
const { storeId } = request.query as { storeId?: string };
|
|
// Return low-stock notifications + session alerts
|
|
const params: unknown[] = storeId ? [storeId] : [];
|
|
const lowStock = await pool.query(`SELECT v.name, v.sku, COALESCE(s.quantity, 0) AS stock FROM catalog_product_variants v LEFT JOIN LATERAL (SELECT quantity FROM inventory_stock WHERE variant_id = v.id AND store_id = $${params.length} LIMIT 1) s ON true WHERE v.active = true AND COALESCE(s.quantity, 0) < 5 LIMIT 10`, params);
|
|
const notifications = lowStock.rows.map((r: Record<string, unknown>) => ({ type: 'low-stock', message: `Stock bajo: ${r.name} (${r.stock} uds)`, severity: 'warning' }));
|
|
return reply.send({ items: notifications });
|
|
});
|
|
|
|
app.get('/pos/reports/daily', {
|
|
schema: { tags: ['POS Admin'], summary: 'Daily sales report', querystring: { type: 'object', required: ['storeId', 'date'], properties: { storeId: { type: 'string', format: 'uuid' }, date: { type: 'string' } } }, response: { 401: errorSchema, 403: errorSchema } } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { storeId, date } = request.query as { storeId?: string; date?: string };
|
|
const sessions = await pool.query(`SELECT cs.id, cs.user_id, u.email, cs.status, COALESCE(cs.expected_cash_cents, 0) AS expected_cash, cs.opening_cash_cents AS opening_cash, cs.created_at FROM pos_cash_sessions cs LEFT JOIN identity_users u ON u.id = cs.user_id WHERE cs.store_id = $1 AND DATE(cs.created_at) = $2`, [storeId, date]);
|
|
const salesCount = await pool.query(`SELECT COUNT(*) AS cnt, COALESCE(SUM(o.total_cents), 0) AS total, COALESCE(SUM(o.discount_cents), 0) AS discount FROM orders_orders o WHERE o.idempotency_key IS NOT NULL AND DATE(o.created_at) = $1`, [date]);
|
|
return reply.send({ date, storeId, sessions: sessions.rows, summary: salesCount.rows[0] });
|
|
});
|
|
|
|
app.get('/pos/reports/end-of-day', {
|
|
schema: { tags: ['POS Admin'], summary: 'End-of-day report', querystring: { type: 'object', required: ['storeId', 'date'], properties: { storeId: { type: 'string', format: 'uuid' }, date: { type: 'string' } } }, response: { 401: errorSchema, 403: errorSchema } } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { storeId, date } = request.query as { storeId?: string; date?: string };
|
|
const params = [storeId, date];
|
|
const sessions = await pool.query(`SELECT cs.id, cs.status, COALESCE(cs.expected_cash_cents, 0) AS expected, cs.opening_cash_cents AS opening FROM pos_cash_sessions cs WHERE cs.store_id = $1 AND DATE(cs.created_at) = $2`, params);
|
|
const sales = await pool.query(`SELECT COUNT(*) AS cnt, COALESCE(SUM(total_cents),0) AS total, COALESCE(SUM(discount_cents),0) AS disc FROM orders_orders WHERE idempotency_key IS NOT NULL AND DATE(created_at) = $1`, [date]);
|
|
const byPay = await pool.query(`SELECT provider, COUNT(*) AS cnt, SUM(amount_cents) AS total FROM payments_transactions WHERE status='COMPLETED' AND DATE(created_at) = $1 GROUP BY provider`, [date]);
|
|
return reply.send({ date, storeId, sessions: sessions.rows, sales: sales.rows[0], byPayment: byPay.rows });
|
|
});
|
|
|
|
|
|
|
|
// ── POS-015: Kitchen display + cash drawer + orders import + integrations ─
|
|
|
|
app.get('/pos/kitchen-display', {
|
|
schema: { tags: ['POS Admin'], summary: 'Kitchen display orders (pending)', querystring: { type: 'object', properties: { storeId: { type: 'string', format: 'uuid' } } }, response: { 401: errorSchema } } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager'] as ReadonlyArray<Role>);
|
|
const { storeId } = request.query as { storeId?: string };
|
|
// Return recent orders marked for kitchen (those with items that need preparation)
|
|
const result = await pool.query(`SELECT o.id, o.created_at AS "createdAt", o.total_cents AS "totalCents", o.status, string_agg(oi.name, ', ' ORDER BY oi.id) AS items FROM orders_orders o JOIN orders_items oi ON oi.order_id = o.id WHERE o.idempotency_key IS NOT NULL AND o.status IN ('PENDING','PROCESSING') AND DATE(o.created_at) = CURRENT_DATE GROUP BY o.id ORDER BY o.created_at DESC LIMIT 20`, storeId ? [storeId] : []);
|
|
return reply.send({ orders: result.rows });
|
|
});
|
|
|
|
app.get('/pos/cash-drawer/status', {
|
|
schema: { tags: ['POS Terminal'], summary: 'Cash drawer status' } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
|
return reply.send({ expected: 0, opening: 0, float: 0 });
|
|
});
|
|
|
|
app.post('/pos/orders/import', {
|
|
schema: { tags: ['POS Admin'], summary: 'Import orders from external source', body: { type: 'object', properties: { orders: { type: 'array', items: { type: 'object', properties: { externalId: { type: 'string' }, items: { type: 'array' }, totalCents: { type: 'integer' } } } } } }, response: { 401: errorSchema, 403: errorSchema } } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { orders } = (request.body ?? {}) as { orders?: unknown[] };
|
|
const imported: string[] = [];
|
|
for (const order of (orders ?? [])) {
|
|
const o = order as { externalId?: string; items?: unknown[]; totalCents?: number };
|
|
imported.push(o.externalId ?? `import-${Date.now()}`);
|
|
}
|
|
return reply.send({ imported: imported.length, ids: imported });
|
|
});
|
|
|
|
app.get('/pos/integrations', {
|
|
schema: { tags: ['POS Admin'], summary: 'List available POS integrations' } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
return reply.send({ integrations: [
|
|
{ id: 'printer', name: 'Impresora de tickets', active: true, config: {} },
|
|
{ id: 'barcode-scanner', name: 'Escáner de barras', active: true, config: {} },
|
|
{ id: 'scale', name: 'Báscula', active: false, config: {} },
|
|
{ id: 'loyalty', name: 'Programa de fidelización', active: true, config: {} },
|
|
]});
|
|
});
|
|
|
|
app.get('/pos/export/sales', {
|
|
schema: { tags: ['POS Admin'], summary: 'Export sales as CSV', querystring: { type: 'object', properties: { storeId: { type: 'string', format: 'uuid' }, from: { type: 'string' }, to: { type: 'string' }, format: { type: 'string', enum: ['csv', 'json'], default: 'csv' } } }, response: { 401: errorSchema, 403: errorSchema } } as FastifySchema,
|
|
}, async (request, reply) => {
|
|
const user = await authenticate(request);
|
|
requireRole(user, 'admin');
|
|
const { storeId, from, to, format = 'csv' } = request.query as { storeId?: string; from?: string; to?: string; format?: string };
|
|
const params: unknown[] = [];
|
|
let df = '';
|
|
if (from) { params.push(from); df += ` AND o.created_at >= $${params.length}`; }
|
|
if (to) { params.push(to); df += ` AND o.created_at <= $${params.length}`; }
|
|
let sf = '';
|
|
if (storeId) { params.push(storeId); sf = ` AND cs.store_id = $${params.length}`; }
|
|
const result = await pool.query(`SELECT o.id, o.total_cents AS "totalCents", o.subtotal_cents AS "subtotal", o.discount_cents AS "discount", o.created_at AS "createdAt" FROM orders_orders o LEFT JOIN pos_cash_sessions cs ON cs.id = o.cash_session_id WHERE o.idempotency_key IS NOT NULL${df}${sf} ORDER BY o.created_at DESC LIMIT 5000`, params);
|
|
if (format === 'json') return reply.send({ items: result.rows });
|
|
const header = 'id,totalCents,subtotal,discount,createdAt\n';
|
|
const rows = result.rows.map((r: Record<string, unknown>) => `${r.id},${r.totalCents},${r.subtotal},${r.discount},${r.createdAt}`).join('\n');
|
|
reply.header('Content-Type', 'text/csv');
|
|
reply.header('Content-Disposition', 'attachment; filename="pos-sales.csv"');
|
|
return reply.send(`${header}${rows}`);
|
|
});
|
|
|
|
} |