rubis/apps/api/start/routes.ts
ordinarthur 6dcae6956c
All checks were successful
Build & Deploy Web / build-and-deploy (push) Successful in 1m32s
Build & Deploy API / build-and-deploy (push) Successful in 2m20s
Build & Deploy Landing / build-and-deploy (push) Successful in 1m20s
feat(blog): admin CRUD + image upload + sidebar link
L'éditeur du blog (jusqu'ici limité au seeder) a maintenant une vraie
interface au-dessus de l'API.

Backend (apps/api) :
* Migration users.is_admin (boolean default false).
* Middleware admin (404 si user.is_admin=false après auth).
* Commande ace promote:admin --email=… [--revoke].
* AdminPostsController CRUD complet : list/show/store/update/publish/
  unpublish/destroy + suggest-slug. Au save, contentHtml + wordCount +
  readingTime sont re-calculés via blog_renderer. Au publish, durcit la
  validation SEO (titre ≤60, excerpt 120-160, hero+alt requis, ≥600 mots),
  flippe status='published' + publishedAt, ping Google+Bing pour le sitemap.
* BlogUploadsController :
  - POST /api/v1/admin/uploads (multipart, JPEG/PNG/WebP, max 4MB)
    → MinIO clé uploads/blog/{uuid}.{ext}
    → renvoie URL relative /api/v1/uploads/blog/{filename}
  - GET /api/v1/uploads/blog/:filename (public, cache immutable 1 an)
    → stream depuis MinIO, regex anti-traversal sur le nom.
* UserTransformer expose isAdmin (cf. shared/types/user).
* k3s/app/landing.yml : NodePort 30111 explicite (pour Traefik repo proxmox).

Frontend (apps/web) :
* Lib typée admin-blog (calls API, queryKeys, helpers URL).
* Route /admin/blog : liste filtrable avec status badge, ouverture
  publique, dépublier, supprimer, "+ Nouveau brouillon".
* Route /admin/blog/:id : éditeur 2-colonnes
  - Gauche : @uiw/react-md-editor (lazy import) avec preview live.
  - Droite : hero image (drag&drop + alt), excerpt avec compteur
    120-160, tags, aperçu Google snippet, validations bloquantes.
  - Autosave debounce 2s + bouton Publier qui sauve d'abord.
  - Hero image upload via MinIO (HeroImageUpload component).
* Sidebar : lien "Blog (admin)" si user.isAdmin.
* Gate côté client (beforeLoad redirect si non admin) + côté serveur
  (middleware admin) — defense in depth.

Note : les requirements de publish miroir backend ↔ frontend (cf.
PUBLISH_REQUIREMENTS dans validators/post.ts et VALIDATION_RULES dans
admin.blog_.\$id.tsx). À synchroniser si un seuil bouge.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 17:25:34 +02:00

374 lines
13 KiB
TypeScript

