Commit Graph
109 Commits
Author SHA1 Message Date
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
g-butandClaude Sonnet 4.6 cd942f2387 feat: ranked-choice voting, AI decision recommendations, membership dashboard
- VotingPanel/ResultsPanel: Borda ranked-choice voting method with drag-free
  reordering (move up/down arrows), Borda point calculation and results display
- AI prompts: decision assistant now recommends optimal voting method, type,
  participant scope, quorum, and category with reason field
- dashboard/membership: complete membership status page (type, payment status,
  benefits, member-since date, payment deadline countdown)
- migration 063: add participant_scope and ai_outcome_narrative to decisions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 15:29:18 +02:00
g-butandClaude Sonnet 4.6 fce743b182 feat: real membership application system (replaces email-only flow)
Architecture:
- User ≠ Member: users are accounts, members are users with is_member=true
- Migration 062: adds is_member/member_since/member_type/member_paid_until
  to users + creates membership_applications table
- Fixed misleading "Mitglieder" stat label (now "Nutzer:innen")

New membership flow:
- /mitglied-werden now has a real form (not mailto: link)
- Works both for logged-in and anonymous users
- Logged-in: pre-fills name/email, links application to user_id
- Anonymous: accepts application, admin manually links later
- Shows 3 states: form, pending application, already a member
- Member type selection: Regular CHF 50 / Reduced CHF 20

API:
- POST /api/membership/apply — validated, rate-limited
- Prevents duplicate pending applications from same user
- Stores in membership_applications with pending status

FAQ updated to clarify:
- Difference between user account and Verein membership
- How application process works
- How to pay annual dues

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 17:12:35 +02:00
g-butandClaude Sonnet 4.6 12a23fbc70 feat: unify technician profiles — Phase 1+2 (DB migration + API)
Phase 1 — Database:
- Migration 061: adds community columns to repairer_profiles
  (accepts_gratis, accepts_kulturlegi, max_travel_km, service_delivery_types,
  profile_tier), migrates helper_profiles data, creates compat view
- Schema updated in services.ts and itHilfe.ts

Phase 2 — Unified API:
- New GET /api/technicians — unified list with tier/skills/gratis filters
- New GET /api/technicians/[id] — unified detail with skills + services
- Updated PUT /api/user/technician-profile to write to repairer_profiles
  with profile_tier='community'
- Old endpoints marked as legacy proxies

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:09:13 +02:00
g-butandClaude Opus 4.6 f29dfcf411 feat: close the loop — IT-Hilfe completion, order flow, blog status
IT-Hilfe completion flow (migration 059):
- Helper marks request as completed (verifies accepted offer ownership)
- Requester confirms + submits 5-star rating with optional review text
- Creates review in reviews table (target_type='it_hilfe')
- Updates helper's average rating + total helps counter
- Email notifications: itHilfeCompleted, itHilfeReviewReceived
- New UI cards: MarkCompletedCard (helper), ConfirmReviewCard (requester)

Marketplace order completion (migration 060):
- Buyer confirm-receipt endpoint (captures escrow, transitions to completed)
- Order review endpoint (1-5 stars, optional content, recommend toggle)
- Updates seller's averageRating from all listing reviews
- OrderStatusTimeline component (5 steps: Bestellt→Bezahlt→Versandt→Erhalten→Bewertet)
- OrderReviewForm inline on buyer's order detail page
- Email templates: orderReceiptConfirmed, orderReviewPrompt, orderReviewReceived

Blog submitter status (migration 058):
- New /dashboard/blog-submissions page with status badges + stats
- Inline rejection reason display, revise-and-resubmit editor
- API: /api/blog/my-submissions and /api/blog/submissions/[id]/resubmit
- In-app notifications on admin status changes (previously email only)
- FIX: requestChanges() was setting status to 'pending' instead of
  'requires_changes' — now correctly uses APPROVAL_STATUS.REQUIRES_CHANGES

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:40:02 +02:00
g-butandClaude Opus 4.6 c447f748ec feat: upgrade decision tool for Swiss Verein compliance
Decision categories:
- 6 Verein categories: Vorstandsbeschluss, Mitgliederbeschluss,
  Ratifizierung, Statutenänderung, Budget, Operative Entscheidung
- Category dropdown in creation form + displayed in detail header

Deadlines:
- Discussion + voting deadline date pickers in creation form
- Countdown timer in voting UI (red <24h, amber <3 days)
- Helper text about auto-close behavior

Participant selector:
- Team member picker with search in creation form
- "Abstimmungsberechtigt" section with checkboxes
- Empty = all staff can vote, selected = restricted

Quorum enforcement:
- Blocks closing decisions that don't meet quorum threshold
- Shows quorum progress with green/red indicator
- Warning message when quorum not yet met

