Files
evig/docs/ARCHITECTURE_DEBT.md
GandClaude Opus 4.8 a54d69db25 docs(debt): close ARCHITECTURE_DEBT — all #1–#5 resolved (#183)
Mark the architecture-debt doc CLOSED. All tracked parallel-implementation /
spaghetti patterns are resolved:
- #1 decision systems, #2 notification pipeline, #3 status taxonomy (2026-06-15)
- #1 repairer→technician table rename (migration 105), #4 lifecycle engine
  (Phases 1–2), #5 profile fragmentation (Phases 1–4)

#5 Phase 3 cosmetic leftovers were assessed and intentionally DECLINED as
premature abstraction (documented inline):
- adopting <Avatar> in the avatar UPLOAD widgets (128px/64px, live data-URL
  preview, icon placeholder, URL-input) — distinct from the 32–80px identity
  chip; forcing it bloats <Avatar> + regresses the upload UX.
- deriving ProfileData from Zod — ProfileData ≠ z.infer<UpdateProfileSchema>
  (interests + a divergent availability shape), so deriving adds risk for no gain.

The "escaped-bracket filesystem ghost" noted in the doc no longer exists (only the
real [id] route remains). No code change.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 11:14:06 +02:00

18 KiB
Raw Permalink Blame History

Architecture Debt — Parallel Implementations + Spaghetti Patterns

