batchCooking/apps/api/test-support/reset-db.ts
Nicolas b08081e48d
Some checks failed
CI / lint (push) Failing after 36s
CI / build (push) Successful in 3m41s
CI / e2e (push) Successful in 11m54s
CI / intent-service-test (push) Successful in 19m33s
CI / test (push) Failing after 22m32s
feat(admin): metriques d'utilisation (derive DB + AnalyticsEvent)
PR 3 du chantier admin. Tableau de bord metriques : snapshot de compteurs
+ series temporelles journalieres.

Schema (migration admin_metrics) :
- AnalyticsEvent (type String libre, actorType/actorId sans FK, context Json,
  index [type, created_at]) + WorkerHeartbeat (cable en PR 4).
- colonnes createdAt @default(now()) sur UserProfile / Recipe / Planning /
  PlanningItem (lecture admin uniquement ; lignes existantes = timestamp de
  la migration).

Instrumentation (lib/analytics.service.ts, fire-and-forget) :
- analytics.recordEvent(type, {actorId?, context?}) : retourne void, insert
  detache, echec loggue+avale, jamais de latence sur la requete.
- points d'appel : user.signup, recipe.created, recipe.imported,
  planning.item_added, tech_step.correction_submitted, shopping_list.viewed.

API : GET /admin/metrics?days= (7-365, defaut 30, requireAdmin) ->
admin-metrics.service.ts. bucketByDay pur (zero-remplissage, teste sans
base). MetricsView dans packages/shared.

Front : DashboardPage (tuiles KPI + un graphe recharts par serie + listes
recettes-par-source / evenements), logique pure dans dashboard.ts, i18n
admin.dashboard.*. AdminApiClient.getMetrics.

reset-db.ts truncate analytics_events + worker_heartbeats.
Tests : Mocha admin-metrics.test.ts (bucketByDay pur x2 verts ; snapshot,
series zero-remplies, event user.signup fire-and-forget) ; Cypress
dashboard.cy.ts (2 verts). specs/backend-architecture.md : section admin.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-28 12:46:54 +02:00

56 lines
2.8 KiB
TypeScript

import { env } from "../src/config/env.js";
import { prisma } from "../src/db/prisma.js";
import { syncRecipeSources } from "../src/db/recipe-source-sync.js";
import { seedReferenceData } from "../src/db/reference-seed-data.js";
/**
* Refuses to run outside a database that's obviously a test one — belt and
* braces alongside `config/env.ts` loading `.env.test` (not `.env`) under
* `NODE_ENV=test`: this already wiped a real local dev database once, when
* both env files shared one `DATABASE_URL`. `resetDatabase()` below
* TRUNCATEs almost the entire schema before every single test, so a
* misconfigured/missing `.env.test` must fail loudly here rather than
* silently truncate whatever `DATABASE_URL` happens to be set.
*/
function assertRunningAgainstTestDatabase() {
if (env.NODE_ENV !== "test") {
throw new Error(
`resetDatabase() TRUNCATEs almost the whole schema — refusing to run outside NODE_ENV=test (currently "${env.NODE_ENV}").`,
);
}
// "test" covers a local `.env.test` (`batchcooking_test`); "ci" covers
// CI's own service database (`batchcooking_ci`, set directly via the
// workflow's `env:`, not a `.env.test` file — see ci.yml). Neither
// matches the real dev database's name (`batchcooking`), which is the
// one case this must actually catch.
if (!env.DATABASE_URL?.includes("test") && !env.DATABASE_URL?.includes("ci")) {
throw new Error(
`resetDatabase() refuses to run against a DATABASE_URL that doesn't look like a test database (got "${env.DATABASE_URL}", expected it to contain "test" or "ci") — see .env.test.example.`,
);
}
}
// Single TRUNCATE ... CASCADE covers FK ordering and resets identity
// sequences — used between tests/scenarios to start from a clean slate.
// Re-seeds the Diet/Category/Allergy/Unit reference data right after
// truncating it, so every test starts from the same realistic reference
// data the real app seeds (`prisma/seed.ts`) rather than empty tables —
// tests exercising dietId/allergyIds/unitId need real rows to reference.
// `syncRecipeSources` runs last, for the same reason: `sources` should
// reflect whatever adapters this test run happens to have registered
// (usually none — see recipe-source-registry.ts).
export async function resetDatabase() {
assertRunningAgainstTestDatabase();
await prisma.$executeRawUnsafe(`
TRUNCATE TABLE
"user_profile_allergy", "user_preference", "allergy", "category",
"planning_item", "planning",
"recipe_ingredient", "step_tech_step", "step", "tech_step",
"recipe", "ingredients", "sources", "unit",
"user_profiles", "diet", "house",
"admin_users", "analytics_events", "worker_heartbeats"
RESTART IDENTITY CASCADE;
`);
await seedReferenceData(prisma);
await syncRecipeSources(prisma);
}