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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
- 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>
- 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>
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>
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>
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>
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>
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>
- 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>
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>
- 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>
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
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>
- 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>
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>
Sends in-app + email notification to the person who created a task request
when someone responds to it, closing the feedback loop in the request flow.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Connect notification service to email infrastructure — each notification
now sends an email when user has email_notifications enabled (default).
Replace hardcoded navigation in NotificationBell with SSOT config lookup.
Fix CHECK constraint to include decision_voting, decision_closed, and
protocol_finalized types that the codebase actually inserts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Migration 038 adds 12 columns to workshops and 2 to workshop_instances so
the proposal approve route no longer crashes with 500. Approvals page now
only shows workshop proposals and blog posts (products/services are
admin-only), and surfaces permission requests for super admins. Removed
dead Medusa product-publish logic from the approval API route.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Previously inventory products showed "Anfrage senden" because they had
no Medusa variant ID, and the order service used hardcoded placeholder
data. This wires up the full end-to-end flow:
- Add medusa_variant_id column to inventory_items (migration 037)
- Extract Medusa publish logic into medusa-publish-service.ts
- Auto-publish to Medusa on product publish (fire-and-forget)
- Return Medusa IDs from inventory detail API
- Enable "In den Warenkorb" when variant ID exists on product page
- Rewrite order service to fetch real cart data from Medusa
- Make paymentIntentId optional (payments deferred)
- Update order-service tests for new Medusa cart integration
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
All organizational numbers now flow from a single `org_numbers` table
in the shared Neon database, resolving contradictions across 6+ files
(e.g. internship success 40% vs 90%, devices 150 vs 1000, CO₂ 300kg
vs 350kg). Numbers reconciled against audited revamp-info registry.
Key corrections: CO₂ production 300→350kg (Fraunhofer IZM 2023),
refurbishment 15→65kg, annual CO₂ saved ~43t (not 285t), internship
success ~40% (not 90%), people helped 100+ (not 347), team ~20 (not 23).
Also fixes German language consistency in services.ts (Linux & Web
pricing/features were in English).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add EditHistoryEntry type and edit tracking fields to WorkshopProposal
- Add reviewer_name and editor_name to WorkshopProposalWithProposer
- Fix type assertions in API routes (currentProposal as WorkshopProposal)
- Fix optional property access in EditProposalModal and EditSubmissionModal
- Fix Heading import (default vs named export)
- Add null checks in test file
- All typechecks now pass
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>