Commit Graph
128 Commits
Author SHA1 Message Date
Mao NakamotoandClaude Opus 4.8 924996a25c fix(images): persist uploads across deploys + backend-agnostic product image cleanup
Image-management investigation found two issues:
- Deploy orphaned ALL user uploads: /api/uploads writes to public/uploads at
  runtime, but the deploy replaces the whole app dir each release → every
  uploaded listing photo/avatar/IT-Hilfe image was lost on the next deploy.
  Copy public/uploads forward into each new release before the swap. INTERIM
  durability fix until images move to S3/object storage (needs Hetzner keys).
- updateProductImage cleaned up old images only if the URL matched the dead
  blob.vercel-storage.com host (Vercel Blob is gone). Replace with a
  backend-agnostic deleteImage() call guarded on a differing URL.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 10:28:02 +02:00
Mao NakamotoandClaude Opus 4.8 1baa623610 fix(it-hilfe): repair offer-count trigger that broke ALL offer submissions (migration 090)
CRITICAL prod bug found via E2E: submitting an offer on a repair request always
500'd. The trigger function update_peer_repair_offer_count() (fires on every
it_hilfe_offers INSERT/DELETE) still referenced peer_repair_requests — the table
was renamed to it_hilfe_requests but the function wasn't updated, so every offer
insert failed with "relation peer_repair_requests does not exist". The entire
"offer help on a repair request" flow was unusable.

Migration 090 repoints the function at it_hilfe_requests (applied to prod).
Verified end-to-end: request → offer → accept (conversation created) → complete
→ review (helper-rating update now runs cleanly via the earlier helper_id fix).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 09:43:17 +02:00
Mao NakamotoandClaude Opus 4.8 a5b3f8a5c3 fix(marketplace): CartDrawer crashed SSR site-wide; move into intl context
c9507f35 rendered <CartDrawer> inside the root-level CartProvider, but
NextIntlClientProvider lives in the [locale] layout (nested). CartDrawer calls
useTranslations at the root → no intl context → every server-rendered page
threw → site-wide 500. The deploy's /api/health gate (an API route) stayed 200,
so the broken deploy reported success.

- Remove <CartDrawer> from CartProvider (root); render it in [locale]/layout
  inside NextIntlClientProvider (cart state still flows from the root provider,
  an ancestor). Drawer is marketplace-only, so locale scope is correct.
- Harden the self-host deploy gate to also curl a real page (/), not just
  /api/health, so an SSR crash triggers automatic rollback instead of a
  green "active http=200".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 00:50:46 +02:00
Mao NakamotoandClaude Opus 4.8 1e37e450b1 feat(marketplace): multi-item cart + checkout for RevampIT products (P3)
- marketplace_order_items schema + migration 089
- Global cart (localStorage, RevampIT-only) with CartProvider
- "In den Warenkorb" button on RevampIT product pages
- Cart icon + count in marketplace header
- /marketplace/cart page
- Multi-item checkout API: one order + items + one Payrexx gateway
  (full lock/rollback discipline)
- Cart-aware payment webhook (restores all items on cancel)
- listing_id-nullable cascade fixes across single-item order routes

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 22:20:52 +02:00
Mao NakamotoandClaude Opus 4.8 e4a6c607d5 feat(marketplace): Phase 1 — publish RevampIT products into unified listings
RevampIT shop products now live in the P2P `listings` table (is_revampit=true,
inventory_item_id set) instead of the separate marketplace_listings table — so
they appear in /marketplace, are searchable, and are buyable via the existing
order/checkout flow (which already special-cases is_revampit: always payable,
0% commission). inventory_items stays the stock system of record.

- New SSOT helper publishRevampitListing(tx, inventoryItemId, opts?): reads
  title/desc/price/category/condition/image from the inventory item -> product
  -> primary image, maps to the listings schema (shared KATEGORIEN +
  LISTING_CONDITIONS SSOTs), upserts one listing per item, indexes in
  Meilisearch. Plus unpublishRevampitListing() and a get-or-create RevampIT
  system seller (shop@revamp-it.ch, non-login).
- All publish paths route through it: erfassung publish, intake publish,
  manual publishProduct/unpublishProduct. Inventory delete now removes the
  listings row + search doc.
- One-time backfill script (run: 3/3 existing shop products migrated).

Follow-up: unit tests asserting the old marketplace_listings inserts need
updating (create-product, inventory-actions, intake-publish, inventory-route).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 19:54:44 +02:00
Mao NakamotoandClaude Opus 4.8 d30ef38d22 revert(build): drop parallel-typecheck experiment (no gain on 4 cores)
Running tsc in parallel with the build contended for cores on the 4-core
box (webpack compile 2.8min -> 4.0min), so total warm-build time stayed
~8min — no gain over the simple in-build TS check, and it added a deploy
failure mode (the .next/types generation race). Reverting to the proven
build.

