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

@@ -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,
};