/*
|--------------------------------------------------------------------------
| Routes file
|--------------------------------------------------------------------------
|
| Toutes les routes sont sous /api/v1/. Les groupes auth et account sont
| importés depuis le contrôleur généré par Tuyau pour garantir le contrat
| client typé (cf. docs/tech/backend.md §8).
|
*/
import { middleware } from '#start/kernel'
import router from '@adonisjs/core/services/router'
import { controllers } from '#generated/controllers'
/**
* Blog public — endpoints JSON consommés par apps/landing (Astro SSR).
* Pas auth, pas de paginiation V1 (volume cible <100 articles).
*/
const BlogController = () => import('#controllers/blog_controller')
const AdminPostsController = () => import('#controllers/admin_posts_controller')
const BlogUploadsController = () => import('#controllers/blog_uploads_controller')
router
.group(() => {
/**
* Health check — public, utilisé par les sondes K3s (startup/liveness/
* readiness) et le healthcheck Docker. Retourne 200 sans toucher la DB
* pour rester rapide ; la DB est implicitement vérifiée au boot par
* le init-container migrate.
*/
router.get('health', () => ({ status: 'ok', uptime: process.uptime() })).as('health')
/**
* Sentry test trigger — endpoint debug qui throw délibérément pour
* vérifier l'E2E observability (capture, release tag, sourcemaps,
* user context). Disponible UNIQUEMENT si NODE_ENV !== 'production'
* OU si DEBUG_SENTRY_TEST=true. À retirer une fois l'intégration
* validée sur la prod.
*/
if (process.env.NODE_ENV !== 'production' || process.env.DEBUG_SENTRY_TEST === 'true') {
router.get('_debug/sentry-test', () => {
throw new Error(`Sentry test from rubis-api — ${new Date().toISOString()}`)
})
}
/**
* Blog — endpoints JSON publics consommés par apps/landing en SSR.
* Cf. apps/landing/src/pages/blog/*.astro pour la consommation et
* apps/api/app/controllers/blog_controller.ts pour l'implémentation.
*/
router
.group(() => {
router.get('', [BlogController, 'index']).as('index')
router.get(':slug', [BlogController, 'show']).as('show')
})
.prefix('posts')
.as('posts')
/**
* Image hero servie depuis MinIO. Public, cache infini (le filename est
* un UUID immuable, chaque upload = nouvelle URL).
*/
router
.get('uploads/blog/:filename', [BlogUploadsController, 'show'])
.as('uploads.blog.show')
})
.prefix('/api/v1')
router
.group(() => {
/**
* Auth — public. /refresh utilise le cookie httpOnly `rubis_refresh`
* posé par signup/login pour émettre une nouvelle AuthSession.
* /google/* → SSO via Ally, callback pose aussi le refresh cookie.
*/
router
.group(() => {
router.post('signup', [controllers.NewAccount, 'store']).as('signup')
router.post('login', [controllers.AccessTokens, 'store']).as('login')
router.post('refresh', [controllers.Refresh, 'handle']).as('refresh')
router
.get('google/redirect', [controllers.AuthGoogle, 'redirect'])
.as('google.redirect')
router
.get('google/callback', [controllers.AuthGoogle, 'callback'])
.as('google.callback')
router
.get('microsoft/redirect', [controllers.AuthMicrosoft, 'redirect'])
.as('microsoft.redirect')
router
.get('microsoft/callback', [controllers.AuthMicrosoft, 'callback'])
.as('microsoft.callback')
})
.prefix('auth')
.as('auth')
/**
* Check-in in-app — auth requise. La modale au login liste les factures
* en attente de confirmation et permet à l'user d'y répondre directement
* sans passer par l'email.
*
* IMPORTANT : ce groupe doit être déclaré AVANT le groupe public à token,
* sinon `/checkin/:token/pending` mange `/checkin/inapp/pending` (token
* littéral = "inapp") et redirige vers le SPA en 302.
*/
router
.group(() => {
router
.get('pending', [controllers.Checkin, 'inappPending'])
.as('pending')
router
.post(':invoiceId/paid', [controllers.Checkin, 'inappRespondPaid'])
.as('paid')
.where('invoiceId', router.matchers.uuid())
router
.post(':invoiceId/pending', [controllers.Checkin, 'inappRespondPending'])
.as('pending.post')
.where('invoiceId', router.matchers.uuid())
})
.prefix('checkin/inapp')
.as('checkin.inapp')
.use(middleware.auth())
/**
* Check-in — public (pas d'auth Bearer). Token signé en URL,
* lookup hash en DB. Redirige vers le SPA avec ?checkin=... pour
* que l'UI affiche un toast.
*/
router
.group(() => {
router
.get(':token/paid', [controllers.Checkin, 'respondPaid'])
.as('paid')
router
.get(':token/pending', [controllers.Checkin, 'respondPending'])
.as('pending')
})
.prefix('checkin')
.as('checkin')
/**
* Compte courant — auth requise.
*/
router
.group(() => {
router.get('profile', [controllers.Profile, 'show']).as('profile.show')
router.patch('profile', [controllers.Profile, 'update']).as('profile.update')
router.post('logout', [controllers.AccessTokens, 'destroy']).as('logout')
})
.prefix('account')
.as('account')
.use(middleware.auth())
/**
* Organisation rattachée à l'utilisateur courant — auth requise.
*/
router
.group(() => {
router.get('me', [controllers.Organizations, 'show']).as('show')
router.patch('me', [controllers.Organizations, 'update']).as('update')
})
.prefix('organizations')
.as('organizations')
.use(middleware.auth())
/**
* Clients — auth requise, scope par organization de l'utilisateur courant.
*/
router
.group(() => {
router.get('', [controllers.Clients, 'index']).as('index')
router.post('', [controllers.Clients, 'store']).as('store')
router.get(':id', [controllers.Clients, 'show']).as('show').where('id', router.matchers.uuid())
router
.get(':id/timeseries', [controllers.Clients, 'timeseries'])
.as('timeseries')
.where('id', router.matchers.uuid())
router.patch(':id', [controllers.Clients, 'update']).as('update').where('id', router.matchers.uuid())
})
.prefix('clients')
.as('clients')
.use(middleware.auth())
/**
* IA — auth requise. Génération de templates de relance avec Mistral
* pour le wizard de création de plan custom.
*/
router
.group(() => {
router.post('generate-relance', [controllers.Ai, 'generateRelance']).as('generate-relance')
})
.prefix('ai')
.as('ai')
.use(middleware.auth())
/**
* Plans — auth requise. Lookup par slug (stable et lisible :
* /parametres/plans/standard-30j). POST = création d'un plan custom,
* slug auto-généré depuis le name.
*/
router
.group(() => {
router.get('', [controllers.Plans, 'index']).as('index')
router.post('', [controllers.Plans, 'store']).as('store')
router.get(':slug', [controllers.Plans, 'show']).as('show')
router.patch(':slug', [controllers.Plans, 'update']).as('update')
})
.prefix('plans')
.as('plans')
.use(middleware.auth())
/**
* Billing / Stripe — auth requise pour subscription/checkout/portal.
* Le webhook est PUBLIC (signature Stripe vérifiée côté handler).
*/
router
.post('billing/webhook', [controllers.Billing, 'webhook'])
.as('billing.webhook')
router
.group(() => {
router
.get('subscription', [controllers.Billing, 'subscription'])
.as('subscription')
router
.post('checkout', [controllers.Billing, 'checkout'])
.as('checkout')
router.post('portal', [controllers.Billing, 'portal']).as('portal')
router
.post('reactivate', [controllers.Billing, 'reactivate'])
.as('reactivate')
})
.prefix('billing')
.as('billing')
.use(middleware.auth())
/**
* Demo — auth requise. Mode démo opt-in par org (cf. CLAUDE.md →
* Architecture). Routes opérantes seulement si `org.demo_mode = true`.
*/
router
.group(() => {
router.post('start', [controllers.Demo, 'start']).as('start')
router.post('end', [controllers.Demo, 'end']).as('end')
router.post('tick', [controllers.Demo, 'tick']).as('tick')
router.get('state', [controllers.Demo, 'state']).as('state')
router.get('inbox', [controllers.Demo, 'inbox']).as('inbox')
})
.prefix('demo')
.as('demo')
.use(middleware.auth())
/**
* Dashboard — auth requise. Calculs agrégés on-the-fly (pas de cache V1).
*/
router
.group(() => {
router.get('kpis', [controllers.Dashboard, 'kpis']).as('kpis')
router.get('activity', [controllers.Dashboard, 'activity']).as('activity')
router.get('top-late', [controllers.Dashboard, 'topLate']).as('top-late')
router
.get('timeseries', [controllers.Dashboard, 'timeseries'])
.as('timeseries')
})
.prefix('dashboard')
.as('dashboard')
.use(middleware.auth())
/**
* Invoices — auth requise. Ordre IMPORTANT : les routes statiques
* (/upload, /counts, /import-batch/...) sont déclarées AVANT /:id
* sinon `:id` matche les segments littéraux.
*/
router
.group(() => {
router.get('', [controllers.Invoices, 'index']).as('index')
router.post('', [controllers.Invoices, 'store']).as('store')
router.get('counts', [controllers.Invoices, 'counts']).as('counts')
// OCR / Import batch (cf. ImportBatchesController)
router.post('upload', [controllers.ImportBatches, 'upload']).as('upload')
router
.get('import-batch/:id', [controllers.ImportBatches, 'show'])
.as('import-batch.show')
.where('id', router.matchers.uuid())
router
.get('import-batch/:id/drafts/:draftId/pdf', [
controllers.ImportBatches,
'draftPdf',
])
.as('import-batch.draft.pdf')
.where('id', router.matchers.uuid())
.where('draftId', router.matchers.uuid())
router
.post('import-batch/:id/drafts/:draftId/validate', [
controllers.ImportBatches,
'validateDraft',
])
.as('import-batch.draft.validate')
.where('id', router.matchers.uuid())
.where('draftId', router.matchers.uuid())
router
.post('import-batch/:id/drafts/:draftId/skip', [
controllers.ImportBatches,
'skipDraft',
])
.as('import-batch.draft.skip')
.where('id', router.matchers.uuid())
.where('draftId', router.matchers.uuid())
router
.delete('import-batch/:id', [controllers.ImportBatches, 'destroy'])
.as('import-batch.destroy')
.where('id', router.matchers.uuid())
router.get(':id', [controllers.Invoices, 'show']).as('show').where('id', router.matchers.uuid())
router
.get(':id/pdf', [controllers.Invoices, 'pdf'])
.as('pdf')
.where('id', router.matchers.uuid())
router
.post(':id/mark-paid', [controllers.Invoices, 'markPaid'])
.as('mark-paid')
.where('id', router.matchers.uuid())
})
.prefix('invoices')
.as('invoices')
.use(middleware.auth())
/**
* Admin — édition du blog. Toutes auth + admin (cf. is_admin sur users).
* Cf. apps/web/src/routes/_app/admin.* pour le SPA consommateur.
*/
router
.group(() => {
router
.group(() => {
router.get('', [AdminPostsController, 'index']).as('index')
router.post('', [AdminPostsController, 'store']).as('store')
router.get('suggest-slug', [AdminPostsController, 'suggestSlug']).as('suggest-slug')
router
.get(':id', [AdminPostsController, 'show'])
.as('show')
.where('id', router.matchers.uuid())
router
.patch(':id', [AdminPostsController, 'update'])
.as('update')
.where('id', router.matchers.uuid())
router
.post(':id/publish', [AdminPostsController, 'publish'])
.as('publish')
.where('id', router.matchers.uuid())
router
.post(':id/unpublish', [AdminPostsController, 'unpublish'])
.as('unpublish')
.where('id', router.matchers.uuid())
router
.delete(':id', [AdminPostsController, 'destroy'])
.as('destroy')
.where('id', router.matchers.uuid())
})
.prefix('posts')
.as('posts')
router.post('uploads', [BlogUploadsController, 'store']).as('uploads.store')
})
.prefix('admin')
.as('admin')
.use(middleware.auth())
.use(middleware.admin())
})
.prefix('/api/v1')