feat(F-187): completed feature

This commit is contained in:
chattie
2026-08-22 22:23:44 +02:00
parent a3f6edd325
commit ca12f46bff
22 changed files with 1053 additions and 59 deletions

View File

@@ -71,7 +71,7 @@ export async function registerBackofficeRoutes(
properties: {
id: { type: 'string', format: 'uuid' },
email: { type: 'string', format: 'email' },
role: { type: 'string', enum: ['admin', 'editor'] },
role: { type: 'string', enum: ['admin', 'editor', 'pos_manager', 'pos_cashier'] },
},
},
401: errorSchema,
@@ -97,7 +97,7 @@ export async function registerBackofficeRoutes(
properties: {
id: { type: 'string', format: 'uuid' },
email: { type: 'string', format: 'email' },
role: { type: 'string', enum: ['admin', 'editor'] },
role: { type: 'string', enum: ['admin', 'editor', 'pos_manager', 'pos_cashier'] },
},
},
{ type: 'object', properties: { user: { type: 'null' } } },

View File

@@ -3,13 +3,16 @@
* Backoffice users (admin/editor) are physically separated from storefront
* customers (identity_users) and authenticate through a separate mechanism.
*/
export type BackofficeRole = 'admin' | 'editor';
export type BackofficeRole = 'admin' | 'editor' | 'pos_cashier' | 'pos_manager';
export interface BackofficeUser {
id: string;
email: string;
role: BackofficeRole;
mfaEnrolled: boolean;
active: boolean;
deactivatedAt: Date | null;
deletedAt: Date | null;
createdAt: Date;
updatedAt: Date;
}

View File

@@ -4,7 +4,7 @@
*/
import type { FastifyRequest } from 'fastify';
import type pg from 'pg';
import type { Authenticate } from '../../../shared/auth.js';
import type { Authenticate, Role } from '../../../shared/auth.js';
import { AppError } from '../../../shared/errors.js';
import { hashBackofficeToken } from './backoffice-session-token.js';
import { BACKOFFICE_SESSION_COOKIE_NAME } from '../api/backoffice.routes.js';
@@ -22,6 +22,8 @@ const RESOLVE_SQL = `
WHERE s.token_hash = $1
AND s.revoked_at IS NULL
AND s.expires_at > now()
AND u.active = true
AND u.deleted_at IS NULL
`;
export function createBackofficeSessionAuthenticator(pool: pg.Pool): Authenticate {
@@ -31,7 +33,7 @@ export function createBackofficeSessionAuthenticator(pool: pg.Pool): Authenticat
const result = await pool.query<ResolvedRow>(RESOLVE_SQL, [hashBackofficeToken(token)]);
const row = result.rows[0];
if (!row) throw new AppError(401, 'UNAUTHORIZED', 'Backoffice authentication required');
return { id: row.id, email: row.email, role: row.role as 'admin' | 'editor' };
return { id: row.id, email: row.email, role: row.role as Role };
};
}

View File

