Files
LogiFlow/server/index.ts
MichaelandClaude Fable 5 753b301066 perf: add missing indexes and remove N+1 queries
The app degraded progressively over a year of data growth. Four causes,
all cumulative:

1. No indexes. Apart from primary keys, unique constraints and
   session.expire, no table carried an index. PostgreSQL does not index
   foreign keys automatically, so every filter and join on group_id,
   supplier_id, order_id and the date columns did a sequential scan.
   Worst offender: user_groups.user_id, read by getUserWithGroups() on
   every authenticated request.

2. N+1 in the order and delivery listings. getOrders,
   getOrdersByDateRange, getDeliveries and getDeliveriesByDateRange
   issued one to two queries per row to load relations. Relations are now
   loaded in bulk and grouped in Node: three queries regardless of volume.

3. /api/sync-order-delivery-status reloaded the whole deliveries table on
   every iteration of its loop over orders. It now uses the deliveries
   getOrders() already attaches.

4. clearExpiredCache() was implemented but never called, so
   invoice_verification_cache grew without bound. Now scheduled every 6h.

Also replaces the full-history downloads on the Groups and Suppliers
pages, which fetched every order and delivery with nested relations only
to count rows, with aggregate endpoints that count in the database.

Indexes are created via scripts/auto-migrate-production.sh, the script
that actually runs at deploy time, using CREATE INDEX CONCURRENTLY so no
write lock is taken. Note that server/migrations.ts explicitly ignores
the migrations/ directory and runs only hardcoded migrations; the SQL
file added there is for reference and manual application.

Verified: typecheck baseline 440 errors, 430 after, none new in the
changed code; vite build passes; server boots; functional test confirms
the aggregate endpoints match the source data including the delivered
count.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 11:55:49 +02:00

84 lines
2.5 KiB
TypeScript

import express, { type Request, Response, NextFunction } from "express";
import cookieParser from "cookie-parser";
import { registerRoutes } from "./routes.js";
import { setupVite, serveStatic } from "./vite.js";
import {
setupSecurityHeaders,
setupRateLimiting,
setupInputSanitization,
setupCsrfProtection,
setupCsrfTokenEndpoint
} from "./security.js";
// Forcer la création de la table webhook_bap_config au démarrage de l'application
if (process.env.NODE_ENV === 'production') {
const { ensureWebhookBapConfigTable } = await import('./createWebhookTable.js');
await ensureWebhookBapConfigTable();
}
// Initialize weather system
console.log('🌤️ [STARTUP] Initializing weather system...');
const { initializeWeatherConfig } = await import('./weatherAutoConfig.js');
await initializeWeatherConfig();
console.log('✅ [STARTUP] Weather system initialized');
const app = express();
// Parse cookies (required for CSRF)
app.use(cookieParser());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: false, limit: '10mb' }));
// Setup security middlewares
console.log('🔐 [STARTUP] Setting up security middlewares...');
setupSecurityHeaders(app);
setupRateLimiting(app);
setupInputSanitization(app);
// CSRF Protection (only in production to avoid dev friction)
if (process.env.NODE_ENV === 'production') {
setupCsrfProtection(app);
console.log('✅ [STARTUP] CSRF protection enabled');
}
// CSRF token endpoint (always available for frontend to fetch token)
setupCsrfTokenEndpoint(app);
console.log('✅ [STARTUP] Security middlewares configured');
app.use((req, res, next) => {
const start = Date.now();
res.on("finish", () => {
const duration = Date.now() - start;
if (req.path.startsWith("/api")) {
console.log(`${req.method} ${req.path} ${res.statusCode} in ${duration}ms`);
}
});
next();
});
const server = await registerRoutes(app);
// Tâches de maintenance périodiques (purge du cache factures expiré)
const { startMaintenanceJobs } = await import('./maintenance.js');
startMaintenanceJobs();
app.use((err: any, _req: Request, res: Response, _next: NextFunction) => {
const status = err.status || err.statusCode || 500;
const message = err.message || "Internal Server Error";
res.status(status).json({ message });
throw err;
});
// Setup Vite in development
if (app.get("env") === "development") {
await setupVite(app, server);
} else {
serveStatic(app);
}
const port = 5000;
server.listen(port, "0.0.0.0", () => {
console.log(`serving on port ${port}`);
});