feat(F-106): completed feature

This commit is contained in:
chattie
2026-08-21 09:27:55 +02:00
parent 5458789634
commit dca7c3214f
21 changed files with 958 additions and 73 deletions

View File

@@ -12,6 +12,7 @@ import { OrderNotFoundError, OrderStateTransitionError } from '../domain/errors.
import type { OrderState } from '../domain/order.js';
import { PgOrderRepository } from '../infrastructure/pg-order-repository.js';
import { NoOpOrderEventPublisher } from '../infrastructure/no-op-event-publisher.js';
import { sendOrderStatusEmail } from '../infrastructure/order-status-mailer.js';
export interface OrdersRoutesDeps {
pool: pg.Pool;
@@ -225,6 +226,7 @@ export async function registerOrdersRoutes(
'PARTIALLY_REFUNDED',
],
},
trackingNumber: { type: 'string', maxLength: 120, description: 'Número de seguimiento del envío (obligatorio al marcar como Enviado)' },
},
},
response: { 401: errorSchema, 403: errorSchema, 404: errorSchema },
@@ -236,15 +238,157 @@ export async function registerOrdersRoutes(
const user = await deps.authenticate(request);
requireRole(user, 'admin');
const { id } = parseJson(orderIdParamSchema, request.params);
const { state } = parseJson(transitionSchema, request.body);
const { state, trackingNumber } = parseJson(
transitionSchema.extend({ trackingNumber: z.string().min(1).max(120).optional() }),
request.body,
);
if (state === 'SHIPPED' && !trackingNumber?.trim()) {
throw new AppError(422, 'TRACKING_NUMBER_REQUIRED', 'Indica el número de seguimiento para marcar el pedido como enviado');
}
let order;
try {
const order = await service.transitionAdmin(id, state as OrderState);
return reply.send(serializeOrder(order));
order = await service.transitionAdmin(id, state as OrderState, trackingNumber?.trim() || undefined);
} catch (error) {
throw mapOrderError(error);
}
// Notificar al cliente el cambio de estado (sin bloquear la transición).
let notified = false;
let notificationError = '';
try {
const emailRow = await deps.pool.query<{ email: string }>(
'SELECT email FROM identity_users WHERE id = $1',
[order.userId],
);
const to = emailRow.rows[0]?.email;
if (to) {
await sendOrderStatusEmail(deps.pool, {
to,
orderId: order.id,
state: order.state,
trackingNumber: order.trackingNumber,
});
notified = true;
} else {
notificationError = 'El cliente no tiene email asociado';
}
} catch (error) {
notificationError = error instanceof Error ? error.message : 'No se pudo enviar el email';
request.log.warn({ err: error, orderId: order.id }, 'order_status_email_failed');
}
return reply.send({ ...serializeOrder(order), notified, notificationError: notificationError || undefined });
},
);
const editItemsSchema: FastifySchema = {
tags: ['Orders'],
summary: 'Edit order items (admin)',
description:
'Reemplaza los artículos del pedido (agregar/quitar productos y ajustar cantidades). Los totales se recalculan con los precios e IVA actuales.',
params: {
type: 'object',
required: ['id'],
properties: { id: { type: 'string', format: 'uuid' } },
},
body: { type: 'object' },
response: { 401: errorSchema, 403: errorSchema, 404: errorSchema, 422: errorSchema },
};
app.put('/orders/:id/items', { schema: editItemsSchema }, async (request, reply) => {
const user = await deps.authenticate(request);
requireRole(user, 'admin');
const { id } = parseJson(orderIdParamSchema, request.params);
const body = parseJson(
z.object({
items: z
.array(
z.object({
variantId: z.uuid(),
quantity: z.number().int().positive().max(999),
}),
)
.min(1),
}),
request.body,
);
const existing = await service.getOrderAdmin(id);
if (!existing) throw new AppError(404, 'ORDER_NOT_FOUND', 'Order not found');
// Consolidar cantidades por variante.
const byVariant = new Map<string, number>();
for (const item of body.items) {
byVariant.set(item.variantId, (byVariant.get(item.variantId) ?? 0) + item.quantity);
}
const variantIds = [...byVariant.keys()];
// Resolver datos de catálogo y precio vigente de cada variante.
const variantResult = await deps.pool.query<{
variant_id: string;
sku: string;
ean: string | null;
product_id: string;
product_name: string;
net_unit_amount_cents: number | null;
vat_rate: string | null;
}>(
`SELECT v.id AS variant_id, v.sku, v.ean, v.product_id, p.name AS product_name,
pr.net_unit_amount_cents, pr.vat_rate
FROM catalog_product_variants v
JOIN catalog_products p ON p.id = v.product_id
LEFT JOIN pricing_variant_prices pr ON pr.variant_id = v.id
WHERE v.id = ANY($1::uuid[])`,
[variantIds],
);
const found = new Map(variantResult.rows.map((row) => [row.variant_id, row]));
for (const variantId of variantIds) {
if (!found.has(variantId)) {
throw new AppError(422, 'VARIANT_NOT_FOUND', `La variante ${variantId.slice(0, 8)} no existe en el catálogo`);
}
const row = found.get(variantId);
if (row?.net_unit_amount_cents == null) {
throw new AppError(422, 'PRICE_MISSING', `Falta el precio de la variante ${row?.sku ?? variantId.slice(0, 8)}`);
}
}
const VAT_POINTS: Record<string, number> = { general: 2100, reduced: 1000, 'super-reduced': 400 };
const itemInputs = variantIds.map((variantId) => {
const row = found.get(variantId)!;
const quantity = byVariant.get(variantId)!;
const unitPriceCents = row.net_unit_amount_cents!;
const points = VAT_POINTS[row.vat_rate ?? 'general'] ?? 2100;
const taxCents = Math.round((unitPriceCents * quantity * points) / 10_000);
return {
productId: row.product_id,
variantId,
sku: row.sku,
ean: row.ean,
name: row.product_name,
unitPriceCents,
discountCents: 0,
taxCents,
quantity,
};
});
const netSubtotalCents = itemInputs.reduce((acc, item) => acc + item.unitPriceCents * item.quantity, 0);
const taxCents = itemInputs.reduce((acc, item) => acc + item.taxCents, 0);
const subtotalCents = netSubtotalCents + taxCents;
const discountCents = Math.min(existing.discountCents, subtotalCents);
// El coste de envío original se conserva: total - (subtotal - descuento).
const shippingCents = Math.max(0, existing.totalCents - Math.max(0, existing.subtotalCents - existing.discountCents));
const totalCents = Math.max(0, subtotalCents - discountCents) + shippingCents;
try {
const updated = await service.editItems(id, itemInputs, {
subtotalCents,
discountCents,
taxCents,
totalCents,
});
return reply.send(serializeOrder(updated));
} catch (error) {
throw mapOrderError(error);
}
});
}
function mapOrderError(error: unknown): Error {
@@ -263,6 +407,7 @@ function serializeOrder(order: {
discountCents: number;
taxCents: number;
totalCents: number;
trackingNumber?: string | null;
createdAt: Date;
updatedAt: Date;
idempotencyKey: string | null;
@@ -290,6 +435,7 @@ function serializeOrder(order: {
discountCents: order.discountCents,
taxCents: order.taxCents,
totalCents: order.totalCents,
trackingNumber: order.trackingNumber ?? null,
idempotencyKey: order.idempotencyKey,
items: order.items.map((item) => ({
id: item.id,

View File

@@ -5,7 +5,7 @@ import type {
OrderServicePort,
CreateOrderCommand,
} from '../domain/ports.js';
import { isTransitionAllowed, type OrderState, type OrderView } from '../domain/order.js';
import { isTransitionAllowed, type OrderState, type OrderView, type OrderItemInput } from '../domain/order.js';
export class OrderService implements OrderServicePort {
constructor(
@@ -39,6 +39,20 @@ export class OrderService implements OrderServicePort {
return this.repo.search(filters);
}
/** Edición admin: reemplaza artículos y totales del pedido. */
async editItems(
id: string,
items: OrderItemInput[],
totals: { subtotalCents: number; discountCents: number; taxCents: number; totalCents: number },
): Promise<OrderView> {
const existing = await this.repo.findById(id);
if (!existing) throw new OrderNotFoundError();
if (!this.repo.replaceItems) throw new Error('Order repository does not support item editing');
const updated = await this.repo.replaceItems(id, items, totals);
if (!updated) throw new OrderNotFoundError();
return updated;
}
async transition(id: string, next: OrderState, userId: string): Promise<OrderView> {
const existing = await this.repo.findByIdAndUserId(id, userId);
if (!existing) throw new OrderNotFoundError();
@@ -60,12 +74,12 @@ export class OrderService implements OrderServicePort {
return this.repo.findById(id);
}
async transitionAdmin(id: string, next: OrderState): Promise<OrderView> {
async transitionAdmin(id: string, next: OrderState, trackingNumber?: string): Promise<OrderView> {
const existing = await this.repo.findById(id);
if (!existing) throw new OrderNotFoundError();
if (!isTransitionAllowed(existing.state, next))
throw new OrderStateTransitionError(existing.state, next);
const updated = await this.repo.updateState(id, next);
const updated = await this.repo.updateState(id, next, trackingNumber);
if (!updated) throw new OrderNotFoundError();
if (next === 'PAID')
await this.events.emit({ type: 'OrderPaid', orderId: id, userId: existing.userId });

View File

@@ -37,6 +37,7 @@ export interface Order {
discountCents: number;
taxCents: number;
totalCents: number;
trackingNumber?: string | null;
createdAt: Date;
updatedAt: Date;
}

View File

@@ -16,7 +16,13 @@ export interface OrderRepository {
}): Promise<{ items: OrderView[]; total: number }>;
findById(id: string): Promise<OrderView | undefined>;
findByIdAndUserId(id: string, userId: string): Promise<OrderView | undefined>;
updateState(id: string, state: OrderState): Promise<OrderView | undefined>;
updateState(id: string, state: OrderState, trackingNumber?: string): Promise<OrderView | undefined>;
/** Reemplaza los artículos y totales del pedido (edición admin). */
replaceItems?(
id: string,
items: OrderItemInput[],
totals: { subtotalCents: number; discountCents: number; taxCents: number; totalCents: number },
): Promise<OrderView | undefined>;
}
export interface OrderEventPublisher {
@@ -38,7 +44,7 @@ export interface OrderServicePort {
offset: number;
}): Promise<{ items: OrderView[]; total: number }>;
transition(id: string, next: OrderState, userId: string): Promise<OrderView>;
transitionAdmin(id: string, next: OrderState): Promise<OrderView>;
transitionAdmin(id: string, next: OrderState, trackingNumber?: string): Promise<OrderView>;
getOrder(id: string, userId: string): Promise<OrderView | undefined>;
getOrderAdmin(id: string): Promise<OrderView | undefined>;
}

View File

@@ -0,0 +1,100 @@
import nodemailer from 'nodemailer';
import type pg from 'pg';
const SMTP_KEYS = ['smtp_host', 'smtp_port', 'smtp_secure', 'smtp_user', 'smtp_pass', 'smtp_from'] as const;
export const ORDER_STATE_LABELS: Record<string, string> = {
PENDING: 'Pendiente',
AWAITING_PAYMENT: 'Esperando pago',
PAID: 'Pagado',
PROCESSING: 'En preparación',
SHIPPED: 'Enviado',
DELIVERED: 'Entregado',
CANCELLED: 'Cancelado',
REFUNDED: 'Reembolsado',
PARTIALLY_REFUNDED: 'Reembolso parcial',
};
function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, (character) => ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
})[character] ?? character);
}
export interface OrderStatusNotificationInput {
to: string;
orderId: string;
state: string;
trackingNumber?: string | null;
}
/**
* Sends order status change emails through the SMTP configuration stored in
* store_settings (Ajustes → SMTP / Email), with env fallback. Failures are
* thrown so callers can report `notified: false` without breaking the flow.
*/
export async function sendOrderStatusEmail(
pool: pg.Pool,
input: OrderStatusNotificationInput,
): Promise<void> {
const result = await pool.query<{ key: string; value: string }>(
`SELECT key, value FROM store_settings WHERE key = ANY($1::text[])`,
[SMTP_KEYS],
);
const settings = Object.fromEntries(result.rows.map((row) => [row.key, row.value]));
const host = settings.smtp_host?.trim() || process.env.SMTP_HOST?.trim();
const user = settings.smtp_user?.trim() || process.env.SMTP_USER?.trim();
const password = settings.smtp_pass || process.env.SMTP_PASS;
const from = settings.smtp_from?.trim() || process.env.SMTP_FROM?.trim() || user;
if (!host || !user || !password || !from) {
throw new Error('SMTP is not configured in Ajustes → SMTP / Email');
}
const port = Number(settings.smtp_port || process.env.SMTP_PORT || '465');
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('SMTP port is invalid in Ajustes → SMTP / Email');
}
const transporter = nodemailer.createTransport({
host,
port,
secure: (settings.smtp_secure ?? process.env.SMTP_SECURE) !== 'false' || port === 465,
auth: { user, pass: password },
});
const shortId = input.orderId.slice(0, 8);
const stateLabel = ORDER_STATE_LABELS[input.state] ?? input.state;
const trackingLine = input.trackingNumber
? `Número de seguimiento: ${input.trackingNumber}`
: '';
await transporter.sendMail({
from,
to: input.to,
subject: `Tu pedido #${shortId} ahora está: ${stateLabel} — Mercado de Vida`,
text: [
`Hola,`,
'',
`Tu pedido #${shortId} ha cambiado de estado: ${stateLabel}.`,
trackingLine,
'',
'Puedes consultar el detalle desde tu cuenta en mercadodevida.',
'',
'Gracias por tu compra.',
]
.filter((line) => line !== '')
.join('\n'),
html: [
`<p>Hola,</p>`,
`<p>Tu pedido <strong>#${escapeHtml(shortId)}</strong> ha cambiado de estado: <strong>${escapeHtml(stateLabel)}</strong>.</p>`,
trackingLine ? `<p>Número de seguimiento: <strong>${escapeHtml(input.trackingNumber ?? '')}</strong></p>` : '',
`<p>Puedes consultar el detalle desde tu cuenta en mercadodevida.</p>`,
`<p>Gracias por tu compra.</p>`,
]
.filter((line) => line !== '')
.join(''),
});
}

View File

@@ -12,6 +12,7 @@ interface OrderRow {
discount_cents: number;
tax_cents: number;
total_cents: number;
tracking_number: string | null;
created_at: Date;
updated_at: Date;
}
@@ -177,19 +178,62 @@ export class PgOrderRepository implements OrderRepository {
return { ...toOrder(order), items: items.rows.map(toItem) };
}
async updateState(id: string, state: OrderState): Promise<OrderView | undefined> {
async updateState(id: string, state: OrderState, trackingNumber?: string): Promise<OrderView | undefined> {
const result = await this.pool.query<OrderRow>(
`UPDATE orders_orders SET state = $2, updated_at = now()
`UPDATE orders_orders SET state = $2, tracking_number = COALESCE($3, tracking_number), updated_at = now()
WHERE id = $1 RETURNING *`,
[id, state],
[id, state, trackingNumber ?? null],
);
const order = result.rows[0];
if (!order) return undefined;
const items = await this.pool.query<ItemRow>(
'SELECT * FROM orders_items WHERE order_id = $1 ORDER BY created_at, id',
[id],
);
return { ...toOrder(order), items: items.rows.map(toItem) };
return this.findById(order.id);
}
async replaceItems(
id: string,
items: OrderItemInput[],
totals: { subtotalCents: number; discountCents: number; taxCents: number; totalCents: number },
): Promise<OrderView | undefined> {
const client = await this.pool.connect();
try {
await client.query('BEGIN');
const orderResult = await client.query<OrderRow>(
`UPDATE orders_orders
SET subtotal_cents = $2, discount_cents = $3, tax_cents = $4, total_cents = $5, updated_at = now()
WHERE id = $1 RETURNING *`,
[id, totals.subtotalCents, totals.discountCents, totals.taxCents, totals.totalCents],
);
if (!orderResult.rows[0]) {
await client.query('ROLLBACK');
return undefined;
}
await client.query('DELETE FROM orders_items WHERE order_id = $1', [id]);
for (const item of items) {
await client.query<ItemRow>(
`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)`,
[
id,
item.productId,
item.variantId,
item.sku,
item.ean,
item.name,
item.unitPriceCents,
item.discountCents,
item.taxCents,
item.quantity,
],
);
}
await client.query('COMMIT');
return this.findById(id);
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
}
@@ -204,6 +248,7 @@ function toOrder(row: OrderRow): Order {
discountCents: row.discount_cents,
taxCents: row.tax_cents,
totalCents: row.total_cents,
trackingNumber: row.tracking_number,
createdAt: row.created_at,
updatedAt: row.updated_at,
};