feat(F-186): completed feature
This commit is contained in:
@@ -12,6 +12,9 @@ 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 { buildPosReceipt } from '../application/build-pos-receipt.js';
|
||||
import { sendTransactionalEmail } from '../../notifications/index.js';
|
||||
import { Argon2PasswordHasher } from '../../identity/index.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';
|
||||
@@ -25,7 +28,31 @@ export interface PosRouteDeps {
|
||||
const idParamSchema = z.object({ id: z.string().uuid() });
|
||||
// Zod's strict UUID parser rejects the RFC nil UUID used by the seeded default
|
||||
// store. Store references accept the canonical UUID shape, including nil.
|
||||
const storeIdSchema = z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
|
||||
const storeIdSchema = z
|
||||
.string()
|
||||
.regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
|
||||
|
||||
async function assertReceiptAccess(
|
||||
pool: pg.Pool,
|
||||
user: CurrentUser,
|
||||
terminalId: string | string[] | undefined,
|
||||
orderId: string,
|
||||
): Promise<void> {
|
||||
if (user.role === 'admin') return;
|
||||
if (typeof terminalId !== 'string') {
|
||||
throw new AppError(403, 'POS_TERMINAL_REQUIRED', 'El terminal vinculado es obligatorio');
|
||||
}
|
||||
const result = await pool.query<{ allowed: boolean }>(
|
||||
`SELECT EXISTS (
|
||||
SELECT 1 FROM orders_orders
|
||||
WHERE id = $1 AND source = 'pos' AND terminal_id = $2
|
||||
) AS allowed`,
|
||||
[orderId, terminalId],
|
||||
);
|
||||
if (!result.rows[0]?.allowed) {
|
||||
throw new AppError(403, 'POS_RECEIPT_FORBIDDEN', 'El ticket pertenece a otro terminal');
|
||||
}
|
||||
}
|
||||
|
||||
export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps) {
|
||||
const { pool, authenticate } = deps;
|
||||
@@ -235,9 +262,12 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
properties: {
|
||||
touchNavigationEnabled: { type: 'boolean' },
|
||||
quickProductVariantIds: {
|
||||
type: 'array', minItems: 4, maxItems: 4,
|
||||
type: 'array',
|
||||
minItems: 8,
|
||||
maxItems: 8,
|
||||
items: { type: ['string', 'null'], format: 'uuid' },
|
||||
},
|
||||
lineDiscountsEnabled: { type: 'boolean' },
|
||||
},
|
||||
},
|
||||
response: { 401: errorSchema, 403: errorSchema, 404: errorSchema },
|
||||
@@ -250,13 +280,20 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
const body = parseJson(
|
||||
z.object({
|
||||
touchNavigationEnabled: z.boolean(),
|
||||
quickProductVariantIds: z.array(z.string().uuid().nullable()).length(4),
|
||||
quickProductVariantIds: z.array(z.string().uuid().nullable()).length(8),
|
||||
lineDiscountsEnabled: z.boolean().default(true),
|
||||
}),
|
||||
request.body ?? {},
|
||||
);
|
||||
const selected = body.quickProductVariantIds.filter((value): value is string => value !== null);
|
||||
const selected = body.quickProductVariantIds.filter(
|
||||
(value): value is string => value !== null,
|
||||
);
|
||||
if (new Set(selected).size !== selected.length) {
|
||||
throw new AppError(400, 'DUPLICATE_QUICK_PRODUCT', 'Cada acceso rápido debe usar un producto diferente');
|
||||
throw new AppError(
|
||||
400,
|
||||
'DUPLICATE_QUICK_PRODUCT',
|
||||
'Cada acceso rápido debe usar un producto diferente',
|
||||
);
|
||||
}
|
||||
if (selected.length > 0) {
|
||||
const valid = await pool.query<{ count: string }>(
|
||||
@@ -274,11 +311,17 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
SET interface_mode = CASE WHEN $2 THEN 'touch' ELSE 'auto' END,
|
||||
settings = COALESCE(settings, '{}'::jsonb) || jsonb_build_object(
|
||||
'touchNavigationEnabled', $2::boolean,
|
||||
'quickProductVariantIds', $3::jsonb
|
||||
'quickProductVariantIds', $3::jsonb,
|
||||
'lineDiscountsEnabled', $4::boolean
|
||||
),
|
||||
updated_at = now()
|
||||
WHERE id = $1 RETURNING *`,
|
||||
[id, body.touchNavigationEnabled, JSON.stringify(body.quickProductVariantIds)],
|
||||
[
|
||||
id,
|
||||
body.touchNavigationEnabled,
|
||||
JSON.stringify(body.quickProductVariantIds),
|
||||
body.lineDiscountsEnabled,
|
||||
],
|
||||
);
|
||||
if (!result.rows[0]) throw new AppError(404, 'TERMINAL_NOT_FOUND', 'Terminal not found');
|
||||
return reply.send({ ok: true });
|
||||
@@ -519,7 +562,8 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
tags: ['POS Terminal'],
|
||||
summary: 'Get category navigation and quick products for the bound terminal',
|
||||
headers: {
|
||||
type: 'object', required: ['x-terminal-id'],
|
||||
type: 'object',
|
||||
required: ['x-terminal-id'],
|
||||
properties: { 'x-terminal-id': { type: 'string', format: 'uuid' } },
|
||||
},
|
||||
response: { 401: errorSchema, 404: errorSchema },
|
||||
@@ -529,11 +573,14 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
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 terminalResult = await pool.query<{ store_id: string; settings: Record<string, unknown> }>(
|
||||
`SELECT store_id, settings FROM pos_terminals WHERE id = $1 AND status = 'active'`,
|
||||
[terminalId],
|
||||
);
|
||||
if (!terminalId)
|
||||
throw new AppError(400, 'MISSING_TERMINAL_ID', 'x-terminal-id header required');
|
||||
const terminalResult = await pool.query<{
|
||||
store_id: string;
|
||||
settings: Record<string, unknown>;
|
||||
}>(`SELECT store_id, settings FROM pos_terminals WHERE id = $1 AND status = 'active'`, [
|
||||
terminalId,
|
||||
]);
|
||||
const terminal = terminalResult.rows[0];
|
||||
if (!terminal) throw new AppError(404, 'TERMINAL_NOT_FOUND', 'Terminal not found');
|
||||
const [categoryResult, productResult] = await Promise.all([
|
||||
@@ -560,18 +607,19 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
]);
|
||||
const configured = Array.isArray(terminal.settings?.quickProductVariantIds)
|
||||
? terminal.settings.quickProductVariantIds
|
||||
: [null, null, null, null];
|
||||
: Array.from({ length: 8 }, () => null);
|
||||
const uniqueProducts = new Map<string, Record<string, unknown>>();
|
||||
for (const row of productResult.rows as Array<Record<string, unknown>>) {
|
||||
if (!uniqueProducts.has(String(row.variantId))) uniqueProducts.set(String(row.variantId), row);
|
||||
if (!uniqueProducts.has(String(row.variantId)))
|
||||
uniqueProducts.set(String(row.variantId), row);
|
||||
}
|
||||
return reply.send({
|
||||
enabled: terminal.settings?.touchNavigationEnabled !== false,
|
||||
categories: categoryResult.rows,
|
||||
products: productResult.rows,
|
||||
quickProducts: [0, 1, 2, 3].map((slot) => {
|
||||
quickProducts: Array.from({ length: 8 }, (_, slot) => {
|
||||
const variantId = configured[slot];
|
||||
return typeof variantId === 'string' ? uniqueProducts.get(variantId) ?? null : null;
|
||||
return typeof variantId === 'string' ? (uniqueProducts.get(variantId) ?? null) : null;
|
||||
}),
|
||||
});
|
||||
},
|
||||
@@ -750,9 +798,14 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
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 });
|
||||
const { storeId } = parseJson(z.object({ storeId: storeIdSchema }), request.query);
|
||||
const methods = await pool.query(
|
||||
`SELECT id, store_id AS "storeId", code, label, kind, active,
|
||||
sort_order AS "sortOrder", config, created_at AS "createdAt", updated_at AS "updatedAt"
|
||||
FROM pos_payment_methods WHERE store_id = $1 ORDER BY sort_order, label`,
|
||||
[storeId],
|
||||
);
|
||||
return reply.send({ items: methods.rows });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -782,8 +835,12 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
requireRole(user, 'admin');
|
||||
const body = parseJson(
|
||||
z.object({
|
||||
storeId: z.string().uuid(),
|
||||
code: z.string().min(1).max(32),
|
||||
storeId: storeIdSchema,
|
||||
code: z
|
||||
.string()
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.regex(/^[a-z0-9_-]{1,32}$/),
|
||||
label: z.string().min(1).max(64),
|
||||
kind: z.enum(['cash', 'card', 'other']),
|
||||
active: z.boolean().default(true),
|
||||
@@ -855,6 +912,129 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
},
|
||||
);
|
||||
|
||||
app.get(
|
||||
'/pos/admin/receipt-settings',
|
||||
{
|
||||
schema: {
|
||||
tags: ['POS Admin'],
|
||||
summary: 'Get company and receipt numbering settings',
|
||||
querystring: {
|
||||
type: 'object',
|
||||
required: ['storeId'],
|
||||
properties: { storeId: { type: 'string', format: 'uuid' } },
|
||||
},
|
||||
response: { 401: errorSchema, 403: errorSchema, 404: errorSchema },
|
||||
} as FastifySchema,
|
||||
},
|
||||
async (request, reply) => {
|
||||
const user = await authenticate(request);
|
||||
requireRole(user, 'admin');
|
||||
const { storeId } = parseJson(z.object({ storeId: storeIdSchema }), request.query);
|
||||
await pool.query(
|
||||
`INSERT INTO pos_receipt_settings (store_id) VALUES ($1)
|
||||
ON CONFLICT (store_id) DO NOTHING`,
|
||||
[storeId],
|
||||
);
|
||||
const result = await pool.query(
|
||||
`SELECT store.id AS "storeId", store.name, store.address, store.tax_id AS "taxId",
|
||||
store.contact_email AS "contactEmail", store.contact_phone AS "contactPhone",
|
||||
store.receipt_header AS "receiptHeader", store.receipt_footer AS "receiptFooter",
|
||||
receipt.prefix, receipt.next_number::float8 AS "nextNumber", receipt.padding,
|
||||
receipt.return_policy AS "returnPolicy"
|
||||
FROM pos_stores store
|
||||
JOIN pos_receipt_settings receipt ON receipt.store_id = store.id
|
||||
WHERE store.id = $1`,
|
||||
[storeId],
|
||||
);
|
||||
if (!result.rows[0]) throw new AppError(404, 'STORE_NOT_FOUND', 'No se encontró la tienda');
|
||||
return reply.send(result.rows[0]);
|
||||
},
|
||||
);
|
||||
|
||||
app.patch(
|
||||
'/pos/admin/receipt-settings',
|
||||
{
|
||||
schema: {
|
||||
tags: ['POS Admin'],
|
||||
summary: 'Update company and receipt numbering settings',
|
||||
body: {
|
||||
type: 'object',
|
||||
required: ['storeId'],
|
||||
properties: { storeId: { type: 'string', format: 'uuid' } },
|
||||
},
|
||||
response: { 400: errorSchema, 401: errorSchema, 403: errorSchema, 404: errorSchema },
|
||||
} as FastifySchema,
|
||||
},
|
||||
async (request, reply) => {
|
||||
const user = await authenticate(request);
|
||||
requireRole(user, 'admin');
|
||||
const body = parseJson(
|
||||
z.object({
|
||||
storeId: storeIdSchema,
|
||||
name: z.string().trim().min(1).max(200).optional(),
|
||||
address: z.string().trim().max(500).optional(),
|
||||
taxId: z.string().trim().max(64).optional(),
|
||||
contactEmail: z.union([z.string().trim().email(), z.literal('')]).optional(),
|
||||
contactPhone: z.string().trim().max(64).optional(),
|
||||
receiptHeader: z.string().trim().max(500).optional(),
|
||||
receiptFooter: z.string().trim().max(1000).optional(),
|
||||
prefix: z
|
||||
.string()
|
||||
.trim()
|
||||
.regex(/^[A-Za-z0-9_-]{1,16}$/)
|
||||
.optional(),
|
||||
nextNumber: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
|
||||
padding: z.number().int().min(1).max(12).optional(),
|
||||
returnPolicy: z.string().trim().min(1).max(2000).optional(),
|
||||
}),
|
||||
request.body ?? {},
|
||||
);
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const store = await client.query(
|
||||
`UPDATE pos_stores
|
||||
SET name = COALESCE($2, name), address = COALESCE($3, address),
|
||||
tax_id = COALESCE($4, tax_id), contact_email = COALESCE($5, contact_email),
|
||||
contact_phone = COALESCE($6, contact_phone),
|
||||
receipt_header = COALESCE($7, receipt_header),
|
||||
receipt_footer = COALESCE($8, receipt_footer), updated_at = now()
|
||||
WHERE id = $1 RETURNING id`,
|
||||
[
|
||||
body.storeId,
|
||||
body.name,
|
||||
body.address,
|
||||
body.taxId,
|
||||
body.contactEmail,
|
||||
body.contactPhone,
|
||||
body.receiptHeader,
|
||||
body.receiptFooter,
|
||||
],
|
||||
);
|
||||
if (!store.rows[0]) throw new AppError(404, 'STORE_NOT_FOUND', 'No se encontró la tienda');
|
||||
await client.query(
|
||||
`INSERT INTO pos_receipt_settings (store_id, prefix, next_number, padding, return_policy)
|
||||
VALUES ($1, COALESCE($2, 'TPV'), COALESCE($3, 1), COALESCE($4, 6),
|
||||
COALESCE($5, 'Se admiten devoluciones durante 15 días con el ticket de compra.'))
|
||||
ON CONFLICT (store_id) DO UPDATE
|
||||
SET prefix = COALESCE($2, pos_receipt_settings.prefix),
|
||||
next_number = COALESCE($3, pos_receipt_settings.next_number),
|
||||
padding = COALESCE($4, pos_receipt_settings.padding),
|
||||
return_policy = COALESCE($5, pos_receipt_settings.return_policy),
|
||||
updated_at = now()`,
|
||||
[body.storeId, body.prefix, body.nextNumber, body.padding, body.returnPolicy],
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
return reply.send({ ok: true });
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// ── POS-008: POST /pos/sales idempotent ───────────────────────────────────
|
||||
|
||||
app.post(
|
||||
@@ -862,7 +1042,7 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
{
|
||||
schema: {
|
||||
tags: ['POS Terminal'],
|
||||
summary: 'Record a POS sale (idempotent)',
|
||||
summary: 'Confirm a POS sale with complete payment allocation',
|
||||
body: {
|
||||
type: 'object',
|
||||
required: ['idempotencyKey', 'cashSessionId', 'terminalId', 'items', 'payments'],
|
||||
@@ -870,86 +1050,71 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
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 },
|
||||
},
|
||||
},
|
||||
},
|
||||
items: { type: 'array', minItems: 1, items: { type: 'object' } },
|
||||
payments: { type: 'array', minItems: 1, items: { type: 'object' } },
|
||||
customerId: { type: 'string', format: 'uuid' },
|
||||
},
|
||||
},
|
||||
response: { 400: errorSchema, 401: errorSchema, 404: errorSchema, 409: errorSchema },
|
||||
response: {
|
||||
400: errorSchema,
|
||||
401: errorSchema,
|
||||
403: 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 stockLine = z.object({
|
||||
kind: z.literal('stock').optional(),
|
||||
variantId: z.string().uuid(),
|
||||
quantity: z.number().int().min(1),
|
||||
discountCents: z.number().int().min(0).optional(),
|
||||
});
|
||||
const freeLine = z.object({
|
||||
kind: z.literal('free'),
|
||||
name: z.string().trim().min(1).max(200),
|
||||
unitPriceCents: z.number().int().min(1),
|
||||
quantity: z.number().int().min(1).max(999),
|
||||
});
|
||||
const payment = z
|
||||
.object({
|
||||
methodCode: z
|
||||
.string()
|
||||
.regex(/^[a-z0-9_-]{1,32}$/)
|
||||
.optional(),
|
||||
kind: z.enum(['cash', 'card', 'other']).optional(),
|
||||
amountCents: z.number().int().min(1),
|
||||
tenderedCents: z.number().int().min(0).optional(),
|
||||
last4: z
|
||||
.string()
|
||||
.regex(/^\d{1,4}$/)
|
||||
.optional(),
|
||||
})
|
||||
.refine((value) => Boolean(value.methodCode || value.kind), {
|
||||
message: 'methodCode is required',
|
||||
});
|
||||
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(),
|
||||
}),
|
||||
),
|
||||
items: z.array(z.union([freeLine, stockLine])).min(1),
|
||||
payments: z.array(payment).min(1),
|
||||
customerId: z.string().uuid().optional(),
|
||||
}),
|
||||
request.body ?? {},
|
||||
);
|
||||
const boundTerminalId = request.headers['x-terminal-id'];
|
||||
if (typeof boundTerminalId !== 'string' || boundTerminalId !== body.terminalId) {
|
||||
throw new AppError(
|
||||
403,
|
||||
'POS_TERMINAL_MISMATCH',
|
||||
'La venta no pertenece al terminal vinculado',
|
||||
);
|
||||
}
|
||||
const result = await createPosSale.execute({ ...body, userId: user.id });
|
||||
return reply.code(201).send(result);
|
||||
},
|
||||
@@ -1014,16 +1179,22 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
|
||||
const body = parseJson(
|
||||
z.object({
|
||||
email: z.string().trim().email().transform((value) => value.toLowerCase()),
|
||||
email: z
|
||||
.string()
|
||||
.trim()
|
||||
.email()
|
||||
.transform((value) => value.toLowerCase()),
|
||||
displayName: z.string().trim().min(1).max(160).optional(),
|
||||
phone: z.string().trim().min(1).max(40).optional(),
|
||||
}),
|
||||
request.body ?? {},
|
||||
);
|
||||
const existing = await pool.query('SELECT id FROM identity_users WHERE lower(email) = $1', [body.email]);
|
||||
if (existing.rows[0]) throw new AppError(409, 'CUSTOMER_EXISTS', 'Ya existe un cliente con ese email');
|
||||
const existing = await pool.query('SELECT id FROM identity_users WHERE lower(email) = $1', [
|
||||
body.email,
|
||||
]);
|
||||
if (existing.rows[0])
|
||||
throw new AppError(409, 'CUSTOMER_EXISTS', 'Ya existe un cliente con ese email');
|
||||
const { randomBytes } = await import('node:crypto');
|
||||
const { Argon2PasswordHasher } = await import('../../identity/infrastructure/argon2-password-hasher.js');
|
||||
const passwordHash = await new Argon2PasswordHasher().hash(randomBytes(32).toString('hex'));
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
@@ -1034,7 +1205,8 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
[body.email, passwordHash, body.phone ?? null],
|
||||
);
|
||||
const customer = created.rows[0];
|
||||
if (!customer) throw new AppError(500, 'CUSTOMER_CREATE_FAILED', 'No se pudo crear el cliente');
|
||||
if (!customer)
|
||||
throw new AppError(500, 'CUSTOMER_CREATE_FAILED', 'No se pudo crear el cliente');
|
||||
await client.query(
|
||||
`INSERT INTO users_profiles (user_id, display_name, phone)
|
||||
VALUES ($1, $2, $3)
|
||||
@@ -1042,7 +1214,9 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
[customer.id, body.displayName ?? null, body.phone ?? null],
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
return reply.code(201).send({ ...customer, displayName: body.displayName ?? null, phone: body.phone ?? null });
|
||||
return reply
|
||||
.code(201)
|
||||
.send({ ...customer, displayName: body.displayName ?? null, phone: body.phone ?? null });
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
throw error;
|
||||
@@ -1221,22 +1395,9 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
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,
|
||||
});
|
||||
const { id } = parseJson(idParamSchema, request.params);
|
||||
await assertReceiptAccess(pool, user, request.headers['x-terminal-id'], id);
|
||||
return reply.send({ receipt: await buildPosReceipt(pool, id) });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1355,35 +1516,74 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
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 })),
|
||||
const { id } = parseJson(idParamSchema, request.params);
|
||||
await assertReceiptAccess(pool, user, request.headers['x-terminal-id'], id);
|
||||
return reply.send({ receipt: await buildPosReceipt(pool, id) });
|
||||
},
|
||||
);
|
||||
|
||||
app.post<{ Params: { id: string } }>(
|
||||
'/pos/sales/:id/receipt/email',
|
||||
{
|
||||
schema: {
|
||||
tags: ['POS Terminal'],
|
||||
summary: 'Email a generated POS receipt',
|
||||
params: { type: 'object', properties: { id: { type: 'string', format: 'uuid' } } },
|
||||
body: {
|
||||
type: 'object',
|
||||
required: ['email'],
|
||||
properties: { email: { type: 'string', format: 'email', maxLength: 254 } },
|
||||
},
|
||||
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 } = parseJson(idParamSchema, request.params);
|
||||
const { email } = parseJson(
|
||||
z.object({ email: z.string().trim().email().max(254) }),
|
||||
request.body ?? {},
|
||||
);
|
||||
await assertReceiptAccess(pool, user, request.headers['x-terminal-id'], id);
|
||||
const receipt = await buildPosReceipt(pool, id);
|
||||
const euros = (cents: number) =>
|
||||
new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR' }).format(cents / 100);
|
||||
const text = [
|
||||
receipt.company.name,
|
||||
receipt.company.address ?? '',
|
||||
receipt.company.taxId ? `NIF/CIF: ${receipt.company.taxId}` : '',
|
||||
receipt.company.phone ?? '',
|
||||
receipt.company.email ?? '',
|
||||
'',
|
||||
`Ticket ${receipt.receiptNumber}`,
|
||||
new Date(receipt.issuedAt).toLocaleString('es-ES'),
|
||||
'',
|
||||
...receipt.items.map(
|
||||
(item) => `${item.quantity} × ${item.name} — ${euros(item.totalCents)}`,
|
||||
),
|
||||
'',
|
||||
`Subtotal: ${euros(receipt.subtotalCents)}`,
|
||||
`Descuentos: ${euros(receipt.discountCents)}`,
|
||||
`IVA: ${euros(receipt.taxCents)}`,
|
||||
`TOTAL: ${euros(receipt.totalCents)}`,
|
||||
'',
|
||||
...receipt.payments.map(
|
||||
(payment) =>
|
||||
`${payment.methodLabel}: ${euros(payment.amountCents)}${payment.changeCents ? ` · cambio ${euros(payment.changeCents)}` : ''}`,
|
||||
),
|
||||
'',
|
||||
receipt.returnPolicy,
|
||||
receipt.footer ?? '',
|
||||
]
|
||||
.filter((line, index, lines) => line !== '' || lines[index - 1] !== '')
|
||||
.join('\n');
|
||||
await sendTransactionalEmail(pool, {
|
||||
to: email,
|
||||
subject: `Ticket ${receipt.receiptNumber} · ${receipt.company.name}`,
|
||||
text,
|
||||
});
|
||||
return reply.send({ ok: true, email, receiptNumber: receipt.receiptNumber });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1989,9 +2189,9 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
async (request, reply) => {
|
||||
const user = await authenticate(request);
|
||||
requireRole(user, 'admin');
|
||||
const { storeId } = request.query as { storeId?: string };
|
||||
const result = await pool.query(
|
||||
`SELECT u.id, u.email, u.role, p.first_name AS "firstName", p.last_name AS "lastName" FROM identity_users u LEFT JOIN users_profiles p ON p.user_id = u.id WHERE u.role IN ('pos_manager','pos_cashier') ORDER BY u.email`,
|
||||
`SELECT id, email, role FROM backoffice_users
|
||||
WHERE role IN ('pos_manager','pos_cashier') ORDER BY email`,
|
||||
);
|
||||
return reply.send({ items: result.rows });
|
||||
},
|
||||
@@ -2020,38 +2220,33 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
async (request, reply) => {
|
||||
const user = await authenticate(request);
|
||||
requireRole(user, 'admin');
|
||||
const body = (request.body ?? {}) as {
|
||||
email?: string;
|
||||
password?: string;
|
||||
role?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
};
|
||||
// Delegate to identity module (simple insert for now)
|
||||
const existing = await pool.query('SELECT id FROM identity_users WHERE email = $1', [
|
||||
const body = parseJson(
|
||||
z.object({
|
||||
email: z
|
||||
.string()
|
||||
.trim()
|
||||
.email()
|
||||
.transform((value) => value.toLowerCase()),
|
||||
password: z.string().min(8).max(200),
|
||||
role: z.enum(['pos_manager', 'pos_cashier']),
|
||||
firstName: z.string().trim().max(100).optional(),
|
||||
lastName: z.string().trim().max(100).optional(),
|
||||
}),
|
||||
request.body ?? {},
|
||||
);
|
||||
const existing = await pool.query('SELECT id FROM backoffice_users WHERE email = $1', [
|
||||
body.email,
|
||||
]);
|
||||
if (existing.rows[0]) throw new AppError(409, 'EXISTS', 'Email already exists');
|
||||
const { hash } = await import('crypto').then((c) => ({ hash: c.default?.webcrypto ?? null }));
|
||||
const hashSync = (pwd: string) => {
|
||||
const h = require('crypto').createHash('sha256');
|
||||
h.update(pwd);
|
||||
return h.digest('hex');
|
||||
};
|
||||
const pwdHash = hashSync(body.password ?? '');
|
||||
const passwordHash = await new Argon2PasswordHasher().hash(body.password);
|
||||
const newUser = await pool.query<{ id: string }>(
|
||||
`INSERT INTO identity_users (email, password_hash, role, created_at) VALUES ($1, $2, $3, now()) RETURNING id`,
|
||||
[body.email, pwdHash, body.role],
|
||||
`INSERT INTO backoffice_users (email, password_hash, role)
|
||||
VALUES ($1, $2, $3) RETURNING id`,
|
||||
[body.email, passwordHash, body.role],
|
||||
);
|
||||
const nu = newUser.rows[0];
|
||||
if (!nu) throw new AppError(500, 'USER_CREATE_FAILED', 'User insert returned no row');
|
||||
if (body.firstName || body.lastName) {
|
||||
await pool.query(
|
||||
`INSERT INTO users_profiles (user_id, first_name, last_name) VALUES ($1, $2, $3)`,
|
||||
[nu.id, body.firstName ?? null, body.lastName ?? null],
|
||||
);
|
||||
}
|
||||
return reply.code(201).send({ id: nu.id, email: body.email, role: body.role });
|
||||
const created = newUser.rows[0];
|
||||
if (!created) throw new AppError(500, 'USER_CREATE_FAILED', 'User insert returned no row');
|
||||
return reply.code(201).send({ id: created.id, email: body.email, role: body.role });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -2077,7 +2272,6 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
|
||||
const user = await authenticate(request);
|
||||
requireRole(user, 'admin');
|
||||
const {
|
||||
storeId,
|
||||
from,
|
||||
to,
|
||||
limit = 50,
|
||||
|
||||
Reference in New Issue
Block a user