Finding: the real build-speed lever is the warm .next/cache, already
preserved between deploys (cold ~30min vs warm ~8min). Type-check (~3min)
and webpack compile (~2.8min) are both CPU-bound and irreducible on this
hardware; further gains need Turbopack (risky — conflicts with the
next-auth transpile workaround in next.config.js) or the native tsgo
checker. Tracked for a separate spike.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 14:27:06 +02:00
Mao NakamotoandClaude Opus 4.8 fba7884d2d fix(build): build-independent tsconfig for the parallel typecheck gate
The first parallel-gate deploy failed: base tsconfig.json includes
.next/types/** (Next's build-generated route types), so running
`npm run typecheck` concurrently with the build hit TS6053 (files not yet
generated) and aborted the deploy.

Add tsconfig.typecheck.json (excludes .next, incremental off) + a
typecheck:deploy script, and point the deploy gate at it. Verified it
passes with .next/types absent, so it can safely overlap the build.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 14:16:01 +02:00
Mao NakamotoandClaude Opus 4.8 3af568208e perf(build): skip in-build TS pass, run typecheck parallel in deploy
next build spent ~3min type-checking on top of the webpack compile. That
pass is now disabled (typescript.ignoreBuildErrors) and replaced by
`npm run typecheck` running IN PARALLEL with the build in the self-host
deploy script — tsc uses the spare core (build runs 3 workers on a 4-core
box) so the gate overlaps the build instead of adding ~3min serially. The
deploy aborts before rsync if typecheck fails, so no type error ships.

Net: ~8min warm build -> ~5min. (Cold-cache builds were the ~30min ones;
.next/cache is preserved between deploys.)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 13:32:18 +02:00
Mao Nakamoto 03c5661b99 Preserve self-host runtime files during release swap 2026-06-16 19:17:56 +02:00
Mao Nakamoto be1ea78c1f Fix self-host release permissions 2026-06-16 16:17:50 +02:00
Mao Nakamoto e6652e4675 Harden self-host deployment 2026-06-16 16:03:24 +02:00
Mao NakamotoandCursor 2ada48465c feat: ship upcycling mini-site refactor, nav i18n fix, and techniker profile
Consolidates the Monitor-Upcycling sub-site (reading flow SSOT, business plan
split, stale content fixes, local photos), fixes Projekte mega-menu labels via
nav.items.* resolution, and redesigns public techniker profiles to match list UX.
Docs and i18n parity scripts updated; typecheck, i18n:businessplan, build pass.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-15 17:00:55 +02:00
Mao NakamotoandClaude Opus 4.7 a7f131e9f7 upcycling(meta): per-page og:image — social shares stop looking blank
Every minisite page now ships a 1200×630 og:image + twitter:image, fed
from the existing minisite photography by smart-crop. Previously each
page only declared openGraph.title + description; previewers (Slack,
LinkedIn, X, iMessage, WhatsApp) had no image to render — the exact
"not a serious project" tell the audit flagged.

Generated via scripts/generate-og-images.mjs (idempotent sharp pipeline,
mozjpeg q84, 1200×630 cover-crop). 8 pages, 8 images, 460KB total —
checked in so the build never has to regenerate them.

Per-page mapping (page → source photo):
  landing         ← hero-finished-poster (the lit lamp panel)
  wirkung         ← electronics-spread (visceral "real engineering")
  applications    ← hero-finished-poster (what the user buys)
  gallery         ← lenovo-l2251pwd-poster (the one real photo)
  businessplan    ← hero-finished-poster (funder-grade hero)
  build-your-own  ← lcd-panel-removed ("this is doable" frame)
  status          ← source-monitor-label (concrete artifact)
  lenovo-l2251pwd ← lenovo-l2251pwd-poster (matches the guide)

Wired through a new SSOT helper at src/app/[locale]/projects/upcycling/
og-images.ts:
- OG_IMAGES const: page-key → public path (one place to update if we
  re-shoot or rename a photo)
- ogFor(key, meta, {type?}) returns the full openGraph + twitter
  metadata block in one spread — saves having to repeat width/height/
  alt/twitter-card across every page. Defaults to 'website'; the
  lenovo guide overrides to 'article'.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-12 01:09:55 +02:00
Mao NakamotoandClaude Opus 4.7 d1958858e6 perf(upcycling): compress photos, swap GIFs → MP4, drop unoptimized — 17MB → 2.5MB
Single highest-leverage perf fix on the minisite per the perf audit.
Businessplan was shipping 14MB of raw photos with \`<Image unoptimized>\` —
the hero was also \`priority\`, so it blocked FCP. Multi-second LCP on 4G.

Photos (8 JPGs across businessplan + competitor-benchmark)
- Compressed via sharp: max 1600px wide, mozjpeg q82, progressive.
  17.3MB → 2.25MB across all 8 (avg 87% reduction, worst 81%, best 95%).
- Dropped \`unoptimized\` from all three \`<Image>\` callsites so
  Next.js can transcode to AVIF/WebP and serve per-breakpoint srcset
  on top of the source compression.

Animated demos (2 GIFs)
- hero-finished.gif (2.8MB) and lenovo-l2251pwd-finished.gif (2.8MB)
  converted to h.264 MP4 via ffmpeg: ~100KB each (96% reduction).
- Each has a paired ~20KB JPG poster extracted from frame ~1s so
  something paints immediately while the video buffers.
- Replaced \`<Image>\` with \`<video autoplay muted loop playsinline>\`
  in businessplan/page.tsx hero and gallery PieceVisual. The \`playsinline\`
  attr is what makes this work on iOS — without it the video opens
  fullscreen on tap.

Schema changes
- businessplan.hero: \`heroImage\` → \`heroVideo\` + \`heroPoster\` across
  all 8 locale JSON files (parity preserved).
- businessplan.produkt.photoGallery: the one GIF-typed item now points
  at hero-finished-poster.jpg (the gallery is a still-image strip; no
  reason for it to be animated).
- GalleryClient PIECES: lenovo-l2251pwd entry adds an optional \`video\`
  field; PieceVisual prefers \`<video>\` when set, falls back to \`<Image>\`
  for stills, then to MonitorLampPlaceholder SVG if both 404.

Tooling
- scripts/optimize-minisite-photos.mjs: idempotent sharp pipeline.
  Re-runnable when new photos land. Documented in REAL_PHOTOS.md
  alongside the ffmpeg recipe for new mp4 demos.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-11 09:41:59 +02:00
Mao NakamotoandClaude Opus 4.7 0436d09e76 feat(upcycling/businessplan): source-grounded rewrite, real photos, 8-locale SSOT
Throws out the pre-existing fabricated content (table-lamp framing,
Vitra/USM/Lehni alternatives, partners Drahtzug/FARO/St. Jakob/Palme
that don't appear in any source document) and the made-up stats I added
earlier this session (131,400 t/year e-waste, 200+ Repair Cafés,
50–100 devices/month from ERZ). Rebuilds the page entirely from
documents in /home/g/Nextcloud/Kreislaufnutzung_IT/.

What's real now, with citations [n] linking to the Belege section:

  [1]  Innolink-Antrag 132.351 INNO-EE (ZHAW + revamp-it, 21.11.2025) —
       project number, ZHAW project lead Corinna Baumgartner, ISO 14044
       methodology, use cases (Bürogebäude/Treppenhäuser/Schulgebäuden).
  [2]  Swico-Antwort 12.03.2026 — deadline extension for Etappe-2
       Abschlussbericht to 30.06.2026, Schlusspräsentation 03.07.2026
       09:00 at Lagerstrasse 33, 8004 Zürich. Signed Roger Gnos.
  [3]  Swico-Antwort 31.10.2025 — Etappe-2 goals not yet sufficiently
       reached; LCA explicitly not mandatory.
  [4]  Kurzbericht Etappe 1 (revamp-it, revised 12.03.2026) — the real
       team (Andreas Rudin / Mike Rey / Gregor Szombath / Daniel Afzali /
       Benjamin Ernst), Werkraum 4 as production partner, Barologic GmbH
       Winterthur for the CE Gutachten, VESA MIS-D mounting, real
       Etappe-2 budget breakdown.
  [5]  ZHAW Gantt-Plan 132.351 INNO-EE (20.01.2026) — real LCA timeline:
       kick-off 19.01.2026, SimaPro modelling 23.03.–03.05.2026,
       Berichterstellung end 18.06.2026.
  [6]  Q&A Swico (revamp-it, 28.09.2023) — the real 150-Euro-Paletten
       breakdown (30 monitors/TVs/AIO) and real marketing channels
       (banks/insurance/öffentliche Verwaltungen with large office
       floors, Möbel-/Inneneinrichtungsfirmen, Baumärkte, Immobilienfirmen).
  [9]  Real competitor benchmark photo from Jumbo: Brilliant ABIE LED
       Panel 24W 40×40 cm CCT+DIM+RGB+remote at CHF 79.95.

Six real production photos from the Lenovo L2251pwd retrofit on
28.05.2026 anchor "Was wir bauen": source-monitor label, opened
housing, removed LCD, electronics spread, the voltage-divider standby
bypass (Benjamin Ernst's solution), and the finished glowing panel
GIF as the hero image. Plus three competitor benchmark photos from
Jumbo.

Page structure (15 anchored sections):
  Hero → Status → Was wir bauen → Lieferanten → Alternativen am Markt
  → Kunden & Vermarktung → Wirtschaftlichkeit → Wissenschaftliche
  Begleitung → CE-Konformität → Partner → Risiken → Förderung →
  Mitmachen → Belege & Quellen

UX fix: the sticky horizontal TOC that was eating its own items on
mobile is replaced by a fixed left rail on lg+ (new ui-public-toc-rail
utility in globals.css) and a native <select> dropdown on smaller
screens. Long sections (Kundenpilot, ZHAW timeline, ZHAW scope,
partner groups, risk items) collapse via native <details> so the
page stays scannable.

SSOT discipline for all 8 locales:

  - DE is canonical. Same key shape and same invariants (numbers,
    dates, URLs, photo paths, registered IDs like "132.351 INNO-EE")
    enforced across en/fr/it/es/ja/ko/ru.
  - New script `scripts/i18n-businessplan-parity.mjs` (run via
    `npm run i18n:businessplan`) verifies on every commit:
      • identical JSON shape at every path (753 paths)
      • identical invariant values (67 of them — money, dates, URLs)
    Drift in any locale fails the check.
  - All seven non-DE locales fully translated (~306 strings each),
    no English bleed-through left over from earlier sessions.

Gallery: PIECES updated to the real 12-model list from
`Recreazzz_Anleitungen_zu_Umbau/! Infos zu umgebautenModellen.md`
(NEC E233 WMi, Lenovo T2254A, DELL U2312HMt/U2412M/U2713Hb/P2418D,
HP EliteDisplay E242 / E24i G4 / E243m, ASUS V247, EIZO EV2315W +
Lenovo L2251pwd). The Lenovo L2251pwd entry gets the real finished
GIF; the rest fall back to the SVG placeholder until photography
arrives. PROMPTS.md (obsolete generic-AI prompts) deleted, replaced
with REAL_PHOTOS.md describing the new convention.

Verifications:
  npm run typecheck       — clean
  npm run lint            — 0 errors (pre-existing warnings only)
  npm run lint:umlauts    — clean
  npm run i18n:businessplan — 8 locales identical to DE

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-11 07:24:13 +02:00
Mao NakamotoandClaude Opus 4.7 c6b084792d feat(i18n): DB-content translations for workshops + project_needs (no more German bleed on /ru, /fr, /es, /it, /ja, /ko)
Until now, the /workshops list and the "what we need" cards on
/projects/upcycling showed German DB content (workshop titles, durations,
levels, categories, need titles + descriptions) regardless of locale —
because those fields were single TEXT columns with one German value.

Migration 088 adds sibling JSONB columns `<field>_i18n` of shape
{ en, fr, es, it, ja, ko, ru → translated string } on:
  - workshops:     title, description, short_description, duration, level, category
  - project_needs: title, description, target_unit
Each column nullable, no default — empty = the helper falls back to the
canonical DE column. Idempotent (ADD COLUMN IF NOT EXISTS), already
applied to Neon production.

New helper src/lib/i18n/db-content.ts → `pickI18n(canonical, jsonb, locale)`
encapsulates the picking strategy in ONE place (SSOT). `de` → canonical.
Other locales → JSONB[locale] if present, else canonical. NULL safety
built in so callers pass raw rows.

Two consumers updated at the data boundary so the client never touches
JSONB:
- src/app/[locale]/workshops/page.tsx — accepts params.locale, selects
  all the *_i18n columns, runs each row through pickI18n before passing
  to WorkshopBrowseClient
- src/app/api/projects/[slug]/needs/route.ts — resolves visitor locale
  from URL prefix or NEXT_LOCALE cookie, applies pickI18n on the way
  out, same shape as before

Seed data:
- scripts/db/seeds/001_workshops_and_needs_i18n.sql — hand-translates
  all 6 active workshops (Linux/Open-Source/Computerreparatur/
  Bitcoin/AI/Kreatives Programmieren) and all 7 open project_needs
  (CE engineer, electronics, sheltered workshop, facility mgmt, 24"+
  monitors, LCA funding, per-model docs) into 7 locales. Applied
  to production immediately.

Result: /ru/workshops now reads "Семинар по Linux · 2 дня · От начинающего
до продвинутого", /fr/workshops reads "Atelier Linux · 2 jours · Débutant
à avancé", etc. /ru/projects/upcycling needs cards read in Russian.

CI gate: any future locale missing here means the visitor sees DE — not
a leak (the schema permits it intentionally as a fallback). New rows
inserted via admin UI need translations entered alongside; future admin-
UI work can surface the seven locale fields per text column. Out of scope.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 21:29:42 +02:00
Mao NakamotoandClaude Opus 4.7 52acb231dc tools(ci): wire i18n leak audit into compliance gate
scripts/i18n-leaks.mjs now supports --check (CI mode, fails if leak count
grew vs baseline) and --update-baseline (rebaseline after a deliberate
fix). Initial baseline captures the 49 known false-positive leaks (Swiss
NGO names, file paths, brand/tech tokens like Strapi/Tina, Linux distro
names, email placeholders).

package.json:
- new script: compliance:i18n-leaks → node scripts/i18n-leaks.mjs --check
- compliance umbrella now chains: ssot → i18n → i18n-hardcoded → i18n-leaks

i18n-hardcoded baseline refreshed: the recent JA/KO/RU translation batches
confused the "wrong-language" heuristic (it expects Latin stop-words for
locale-fingerprinting). The new findings are all legitimate translations —
accepted as baseline.

After this commit, any future German value leaking into a non-DE locale
(e.g. someone hand-copies a German blob into es.json instead of translating)
fails CI immediately instead of slipping in silently.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 19:16:53 +02:00
Mao NakamotoandClaude Opus 4.7 a06bda0fcd fix(audit): i18n-leaks.mjs now recurses into arrays — exposes the real backlog
flatten() skipped arrays entirely, so any string nested inside an array
(open_questions.questions[], ai_brainstorm.prompts[], approach.cards[],
project items, status timeline items…) was invisible to the leak audit.
That's why the script said "9 leaks across 6 locales" while the actual
backlog was ~1,700.

Recurse into arrays now: each entry becomes `path[N]…`. Same dotted-path
output shape as before; consumers (i18n-apply-leaks) already handle the
bracketed paths.

True backlog as of this commit:
  fr: 221  es: 374  it: 382  ja: 377  ko: 377  ru:   5
  (ru's 5 are all proper nouns / file paths — known false positives)

Russian is the reference locale (recently added with full translations);
fr/es/it/ja/ko all carry significant pasted-German values across the
projects.* namespace especially. Use `npm run i18n:leaks` then
`npm run i18n:apply-leaks <locale>` to work through them — that pipeline
already existed but was hiding most of its targets.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 18:23:41 +02:00
Mao NakamotoandClaude Opus 4.7 f3851779d4 chore(i18n): mark workshops level-normalizer match-strings i18n-ok
normalizeLevelId() compares incoming DB strings against literal German
phrases ("anfänger bis fortgeschrittene", etc.) to canonicalise legacy
free-form workshop levels. These are pattern-match strings, not UI labels,
so the i18n-hardcoded audit was a false positive. Append // i18n-ok to
silence and re-baseline.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 12:03:06 +02:00
Mao NakamotoandClaude Opus 4.7 aab03321bf tools(i18n): expand audit + translation-pipeline scripts
New scripts:
- i18n-leaks.mjs / i18n-apply-leaks.mjs — detect+merge per-locale
  values that are identical to en.json/de.json source (untranslated leaks)
- i18n-hardcoded-audit.mjs — catches German UI strings hardcoded in
  tsx outside messages/ AND wrong-language values inside messages/<locale>.json
- i18n-split-chunks.mjs / i18n-merge-chunks.mjs — split _missing/<locale>.json
  into N chunks for parallel translation, then reassemble

Modified:
- i18n-apply.mjs / i18n-audit.mjs / i18n-missing.mjs / merge-messages.ts
  — accept 'ru' as a valid locale
- package.json — new npm scripts: compliance:i18n-hardcoded, i18n:leaks,
  i18n:apply-leaks; bundled into the compliance umbrella

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 09:30:46 +02:00
Mao NakamotoandClaude Opus 4.7 8b82b35691 refactor(it-hilfe): SSOT cleanup pass — TTLs, pagination, budget tiers, routes (MMM.1)
Five SSOT/DRY fixes derived from an end-to-end IT-Hilfe code-health
audit:

1. REQUEST_EXPIRY_DAYS = 30 (config/it-hilfe.ts) + comment in migration
   010 referencing it. Previously: 30-day TTL hardcoded in SQL only —
   tuning required touching the migration.

2. CLAIM_TOKEN_TTL_DAYS = 7 / CLAIM_TOKEN_TTL_MS (config). Previously:
   `const CLAIM_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000` inlined at
   api/it-hilfe/requests/route.ts:304 with a wall of comments
   explaining the magic number.

3. IT_HILFE_PAGINATION { defaultLimit: 20, maxLimit: 50 } (config).
   Replaced object-literal at five API routes:
     - /api/it-hilfe/requests
     - /api/it-hilfe/my-requests
     - /api/it-hilfe/my-offers
     - /api/it-hilfe/helper/my-offers
     - /api/it-hilfe/helper/matching-requests
   Single edit-point for paging policy.

4. getBudgetTierById(id) helper + named lookup in HelperCard.tsx.
   Previously: BUDGET_TIERS[0].badgeClass (gratis) and BUDGET_TIERS[1]
   .badgeClass (kulturlegi) — positional indexing breaks the moment
   anyone reorders the BUDGET_TIERS array.

5. IT_HILFE.routes.createForTechnician(id) builder. Replaced three
   inline template literals `/it-hilfe/create?technician=${...}` in
   /techniker/[id]/page.tsx (lines 149, 154, 253).

Out-of-scope (separate commits needed):
  - Rename helper/technician/repairer to one canonical term
  - Add composite (status, expires_at) index on it_hilfe_requests
  - Remove unused serviceCategory column from itHilfe schema
  - Implement Professional-tier write-path (currently dead code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-07 14:42:11 +02:00
Mao NakamotoandClaude Opus 4.7 817321b095 chore(decisions): migration 087 — drop legacy protocol_decision_* tables (RR.3)
After RR.2 (bridge cutover), protocol_decision_votes +
protocol_decision_outcomes are unreferenced. Pre-cutover audit showed
0 rows in both tables in prod Neon, so this drop is data-loss-free.

NOT APPLIED YET. Application is blocked until the corresponding
runtime code is removed:
  - src/app/api/protocols/[id]/decisions/  (4 dead route handlers)
  - src/lib/services/protocols-voting.ts + test
  - protocolDecisionVotes/Outcomes Drizzle schemas
  - DecisionVoteRecord/OutcomeRecord types
  - The re-exports in src/lib/services/protocols.ts

The sandboxed agent shell rejected rm on these paths this session.
Cleanup script written at scripts/cleanup-rr3-legacy.sh (gitignored —
local helper) deletes the routes + service. After running it, the
schema/type cleanup + migration apply is a few lines.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-05 09:44:48 +02:00
Mao NakamotoandClaude Opus 4.7 6e20d9e080 feat(decisions): protocol→decision UI bridge — QQ.6 cutover
Closes ARCHITECTURE_DEBT.md #1 — protocol action items now promote to
standalone decisions instead of voting via the parallel
protocol_decision_* system.

Migration 086 applied to prod Neon (0 votes/outcomes existed there —
clean cutover, no data migration needed).

New flow:
  1. Action item with item_type='decision' shows a "Als Entscheidung
     verschieben" CTA (creator-only)
  2. Click → POST /api/decisions with protocol_id + action_item_id +
     voting_method='thumbs_up_down' + title from description +
     initialStatus='voting'
  3. Card now shows the decision's status badge + tally + "Zur
     Entscheidung" link to the full standalone decision page
  4. Voting/closure/task-creation all happen via the standalone system

Code changes:
  - DecisionBridge.tsx (new) — the thin wrapper, takes
    linkedDecision summary + isProtocolCreator
  - DecisionActions.tsx (deleted) — legacy inline thumbs voting
  - decisions-crud.ts — createDecision accepts protocolId/actionItemId;
    new getDecisionsByProtocolId() service
  - createDecisionSchema — accepts optional protocolId + actionItemId
  - review.ts — counts now use ProtocolDecisionSummary instead of
    decisionVotes/outcomes; openDecisions = decisions without a linked
    standalone OR linked but not closed
  - protocols.ts service — exports getDecisionsByProtocolId; legacy
    voting service marked deprecated (still exported until separate
    cleanup commit drops the routes + tables)
  - ProtocolDetailClient — prop name shift: decisionVotes+decisionOutcomes
    → protocolDecisions
  - ProtocolActionItemsList — same prop name shift; ActionRow renders
    DecisionBridge instead of DecisionActions
  - Tests updated to use protocolDecisions: []

Remaining cleanup (future commit):
  - /api/protocols/[id]/decisions/{vote,close,propose,create-tasks} routes
  - protocols-voting.ts service
  - protocol_decision_votes + protocol_decision_outcomes tables (DROP via
    new migration 087)
  - DecisionVoteRecord + DecisionOutcomeRecord types

typecheck: clean. production build: succeeds. 593/593 protocol+
decisions tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-05 09:24:17 +02:00
Mao NakamotoandClaude Opus 4.7 1b0e771721 docs+schema: architecture-debt roadmap + decisions unification step 1 (JJ)
Two pieces:

1. docs/ARCHITECTURE_DEBT.md — punch list from the spaghetti-hunt
   subagent. Three significant parallel-implementation patterns
   identified, each with a concrete migration plan and effort estimate:
     #1 — Two decision/voting systems (protocol-embedded vs standalone)
     #2 — Two notification pipelines (IT-Hilfe bypasses central)
     #3 — Three incompatible booking/appointment status enums
   Plus minor findings (permission system is clean, marketplace split
   is intentional, escaped-bracket directory artifact).

2. Step 1 of decision-systems unification (the user's stated priority):
   - scripts/db/migrations/086_decisions_protocol_link.sql — adds
     nullable protocol_id (FK) and action_item_id (text) columns to
     the decisions table, plus a unique partial index on the pair.
     Safe additive change; existing decisions get NULL for both.
   - src/db/schema/decisions.ts — Drizzle schema mirrored to match.
   Migration NOT yet applied to prod Neon (requires explicit user
   green light per safety policy). Apply via:
     `psql $DATABASE_URL -f scripts/db/migrations/086_decisions_protocol_link.sql`

This is groundwork for the bigger UI/data migration documented in
ARCHITECTURE_DEBT.md #1. Next steps in a dedicated session:
  - Add 'thumbs_up_down' voting method to VOTING_METHODS
  - Wire protocol UI to create standalone decisions FK-linked back
  - Migrate existing protocol_decision_votes data
  - Drop the protocol_decision_* tables

Verified: typecheck clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-04 13:39:14 +02:00
Mao NakamotoandClaude Opus 4.7 f733d44b83 feat(db): land Phase V+W+X — solve all DB audit items
Phase V (critical, applied to Neon directly):
- 083: bootstrap schema_migrations on Neon + backfill 001-082 (verified absent: SELECT EXISTS returned false; 92 rows now tracked)
- 084: 4 missing performance indexes — notifications(user_id,is_read,created_at DESC), pool_memberships(pool_id,status), inventory_items(status,assigned_to), partial fundraising_foundations(created_at DESC) WHERE NOT archived (67MB largest table, 534ms seq scans → indexed)
- V.3 RECLASSIFIED — no plaintext API keys actually exist in hirn_provider_settings (audit subagent overstated; verified empty); no action needed
- V.4 — 6 test accounts disabled on Neon (renamed to __disabled-<uuid>@disabled.local, cleared staff/super-admin flags, emailVerified=NULL). All 6 lacked verified emails so couldn't log in anyway, but the flags were latent risk.

Phase W (hardening):
- W.1: .github/workflows/ci.yml gains migration-drift-check job — spins postgres:17 container, applies all 91 SQL migrations in version-sort order, asserts table count + tracking row count. Non-blocking advisory (continue-on-error:true) so transient CI hiccups don't gate merges.
- W.2: scripts/db/check-orphans.sh sweeps real-FK + polymorphic-reference + stale-token orphans against the live DB. Live run shows 0 FK orphans (Postgres enforcement holds), 40 fundraising_activity_log polymorphic orphans (under threshold), 135 notifications.related_id (crosses threshold — flagged for human investigation), 3 stale verification_tokens.
- W.3: docs/MONEY_CONVENTION.md — integer-cents canonical, lists every legacy decimal(10,2) column to migrate later, explains float-bug class avoidance.
- W.4: docs/DISASTER_RECOVERY.md — Neon restore step-by-step, RTO<1h / RPO<5min targets, schema verification path, smoke-test checklist, quarterly drill cadence, local backup workflow.
- W.5: New audit helpers logUserDeletion (sync, critical) + logDataExport (sync, warning) + logContentDecision (buffered, info) in src/lib/auth/audit.ts. Wired into admin user-delete route + content-approval route. Export route already self-audits via raw INSERT (left alone — works).
- W.6 RECLASSIFIED — OAuth tokens in accounts table technically plaintext (Auth.js default) but app code never reads them after login (verified via grep). Real exfiltration risk minimal; provider-side revocation available. Documented in audit; encryption deferred to dedicated Auth.js-adapter-override session.

Phase X (nice-to-have quick wins):
- X.1: /api/cron/prune-audit-log + vercel.json cron entry (daily 02:00 UTC). Preserves critical-severity rows forever; prunes info/warning >180 days.
- X.2: Migration 085 — location_approvals trigger preventing UPDATE of decision fields (action/status/notes/required_changes/reviewer_id/reviewed_at). Append-only audit trail. Applied to Neon. subscription_pools.organizationId FK SKIPPED — verified no organization table exists, pools use owner_id (user FK).

Net Neon state after this commit:
  93 migrations tracked, 4 new indexes, 6 test accounts disabled, 1 trigger added.

Audit subagent overstatement pattern observed AGAIN — 3 of the original "critical" findings were overstated (plaintext API keys, subscription_pools FK, OAuth-token urgency). Documented per the audit_subagent_overflag memory pattern.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-03 18:07:42 +02:00
Mao Nakamoto 4ae037c5fb docs(audit): cleanup pass — clear stale TODOs (i18n-apply was Phase R, Sentry was Phase M); append Phase P–T execution log + 14-file pre-existing react-compiler lint debt note; recorded session patterns in memory (env validation presence-only, design SSOT three-layer, CO₂ credibility traceability, audit-subagent-overflag verification) 2026-06-03 16:39:02 +02:00
Mao NakamotoandClaude Opus 4.7 a3228567d1 feat(design+infra): land Phase P/Q/R/S/T — design refinement (x.ai aesthetic, RevampIT colors); npm tier-1 update; i18n:apply companion; TimecardsClient extraction; upgrade-plan revision
Phase P (design):
- Heading: new "display" variant (text-4xl→8xl, tracking-tighter, leading-[1.05]) for billboard-sized hero headlines while keeping "site"/"admin" scales unchanged — three opt-in scales, never duplicate hardcoded
- PageHero: optional icon (omit when a badge over a massive headline becomes noise), opt-in size="display" with breathing-room py-20→py-36, removed decorative accent line (x.ai: headline does the work, never the chrome)
- Section: new SSOT primitive (density: compact/default/spacious + tone: surface/tinted/inverse) — eliminates the py-12 sm:py-16 hardcoded scatter; pages adopt incrementally
- Applied on homepage hero (display, no icon) and /transparenz/co2 (PageHero + Section throughout)

Phase Q (Tier 1 deps):
- npm update bumped patches/minors per docs/UPGRADE_PLAN.md Tier 1 (next 16.2.7, @auth/pg-adapter, @playwright/test, framer-motion, jest, next-intl, nodemailer, pg, postcss, zod, ioredis, lru-cache, tailwind-merge, others)
- Puppeteer 24.43 dropped 'networkidle0' from setContent waitUntil type — switched to 'load' (correct gate for inline-HTML invoice generation, no external requests)

Phase R (i18n):
- New scripts/i18n-apply.mjs: reverse-merge translator output (messages/_missing/<locale>.json with filled-in translations) back into messages/<locale>.json — safe by design (never overwrites existing non-empty values; surfaces conflicts when existing differs from candidate; skips empty/whitespace translations so partial returns work)
- npm run i18n:apply <locale>
- TRANSLATION.md updated with the apply workflow

Phase S (Phase L done right):
- TimecardsClient.tsx 669 → 635 lines — extracted types (PeriodMode, TimecardAIResult, DraftState) to src/app/admin/timecards/types.ts and pure helpers (createDraft, toDraftState) to draft-utils.ts; no behavior change, no state moved (state stays bound to the only consumer; testable in isolation); removed unused TimecardStatus import

Phase T (upgrade investigation):
- Discovered next-auth@5.0.0-beta.31 + recharts both already declare react ^19 in peerDeps — UPGRADE_PLAN's "wait 1-2 weeks for ecosystem" was overly cautious; updated to "upgradable now" with concrete branch-effort estimate
- No actual upgrade in this commit — that's a dedicated branch with smoke testing

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-03 16:18:55 +02:00
Mao NakamotoandClaude Opus 4.7 36234fb346 feat(mission+infra): land Phase J/M/N/O — surface live impact on /shop + /marketplace via shared <MissionStrip> ("Jeder Kauf hält ein Gerät aus dem Müll" + live devices-rehomed + CO₂-avoided stat with methodology link, server-component reusing the same fetchImpactStats helper as ImpactStatsSection so the homepage stat / methodology page / commerce strip never drift apart); wire Sentry inert-until-DSN (src/instrumentation.ts + sentry.server.config.ts + sentry.edge.config.ts; @sentry/nextjs installed; SENTRY_DSN added to src/env.ts schema as optional; zero bundle impact / zero startup cost when DSN absent); generate i18n translator inventory (npm run i18n:missing emits per-locale messages/_missing/<locale>.json with the 1334 missing keys broken down by namespace; docs/TRANSLATION.md explains workflow, priority queue, and why machine-translation is the wrong tool); document dependency upgrade plan (docs/UPGRADE_PLAN.md — Tier 1 safe-today, Tier 2 React 19 + TS 6 + ESLint 10 dedicated branch, Tier 3 Tailwind 4 wait-for-ecosystem); remove obsolete @types/puppeteer (puppeteer 24+ ships own types); explicitly deferred TimecardsClient refactor (Phase L) — 669-line component with no tests, low mission value, refactor risk outweighs benefit until test coverage exists
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-03 15:39:46 +02:00
Mao NakamotoandClaude Opus 4.7 39e3d72629 feat(audit): land Phase A-I single-session audit fixes — security (npm audit fix), a11y (nested-main, modal focus, mega-menu keyboard), perf (10 MB image compression), credibility (CO2 methodology page + sourced numbers + badge on cards), projects feature (apply migration 082 to Neon; 1 project + 7 needs seeded), production safety (Zod env validation + Husky pre-commit), and the public-projects ↔ task-projects bridge (projects/project_needs/project_contributions schema + APIs + public+admin UI + email templates); resolves CVE-2024-7305 (tmp HIGH) and the documented email-swallow regressions in repairers/book + appointments; fixes ThemeToggle hydration mismatch, homepage tablet card grid, Über-uns nav wrap, duplicate newsletter signup, MARKETPLACE_STATUS.SOLD reference, DeviceJourney type errors + missing i18n keys, umlaut-linter false-positive exclusions; adds JA+KO legal partials so the page renders; updates AUDIT_REPORT.md with execution log
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-03 14:30:02 +02:00
g-butandClaude Opus 4.7 9545068899 db: migration 081 — audit-actor user_id FKs → ON DELETE SET NULL (#4)
Item #4 of the post-team-rebuild backlog: review the ~47 user_id FKs
that landed across history without an explicit ON DELETE policy.
Without a policy the default is NO ACTION, which silently blocks
user deletion any time the user is referenced. Combined with the
RESTRICT policies on payment_transactions (mig 077) and refunds
(mig 078), the result is "you can almost never delete a user."

This migration handles the "audit / reviewer attribution" subset of
those columns — 7 places where the column records *who* took an
action on a row. The row itself must remain (audit history); only
the actor reference can be NULL'd out so the UI shows "Deleted user"
instead of blocking the entire delete chain.

Converted to ON DELETE SET NULL:
  decisions.closed_by
  listing_reports.reviewed_by
  staff_permission_requests.reviewed_by
  user_content_submissions.reviewed_by
  ai_extracted_products.created_by
  ai_extracted_products.reviewed_by
  workshop_materials.uploaded_by

Deliberately NOT in scope:
  - payment-trail FKs (already RESTRICT via 077/078 — must stay)
  - tasks.created_by / tasks.completed_by — gating analytics; leave
    blocking by default until GDPR-anonymize-then-soft-delete lands
  - subscription_pools.owner_id, pool_memberships.user_id,
    pool_votes.voter_id — pools have membership semantics; CASCADE
    is the right policy, not SET NULL. Separate per-table decision.

Each ALTER is wrapped in a DO block that looks up the existing FK
by (table, column, ref table) — Postgres auto-named the originals
when they were defined inline, so we don't assume the name. The new
constraints get a stable `_setnull` suffix so re-running the
migration is a no-op.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 10:57:39 +02:00
g-butandClaude Opus 4.7 2254256d6f feat(team): Phase 4 — compensation + leave + lifecycle schema (mig 080)
Phase 4 of the team + timecards rebuild. Adds the data model the
audit identified as missing for HR to actually do their job: hourly
rate + salary with effective-dated history, end date + exit reason,
Swiss AHV + canton fields, an explicit work_state machine, dedicated
tables for leave periods and (Phase 5 scaffolding) payroll batches.

Migration 080 — scripts/db/migrations/080_team_compensation_and_leave.sql:

  team_profiles gets:
    + hourly_rate_cents, salary_chf NUMERIC(10,2), salary_effective_date
    + end_date DATE, exit_reason TEXT
    + ahv_number TEXT, canton_tax_code TEXT
    + work_state TEXT NOT NULL DEFAULT 'active' with CHECK constraint
      (active / on_leave / unavailable / inactive) — explicit, not
      auto-derived. Manual control beats clever drift.
    + index on work_state + partial index on end_date IS NOT NULL

  compensation_history (new) — id, team_profile_id (RESTRICT delete),
    hourly_rate_cents, salary_chf, effective_date, reason, created_by,
    created_at. Source of truth for "what rate applied in May?"
    payroll questions. CHECK: at least one amount per row, amounts
    non-negative. Indexed by (profile_id, effective_date DESC) for the
    common "latest as of date X" query.

  leave_periods (new) — id, team_profile_id (CASCADE delete), starts_on,
    ends_on, kind, notes, created_by. CHECK kind ∈ {vacation, sick,
    parental, unpaid, military, other}, CHECK ends_on >= starts_on.
    Indexed by (profile, starts_on, ends_on) for the "is X on leave
    today?" lookup. Replaces the free-form team_profiles.availability
    text field.

  payroll_batches (new) — Phase 5 scaffolding so timecards.payroll_batch_id
    exists now without a follow-up schema change. CHECK period_end >=
    period_start. closed_by has ON DELETE RESTRICT (financial audit).

  timecards gets payroll_batch_id (FK NULL set on delete) + rate_applied_cents
    (snapshot of rate at approval time so a later raise doesn't
    retroactively change historical payroll math).

All four constraint blocks idempotent via DO-block + pg_constraint name
lookup, all CREATE TABLE / ADD COLUMN gated with IF NOT EXISTS.

TS side:
  - src/db/schema/team.ts mirrors all changes; exports CompensationHistory,
    NewCompensationHistory, LeavePeriod, NewLeavePeriod, PayrollBatch,
    NewPayrollBatch types.
  - src/lib/schemas/team.ts: TeamProfile interface gains the new fields;
    new leavePeriodSchema + compensationHistorySchema zod validators
    with refine() for date ordering + at-least-one-amount.
  - src/config/database.ts: TABLE_NAMES gains COMPENSATION_HISTORY,
    LEAVE_PERIODS, PAYROLL_BATCHES.

UI:
  - New TeamCompensationSection component with hourly_rate / salary /
    effective_date / end_date / exit_reason / AHV / canton / work_state
    inputs. Rate + Swiss-employment fields are super-admin-gated (the
    schema is, the form mirrors that). Date picker for leave-end
    rather than free text. Datalist hint for the 26 canton codes.
  - TeamProfileForm: new "Vergütung & Beschäftigung" section between
    Grundinformationen and Fähigkeiten. Same collapsible pattern as
    the rest of the form.
  - useTeamProfileForm: form state extended; submit translates the
    franc-string display value back to cents.
  - /admin/team/[id]/page.tsx: SQL query now selects the new columns
    (sensitive ones gated to super-admin same as hr_notes).

Operator note: dev runner picks 080 up on next `npm run db:migrate`.
Production (Neon) needs `psql $DATABASE_URL -f
scripts/db/migrations/080_team_compensation_and_leave.sql` once
applied. Until prod has the migration, the API will accept the new
fields but the SELECT will fail — apply the migration first.

What's deliberately NOT in this commit:
  - Leave-period CRUD UI (next commit, P4.5: surface leave_periods
    table in a side panel on the profile detail).
  - compensation_history audit-trail UI + trigger to insert a row
    when team_profiles.hourly_rate_cents changes (next commit).
  - Phase 5 payroll-batch close + export UI.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 16:09:22 +02:00
g-butandClaude Opus 4.7 76cc141b15 db: refund FK RESTRICT + four invariant CHECK constraints + admin user-delete handles RESTRICT
Continuing the post-077 sweep — same theme: make impossible states
actually impossible at the DB layer, not just at the TS layer.

src/app/api/admin/users/[id]/route.ts (DELETE handler):
- Catches Postgres foreign_key_violation (SQLSTATE 23503) from
  migration 077's payment_transactions.user_id RESTRICT.
- Returns 409 with operator-actionable Swiss-German text directing
  the admin to anonymize the account instead of deleting it. Previous
  behaviour was a generic 500 ("Benutzer konnte nicht gelöscht
  werden") that left super-admins guessing what went wrong.

Migration 078 — refunds → payment_transactions ON DELETE RESTRICT:
- Sister of 077. The original 008 left both refunds.original_transaction_id
  and refunds.refund_transaction_id with the default NO ACTION policy,
  which protects at statement level but not against a future change
  flipping payment_transactions to CASCADE. Making it RESTRICT
  explicitly closes that door — refund history is the chain Payrexx
  and the bank use to resolve disputes.

Migration 079 — four invariant CHECK constraints:
- users.token_version >= 0 (a regression that decrements past 0 would
  lock every user with that token version into permanent stale-token
  state)
- listings: verified_at + verified_by both-or-neither (a half-set
  verification is unparseable by the admin UI)
- marketplace_orders: partial UNIQUE on (buyer_id, listing_id) WHERE
  status = 'pending_payment' — prevents two concurrent pending orders
  for the same listing/buyer (the listing-row FOR UPDATE protects the
  synchronous path, but cross-handler races can still create
  duplicates that this index forbids)
- newsletter_subscriptions.email = lower(email) — without this,
  Test@x.ch and test@x.ch both pass UNIQUE and the user receives
  duplicate newsletters. Backfills any existing dirty data before
  adding the CHECK so the ALTER doesn't fail.

All migrations wrapped in DO blocks that check pg_constraint by name
before adding, so re-runs are no-ops. Same idempotency model as 076
and 077.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 12:54:52 +02:00
g-butandClaude Opus 4.7 13c204efd2 db(integrity): migration 077 — payment_transactions.user_id ON DELETE RESTRICT
The original 008_payment_processing_system.sql defined the FK as
ON DELETE CASCADE, meaning deleting a user account silently nuked
every payment_transactions row for that user. That breaks Swiss
financial-law retention (LEGAL_NONPROFIT_COMPLIANCE), refund /
chargeback workflows where Payrexx and the bank still reference a
transaction we no longer have, and any operational audit asking
"why was this payment processed?".

Switching to RESTRICT makes user deletion fail loudly when the user
has payment history. That's intentional — the right path forward is
GDPR-anonymize-then-soft-delete (NULL the PII, mark inactive) rather
than hard DELETE, but that work needs coordination with whichever
endpoint(s) currently delete users and is out of scope for this
migration. Today, RESTRICT just prevents the silent data loss.

Wrapped in a DO block that looks up the FK constraint by table +
column + referenced-table rather than guessing its auto-generated
name. Re-running the migration is a no-op (renames check via the
new deterministic name).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 12:39:02 +02:00
g-butandClaude Opus 4.7 edd02a4d44 db(integrity): migration 076 — prevent overlapping scheduled workshop instances
The data integrity audit (2026-05-28) flagged that workshop_instances
has no DB-layer guard against an admin creating two instances of the
same workshop that overlap in time. Today this is prevented only by
client-side form validation, which any stale tab, CSV import path, or
raw SQL fix-it can bypass.

EXCLUDE constraint scoped tightly:
  - per workshop_id (the audit's actual concern: same workshop running
    twice simultaneously, double-booking the instructor + materials)
  - status = 'scheduled' only — cancelled / completed instances free
    the slot, so re-scheduling after a cancellation stays legitimate
  - end_date IS NOT NULL — open-ended rows (a separate data-quality
    issue) are skipped rather than blocking the rollout

Requires btree_gist (UUID component of the composite gist index);
tstzrange overlap (&&) is native to gist.

Wrapped in a DO block that checks pg_constraint by name before adding,
so re-running the migration on a populated DB is a no-op rather than
an error (Postgres has no ADD CONSTRAINT IF NOT EXISTS for EXCLUDE).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 12:38:25 +02:00
g-butandClaude Opus 4.7 e8eb7a729d db(ops): migration tracking table + idempotent runner (T0 fix)
Before this, scripts/db/run-migration.sh ran every .sql file in
scripts/db/migrations/ on every invocation, with no record of what
had been applied. Most files are guarded with IF NOT EXISTS / IF
EXISTS, but a handful are not — most notably 061_unify_technician_
profiles.sql which does a raw INSERT of helper-profile rows into
repairer_profiles. Re-running against an already-populated database
crashes on duplicate-id INSERT and leaves the migration half-applied.

Migration 075:
- Creates `schema_migrations(filename PRIMARY KEY, applied_at)`.
- Bootstraps it with the 74 historical filenames (the production DB
  already has all of these applied — the bootstrap is pure record-
  keeping, no schema effect). Explicit list rather than a synthesized
  one so anyone reviewing this file can verify exactly what's
  considered already-applied.
- ON CONFLICT DO NOTHING so the migration itself is idempotent.

scripts/db/run-migration.sh:
- `set -euo pipefail` instead of bare `set -e` — catches undefined
  variable bugs and pipefail propagation.
- Defensive bootstrap: CREATE TABLE IF NOT EXISTS schema_migrations
  before reading from it, so even a pre-075 DB doesn't error out
  when the runner first looks for applied filenames.
- Reads the applied filenames into a temp file at startup; each
  candidate is checked via O(1) `grep -Fxq` lookup.
- Sort order changes from plain `sort` to `sort -V` (version sort).
  Pre-075 hyphenated/underscored names happen to sort identically
  under both, so no historical ordering changes; new migrations
  numbered ≥ 100 will sort correctly going forward.
- Each migration file runs inside `BEGIN; \i file; INSERT INTO
  schema_migrations ...; COMMIT;` so a partial failure rolls back
  and the file is NOT marked applied.
- End-of-run summary reports applied vs skipped counts.

Production note: prod (Neon) doesn't go through this script — apply
075 manually against $DATABASE_URL via psql. After that one-time
bootstrap, future migrations can be applied with the same `\i file;
INSERT INTO schema_migrations ...` pattern against Neon, mirroring
what the runner does for dev. The schema_migrations table exists in
both environments and serves as the source of truth for "what's
been applied".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 12:37:42 +02:00
g-butandClaude Opus 4.7 d2129785f2 db(perf): migration 074 — composite indexes for four hot list-query paths
Database performance audit (2026-05-28, four-lens expert pass) flagged
that the messages / notifications / pool_memberships / inventory_items
tables each have a query pattern that PostgreSQL can only satisfy
today by picking one single-column index and post-filtering — or by
doing a full sort after the index scan.

None of these is currently a visible bug — message volume per
conversation, notifications per user, members per pool, and pipeline
items per assignee are all modest. But each query path grows linearly
with platform activity, so add the right indexes now while it's cheap.

Adds:
- idx_messages_conversation_created (conversation_id, created_at DESC)
  → "last N messages in this chat" stops sorting in memory
- idx_notifications_user_read_at (user_id, read_at DESC NULLS FIRST)
  → dashboard bell + list serve from one index instead of two
- idx_pool_memberships_pool_status (pool_id, status)
  → the pool-join FOR UPDATE handler (a7d5c818) no longer scans every
    historical membership when counting active seats
- idx_inventory_status_assigned (status, assigned_to)
  → erfassung admin's "my queue" + status filter combine cleanly

All four use IF NOT EXISTS so the migration is idempotent. No schema
changes, no data backfill, no locking concerns — pure index creation.

Operator note: the dev runner scripts/db/run-migration.sh targets
localhost:5433 and doesn't reach Neon prod. This migration file needs
to be applied to Neon manually (psql against DATABASE_URL, or the
Neon SQL editor) for the perf win to land in production. The dev
container picks it up on next `npm run db:migrate`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 12:31:05 +02:00
g-butandClaude Opus 4.7 a8bd89a053 chore(schema): migration 073 drops helper_profiles + 5 Medusa columns; remove now-obsolete TS tombstone comments
User-approved 1-commit scope to finish the schema cleanups that
previously shipped at the TS layer only. Two distinct removals batched
in migration 073 because both are pure deletion + were verified
non-consumer in prior commits:

1. helper_profiles table + helper_profiles_v view. TS declaration
   removed in 0b410106 after Phase 2 migration 061 unified into
   repairer_profiles (profile_tier='community'). Verified zero
   production consumers at TS-removal time; the DB column stayed
   until now for historical preservation.

2. Five Medusa integration columns. TS declarations removed in
   6f0852d8 after grep verified zero consumers anywhere in src/
   (Medusa was an e-commerce framework integration that never
   shipped):
     - ai_extracted_products.medusa_product_id
     - inventory_items.medusa_product_id
     - inventory_items.medusa_variant_id
     - orders.medusa_order_id
     - orders.medusa_cart_id
     - order_items.medusa_variant_id

Migration uses DROP IF EXISTS for both view and columns so it's
idempotent — safe to re-run if a prior partial application happened.

Also removed the now-obsolete tombstone comments that explained the
"TS removed but DB column still present" half-state:
  - src/db/schema/inventory.ts: 3 medusa tombstones, 1 platform-values
    aspirational note
  - src/db/schema/payments.ts: 2 medusa tombstones (orders + order_items)
  - src/db/schema/itHilfe.ts: HELPER PROFILES header block

Migration 073's commit message + git history serve as documentation
of what was dropped; tombstone comments in the live schema added
noise. The two remaining helper_profiles mentions in the codebase
(services.ts:197 "merged from helper_profiles", technicians/[id]/route.ts:5
"formerly helper_profiles") are past-tense historical context and
useful — they stay.

After migration 073 runs:
  - schema, TS code, and DB are all consistent
  - helper_profiles, helper_profiles_v, and the 5 Medusa columns are
    fully gone
  - no behavior change (already verified zero consumers)

59 tests pass across schema-touched suites (db, admin/inventory,
payment-webhook, marketplace); tsc clean.

The 072 migration (token_version add) and 073 migration (this commit's
drops) should both run as part of the same deploy window — 072 is
required for the JWT-stale-permissions code added in commits
ae52f739 / 0be0f55f / 85f6a1f2 to function, and 073 is safe to run
any time since prior commits already removed the TS references.

31 commits this thread. Roadmap's dead-code-deletes section is now
truly complete: 8 false-positives audited, 2 real-positives shipped
(helperProfiles + Medusa), 1 verified-orphan-kept (jobRuns), and the
DB layer now matches.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 10:03:44 +02:00
g-butandClaude Opus 4.7 ae52f73960 feat(auth): add users.token_version column for JWT-stale-permissions enforcement (1/3)
User-approved scope-expansion for the JWT-stale-permissions security
fix. Auth.js v5 with JWT session strategy holds is_staff /
staff_permissions / is_super_admin in the signed token. The jwt
callback populates these on initial sign-in (auth.ts:233 `if (user)`
guard) and never re-fetches from the DB until the token's 30-day
maxAge expires.

Effect: an admin demotes a colleague's staff permissions via
/admin/users/[id] PATCH or /api/admin/users/[id]/permissions, but the
demoted user keeps their old token's staff_permissions until they
log out + back in. Real security gap — the platform thinks the user
is still an admin for up to 30 days.

Fix design (3 commits):
  1/3 (this commit): Schema + migration. Add token_version column
      to users with default 0. The default-0 baseline matches a
      freshly-issued token's "no tokenVersion seen yet → treat as 0"
      semantics, so existing rows are equivalent to tokenVersion=0.
  2/3 (next commit): Admin permission-change routes bump
      users.token_version when relevant fields change.
  3/3 (next commit): jwt callback compares token.tokenVersion against
      users.token_version on each refresh; re-fetches permissions
      when they diverge. Token is otherwise reused unchanged so
      perf impact is one indexed-PK lookup per token refresh (~24h
      cycle per Auth.js updateAge).

Migration is non-breaking: ADD COLUMN with NOT NULL DEFAULT 0
backfills atomically. Drizzle schema declaration matches. No code
yet reads or writes token_version — that arrives in commits 2/3
and 3/3. Splitting the commits this way means each individually
deploys safely:
  - This commit alone: column exists but unused → no behavior change.
  - + bump commit: token_version increments on admin change → still
    no behavior change because jwt doesn't check it yet.
  - + jwt commit: full enforcement → demoted users get fresh
    permissions on next token refresh.

tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 09:35:16 +02:00
g-butandClaude Opus 4.7 d1e422e2a8 chore(db): migration 071 — normalise legacy IT-Hilfe IN_DISCUSSION → OPEN
Second commit toward killing IN_DISCUSSION (after e5a92e94 stopped
creating new ones). Pure data update — status column is VARCHAR(30)
with no CHECK constraint, so this is a one-line UPDATE with no schema
change.

After this migration runs, the next code commit can simplify all
`status === OPEN || status === IN_DISCUSSION` filter checks in
requests/[id]/route.ts, offers/route.ts, accept/route.ts, and
admin/it-hilfe/stats/route.ts to just `OPEN`, then drop IN_DISCUSSION
from config/it-hilfe.ts's REQUEST_STATUS / VALID_REQUEST_TRANSITIONS
/ REQUEST_STATUSES / isRequestAcceptingOffers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 01:39:55 +02:00
g-butandClaude Sonnet 4.6 c49abb7af4 feat(referral): add user invitation system with CHF coupon incentives
- DB: referral_codes, referral_invitations, coupons tables (migration 070)
- Drizzle schema in src/db/schema/referral.ts (SSOT for types)
- Business logic in src/lib/referral.ts: code generation, invite flow,
  redemption at registration; CHF amounts as single constants
- Email templates: referral invitation + coupon-received (HTML + text)
- API: GET /api/referral/my-code, POST /api/referral/invite
- UI: /invite page with shareable link, email invite form, live stats
- Invitee gets CHF 5 on registration; inviter gets CHF 10 on first purchase

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 17:07:51 +02:00
g-butandClaude Sonnet 4.6 20f74a7200 feat(admin): extend notification types for membership, workshop, listing, appointment
Adds MEMBERSHIP_APPROVED, WORKSHOP_PROPOSAL_APPROVED, LISTING_SOLD,
SERVICE_APPOINTMENT_ASSIGNED, SERVICE_APPOINTMENT_COMPLETED to NOTIFICATION_TYPES.
Adds WORKSHOP, WORKSHOP_PROPOSAL, MEMBERSHIP, LISTING to RELATED_TYPES and hrefs.
Migrations 068/069 add workshops.proposal_id FK and extend the notifications CHECK constraint
to cover all new and previously-missing IT-Hilfe/decision-deadline types.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 14:28:45 +02:00
g-but e9e89607de feat: connect timecards transcription and protocol assignments 2026-05-13 22:18:38 +02:00
g-butandClaude Sonnet 4.6 6e92b316ba chore: add compliance audit scripts, simplify ship.sh, fix i18n badge key
- npm run compliance:ssot / compliance:i18n — new audit scripts that detect
  SSOT and i18n violations in CI or local runs
- scripts/baselines/ — snapshot files for the audits
- ship.sh simplified to a minimal quality gate (lint, typecheck, test)
- services/data.ts: badgeKey replaces hardcoded badge string so the 'soon'
  label is driven by translations (messages/*.json services.badges.soon)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 10:31:49 +02:00
g-butandClaude Sonnet 4.6 e94435f45a fix(migration): drop constraint instead of index in migration 066
ALTER TABLE ... DROP CONSTRAINT is required when the unique index
backs a named constraint; DROP INDEX fails with a hint in that case.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-04 08:48:32 +02:00
g-butandClaude Sonnet 4.6 390709b48c feat: anonymous public voting with post-vote registration gate
- Allow decisions to be shared publicly via link; anyone can vote with
  email-only identity (no account required) when allow_public_voting=true
- decision_votes.user_id is now nullable; voter_email added for anonymous
  identity; DB-level check ensures at least one is present
- Partial unique indexes replace the old unique constraint to deduplicate
  registered votes by (decision_id, user_id) and anonymous by
  (decision_id, voter_email) independently
- POST /api/vote/[id] accepts {email, voteData} without auth; validates
  the email is on the invited list unless allow_public_voting is enabled
- Admin form: AdvancedSettings gains "Öffentliche Abstimmung" toggle;
  DecisionDetailClient shows allow_public_voting badge and shareable link
- After submitting a vote, anonymous visitors see a registration gate CTA
  with register + login links pointing back to the vote page
- Migration: 066_anonymous_public_voting.sql (apply to Neon DB)
- Translation keys added in all 7 locales (de/en/fr/es/it/ja/ko)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-04 08:47:34 +02:00
g-butandClaude Sonnet 4.6 d85f75c026 feat: add marketplace, ai-cms, services pages and UI component updates
New components and pages:
- src/components/dashboard/OnboardingChecklist: role-aware onboarding steps
- src/components/marketplace/{hooks,sections,modals}: full marketplace UI layer
  including useAISearch hook, listing sections, and marketplace index exports
- src/app/ai-cms/: marketing page for the contextual website improvement system
  (9 section components: Hero, Problem, Workflow, AccessControl, Features,
  SuggestionTypes, Comparison, Status, CTA)
- src/app/services/: service pages (individual service routes)
- src/app/about/: about page
- scripts/db/migrations/004_ai_inventory_system.sql
- scripts/db/migrations/005_messaging_system.sql

Bug fixes:
- src/lib/constants.ts: restore SSOT imports from @/config/org instead of
  inlining values (prior change had wrong SUPPORT_EMAIL fallback)

UI updates:
- Dashboard pages (main, seller, workshops): integrate OnboardingChecklist
- Admin layout/services: permission-gated service management
- MainLayout, ResponsiveHero: layout consistency improvements
- Service components (AppointmentBookingForm, ServiceCTA, ServiceFeatures,
  ServicePricing, ServiceProcess): UI refinements
- ProjectCallToAction, ProjectHero, ProjectSection: project page components
- ProductManagement: admin product management improvements

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 17:14:37 +02:00
g-butandClaude Sonnet 4.6 e4de077a16 feat(decisions): fix creation bug + add public share/vote link
- Migration 065: ADD COLUMN background to decisions (was in Drizzle only,
  never applied to Neon — caused 'Fehler beim Erstellen der Entscheidung')
- decisions-crud.ts: add null guard on INSERT result row
- DecisionDetailClient: 'Link teilen' button copies /vote/<id> to clipboard
  when decision is in discussion or voting phase
- GET /api/vote/[id]: public endpoint returning decision data (no auth)
- POST /api/vote/[id]: submit vote by email lookup — resolves to DB user ID
  then delegates to existing submitVote() with full eligibility checks
- /vote/[id]: public page (no auth required) — shows decision context,
  collapsible background, options, and reuses existing ballot components

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 08:55:10 +02:00
g-butandClaude Sonnet 4.6 32f400b940 fix: add canton filter to unified technician API and replace legacy proxy routes
Migration 064 adds the missing `canton` column to `repairer_profiles` (omitted
in 061 when helper_profiles was merged in), backfills from helper_profiles, and
rebuilds helper_profiles_v to expose the real column instead of NULL.

The canton filter in /api/technicians was silently ignored since 061 — any
frontend filter by Swiss canton returned all results. Now wired up.

Legacy routes /api/repairers and /api/it-hilfe/helpers reduced from 150-230
lines of duplicated query logic each to 30-line thin proxies that delegate to
/api/technicians and remap the response shape for backwards compatibility.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 13:26:00 +02:00
g-butandClaude Sonnet 4.6 8284cbf887 feat: add next-intl i18n — 7 locales (de/fr/en/it/es/ja/ko)
- Add next-intl v4.9.1 with App Router [locale] directory pattern
- German is SSOT; other locales fall back to German for missing keys
- All public pages moved to src/app/[locale]/ for locale-aware routing
- Non-locale routes (admin, auth, dashboard, profil) use AppShell for providers
- Root layout stripped to html/body shell; locale layout owns providers
- Middleware merges next-intl locale routing with existing CSRF/auth logic
- LocaleSwitcher added to desktop header; MobileMenu updated
- CommunityStats, NewsletterSignup, Header, MobileMenu use useTranslations
- 57 partial message files merged into de/fr/en locale JSONs
- Fix react-hooks/immutability in DecisionFormClient (setInitialStatus)
- TypeScript: 0 errors — ESLint: 0 errors

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-15 12:32:31 +02:00
g-butandClaude Sonnet 4.6 0184238649 refactor: split god components + fix remaining hardcoded strings
## VotingPanel split (615 → ~160 lines)
Extract 6 voting method sections into focused components:
- voting/ConsentVote.tsx — consent response + rationale
- voting/ApprovalVote.tsx — approval (gallery + list modes)
- voting/DotVote.tsx — dot allocation (gallery + list modes)
- voting/ScoreVote.tsx — star scoring (gallery + list modes)
- voting/RankedChoiceVote.tsx — drag-to-rank ordering
- voting/SimpleMajorityVote.tsx — yes/no/abstain
- voting/DeadlineCountdown.tsx — countdown timer
- voting/OptionCard.tsx — shared gallery card
VotingPanel.tsx is now a pure orchestrator (~160 lines)

## DecisionFormClient split (746 → ~190 lines)
Extract form state and UI sections:
- useDecisionForm.ts — all state, handlers, API submit logic
- DecisionTypeSelector.tsx — decision type card grid
- DecisionOptionsEditor.tsx — option add/edit/remove
- ParticipantSelector.tsx — scope selector + invite list
- AdvancedSettings.tsx — voting method, quorum, blind voting
DecisionFormClient.tsx composes the above cleanly

## API route fixes
- locations/route.ts: migrate from manual auth() to withAuth middleware (GET + POST)
- listings/[id]/duplicate: use LISTING_STATUS.REMOVED constant (was 'removed')
- admin/listings/[id]/verify: use LISTING_STATUS.REMOVED constant (was 'removed')

## Lint
- scripts/lint-umlauts.sh: exclude 'statutenaenderung' (known DB slug, legitimate false positive)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 16:33:43 +02:00