Email notifications:
- New templates: decisionVotingOpened, decisionDeadlineReminder
- Email sent when voting opens (with deadline info)
- 24h deadline reminder via daily cron job
- Migration 057 adds category column

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 00:59:04 +02:00
g-butandClaude Opus 4.6 bcc2a9bd48 feat: task assignment + protocol attendees UX improvements
Task assignment:
- Add assigned_to column to tasks table (migration 056)
- Team member dropdown in create/edit forms ("Zuweisen an")
- Show assignee in task list + detail page
- Notification sent to assignee on create/reassign

Protocol attendees:
- Search input in attendee picker ("Teilnehmer suchen...")
- Attendees column in protocol list (name badges, +N overflow)
- Edit attendees in review phase (checkbox picker + save)
- Attendee filter dropdown in protocol list
- Resolve attendee UUIDs to names in list + detail sidebar
- Attendee section open by default in creation form

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 00:18:26 +02:00
g-butandClaude Opus 4.6 4c6f6d0086 fix: database SSOT violations — migrations, TABLE_NAMES, transactions, indexes
- Renumber 8 duplicate migration files (002, 004, 005, 008, 020, 027, 040)
  that caused silent skipping during execution
- Clean TABLE_NAMES: add 12 missing schema tables, keep legacy raw-SQL
  tables with clear comments, remove truly phantom entries
- Wrap bulk import product+inventory in transaction (was 2 separate writes)
- Wrap marketplace conversation+message+metadata in transaction (race fix)
- Add missing indexes: listings(verifiedAt), listings(priceChf),
  users(isStaff, createdAt) + migration 055
- Sync Drizzle schema with new indexes

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 21:02:36 +02:00
g-butandClaude Opus 4.6 a8d97a56e4 feat: add due dates to tasks
- Migration 054 adds due_date column to tasks table
- Schema updated with dueDate field
- Task create/edit forms include date picker
- Task detail shows due date with overdue highlighting
- Task list shows Fällig column with red overdue indicator
- API accepts due_date in POST/PATCH

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 12:58:52 +02:00
g-butandClaude Opus 4.6 ceb469a553 fix: locations page crash — add missing DB columns and fix key casing
The locations Drizzle schema defined 8 columns (accessibility_info,
approval_status, approved_by, approved_at, rejection_reason,
usage_count, last_used_at, created_by) that didn't exist in the DB,
causing db.select().from(locations) to 500.

Migration 053 adds all missing columns and backfills approval_status
from the existing is_approved boolean.

Also fixed the admin locations page which used snake_case property
names (created_at, approval_status, etc.) but the Drizzle API returns
camelCase (createdAt, approvalStatus). Added null guard on date
formatting to prevent toLocaleDateString crash.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 11:22:50 +02:00
g-butandClaude Opus 4.6 5f86a414db fix: resolve critical DB status mismatches in payment workflows
- Add migration 052 to update marketplace_orders CHECK constraint:
  'pending' → 'pending_payment' (matches ORDER_STATUS config)
- Fix Payrexx webhook setting invalid 'paid' status on service
  appointments — use APPOINTMENT_STATUS.CONFIRMED instead
- Fix appointment pay route referencing non-existent 'approved' status
  and setting invalid 'paid' — use APPOINTMENT_STATUS.COMPLETED
- Use APPOINTMENT_STATUS constants instead of PAYMENT_STATUS for
  appointment status updates (type safety)

These mismatches would cause CHECK constraint violations at runtime
when creating marketplace orders or processing payment webhooks.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 16:08:12 +02:00
g-but 2823e25dca feat: connect IT-Hilfe and Repairers, audit Erfassung/Intake
Phase 1 — IT-Hilfe ↔ Repairer unification:
- Add repairer_profile_id to it_hilfe_offers (soft FK to repairer_profiles)
- New API: GET /api/repairers/[id]/matching-requests (skill-based matching)
- New MatchingRequestsTab component on repairer detail pages
- IT-Hilfe offers now display repairer profile info (verified badge, rating)
- Repairers can see and respond to matching IT-Hilfe requests

Phase 2 — Erfassung vs Intake audit:
- docs/ERFASSUNG_INTAKE_AUDIT.md: full overlap analysis and consolidation plan
- Erfassung = AI-powered capture, Intake = checklist pipeline
- Recommended: merge into single pipeline with AI as optional first step
2026-03-23 14:09:46 +01:00
g-but 19e6be6d19 debug: test all listings route imports individually 2026-03-23 13:12:59 +01:00
g-butandClaude Opus 4.6 15f30bda2e feat(it-hilfe): comprehensive IT-Hilfe product improvements
- Fix offer_count never incrementing on new offers (critical bug)
- Add VALID_REQUEST_TRANSITIONS config + deriveBudgetType() helper (SSOT)
- Add IT-Hilfe notification types to config
- Add decline offer endpoint with email + in-app notifications
- Add in-app notifications for offer accept/reject/complete lifecycle
- Add helper profile detail page at /it-hilfe/helfer/[id]
- Add helpers directory pagination (20 per page)
- Store budgetTier on request creation + use in matching
- Add request edit page at /it-hilfe/[id]/edit
- Add decline button UI in OffersList
- Replace alert() with inline success states in HelperCard + detail page
- Add expiry badges to RequestCard + countdown in RequestSidebar
- Add admin status transition validation
- Update tests for new functionality

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 14:22:56 +01:00
g-butandClaude Opus 4.6 f893115ad7 feat: complete all remaining audit items (12 items across 9 batches)
Accessibility:
- Add skip-to-content link in root layout
- Fix 125 gray-400 contrast violations across 92 files (→ gray-500)
- Fix 13 undersized admin touch targets (p-1 → p-2, w-8 → w-10)

