feat(POS-013): completed feature

This commit is contained in:
chattie
2026-08-22 13:50:28 +02:00
parent 82e237aab5
commit d8f942d4bd
10 changed files with 186 additions and 10 deletions

View File

@@ -873,4 +873,116 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
return reply.send({ summary: sum.rows[0], byPayment: byPay.rows });
});
// ── POS-013: Low stock alerts + loyalty + settings + shortcuts ────────────
app.get('/pos/inventory/low-stock', {
schema: {
tags: ['POS Terminal'],
summary: 'List low-stock variants for a store',
querystring: { type: 'object', required: ['storeId'], properties: { storeId: { type: 'string', format: 'uuid' }, threshold: { type: 'integer', minimum: 1, default: 10 } } },
response: { 401: errorSchema },
} as FastifySchema,
}, async (request, reply) => {
const user = await authenticate(request);
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
const { storeId, threshold = 10 } = request.query as { storeId?: string; threshold?: number };
const result = await pool.query(
`SELECT v.id AS "variantId", v.name, v.sku, s.quantity AS stock
FROM catalog_product_variants v
LEFT JOIN LATERAL (SELECT quantity FROM inventory_stock WHERE variant_id = v.id AND store_id = $1 LIMIT 1) s ON true
WHERE v.active = true AND (s.quantity IS NULL OR s.quantity <= $2)
ORDER BY s.quantity ASC NULLS FIRST LIMIT 50`,
[storeId, threshold],
);
return reply.send({ items: result.rows });
});
app.get<{ Params: { customerId: string } }>('/pos/loyalty/:customerId', {
schema: {
tags: ['POS Terminal'],
summary: 'Get loyalty info for a customer',
params: { type: 'object', properties: { customerId: { type: 'string', format: 'uuid' } } },
response: { 401: errorSchema, 404: errorSchema },
} as FastifySchema,
}, async (request, reply) => {
const user = await authenticate(request);
requireAnyRole(user, ['admin', 'pos_manager', 'pos_cashier'] as ReadonlyArray<Role>);
const { customerId } = request.params;
const profile = await pool.query('SELECT user_id, loyalty_points AS "loyaltyPoints", loyalty_tier AS "loyaltyTier" FROM users_profiles WHERE user_id = $1', [customerId]);
if (!profile.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Customer not found');
return reply.send({ customerId, points: profile.rows[0].loyaltyPoints ?? 0, tier: profile.rows[0].loyaltyTier ?? 'bronze' });
});
app.post<{ Params: { customerId: string } }>('/pos/loyalty/:customerId/points', {
schema: {
tags: ['POS Terminal'],
summary: 'Award or redeem loyalty points',
params: { type: 'object', properties: { customerId: { type: 'string', format: 'uuid' } } },
body: { type: 'object', required: ['delta', 'reason'], properties: { delta: { type: 'integer' }, reason: { type: 'string' } } },
response: { 400: errorSchema, 401: errorSchema, 404: errorSchema },
} as FastifySchema,
}, async (request, reply) => {
const user = await authenticate(request);
requireAnyRole(user, ['admin', 'pos_manager'] as ReadonlyArray<Role>);
const { customerId } = request.params;
const { delta, reason } = (request.body ?? {}) as { delta?: number; reason?: string };
const current = await pool.query<{ loyalty_points: number }>('SELECT loyalty_points FROM users_profiles WHERE user_id = $1', [customerId]);
if (!current.rows[0]) throw new AppError(404, 'NOT_FOUND', 'Customer not found');
const newPoints = Math.max(0, (current.rows[0].loyalty_points ?? 0) + (delta ?? 0));
await pool.query('UPDATE users_profiles SET loyalty_points = $1, updated_at = now() WHERE user_id = $2', [newPoints, customerId]);
return reply.send({ customerId, points: newPoints, delta: delta ?? 0, reason });
});
app.get('/pos/settings', {
schema: { tags: ['POS Admin'], summary: 'Get POS store settings', querystring: { type: 'object', properties: { storeId: { type: 'string', format: 'uuid' } } }, response: { 401: errorSchema, 403: errorSchema } } as FastifySchema,
}, async (request, reply) => {
const user = await authenticate(request);
requireRole(user, 'admin');
const { storeId } = request.query as { storeId?: string };
const result = storeId
? await pool.query('SELECT store_id AS "storeId", receipt_footer AS "receiptFooter", receipt_vat AS "receiptVat", default_payment_method AS "defaultPaymentMethod" FROM pos_store_settings WHERE store_id = $1', [storeId])
: await pool.query('SELECT store_id AS "storeId", receipt_footer AS "receiptFooter", receipt_vat AS "receiptVat", default_payment_method AS "defaultPaymentMethod" FROM pos_store_settings LIMIT 1');
return reply.send(result.rows[0] ?? { receiptFooter: 'Gracias por su compra', receiptVat: 'ES00000000', defaultPaymentMethod: 'cash' });
});
app.patch('/pos/settings', {
schema: {
tags: ['POS Admin'],
summary: 'Update POS store settings',
body: { type: 'object', properties: { storeId: { type: 'string', format: 'uuid' }, receiptFooter: { type: 'string' }, receiptVat: { type: 'string' }, defaultPaymentMethod: { type: 'string', enum: ['cash', 'card', 'other'] } } },
response: { 401: errorSchema, 403: errorSchema },
} as FastifySchema,
}, async (request, reply) => {
const user = await authenticate(request);
requireRole(user, 'admin');
const body = (request.body ?? {}) as Record<string, unknown>;
if (!body.storeId) throw new AppError(400, 'MISSING_STORE_ID', 'storeId required');
const sets: string[] = [];
const vals: unknown[] = [];
if (body.receiptFooter !== undefined) { vals.push(body.receiptFooter); sets.push(`receipt_footer = $${vals.length}`); }
if (body.receiptVat !== undefined) { vals.push(body.receiptVat); sets.push(`receipt_vat = $${vals.length}`); }
if (body.defaultPaymentMethod !== undefined) { vals.push(body.defaultPaymentMethod); sets.push(`default_payment_method = $${vals.length}`); }
vals.push(body.storeId);
if (sets.length === 0) return reply.send({ ok: true });
await pool.query(`INSERT INTO pos_store_settings (store_id, receipt_footer, receipt_vat, default_payment_method) VALUES ($${vals.length}, $1, $2, $3) ON CONFLICT (store_id) DO UPDATE SET ${sets.join(', ')}, updated_at = now()`, vals);
return reply.send({ ok: true });
});
app.get('/pos/shortcuts', {
schema: { tags: ['POS Terminal'], summary: 'Get keyboard shortcuts' } as FastifySchema,
}, async (request, reply) => {
await authenticate(request);
return reply.send({ shortcuts: [
{ key: 'F1', action: 'search', description: 'Focus product search' },
{ key: 'F2', action: 'pay-cash', description: 'Pay with cash' },
{ key: 'F3', action: 'pay-card', description: 'Pay with card' },
{ key: 'F4', action: 'discount', description: 'Apply discount' },
{ key: 'F5', action: 'customer', description: 'Associate customer' },
{ key: 'F6', action: 'clear', description: 'Clear cart' },
{ key: 'F7', action: 'receipt', description: 'Print last receipt' },
]});
});
}