STATUS: CLOSED (2026-06-30). All tracked items (#1–#5) are resolved. The #1 repairer→technician table rename (migration 105) and the #5 profile cleanup (Phases 1–4; Phase 3 leftovers assessed + intentionally declined as premature abstraction) are the final pieces. Re-open only when a NEW parallel-implementation or spaghetti pattern is discovered.

Created: 2026-06-04
Last Modified: 2026-06-30
Last Modified Summary: Doc CLOSED — #5 Phase 3 leftovers assessed (not warranted); all #1–#5 resolved

Last updated: 2026-06-15 (auth/onboarding cleanup + notification pipeline closed)

Session progress (QQ + RR commits, 2026-06-04/05):

  • #1 (decision systems): ✓ DONE. Migration 086 applied (protocol FK on decisions). DecisionBridge + standalone voting cut over in QQ.6. Phase AG (2026-06-15): POST /api/decisions/[id]/create-task closes the loop to linked follow-up tasks. RR.3 (2026-06-15): removed legacy /api/protocols/[id]/decisions/* routes, protocols-voting.ts, and Drizzle schemas; apply migration 087_drop_protocol_decision_legacy.sql on each environment.
  • #2 (IT-Hilfe notifications): ✓ DONE (2026-06-15). src/lib/it-hilfe/notifications.ts routes all per-user sends through notifyUsers(). Central getEmailContent() dispatches IT-Hilfe types to rich HTML templates. The only remaining direct sendCustomEmail() is the admin shared inbox alert (REVAMPIT_NOTIFICATION_EMAIL) — intentional; not a per-user path.
  • #3 (status taxonomy): ✓ DONE. Additive LifecycleStage layer in src/config/lifecycle-stage.ts. Maps booking + appointment + IT-Hilfe statuses to pending | active | completed | cancelled. No existing enum changes. Adoption opt-in.

The codebase has three significant parallel-implementation patterns that should be merged. Each requires careful migration work — listing them here as actionable roadmaps so future sessions can execute methodically instead of starting cold.

Pattern of work for each: investigate → write migration plan → land preparatory changes (additive schema, feature flag, dual-write) → gradual migration → flip the switch → delete the old path.


#1 — Two decision/voting systems (highest priority)

The problem:

  • Protocol-embedded: protocol_decision_votes + protocol_decision_outcomes tables. Routes at /api/protocols/[id]/decisions/{vote,close,propose,create-tasks}. Services: src/lib/services/protocols-voting.ts. Vote shape: thumbs up/down per action_item_id (string ID from the AI-extracted action items in meeting_protocols.structured_notes).
  • Standalone: decisions + decision_votes tables. Routes at /api/decisions/[id]/{votes,transition,comments,send-invitations}. Services: src/lib/services/decisions-*.ts. Vote shape: flexible voteData jsonb supporting 6+ voting methods (single choice, ranked, range, dot points, etc.) with options stored on the decision.

These are conceptually the same thing — a team votes on a proposal — but evolved as two systems because the standalone one was too heavyweight to embed in a meeting protocol's "let's quick-vote on this action item" moment.

The fix (proposed):

Make protocol decisions create standalone decisions linked back via new protocol_id + action_item_id columns on the decisions table. The protocol UI surfaces them inline using the existing standalone voting widget. Eventually drop the protocol_decision_* tables once the data is migrated.

Migration plan:

  1. Schema (additive): new migration adds nullable protocol_id (uuid FK to meeting_protocols.id) and action_item_id (text) to decisions. Index on (protocol_id, action_item_id).
  2. Voting method: add 'thumbs_up_down' to VOTING_METHODS in src/config/decisions.ts. The standalone tally logic in decisions-voting.ts learns to compute it from voteData shape { choice: 'up' | 'down' }.
  3. Protocol UI: in ProtocolDetailClient.tsx, replace the DecisionActions component (lines around 230) with a thin wrapper that:
    • When user clicks "Propose as decision" on an action item → creates a standalone decision via POST /api/decisions with protocol_id, action_item_id, voting_method='thumbs_up_down', title from action item description.
    • Renders the existing standalone voting widget for any decision FK-linked to this protocol.
  4. Data migration: SQL migrating existing protocol_decision_votes rows into decision_votes rows (with new decisions rows for each distinct (protocol_id, action_item_id)).
  5. Cutover: the four endpoints /api/protocols/[id]/decisions/{vote,close,propose,create-tasks} become thin proxies to the standalone equivalents. (Or are deleted if all UI callers update to the standalone routes.)
  6. Cleanup: drop protocol_decision_votes and protocol_decision_outcomes tables. Remove protocols-voting.ts.

Estimated effort: 6-10 hours single focused session. Risk: data migration. Mitigation: dual-write phase + read from new path with old as fallback.


#2 — Two notification pipelines (IT-Hilfe bypasses the central one) — ✓ RESOLVED

Was the problem:

  • Central: src/lib/services/notifications.ts — notifyUsers, notifyAllStaff, createNotification, fireNotification. Sends in-app row to notifications table + email via the unified sendEmail pipeline based on user preferences.
  • IT-Hilfe-specific: src/lib/it-hilfe/notifications.ts — previously called sendCustomEmail() directly + used a different helper createInAppNotifications from task-helpers.ts.

Resolution (2026-06-15):

src/lib/it-hilfe/notifications.ts now wraps notifyUsers() for all per-user lifecycle events. getEmailContent() in the central service dispatches NOTIFICATION_TYPES.IT_HILFE_* to templates in src/lib/email/templates/it-hilfe.ts. sendItHilfeNotification() is a thin wrapper for generic SYSTEM-type alerts.

Intentional exception: admin shared inbox (REVAMPIT_NOTIFICATION_EMAIL) still uses sendCustomEmail() — one email to info@…, not per-user rows.

Tests: src/lib/it-hilfe/__tests__/notifications.test.ts


#3 — Three booking/appointment status enums

The problem:

  • src/config/booking-status.ts — repair appointments (requested → accepted → quoted → quote_approved → in_progress → completed, plus rejected/cancelled). 9 states + 2 aliases.
  • src/config/appointment-status.ts — service appointments / generic bookings (pending_approval → requested → confirmed → in_progress → completed, plus cancelled). 6 states.
  • IT-Hilfe — request/offer/matches state lives in its own module (src/config/it-hilfe.ts), no shared enum.

The three describe similar lifecycles but with subtly different states and label maps. Code that crosses paths (e.g. an email template that displays an appointment status) has to know which enum to use.

The fix:

Probably not a full merge — these are conceptually different (repair booking ≠ generic service appointment ≠ peer-help request). What's needed is a shared status taxonomy at a higher level:

LifecycleStage: pending | active | completed | cancelled

Each subsystem maps its specific states to a lifecycle stage. Code that doesn't care about the specifics (badges, generic "is this done?" checks) operates on lifecycle stage; code that does care (e.g. the quote approval flow in repair bookings) keeps its specific enum.

Estimated effort: 2-3 hours. Risk: minimal — additive layer, doesn't change existing enums.


#4 — Lifecycle transition engine (request→accept→complete→review)

Status: Phase 1 ✓ DONE (2026-06-29). Phase 2 ✓ DONE (2026-06-29).

The three flows — IT-Hilfe peer-repair, service appointments, marketplace orders — are each "a row with a status column moving through role-gated actions". They independently re-implemented the read-validate-write step, and only IT-Hilfe did it race-safely (and duplicated that 3×). Decided model: "shared core, separate flows" — share the engine, keep the three transition tables + side-effects distinct.

Phase 1 — race-safe transition guard (src/lib/lifecycle/guardedTransition): SELECT … FOR UPDATE → re-check the precondition under the lock → run the flow's writes in the same transaction. check(row, tx) can read a second entity in the same tx (IT-Hilfe re-reads offer status — without FOR UPDATE, serializing on the request row). All three flows route through it:

  • IT-Hilfe (accept-offer.ts, complete, confirm-review) — collapsed the 3× hand-rolled lock blocks; behavior-preserving (createReview stays post-commit).
  • Marketplace orders (PATCH + confirm-receipt) — both lock the same order row, fixing a latent double Payrexx-capture / double total_sold on concurrent or double-clicked completion. captureTransaction runs inside the lock (relies on Payrexx idempotency by transaction id).
  • Appointments (executeAppointmentUpdate) — now takes expectedStatus; generalized the rate-only compare-and-set to all transitions.

Phase 2 — declarative transition validator (resolveTransition in src/lib/lifecycle/state-machine.ts): one validator over a per-flow TransitionTable (rows of { action, from, role?, to? }), returning { ok, to } or { ok:false, reason: unknown_action|wrong_role|wrong_state } (role checked before state). Replaces the two bespoke mechanisms:

  • Orders: the route's local STATUS_TRANSITIONS matrix → ORDER_TRANSITIONS SSOT in config/marketplace.ts (client sends the target status, so action === to). Same table drives the fast-fail check AND the under-lock re-check. Security boundaries + the "nicht erlaubt" message unchanged.
  • Appointments: the buildActionUpdate switch's role/from/to gates → APPOINTMENT_TRANSITIONS SSOT in config/booking-status.ts (carries the exact per-action roleError/stateError so the 403/400 mapping is preserved). The switch now only builds per-action side-effect fields.

IT-Hilfe keeps VALID_REQUEST_TRANSITIONS as-is — its OPEN→MATCHED is a two-entity offer acceptance, not a single-row transition, so a shared table would add indirection without removing complexity.


#5 — Profile fragmentation (SSOT / DRY / SoC)

Status: Phase 1 in progress (2026-06-29).

The problem: there are 5 profile tables — users, user_profiles, repairer_profiles (technician), seller_profiles, team_profiles — with no shared abstraction, and the same fields/logic are re-declared 3–5× across DB → Zod schema → API field-map → hook → form. (The u.phone admin bug fixed in this session was a direct symptom.)

Key violations found (full audit in session notes):

  • SSOT — contact/identity duplicated: phone lives in 4 tables; address/city/ postal_code/canton in 3; bio/description in 3; avatar in 3 (users.image, user_profiles.avatar_url, seller_profiles.avatar_url). No canonical contact record.
  • DRY — the technician row is mapped 5+ ways (technician-service, /api/technicians, /api/user/technician-profile, /api/repairers/[id], /api/admin/it-hilfe/helpers, legacy-helper-response); user-profile field list redefined 5×; two different types both named TechnicianProfileInput; avatar handled 3 ways + ~8 hand-rolled initials.
  • SoC — layers leak: the canonical user DAL (lib/auth/db-users.ts) is bypassed by its own /api/user/profile route; technician-service is read-only (writes inline in routes); several pages run raw SQL inline.

Note: technician_profiles/helper_profiles tables do NOT exist — already unified into repairer_profiles (migrations 061/096/102). "Technician" is the conceptual name; the API/mapper cleanup was never finished.

Phased remediation (low-risk → high-value):

  • Phase 1 — remove dead/redundant technician read paths (code-only, this change). Delete the genuinely-uncalled endpoints + their mappers: /api/repairers (410 stub) + /api/repairers/[id] (uncalled hand-rolled detail), /api/it-hilfe/helpers (410 stub) + /api/it-hilfe/helpers/[id] (uncalled legacy shim) + src/lib/it-hilfe/legacy-helper-response.ts. /api/admin/it-hilfe/helpers stays — it's LIVE (powers useITHilfeAdmin); renaming it to /api/admin/technicians and routing it through technician-service is Phase 2.
  • Phase 2 — one read+write service for technicians. Add write functions to technician-service (today writes are inline in /api/user/technician-profile); route the self-service + admin endpoints through it; collapse the remaining mappers; resolve the serviceTypes↔serviceDeliveryTypes boundary alias to one name.
  • Phase 3 — one field-list SSOT per profile + canonical avatar.
    • 3a ✓ DONE: <Avatar> is the canonical image-or-initials primitive (shape/size/bordered/ colorClassName/maxInitials); adopted across the 6 hand-rolled-initials chrome sites + the technician profile. Header (UserMenu/MobileMenu) left (already photo-capable).
    • 3b ✓ DONE: /api/user/profile now routes through db-users.ts (getOrCreateProfile/ updateProfile) — eliminates the duplicate snake→camel field map AND fixes a latent bug (GET previously returned camelCase Drizzle rows, so saved fields never populated the snake_case ProfileData client). Removed the dead duplicate TechnicianProfileInput in types/technician.ts (the Zod-inferred one in schemas/repairer.ts is the SSOT).
    • 3c ✓ ASSESSED — the two speculative leftovers were evaluated and intentionally NOT done (premature abstraction; "premature abstraction is worse than duplication"): · <Avatar> in the upload widgets — AvatarUpload (128px) + the seller inline-upload (64px) are upload widgets (live data-URL preview via next/Image, remove button, person-icon placeholder, URL-input), not the small image-or-initials identity chip <Avatar> (32–80px) serves. Forcing it would need new sizes + an icon-placeholder mode on <Avatar> for 2 consumers and would lose the Image optimisation — a net regression. Kept separate. · ProfileData from Zod — ProfileData is NOT z.infer<UpdateProfileSchema>: the schema has interests (client lacks it) and a different availability shape (client {start,end, available} per day vs schema {available, hours}). Deriving would change availability handling for no real gain. (Minor follow-up if ever wanted: reconcile the availability shape — the client's start/end times are stripped by the schema on save; the field appears unused in the profile UI, so low priority.)
  • Phase 4 (schema) ✓ DONE — re-scoped after investigation. The original idea (consolidate contact into user_profiles) was dropped as contraindicated: a per-field write-site audit found NO mirror duplication. The role-profile contact/bio/avatar/display_name fields hold legitimately-distinct business data (seller storefront, repairer service description + application-flow business contact/location, team HR phone) entered via separate forms — collapsing them would destroy real data. The only genuine cleanup (migration 104): repairer_profiles.phone/ address NOT NULL → nullable (self-service techs stored '' placeholders only to satisfy NOT NULL; normalized to NULL + dropped the placeholder writes), and dropped the dead seller_profiles.phone/ address/postal_code columns (never written by any code path).

Other findings (minor)

  • Permission system correctly migrated from ROLES to permissions.ts; no duplication. Old ROLES marked deprecated. Clean.
  • Marketplace storefront unified (2026-06-29) — the legacy inventory.marketplace_listings table + /api/shop/inventory routes + the admin "Shop Produkte" tab were removed (migration 103). RevampIT shop stock and P2P listings now share one marketplace.listings table (RevampIT rows carry is_revampit=true). Two ingestion pipelines, one store.
  • Service appointment dashboard routes — unified under src/config/service-appointments.ts (/dashboard/appointments/*). Legacy /dashboard/bookings/* permanent-redirects; notification bell and customer emails deep-link to /dashboard/appointments/[id]. Admin detail at /admin/appointments/[id]. Pay flow: POST /api/appointments → quote → POST /api/appointments/[id]/pay. Payrexx return UX via PaymentReturnBanner + usePaymentReturnBanner.
  • Marketplace RevampIT checkout — cart is the primary path; listing detail no longer shows a duplicate “buy now” for shop stock.
  • IT-Hilfe browse link — technician dashboards use IT_HILFE.routes.browseRequests (not deprecated browse alias).
  • Escaped-bracket directory artifact at src/app/api/admin/repairer-applications/\[id\]/ is a filesystem ghost from a past cp/git operation. Contains empty reject/ and request-changes/ folders, no route.ts. Manual cleanup needed (rm -rf 'src/app/api/admin/repairer-applications/\[id\]') — the sandboxed agent shell rejects the deletion. Harmless to leave.

Execution order recommendation

All items resolved — doc closed 2026-06-30. The original three patterns (#1 decision systems, #2 notification pipeline, #3 status taxonomy) closed 2026-06-15; #4 lifecycle engine (Phases 1–2) and #5 profile fragmentation (Phases 1–4, with the Phase 3 cosmetic leftovers assessed and intentionally declined) closed 2026-06-29/30. Re-open this doc only when a new parallel-implementation or spaghetti pattern is discovered.