Phase 2b. The packs become the source of truth; the table stays the query surface, so the existing read path (one RLS query returning system + company + team templates) and every template id are untouched. pack_slug is the stable upsert key (migration 20260803230000, backfilled onto all 26 seeded rows). Matching on name instead would have meant that correcting a Swedish label looks like a new template, and because booking_template_usage.template_id is ON DELETE CASCADE, retiring the old row would silently wipe every company's "recently used" history for it. For the same reason a removed pack DEACTIVATES its row rather than deleting it: the read path already filters is_active, so it leaves the picker while usage history survives. The sync fails closed. A pack that will not parse or validate aborts the whole run with zero writes, because a database left in a state no commit of the repo describes is worse than a stale one. An empty catalogue is treated as a broken deploy (packs/ not bundled) rather than an instruction to retire every system template. Runs as a daily cron rather than at boot: boot-time work would have every serverless instance racing to write the same rows, and would re-apply a bad catalogue continuously instead of once a day where it is visible. Idempotent, so a database already matching the packs performs zero writes. Three database guards, each covered by tests/pg/booking-template-pack-slug.pg.test.ts: a partial unique index (one pack, one template), a format CHECK mirroring PACK_SLUG_RE so the database refuses what the loader would, and a CHECK keeping pack_slug off company templates, where it would shadow the pack it collides with. Verified the upgrade path locally the way the pg-upgrade job will run it: base schema, seeded fixture company with posted verifikat, an existing company template, then this migration alone. 26 slugs backfilled, company template intact, upgrade assertions pass. This is that job's first real migration. Payloads are spelled out rather than spread so the phantom-column guard can check them, and docker/crontab.* are regenerated for the new vercel.json entry. Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
68 lines
2.6 KiB
TypeScript
68 lines
2.6 KiB
TypeScript
import { createClient } from '@supabase/supabase-js'
|
|
import { NextResponse } from 'next/server'
|
|
import { withCronContext } from '@/lib/api/with-cron-context'
|
|
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
|
import { syncSystemPacks } from '@/lib/packs/sync'
|
|
|
|
/**
|
|
* GET /api/settings/booking-templates/sync/cron
|
|
*
|
|
* Reconciles the system booking templates in the database with `packs/*.yaml`
|
|
* (schedule in vercel.json). The packs ship with the deploy; this is what makes
|
|
* the deployed catalogue the one companies actually see, so editing a template
|
|
* is a file change plus a deploy rather than a migration.
|
|
*
|
|
* Idempotent by construction: a database already matching the packs performs
|
|
* zero writes, so running it more often than needed costs one SELECT.
|
|
*
|
|
* Deliberately a cron rather than boot-time work: a sync on every cold start
|
|
* would have every serverless instance racing to write the same rows, and a
|
|
* bad catalogue would be re-applied continuously instead of once a day where
|
|
* it is visible in the logs.
|
|
*
|
|
* Service-role client, no company context: system templates belong to no
|
|
* company and RLS forbids writing them from a user session (btl_insert /
|
|
* btl_update both exclude is_system rows).
|
|
*/
|
|
|
|
// The catalogue is small (tens of rows); this never approaches the budget.
|
|
export const maxDuration = 60
|
|
|
|
export const GET = withCronContext('cron.booking_templates_sync', async (_request, ctx) => {
|
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
|
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
|
|
|
if (!supabaseUrl || !supabaseServiceKey) {
|
|
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
|
|
requestId: ctx.requestId,
|
|
details: { reason: 'Missing Supabase configuration' },
|
|
})
|
|
}
|
|
|
|
const supabase = createClient(supabaseUrl, supabaseServiceKey, {
|
|
auth: { persistSession: false, autoRefreshToken: false },
|
|
})
|
|
|
|
const result = await syncSystemPacks(supabase)
|
|
|
|
if (result.errors.length) {
|
|
// A catalogue that fails to load is a deploy problem, not a data problem:
|
|
// syncSystemPacks writes nothing in that case, so the previous state stands.
|
|
ctx.log.error('pack sync aborted: catalogue invalid', { errors: result.errors })
|
|
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
|
|
requestId: ctx.requestId,
|
|
details: { reason: 'Pack catalogue invalid', errors: result.errors },
|
|
})
|
|
}
|
|
|
|
return NextResponse.json({
|
|
data: {
|
|
inserted: result.inserted.length,
|
|
updated: result.updated.length,
|
|
unchanged: result.unchanged.length,
|
|
retired: result.retired.length,
|
|
retired_slugs: result.retired,
|
|
},
|
|
})
|
|
})
|