@@ -14,6 +14,9 @@ interface UserRow {
password_hash: string;
role: string;
mfa_enrolled: boolean;
active: boolean;
deactivated_at: Date | null;
deleted_at: Date | null;
created_at: Date;
updated_at: Date;
}
@@ -47,7 +50,8 @@ export class PgBackofficeUserRepository implements BackofficeUserRepository {
async findByEmail(email: string): Promise<BackofficeUserWithHash | undefined> {
const result = await this.pool.query<UserRow>(
'SELECT * FROM backoffice_users WHERE email = $1',
`SELECT * FROM backoffice_users
WHERE email = $1 AND active = true AND deleted_at IS NULL`,
[email.toLowerCase()],
);
const row = result.rows[0];
@@ -76,6 +80,9 @@ function toUser(row: UserRow): BackofficeUser {
email: row.email,
role: row.role as BackofficeRole,
mfaEnrolled: row.mfa_enrolled,
active: row.active,
deactivatedAt: row.deactivated_at,
deletedAt: row.deleted_at,
createdAt: row.created_at,
updatedAt: row.updated_at,
};

View File

@@ -2190,8 +2190,17 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
const user = await authenticate(request);
requireRole(user, 'admin');
const result = await pool.query(
`SELECT id, email, role FROM backoffice_users
WHERE role IN ('pos_manager','pos_cashier') ORDER BY email`,
`SELECT id, email, role, active,
deactivated_at AS "deactivatedAt", deleted_at AS "deletedAt",
created_at AS "createdAt",
CASE
WHEN deleted_at IS NOT NULL THEN 'deleted'
WHEN active THEN 'active'
ELSE 'inactive'
END AS status
FROM backoffice_users
WHERE role IN ('pos_manager','pos_cashier')
ORDER BY deleted_at NULLS FIRST, active DESC, email`,
);
return reply.send({ items: result.rows });
},
@@ -2246,7 +2255,212 @@ export async function registerPosRoutes(app: FastifyInstance, deps: PosRouteDeps
);
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 });
return reply.code(201).send({
id: created.id,
email: body.email,
role: body.role,
active: true,
deactivatedAt: null,
deletedAt: null,
status: 'active',
});
},
);
app.patch(
'/pos/users/:id/status',
{
schema: {
tags: ['POS Admin'],
summary: 'Activate or deactivate a POS cashier',
params: {
type: 'object',
required: ['id'],
properties: { id: { type: 'string', format: 'uuid' } },
},
body: {
type: 'object',
required: ['active'],
properties: { active: { type: 'boolean' } },
},
response: {
400: errorSchema,
401: errorSchema,
403: errorSchema,
404: errorSchema,
409: errorSchema,
},
} as FastifySchema,
},
async (request, reply) => {
const admin = await authenticate(request);
requireRole(admin, 'admin');
const { id } = parseJson(idParamSchema, request.params);
const { active } = parseJson(z.object({ active: z.boolean() }), request.body ?? {});
const client = await pool.connect();
try {
await client.query('BEGIN');
const targetResult = await client.query<{
id: string;
email: string;
active: boolean;
deleted_at: Date | null;
}>(
`SELECT id, email, active, deleted_at FROM backoffice_users
WHERE id = $1 AND role = 'pos_cashier' FOR UPDATE`,
[id],
);
const target = targetResult.rows[0];
if (!target) {
throw new AppError(404, 'POS_CASHIER_NOT_FOUND', 'Cajero no encontrado');
}
if (target.deleted_at) {
throw new AppError(
409,
'POS_CASHIER_DELETED',
'Un cajero eliminado no se puede reactivar',
);
}
if (!active && target.active) {
const open = await client.query(
`SELECT id FROM pos_cash_sessions
WHERE user_id = $1 AND status = 'OPEN' LIMIT 1`,
[id],
);
if (open.rows[0]) {
throw new AppError(
409,
'POS_CASHIER_HAS_OPEN_SESSION',
'Cierra la sesión de caja antes de desactivar el cajero',
);
}
}
const updated = await client.query<{
id: string;
email: string;
active: boolean;
deactivatedAt: Date | null;
deletedAt: Date | null;
}>(
`UPDATE backoffice_users
SET active = $2,
deactivated_at = CASE WHEN $2 THEN NULL ELSE COALESCE(deactivated_at, now()) END,
updated_at = now()
WHERE id = $1
RETURNING id, email, active,
deactivated_at AS "deactivatedAt", deleted_at AS "deletedAt"`,
[id, active],
);
if (!active) {
await client.query(
`UPDATE backoffice_sessions SET revoked_at = COALESCE(revoked_at, now())
WHERE user_id = $1 AND revoked_at IS NULL`,
[id],
);
}
await client.query(
`INSERT INTO security_audit_log (actor_id, action, target, metadata)
VALUES ($1, $2, $3, jsonb_build_object('email', $4::text))`,
[
admin.id,
active ? 'pos.cashier.reactivated' : 'pos.cashier.deactivated',
id,
target.email,
],
);
await client.query('COMMIT');
return reply.send({
...updated.rows[0],
role: 'pos_cashier',
status: active ? 'active' : 'inactive',
});
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
},
);
app.delete(
'/pos/users/:id',
{
schema: {
tags: ['POS Admin'],
summary: 'Soft-delete a POS cashier while preserving history',
params: {
type: 'object',
required: ['id'],
properties: { id: { type: 'string', format: 'uuid' } },
},
response: {
204: { type: 'null' },
401: errorSchema,
403: errorSchema,
404: errorSchema,
409: errorSchema,
},
} as FastifySchema,
},
async (request, reply) => {
const admin = await authenticate(request);
requireRole(admin, 'admin');
const { id } = parseJson(idParamSchema, request.params);
const client = await pool.connect();
try {
await client.query('BEGIN');
const targetResult = await client.query<{ email: string; deleted_at: Date | null }>(
`SELECT email, deleted_at FROM backoffice_users
WHERE id = $1 AND role = 'pos_cashier' FOR UPDATE`,
[id],
);
const target = targetResult.rows[0];
if (!target) {
throw new AppError(404, 'POS_CASHIER_NOT_FOUND', 'Cajero no encontrado');
}
if (target.deleted_at) {
throw new AppError(409, 'POS_CASHIER_ALREADY_DELETED', 'El cajero ya está eliminado');
}
const open = await client.query(
`SELECT id FROM pos_cash_sessions
WHERE user_id = $1 AND status = 'OPEN' LIMIT 1`,
[id],
);
if (open.rows[0]) {
throw new AppError(
409,
'POS_CASHIER_HAS_OPEN_SESSION',
'Cierra la sesión de caja antes de eliminar el cajero',
);
}
await client.query(
`UPDATE backoffice_users
SET active = false,
deactivated_at = COALESCE(deactivated_at, now()),
deleted_at = now(),
updated_at = now()
WHERE id = $1`,
[id],
);
await client.query(
`UPDATE backoffice_sessions SET revoked_at = COALESCE(revoked_at, now())
WHERE user_id = $1 AND revoked_at IS NULL`,
[id],
);
await client.query(
`INSERT INTO security_audit_log (actor_id, action, target, metadata)
VALUES ($1, 'pos.cashier.deleted', $2, jsonb_build_object('email', $3::text))`,
[admin.id, id, target.email],
);
await client.query('COMMIT');
return reply.code(204).send();
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
},
);

View File

@@ -38,6 +38,12 @@ export class CashSessionNotOpenError extends PosError {
}
}
export class CashierUnavailableError extends PosError {
constructor(userId: string) {
super('POS_CASHIER_UNAVAILABLE', `POS user ${userId} is inactive or deleted`);
}
}
export class TerminalNotBoundError extends PosError {
constructor(terminalId: string) {
super('TERMINAL_NOT_BOUND', `Terminal ${terminalId} is not bound`);

View File

@@ -1,6 +1,11 @@
import type pg from 'pg';
import type { PosCashSessionRepository } from '../domain/ports.js';
import type { PosCashSession, OpenCashSessionInput, CloseCashSessionInput } from '../domain/cash-session.js';
import type {
PosCashSession,
OpenCashSessionInput,
CloseCashSessionInput,
} from '../domain/cash-session.js';
import { CashierUnavailableError } from '../domain/errors.js';
interface SessionRow {
id: string;
@@ -60,21 +65,43 @@ export class PgCashSessionRepository implements PosCashSessionRepository {
}
async open(input: OpenCashSessionInput): Promise<PosCashSession> {
// Get store_id from terminal
const terminal = await this.pool.query<{ store_id: string }>(
'SELECT store_id FROM pos_terminals WHERE id = $1',
[input.terminalId],
);
if (!terminal.rows[0]) throw new Error(`Terminal ${input.terminalId} not found`);
const storeId = terminal.rows[0].store_id;
const client = await this.pool.connect();
try {
await client.query('BEGIN');
// This row lock serializes opening against cashier deactivation/deletion.
const cashier = await client.query<{ active: boolean; deleted_at: Date | null }>(
`SELECT active, deleted_at FROM backoffice_users
WHERE id = $1 AND role IN ('admin', 'pos_manager', 'pos_cashier')
FOR UPDATE`,
[input.userId],
);
const cashierRow = cashier.rows[0];
if (!cashierRow?.active || cashierRow.deleted_at) {
throw new CashierUnavailableError(input.userId);
}
const result = await this.pool.query<SessionRow>(
`INSERT INTO pos_cash_sessions (terminal_id, store_id, user_id, opening_cash_cents)
VALUES ($1, $2, $3, $4) RETURNING *`,
[input.terminalId, storeId, input.userId, input.openingCashCents],
);
if (!result.rows[0]) throw new Error('Failed to create session');
return toSession(result.rows[0]);
const terminal = await client.query<{ store_id: string }>(
'SELECT store_id FROM pos_terminals WHERE id = $1',
[input.terminalId],
);
if (!terminal.rows[0]) throw new Error(`Terminal ${input.terminalId} not found`);
const storeId = terminal.rows[0].store_id;
const result = await client.query<SessionRow>(
`INSERT INTO pos_cash_sessions (terminal_id, store_id, user_id, opening_cash_cents)
VALUES ($1, $2, $3, $4) RETURNING *`,
[input.terminalId, storeId, input.userId, input.openingCashCents],
);
const row = result.rows[0];
if (!row) throw new Error('Failed to create session');
await client.query('COMMIT');
return toSession(row);
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
async close(input: CloseCashSessionInput): Promise<PosCashSession> {
@@ -85,7 +112,13 @@ export class PgCashSessionRepository implements PosCashSessionRepository {
closing_cash_cents = $2, actual_cash_cents = $3,
difference_cents = $4, notes = $5, updated_at = now()
WHERE id = $1 RETURNING *`,
[input.sessionId, input.closingCashCents, input.actualCashCents, difference, input.notes ?? null],
[
input.sessionId,
input.closingCashCents,
input.actualCashCents,
difference,
input.notes ?? null,
],
);
if (!result.rows[0]) throw new Error(`Session ${input.sessionId} not found`);
return toSession(result.rows[0]);