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,
|
||||
|
||||
167
project/src/modules/pos/application/build-pos-receipt.ts
Normal file
167
project/src/modules/pos/application/build-pos-receipt.ts
Normal file
@@ -0,0 +1,167 @@
|
||||
import type pg from 'pg';
|
||||
import type { PosPaymentKind, PosReceipt, PosReceiptPayment } from '../domain/pos-sale.js';
|
||||
import { AppError } from '../../../shared/errors.js';
|
||||
|
||||
type Queryable = Pick<pg.Pool, 'query'> | Pick<pg.PoolClient, 'query'>;
|
||||
|
||||
interface ReceiptOrderRow {
|
||||
id: string;
|
||||
receipt_number: string | null;
|
||||
subtotal_cents: number;
|
||||
discount_cents: number;
|
||||
tax_cents: number;
|
||||
total_cents: number;
|
||||
created_at: Date;
|
||||
cash_session_id: string;
|
||||
terminal_id: string;
|
||||
customer_email: string | null;
|
||||
store_name: string;
|
||||
address: string | null;
|
||||
tax_id: string | null;
|
||||
contact_email: string | null;
|
||||
contact_phone: string | null;
|
||||
receipt_header: string | null;
|
||||
receipt_footer: string | null;
|
||||
terminal_name: string;
|
||||
cashier_email: string;
|
||||
return_policy: string | null;
|
||||
}
|
||||
|
||||
interface ReceiptItemRow {
|
||||
name: string;
|
||||
sku: string;
|
||||
quantity: number;
|
||||
unit_price_cents: number;
|
||||
discount_cents: number;
|
||||
tax_cents: number;
|
||||
is_free_item: boolean;
|
||||
}
|
||||
|
||||
interface ReceiptPaymentRow {
|
||||
amount_cents: number;
|
||||
provider: string;
|
||||
raw: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export async function buildPosReceipt(queryable: Queryable, orderId: string): Promise<PosReceipt> {
|
||||
const orderResult = await queryable.query<ReceiptOrderRow>(
|
||||
`SELECT o.id, o.receipt_number, o.subtotal_cents, o.discount_cents, o.tax_cents,
|
||||
o.total_cents, o.created_at, o.cash_session_id, o.terminal_id,
|
||||
customer.email AS customer_email,
|
||||
store.name AS store_name, store.address, store.tax_id, store.contact_email,
|
||||
store.contact_phone, store.receipt_header, store.receipt_footer,
|
||||
terminal.name AS terminal_name, cashier.email AS cashier_email,
|
||||
receipt_settings.return_policy
|
||||
FROM orders_orders o
|
||||
JOIN pos_stores store ON store.id = o.store_id
|
||||
JOIN pos_terminals terminal ON terminal.id = o.terminal_id
|
||||
JOIN pos_cash_sessions session ON session.id = o.cash_session_id
|
||||
JOIN backoffice_users cashier ON cashier.id = session.user_id
|
||||
LEFT JOIN identity_users customer ON customer.id = o.user_id
|
||||
LEFT JOIN pos_receipt_settings receipt_settings ON receipt_settings.store_id = o.store_id
|
||||
WHERE o.id = $1 AND o.source = 'pos'`,
|
||||
[orderId],
|
||||
);
|
||||
const order = orderResult.rows[0];
|
||||
if (!order) throw new AppError(404, 'POS_RECEIPT_NOT_FOUND', 'No se encontró el ticket');
|
||||
|
||||
const [itemResult, paymentResult] = await Promise.all([
|
||||
queryable.query<ReceiptItemRow>(
|
||||
`SELECT name, sku, quantity, unit_price_cents, discount_cents, tax_cents, is_free_item
|
||||
FROM orders_items WHERE order_id = $1 ORDER BY created_at, id`,
|
||||
[orderId],
|
||||
),
|
||||
queryable.query<ReceiptPaymentRow>(
|
||||
`SELECT amount_cents, provider, raw
|
||||
FROM payments_transactions WHERE order_id = $1 AND status = 'succeeded'
|
||||
ORDER BY created_at, id`,
|
||||
[orderId],
|
||||
),
|
||||
]);
|
||||
|
||||
const payments: PosReceiptPayment[] = paymentResult.rows.map((row) => {
|
||||
const raw = row.raw ?? {};
|
||||
const kind = isPaymentKind(raw.kind) ? raw.kind : providerKind(row.provider);
|
||||
const tendered = integerOrNull(raw.tenderedCents);
|
||||
const change = integerOrZero(raw.changeCents);
|
||||
return {
|
||||
methodCode: stringOr(raw.methodCode, row.provider.replace(/^pos_/, '')),
|
||||
methodLabel: stringOr(raw.methodLabel, paymentKindLabel(kind)),
|
||||
kind,
|
||||
amountCents: Number(row.amount_cents),
|
||||
tenderedCents: tendered,
|
||||
changeCents: change,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
receiptNumber: order.receipt_number ?? `POS-${order.id.slice(0, 8).toUpperCase()}`,
|
||||
orderId: order.id,
|
||||
issuedAt: order.created_at,
|
||||
company: {
|
||||
name: order.store_name,
|
||||
address: order.address,
|
||||
taxId: order.tax_id,
|
||||
email: order.contact_email,
|
||||
phone: order.contact_phone,
|
||||
},
|
||||
terminal: { id: order.terminal_id, name: order.terminal_name },
|
||||
cashier: order.cashier_email,
|
||||
sessionId: order.cash_session_id,
|
||||
customerEmail: order.customer_email,
|
||||
items: itemResult.rows.map((item) => {
|
||||
const subtotalCents = Number(item.unit_price_cents) * Number(item.quantity);
|
||||
const discountCents = Number(item.discount_cents) * Number(item.quantity);
|
||||
const taxCents = Number(item.tax_cents) * Number(item.quantity);
|
||||
return {
|
||||
name: item.name,
|
||||
sku: item.sku,
|
||||
quantity: Number(item.quantity),
|
||||
unitPriceCents: Number(item.unit_price_cents),
|
||||
subtotalCents,
|
||||
discountCents,
|
||||
taxCents,
|
||||
totalCents: subtotalCents - discountCents + taxCents,
|
||||
freeItem: item.is_free_item,
|
||||
};
|
||||
}),
|
||||
subtotalCents: Number(order.subtotal_cents),
|
||||
discountCents: Number(order.discount_cents),
|
||||
taxCents: Number(order.tax_cents),
|
||||
totalCents: Number(order.total_cents),
|
||||
payments,
|
||||
changeCents: payments.reduce((sum, payment) => sum + payment.changeCents, 0),
|
||||
header: order.receipt_header,
|
||||
returnPolicy:
|
||||
order.return_policy ?? 'Se admiten devoluciones durante 15 días con el ticket de compra.',
|
||||
footer: order.receipt_footer,
|
||||
};
|
||||
}
|
||||
|
||||
function isPaymentKind(value: unknown): value is PosPaymentKind {
|
||||
return value === 'cash' || value === 'card' || value === 'other';
|
||||
}
|
||||
|
||||
function providerKind(provider: string): PosPaymentKind {
|
||||
if (provider === 'pos_cash') return 'cash';
|
||||
if (provider === 'pos_card') return 'card';
|
||||
return 'other';
|
||||
}
|
||||
|
||||
function paymentKindLabel(kind: PosPaymentKind): string {
|
||||
if (kind === 'cash') return 'Efectivo';
|
||||
if (kind === 'card') return 'Tarjeta';
|
||||
return 'Otro';
|
||||
}
|
||||
|
||||
function stringOr(value: unknown, fallback: string): string {
|
||||
return typeof value === 'string' && value.trim() ? value : fallback;
|
||||
}
|
||||
|
||||
function integerOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isInteger(value) ? value : null;
|
||||
}
|
||||
|
||||
function integerOrZero(value: unknown): number {
|
||||
return typeof value === 'number' && Number.isInteger(value) ? value : 0;
|
||||
}
|
||||
@@ -1,20 +1,119 @@
|
||||
import type pg from 'pg';
|
||||
import type { PosSaleInput, PosSaleResult, PosPaymentResult } from '../domain/pos-sale.js';
|
||||
import type {
|
||||
PosPaymentInput,
|
||||
PosPaymentKind,
|
||||
PosPaymentResult,
|
||||
PosSaleInput,
|
||||
PosSaleLineItem,
|
||||
PosSaleResult,
|
||||
} from '../domain/pos-sale.js';
|
||||
import { AppError } from '../../../shared/errors.js';
|
||||
import { buildPosReceipt } from './build-pos-receipt.js';
|
||||
|
||||
interface PaymentRow { id: string; amount_cents: number; provider: string; }
|
||||
interface OrderItemRow {
|
||||
interface SessionRow {
|
||||
id: string;
|
||||
terminal_id: string;
|
||||
store_id: string;
|
||||
status: string;
|
||||
terminal_settings: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface CatalogLineRow {
|
||||
variant_id: string;
|
||||
product_id: string;
|
||||
sku: string;
|
||||
ean: string | null;
|
||||
name: string;
|
||||
unit_price_cents: number;
|
||||
discount_cents: number;
|
||||
tax_cents: number;
|
||||
quantity: number;
|
||||
vat_rate: string;
|
||||
}
|
||||
|
||||
export interface ConfiguredPaymentMethod {
|
||||
id: string;
|
||||
code: string;
|
||||
label: string;
|
||||
kind: PosPaymentKind;
|
||||
}
|
||||
|
||||
export interface ValidatedPayment {
|
||||
methodId: string;
|
||||
methodCode: string;
|
||||
methodLabel: string;
|
||||
kind: PosPaymentKind;
|
||||
amountCents: number;
|
||||
tenderedCents: number | null;
|
||||
changeCents: number;
|
||||
last4?: string;
|
||||
}
|
||||
|
||||
export function validatePaymentAllocations(
|
||||
totalCents: number,
|
||||
inputs: PosPaymentInput[],
|
||||
methods: ConfiguredPaymentMethod[],
|
||||
): ValidatedPayment[] {
|
||||
if (inputs.length === 0) {
|
||||
throw new AppError(400, 'POS_PAYMENT_REQUIRED', 'Selecciona al menos una forma de pago');
|
||||
}
|
||||
const byCode = new Map(methods.map((method) => [method.code, method]));
|
||||
const validated = inputs.map((input) => {
|
||||
const methodCode = input.methodCode ?? input.kind;
|
||||
const method = methodCode ? byCode.get(methodCode) : undefined;
|
||||
if (!method) {
|
||||
throw new AppError(400, 'POS_PAYMENT_METHOD_DISABLED', 'La forma de pago no está habilitada');
|
||||
}
|
||||
if (!Number.isInteger(input.amountCents) || input.amountCents <= 0) {
|
||||
throw new AppError(
|
||||
400,
|
||||
'POS_PAYMENT_INVALID_AMOUNT',
|
||||
'El importe del pago debe ser positivo',
|
||||
);
|
||||
}
|
||||
if (method.kind === 'cash') {
|
||||
const tenderedCents = input.tenderedCents ?? input.amountCents;
|
||||
if (!Number.isInteger(tenderedCents) || tenderedCents < input.amountCents) {
|
||||
throw new AppError(
|
||||
400,
|
||||
'POS_CASH_TENDERED_TOO_LOW',
|
||||
'El efectivo entregado no cubre el importe aplicado',
|
||||
);
|
||||
}
|
||||
return {
|
||||
methodId: method.id,
|
||||
methodCode: method.code,
|
||||
methodLabel: method.label,
|
||||
kind: method.kind,
|
||||
amountCents: input.amountCents,
|
||||
tenderedCents,
|
||||
changeCents: tenderedCents - input.amountCents,
|
||||
...(input.last4 ? { last4: input.last4 } : {}),
|
||||
};
|
||||
}
|
||||
if (input.tenderedCents !== undefined) {
|
||||
throw new AppError(400, 'POS_NON_CASH_TENDERED', 'Solo el efectivo admite importe entregado');
|
||||
}
|
||||
return {
|
||||
methodId: method.id,
|
||||
methodCode: method.code,
|
||||
methodLabel: method.label,
|
||||
kind: method.kind,
|
||||
amountCents: input.amountCents,
|
||||
tenderedCents: null,
|
||||
changeCents: 0,
|
||||
...(input.last4 ? { last4: input.last4 } : {}),
|
||||
};
|
||||
});
|
||||
const allocatedCents = validated.reduce((sum, payment) => sum + payment.amountCents, 0);
|
||||
if (allocatedCents !== totalCents) {
|
||||
throw new AppError(
|
||||
400,
|
||||
'POS_PAYMENT_TOTAL_MISMATCH',
|
||||
allocatedCents < totalCents
|
||||
? 'Falta importe por asignar antes de confirmar'
|
||||
: 'Los pagos asignados superan el total',
|
||||
);
|
||||
}
|
||||
return validated;
|
||||
}
|
||||
interface OrderRow { id: string; idempotency_key: string; total_cents: number; created_at: Date; }
|
||||
|
||||
export class CreatePosSaleUseCase {
|
||||
constructor(private readonly pool: pg.Pool) {}
|
||||
@@ -24,82 +123,175 @@ export class CreatePosSaleUseCase {
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
// 1. Idempotency: return existing sale if key already used
|
||||
const existing = await client.query<{ id: string }>(
|
||||
'SELECT id FROM orders_orders WHERE idempotency_key = $1',
|
||||
`SELECT id FROM orders_orders WHERE idempotency_key = $1 AND source = 'pos'`,
|
||||
[input.idempotencyKey],
|
||||
);
|
||||
if (existing.rows[0]) {
|
||||
const existId = existing.rows[0].id;
|
||||
const orderId = existing.rows[0].id;
|
||||
await client.query('ROLLBACK');
|
||||
const order = await this.pool.query<OrderRow>(
|
||||
'SELECT id, idempotency_key, total_cents, created_at FROM orders_orders WHERE idempotency_key = $1',
|
||||
[input.idempotencyKey],
|
||||
);
|
||||
const items = await this.pool.query<OrderItemRow>(
|
||||
`SELECT variant_id, product_id, sku, ean, name, unit_price_cents,
|
||||
discount_cents, tax_cents, quantity
|
||||
FROM orders_items WHERE order_id = $1`,
|
||||
[existId],
|
||||
);
|
||||
const payments = await this.pool.query<PaymentRow>(
|
||||
'SELECT id, amount_cents, provider FROM payments_transactions WHERE order_id = $1',
|
||||
[existId],
|
||||
);
|
||||
const totalCents = (order.rows[0]?.total_cents ?? 0) as number;
|
||||
const mappedItems: PosSaleResult['items'] = items.rows.map((row) => ({
|
||||
variantId: row.variant_id,
|
||||
productId: row.product_id,
|
||||
sku: row.sku,
|
||||
ean: row.ean,
|
||||
name: row.name,
|
||||
unitPriceCents: row.unit_price_cents,
|
||||
discountCents: row.discount_cents,
|
||||
taxCents: row.tax_cents,
|
||||
quantity: row.quantity,
|
||||
}));
|
||||
return {
|
||||
orderId: existId,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
totalCents,
|
||||
items: mappedItems,
|
||||
payments: payments.rows.map((row) => ({
|
||||
id: row.id,
|
||||
kind: providerToPaymentKind(row.provider),
|
||||
amountCents: row.amount_cents,
|
||||
})),
|
||||
createdAt: order.rows[0]?.created_at ?? new Date(),
|
||||
};
|
||||
return this.loadResult(orderId, input.idempotencyKey);
|
||||
}
|
||||
|
||||
// 2. Verify cash session is open (FOR UPDATE lock)
|
||||
const session = await client.query<{ id: string; terminal_id: string; store_id: string; status: string }>(
|
||||
`SELECT id, terminal_id, store_id, status FROM pos_cash_sessions WHERE id = $1 FOR UPDATE`,
|
||||
const sessionResult = await client.query<SessionRow>(
|
||||
`SELECT session.id, session.terminal_id, session.store_id, session.status,
|
||||
terminal.settings AS terminal_settings
|
||||
FROM pos_cash_sessions session
|
||||
JOIN pos_terminals terminal ON terminal.id = session.terminal_id
|
||||
WHERE session.id = $1
|
||||
FOR UPDATE OF session, terminal`,
|
||||
[input.cashSessionId],
|
||||
);
|
||||
const sessionRow = session.rows[0];
|
||||
if (!sessionRow) { await client.query('ROLLBACK'); throw new AppError(404, 'SESSION_NOT_FOUND', 'Cash session not found'); }
|
||||
if (sessionRow.status !== 'OPEN') { await client.query('ROLLBACK'); throw new AppError(409, 'SESSION_CLOSED', 'Cash session is not open'); }
|
||||
if (sessionRow.terminal_id !== input.terminalId) {
|
||||
await client.query('ROLLBACK');
|
||||
throw new AppError(409, 'TERMINAL_SESSION_MISMATCH', 'Cash session belongs to another terminal');
|
||||
const session = sessionResult.rows[0];
|
||||
if (!session)
|
||||
throw new AppError(404, 'SESSION_NOT_FOUND', 'No se encontró la sesión de caja');
|
||||
if (session.status !== 'OPEN')
|
||||
throw new AppError(409, 'SESSION_CLOSED', 'La sesión de caja está cerrada');
|
||||
if (session.terminal_id !== input.terminalId) {
|
||||
throw new AppError(409, 'TERMINAL_SESSION_MISMATCH', 'La sesión pertenece a otro terminal');
|
||||
}
|
||||
if (input.items.length === 0)
|
||||
throw new AppError(400, 'POS_EMPTY_CART', 'El carrito está vacío');
|
||||
|
||||
const lineDiscountsEnabled = session.terminal_settings?.lineDiscountsEnabled !== false;
|
||||
const items: PosSaleLineItem[] = [];
|
||||
for (const inputItem of input.items) {
|
||||
if (inputItem.kind === 'free') {
|
||||
const name = inputItem.name.trim();
|
||||
if (
|
||||
!name ||
|
||||
!Number.isInteger(inputItem.unitPriceCents) ||
|
||||
inputItem.unitPriceCents <= 0
|
||||
) {
|
||||
throw new AppError(
|
||||
400,
|
||||
'POS_INVALID_FREE_ITEM',
|
||||
'El artículo libre requiere nombre y precio positivo',
|
||||
);
|
||||
}
|
||||
items.push({
|
||||
kind: 'free',
|
||||
variantId: null,
|
||||
productId: null,
|
||||
sku: 'LIBRE',
|
||||
ean: null,
|
||||
name,
|
||||
unitPriceCents: inputItem.unitPriceCents,
|
||||
discountCents: 0,
|
||||
taxCents: 0,
|
||||
quantity: inputItem.quantity,
|
||||
vatRate: null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const catalogResult = await client.query<CatalogLineRow>(
|
||||
`SELECT variant.id AS variant_id, variant.product_id, variant.sku, variant.ean,
|
||||
product.name,
|
||||
COALESCE(price.offer_cents, price.net_unit_amount_cents) AS unit_price_cents,
|
||||
price.vat_rate
|
||||
FROM catalog_product_variants variant
|
||||
JOIN catalog_products product ON product.id = variant.product_id
|
||||
JOIN pricing_variant_prices price ON price.variant_id = variant.id AND price.currency = 'EUR'
|
||||
WHERE variant.id = $1 AND product.state = 'active'`,
|
||||
[inputItem.variantId],
|
||||
);
|
||||
const catalog = catalogResult.rows[0];
|
||||
if (!catalog)
|
||||
throw new AppError(404, 'POS_PRODUCT_NOT_FOUND', 'El producto ya no está disponible');
|
||||
const discountCents = inputItem.discountCents ?? 0;
|
||||
if (
|
||||
!Number.isInteger(discountCents) ||
|
||||
discountCents < 0 ||
|
||||
discountCents > Number(catalog.unit_price_cents)
|
||||
) {
|
||||
throw new AppError(400, 'POS_INVALID_DISCOUNT', 'El descuento de línea no es válido');
|
||||
}
|
||||
if (!lineDiscountsEnabled && discountCents > 0) {
|
||||
throw new AppError(
|
||||
403,
|
||||
'POS_DISCOUNTS_DISABLED',
|
||||
'Los descuentos están desactivados en este terminal',
|
||||
);
|
||||
}
|
||||
const stock = await client.query<{ available: number }>(
|
||||
`SELECT available FROM inventory_stock
|
||||
WHERE variant_id = $1 AND store_id = $2
|
||||
FOR UPDATE`,
|
||||
[catalog.variant_id, session.store_id],
|
||||
);
|
||||
if (Number(stock.rows[0]?.available ?? 0) < inputItem.quantity) {
|
||||
throw new AppError(
|
||||
409,
|
||||
'POS_STOCK_UNAVAILABLE',
|
||||
`Stock insuficiente para ${catalog.name}`,
|
||||
);
|
||||
}
|
||||
items.push({
|
||||
kind: 'stock',
|
||||
variantId: catalog.variant_id,
|
||||
productId: catalog.product_id,
|
||||
sku: catalog.sku,
|
||||
ean: catalog.ean,
|
||||
name: catalog.name,
|
||||
unitPriceCents: Number(catalog.unit_price_cents),
|
||||
discountCents,
|
||||
taxCents: 0,
|
||||
quantity: inputItem.quantity,
|
||||
vatRate: catalog.vat_rate,
|
||||
});
|
||||
}
|
||||
|
||||
// 3. Compute totals
|
||||
const subtotalCents = input.items.reduce((s, i) => s + (i.unitPriceCents - i.discountCents) * i.quantity, 0);
|
||||
const taxCents = input.items.reduce((s, i) => s + i.taxCents * i.quantity, 0);
|
||||
const discountCents = input.items.reduce((s, i) => s + i.discountCents * i.quantity, 0);
|
||||
const totalCents = subtotalCents + taxCents;
|
||||
const paymentTotal = input.payments.reduce((s, p) => s + p.amountCents, 0);
|
||||
if (paymentTotal < totalCents) { await client.query('ROLLBACK'); throw new AppError(400, 'INSUFFICIENT_PAYMENT', 'Payments less than total'); }
|
||||
const subtotalCents = items.reduce(
|
||||
(sum, item) => sum + item.unitPriceCents * item.quantity,
|
||||
0,
|
||||
);
|
||||
const discountCents = items.reduce(
|
||||
(sum, item) => sum + item.discountCents * item.quantity,
|
||||
0,
|
||||
);
|
||||
const taxCents = items.reduce((sum, item) => sum + item.taxCents * item.quantity, 0);
|
||||
const totalCents = subtotalCents - discountCents + taxCents;
|
||||
if (totalCents <= 0)
|
||||
throw new AppError(400, 'POS_INVALID_TOTAL', 'El total de la venta debe ser positivo');
|
||||
|
||||
// 4. Create order
|
||||
const orderResult = await client.query<OrderRow>(
|
||||
const methodsResult = await client.query<ConfiguredPaymentMethod>(
|
||||
`SELECT id, code, label, kind
|
||||
FROM pos_payment_methods
|
||||
WHERE store_id = $1 AND active = true
|
||||
ORDER BY sort_order, label`,
|
||||
[session.store_id],
|
||||
);
|
||||
const payments = validatePaymentAllocations(totalCents, input.payments, methodsResult.rows);
|
||||
|
||||
await client.query(
|
||||
`INSERT INTO pos_receipt_settings (store_id) VALUES ($1)
|
||||
ON CONFLICT (store_id) DO NOTHING`,
|
||||
[session.store_id],
|
||||
);
|
||||
const receiptSettings = await client.query<{
|
||||
prefix: string;
|
||||
next_number: string;
|
||||
padding: number;
|
||||
}>(
|
||||
`SELECT prefix, next_number, padding FROM pos_receipt_settings WHERE store_id = $1 FOR UPDATE`,
|
||||
[session.store_id],
|
||||
);
|
||||
const sequence = receiptSettings.rows[0];
|
||||
if (!sequence)
|
||||
throw new AppError(500, 'POS_RECEIPT_CONFIG_MISSING', 'Falta la configuración de tickets');
|
||||
const receiptNumber = `${sequence.prefix}-${String(sequence.next_number).padStart(sequence.padding, '0')}`;
|
||||
await client.query(
|
||||
`UPDATE pos_receipt_settings SET next_number = next_number + 1, updated_at = now() WHERE store_id = $1`,
|
||||
[session.store_id],
|
||||
);
|
||||
|
||||
const orderResult = await client.query<{ id: string; created_at: Date }>(
|
||||
`INSERT INTO orders_orders (
|
||||
user_id, idempotency_key, subtotal_cents, discount_cents, tax_cents, total_cents,
|
||||
source, terminal_id, cash_session_id, store_id
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, 'pos', $7, $8, $9)
|
||||
RETURNING id, idempotency_key, total_cents, created_at`,
|
||||
user_id, idempotency_key, state, subtotal_cents, discount_cents, tax_cents,
|
||||
total_cents, source, terminal_id, cash_session_id, store_id, receipt_number
|
||||
) VALUES ($1, $2, 'COMPLETED', $3, $4, $5, $6, 'pos', $7, $8, $9, $10)
|
||||
RETURNING id, created_at`,
|
||||
[
|
||||
input.customerId ?? null,
|
||||
input.idempotencyKey,
|
||||
@@ -109,65 +301,174 @@ export class CreatePosSaleUseCase {
|
||||
totalCents,
|
||||
input.terminalId,
|
||||
input.cashSessionId,
|
||||
sessionRow.store_id,
|
||||
session.store_id,
|
||||
receiptNumber,
|
||||
],
|
||||
);
|
||||
const orderRow = orderResult.rows[0];
|
||||
if (!orderRow) { await client.query('ROLLBACK'); throw new AppError(500, 'ORDER_CREATE_FAILED', 'Order insert returned no row'); }
|
||||
const orderId = orderRow.id;
|
||||
const order = orderResult.rows[0];
|
||||
if (!order) throw new AppError(500, 'ORDER_CREATE_FAILED', 'No se pudo crear la venta');
|
||||
|
||||
// 5. Insert line items
|
||||
for (const item of input.items) {
|
||||
for (const item of items) {
|
||||
await client.query(
|
||||
`INSERT INTO orders_items (order_id, product_id, variant_id, sku, ean, name, unit_price_cents, discount_cents, tax_cents, quantity)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
|
||||
[orderId, item.productId, item.variantId, item.sku, item.ean, item.name, item.unitPriceCents, item.discountCents, item.taxCents, item.quantity],
|
||||
`INSERT INTO orders_items (
|
||||
order_id, product_id, variant_id, sku, ean, name, unit_price_cents,
|
||||
discount_cents, tax_cents, quantity, vat_rate, is_free_item
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
|
||||
[
|
||||
order.id,
|
||||
item.productId,
|
||||
item.variantId,
|
||||
item.sku,
|
||||
item.ean,
|
||||
item.name,
|
||||
item.unitPriceCents,
|
||||
item.discountCents,
|
||||
item.taxCents,
|
||||
item.quantity,
|
||||
item.vatRate,
|
||||
item.kind === 'free',
|
||||
],
|
||||
);
|
||||
if (item.kind === 'stock') {
|
||||
await client.query(
|
||||
`UPDATE inventory_stock
|
||||
SET available = available - $3, sold = sold + $3, updated_at = now()
|
||||
WHERE variant_id = $1 AND store_id = $2`,
|
||||
[item.variantId, session.store_id, item.quantity],
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO inventory_movements (variant_id, store_id, operation, quantity)
|
||||
VALUES ($1, $2, 'confirm', $3)`,
|
||||
[item.variantId, session.store_id, item.quantity],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Process payments + update cash session
|
||||
const paymentResults: PosPaymentResult[] = [];
|
||||
let cashPaymentCents = 0;
|
||||
for (const p of input.payments) {
|
||||
const kind = p.kind === 'cash' ? 'pos_cash' : p.kind === 'card' ? 'pos_card' : 'pos_other';
|
||||
const payResult = await client.query<{ id: string }>(
|
||||
`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) RETURNING id`,
|
||||
[kind, `pos-${orderId}-${p.kind}`, `pos-${Date.now()}`, orderId, p.amountCents, 'EUR', 'succeeded', JSON.stringify(p)],
|
||||
let cashAppliedCents = 0;
|
||||
for (const [index, payment] of payments.entries()) {
|
||||
const raw = {
|
||||
methodCode: payment.methodCode,
|
||||
methodLabel: payment.methodLabel,
|
||||
kind: payment.kind,
|
||||
tenderedCents: payment.tenderedCents,
|
||||
changeCents: payment.changeCents,
|
||||
...(payment.last4 ? { last4: payment.last4 } : {}),
|
||||
};
|
||||
const inserted = await client.query<{ id: string }>(
|
||||
`INSERT INTO payments_transactions (
|
||||
provider, provider_event_id, provider_payment_id, order_id,
|
||||
amount_cents, currency, status, raw
|
||||
) VALUES ($1, $2, $3, $4, $5, 'EUR', 'succeeded', $6)
|
||||
RETURNING id`,
|
||||
[
|
||||
`pos_${payment.methodCode}`,
|
||||
`pos-${order.id}-${index}`,
|
||||
`pos-${order.id}-${payment.methodCode}-${index}`,
|
||||
order.id,
|
||||
payment.amountCents,
|
||||
JSON.stringify(raw),
|
||||
],
|
||||
);
|
||||
const payRow = payResult.rows[0];
|
||||
if (!payRow) { await client.query('ROLLBACK'); throw new AppError(500, 'PAYMENT_INSERT_FAILED', 'Payment insert returned no row'); }
|
||||
paymentResults.push({ id: payRow.id, kind: p.kind, amountCents: p.amountCents });
|
||||
if (p.kind === 'cash') cashPaymentCents += p.tenderedCents ?? p.amountCents;
|
||||
}
|
||||
|
||||
if (cashPaymentCents > 0) {
|
||||
const paymentId = inserted.rows[0]?.id;
|
||||
if (!paymentId)
|
||||
throw new AppError(500, 'PAYMENT_INSERT_FAILED', 'No se pudo registrar el pago');
|
||||
await client.query(
|
||||
`UPDATE pos_cash_sessions SET expected_cash_cents = COALESCE(expected_cash_cents, 0) + $1, updated_at = now() WHERE id = $2`,
|
||||
[cashPaymentCents, input.cashSessionId],
|
||||
`INSERT INTO reporting_payment_lines (
|
||||
order_id, store_id, terminal_id, cash_session_id, payment_method_id,
|
||||
provider, amount_cents, currency, status, provider_ref
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, 'EUR', 'payment', $8)`,
|
||||
[
|
||||
order.id,
|
||||
session.store_id,
|
||||
input.terminalId,
|
||||
input.cashSessionId,
|
||||
payment.methodId,
|
||||
`pos_${payment.methodCode}`,
|
||||
payment.amountCents,
|
||||
paymentId,
|
||||
],
|
||||
);
|
||||
if (payment.kind === 'cash') cashAppliedCents += payment.amountCents;
|
||||
paymentResults.push({ id: paymentId, ...payment });
|
||||
}
|
||||
|
||||
if (cashAppliedCents > 0) {
|
||||
await client.query(
|
||||
`UPDATE pos_cash_sessions
|
||||
SET expected_cash_cents = COALESCE(expected_cash_cents, opening_cash_cents) + $1,
|
||||
updated_at = now()
|
||||
WHERE id = $2`,
|
||||
[cashAppliedCents, input.cashSessionId],
|
||||
);
|
||||
}
|
||||
|
||||
const receipt = await buildPosReceipt(client, order.id);
|
||||
await client.query('COMMIT');
|
||||
return {
|
||||
orderId,
|
||||
orderId: order.id,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
receiptNumber,
|
||||
totalCents,
|
||||
items: input.items,
|
||||
changeCents: payments.reduce((sum, payment) => sum + payment.changeCents, 0),
|
||||
items,
|
||||
payments: paymentResults,
|
||||
createdAt: orderRow.created_at,
|
||||
receipt,
|
||||
createdAt: order.created_at,
|
||||
};
|
||||
} catch (err) {
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
throw err;
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function providerToPaymentKind(provider: string): PosPaymentResult['kind'] {
|
||||
if (provider === 'pos_cash') return 'cash';
|
||||
if (provider === 'pos_card') return 'card';
|
||||
return 'other';
|
||||
private async loadResult(orderId: string, idempotencyKey: string): Promise<PosSaleResult> {
|
||||
const receipt = await buildPosReceipt(this.pool, orderId);
|
||||
const paymentRows = await this.pool.query<{
|
||||
id: string;
|
||||
amount_cents: number;
|
||||
raw: Record<string, unknown>;
|
||||
}>(
|
||||
`SELECT id, amount_cents, raw FROM payments_transactions
|
||||
WHERE order_id = $1 AND status = 'succeeded' ORDER BY created_at, id`,
|
||||
[orderId],
|
||||
);
|
||||
const payments: PosPaymentResult[] = paymentRows.rows.map((row, index) => ({
|
||||
id: row.id,
|
||||
...(receipt.payments[index] ?? {
|
||||
methodCode: String(row.raw.methodCode ?? 'other'),
|
||||
methodLabel: String(row.raw.methodLabel ?? 'Otro'),
|
||||
kind: 'other' as const,
|
||||
amountCents: Number(row.amount_cents),
|
||||
tenderedCents: null,
|
||||
changeCents: 0,
|
||||
}),
|
||||
}));
|
||||
const items: PosSaleLineItem[] = receipt.items.map((item) => ({
|
||||
kind: item.freeItem ? 'free' : 'stock',
|
||||
variantId: null,
|
||||
productId: null,
|
||||
sku: item.sku,
|
||||
ean: null,
|
||||
name: item.name,
|
||||
unitPriceCents: item.unitPriceCents,
|
||||
discountCents: item.quantity > 0 ? Math.round(item.discountCents / item.quantity) : 0,
|
||||
taxCents: item.quantity > 0 ? Math.round(item.taxCents / item.quantity) : 0,
|
||||
quantity: item.quantity,
|
||||
vatRate: null,
|
||||
}));
|
||||
return {
|
||||
orderId,
|
||||
idempotencyKey,
|
||||
receiptNumber: receipt.receiptNumber,
|
||||
totalCents: receipt.totalCents,
|
||||
changeCents: receipt.changeCents,
|
||||
items,
|
||||
payments,
|
||||
receipt,
|
||||
createdAt: receipt.issuedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,30 @@
|
||||
export interface PosSaleLineItem {
|
||||
export interface PosStockSaleLineInput {
|
||||
kind?: 'stock';
|
||||
variantId: string;
|
||||
productId: string;
|
||||
quantity: number;
|
||||
discountCents?: number;
|
||||
// Legacy snapshot fields are accepted at the API boundary but ignored.
|
||||
productId?: string;
|
||||
sku?: string;
|
||||
ean?: string | null;
|
||||
name?: string;
|
||||
unitPriceCents?: number;
|
||||
taxCents?: number;
|
||||
}
|
||||
|
||||
export interface PosFreeSaleLineInput {
|
||||
kind: 'free';
|
||||
name: string;
|
||||
unitPriceCents: number;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
export type PosSaleLineInput = PosStockSaleLineInput | PosFreeSaleLineInput;
|
||||
|
||||
export interface PosSaleLineItem {
|
||||
kind: 'stock' | 'free';
|
||||
variantId: string | null;
|
||||
productId: string | null;
|
||||
sku: string;
|
||||
ean: string | null;
|
||||
name: string;
|
||||
@@ -8,12 +32,16 @@ export interface PosSaleLineItem {
|
||||
discountCents: number;
|
||||
taxCents: number;
|
||||
quantity: number;
|
||||
vatRate: string | null;
|
||||
}
|
||||
|
||||
export type PosPaymentKind = 'cash' | 'card' | 'other';
|
||||
|
||||
export interface PosPaymentInput {
|
||||
kind: PosPaymentKind;
|
||||
/** Configured payment method code. */
|
||||
methodCode?: string;
|
||||
/** Legacy field; used only to resolve cash/card defaults. */
|
||||
kind?: PosPaymentKind;
|
||||
amountCents: number;
|
||||
/** For cash payments: actual amount given by customer. */
|
||||
tenderedCents?: number;
|
||||
@@ -26,23 +54,71 @@ export interface PosSaleInput {
|
||||
cashSessionId: string;
|
||||
terminalId: string;
|
||||
userId: string;
|
||||
items: PosSaleLineItem[];
|
||||
items: PosSaleLineInput[];
|
||||
payments: PosPaymentInput[];
|
||||
/** Optional customer ID for loyalty. */
|
||||
customerId?: string;
|
||||
}
|
||||
|
||||
export interface PosReceiptItem {
|
||||
name: string;
|
||||
sku: string;
|
||||
quantity: number;
|
||||
unitPriceCents: number;
|
||||
subtotalCents: number;
|
||||
discountCents: number;
|
||||
taxCents: number;
|
||||
totalCents: number;
|
||||
freeItem: boolean;
|
||||
}
|
||||
|
||||
export interface PosReceiptPayment {
|
||||
methodCode: string;
|
||||
methodLabel: string;
|
||||
kind: PosPaymentKind;
|
||||
amountCents: number;
|
||||
tenderedCents: number | null;
|
||||
changeCents: number;
|
||||
}
|
||||
|
||||
export interface PosReceipt {
|
||||
receiptNumber: string;
|
||||
orderId: string;
|
||||
issuedAt: Date;
|
||||
company: {
|
||||
name: string;
|
||||
address: string | null;
|
||||
taxId: string | null;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
};
|
||||
terminal: { id: string; name: string };
|
||||
cashier: string;
|
||||
sessionId: string;
|
||||
customerEmail: string | null;
|
||||
items: PosReceiptItem[];
|
||||
subtotalCents: number;
|
||||
discountCents: number;
|
||||
taxCents: number;
|
||||
totalCents: number;
|
||||
payments: PosReceiptPayment[];
|
||||
changeCents: number;
|
||||
header: string | null;
|
||||
returnPolicy: string;
|
||||
footer: string | null;
|
||||
}
|
||||
|
||||
export interface PosSaleResult {
|
||||
orderId: string;
|
||||
idempotencyKey: string;
|
||||
receiptNumber: string;
|
||||
totalCents: number;
|
||||
changeCents: number;
|
||||
items: PosSaleLineItem[];
|
||||
payments: PosPaymentResult[];
|
||||
receipt: PosReceipt;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface PosPaymentResult {
|
||||
export interface PosPaymentResult extends PosReceiptPayment {
|
||||
id: string;
|
||||
kind: PosPaymentKind;
|
||||
amountCents: number;
|
||||
}
|
||||
|
||||
18
project/src/modules/pos/index.ts
Normal file
18
project/src/modules/pos/index.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/** Public API of the POS module. */
|
||||
export { registerPosRoutes, type PosRouteDeps } from './api/pos.routes.js';
|
||||
export {
|
||||
CreatePosSaleUseCase,
|
||||
validatePaymentAllocations,
|
||||
type ConfiguredPaymentMethod,
|
||||
type ValidatedPayment,
|
||||
} from './application/create-pos-sale.js';
|
||||
export { buildPosReceipt } from './application/build-pos-receipt.js';
|
||||
export type {
|
||||
PosSaleInput,
|
||||
PosSaleResult,
|
||||
PosSaleLineInput,
|
||||
PosSaleLineItem,
|
||||
PosPaymentInput,
|
||||
PosPaymentResult,
|
||||
PosReceipt,
|
||||
} from './domain/pos-sale.js';
|
||||
75
project/src/modules/pos/tests/payment-allocation.test.ts
Normal file
75
project/src/modules/pos/tests/payment-allocation.test.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { AppError } from '../../../shared/errors.js';
|
||||
import {
|
||||
validatePaymentAllocations,
|
||||
type ConfiguredPaymentMethod,
|
||||
} from '../application/create-pos-sale.js';
|
||||
|
||||
const methods: ConfiguredPaymentMethod[] = [
|
||||
{ id: 'cash-id', code: 'cash', label: 'Efectivo', kind: 'cash' },
|
||||
{ id: 'card-id', code: 'card', label: 'Tarjeta', kind: 'card' },
|
||||
{ id: 'bizum-id', code: 'bizum', label: 'Bizum', kind: 'other' },
|
||||
];
|
||||
|
||||
describe('POS payment allocation', () => {
|
||||
it('supports mixed partial payments and calculates cash change', () => {
|
||||
const result = validatePaymentAllocations(
|
||||
2_000,
|
||||
[
|
||||
{ methodCode: 'cash', amountCents: 500, tenderedCents: 1_000 },
|
||||
{ methodCode: 'bizum', amountCents: 1_500 },
|
||||
],
|
||||
methods,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject([
|
||||
{ methodCode: 'cash', amountCents: 500, tenderedCents: 1_000, changeCents: 500 },
|
||||
{ methodCode: 'bizum', amountCents: 1_500, tenderedCents: null, changeCents: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('requires applied amounts to equal the total exactly', () => {
|
||||
expectCode(
|
||||
() =>
|
||||
validatePaymentAllocations(2_000, [{ methodCode: 'card', amountCents: 1_999 }], methods),
|
||||
'POS_PAYMENT_TOTAL_MISMATCH',
|
||||
);
|
||||
expectCode(
|
||||
() =>
|
||||
validatePaymentAllocations(2_000, [{ methodCode: 'card', amountCents: 2_001 }], methods),
|
||||
'POS_PAYMENT_TOTAL_MISMATCH',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects disabled methods and tendered amounts on non-cash methods', () => {
|
||||
expectCode(
|
||||
() => validatePaymentAllocations(100, [{ methodCode: 'stripe', amountCents: 100 }], methods),
|
||||
'POS_PAYMENT_METHOD_DISABLED',
|
||||
);
|
||||
expectCode(
|
||||
() =>
|
||||
validatePaymentAllocations(
|
||||
100,
|
||||
[{ methodCode: 'card', amountCents: 100, tenderedCents: 100 }],
|
||||
methods,
|
||||
),
|
||||
'POS_NON_CASH_TENDERED',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps legacy kind mapping for cash and card clients', () => {
|
||||
expect(
|
||||
validatePaymentAllocations(100, [{ kind: 'card', amountCents: 100 }], methods)[0],
|
||||
).toMatchObject({ methodCode: 'card', kind: 'card' });
|
||||
});
|
||||
});
|
||||
|
||||
function expectCode(action: () => unknown, code: string): void {
|
||||
try {
|
||||
action();
|
||||
throw new Error('Expected action to throw');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(AppError);
|
||||
expect((error as AppError).code).toBe(code);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user