Performance:
- Fix workshops N+1 waterfall: single ?include=instances API call
  replaces O(W×I) client-side fetch loops

Architecture:
- Remove legacy admin-auth.ts dual auth system
- Migrate 4 routes from CMS JWT to Auth.js/withAdmin

Responsive:
- Add mobile-first breakpoints to 5 components (sell page,
  bookings, decisions, product tables, filter bars)

Mission features:
- Public financial transparency page at /about/finances
- Per-listing CO2 impact badge on marketplace (Fraunhofer IZM 2023)
- Subscription exchange design spec + draft migration

0 TypeScript errors, 0 ESLint errors, 362/362 tests passing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 16:30:01 +01:00
g-butandClaude Opus 4.6 25723a7d75 refactor: apply Zod validation to remaining routes, update audit report
Apply Zod validation imports and status config imports across
remaining page components (admin approvals, decisions, locations,
protocols, workshops, blog, dashboard, IT-Hilfe, marketplace).
Delete unused MarketplaceCheckoutForm. Update audit report with
current findings and scores.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 15:16:46 +01:00
g-butandClaude Opus 4.6 45bd7832fe feat: unified intake system, marketplace admin, IT-Hilfe, sidebar cleanup
Major features:
- Unified Device Intake system with AI text/voice extraction, checklist-gated
  publishing, tier change with checklist reset, and audit timeline
- Marketplace admin panel with stats, listing moderation, reports, orders
- IT-Hilfe admin for managing community tech help requests
- Marketplace sell form: AI-assisted listing creation with image upload

Fixes:
- Marketplace image URL validation: accept relative /uploads/ paths (was
  rejecting valid uploads with z.string().url())
- Admin marketplace stats/orders: fix column name mismatch (amount_chf
  not total_cents)
- Metadata title dedup: skip brand prefix when title already contains it
- Remove "Produkte" from admin sidebar (replaced by Geräte-Eingang +
  Marketplace flow)
- Dashboard quick action: "Neues Produkt" → "Neues Gerät" → /admin/intake

Cleanup:
- Delete unused modules: labels.ts, newsletter-status.ts, sensitive-areas.ts,
  role-checks.ts, unified-permissions.ts, mappers.ts, number-sources.ts,
  admin-access.ts, auth middleware, unused hooks
- SSOT consolidation across API routes and config

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 18:56:42 +01:00
g-butandClaude Opus 4.6 5ed9e62e38 feat: replace Stripe with Payrexx for marketplace escrow, reorganize navigation
Marketplace payments now use Payrexx reservation-based escrow instead of
Stripe manual capture. Checkout redirects to Payrexx hosted payment page
rather than rendering inline Stripe Elements. Dev mock mode enables full
E2E testing without Payrexx credentials.

Navigation reorganized: merged standalone Shop into "Marktplatz" mega-menu
alongside Marketplace and IT-Hilfe (7→6 nav items). Homepage hero CTA now
points to /marketplace. Removed 10 unused TABLE_NAMES constants.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 15:02:41 +01:00
g-butandClaude Opus 4.6 c720d2ad93 feat: marketplace Phase 2 — messaging UI, share, report, duplicate, SEO
- Messages dashboard: split-panel conversation list + thread view with
  mobile-responsive layout, deep-linking via ?conversation= param
- Share listing: Web Share API with clipboard fallback + "Kopiert!" toast
- Report listing: modal with reason radio buttons, DB migration, API route
- Duplicate listing: copy fields + specs as draft, redirect to edit
- JSON-LD Product schema on listing detail pages (Schema.org structured data)
- Dynamic sitemap for active marketplace listings (/marketplace/sitemap.xml)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 15:32:38 +01:00
g-butandClaude Opus 4.6 cb734980f1 feat: marketplace Phase 1 — specs, verification, gratis, seller toggle, condition criteria
Implement all 6 Phase 1 features for the marketplace competitive roadmap:

1.1 Seller type toggle (RevampIT Geräte / Community Inserate) on browse page
1.2 RevampIT verified badge with admin verify endpoint and verification details
1.3 Categories migrated to KATEGORIEN SSOT (numeric IDs) + structured tech specs
    (listing_specs table, spec filters on browse, spec tags on cards, spec table on detail)
1.4 Category-specific condition criteria checklists in sell form and detail page
1.5 Gratis listings (price=0) with badge + zero commission (COMMISSION_RATE=0)
1.6 AI spec extraction — enhanced marketplace AI prompt to extract specs from text

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 14:18:22 +01:00