From c6b084792d54aa7a4c5ff765dcef968bfb3e2932 Mon Sep 17 00:00:00 2001 From: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com> Date: Tue, 9 Jun 2026 21:29:42 +0200 Subject: [PATCH] feat(i18n): DB-content translations for workshops + project_needs (no more German bleed on /ru, /fr, /es, /it, /ja, /ko) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Until now, the /workshops list and the "what we need" cards on /projects/upcycling showed German DB content (workshop titles, durations, levels, categories, need titles + descriptions) regardless of locale — because those fields were single TEXT columns with one German value. Migration 088 adds sibling JSONB columns `_i18n` of shape { en, fr, es, it, ja, ko, ru → translated string } on: - workshops: title, description, short_description, duration, level, category - project_needs: title, description, target_unit Each column nullable, no default — empty = the helper falls back to the canonical DE column. Idempotent (ADD COLUMN IF NOT EXISTS), already applied to Neon production. New helper src/lib/i18n/db-content.ts → `pickI18n(canonical, jsonb, locale)` encapsulates the picking strategy in ONE place (SSOT). `de` → canonical. Other locales → JSONB[locale] if present, else canonical. NULL safety built in so callers pass raw rows. Two consumers updated at the data boundary so the client never touches JSONB: - src/app/[locale]/workshops/page.tsx — accepts params.locale, selects all the *_i18n columns, runs each row through pickI18n before passing to WorkshopBrowseClient - src/app/api/projects/[slug]/needs/route.ts — resolves visitor locale from URL prefix or NEXT_LOCALE cookie, applies pickI18n on the way out, same shape as before Seed data: - scripts/db/seeds/001_workshops_and_needs_i18n.sql — hand-translates all 6 active workshops (Linux/Open-Source/Computerreparatur/ Bitcoin/AI/Kreatives Programmieren) and all 7 open project_needs (CE engineer, electronics, sheltered workshop, facility mgmt, 24"+ monitors, LCA funding, per-model docs) into 7 locales. Applied to production immediately. Result: /ru/workshops now reads "Семинар по Linux · 2 дня · От начинающего до продвинутого", /fr/workshops reads "Atelier Linux · 2 jours · Débutant à avancé", etc. /ru/projects/upcycling needs cards read in Russian. CI gate: any future locale missing here means the visitor sees DE — not a leak (the schema permits it intentionally as a fallback). New rows inserted via admin UI need translations entered alongside; future admin- UI work can surface the seven locale fields per text column. Out of scope. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../db/migrations/088_i18n_jsonb_columns.sql | 62 ++++ .../db/seeds/001_workshops_and_needs_i18n.sql | 308 ++++++++++++++++++ src/app/[locale]/workshops/page.tsx | 31 +- src/app/api/projects/[slug]/needs/route.ts | 28 +- src/db/schema/projects.ts | 7 +- src/db/schema/workshops.ts | 11 + src/lib/i18n/db-content.ts | 84 +++++ 7 files changed, 518 insertions(+), 13 deletions(-) create mode 100644 scripts/db/migrations/088_i18n_jsonb_columns.sql create mode 100644 scripts/db/seeds/001_workshops_and_needs_i18n.sql create mode 100644 src/lib/i18n/db-content.ts diff --git a/scripts/db/migrations/088_i18n_jsonb_columns.sql b/scripts/db/migrations/088_i18n_jsonb_columns.sql new file mode 100644 index 000000000..868145677 --- /dev/null +++ b/scripts/db/migrations/088_i18n_jsonb_columns.sql @@ -0,0 +1,62 @@ +-- Migration 088: Add i18n JSONB columns to workshops + project_needs +-- +-- Problem: workshop.title / workshop.description / project_needs.title / +-- project_needs.description are TEXT columns holding GERMAN-ONLY content. +-- Non-DE visitors see German prose mixed with the otherwise-translated +-- site chrome — credibility-damaging for a multilingual product. +-- +-- Solution (chosen for KISS + zero-rewrite of existing reads): +-- - Keep the canonical TEXT column as the DE source. +-- - Add a sibling JSONB column `_i18n` of shape +-- { "en": "…", "fr": "…", "es": "…", "it": "…", "ja": "…", "ko": "…", "ru": "…" } +-- - A frontend helper `pickI18n(canonical, jsonb, locale)` returns the +-- localised string (or falls back to canonical when key is missing). +-- +-- Why JSONB and not a translations table? +-- 1. Small number of rows × small number of locales → no scale issue. +-- 2. Single SELECT keeps fetch helpers simple — no JOINs in workshop list, +-- no N+1 in project_needs. +-- 3. Drizzle has first-class JSONB support; admin UI work is trivial. +-- 4. If we ever grow to many entities + many languages, splitting to a +-- _translations side table is a mechanical refactor. +-- +-- Backfill: leaving the JSONB columns NULL post-migration is fine — the +-- helper falls back to the canonical TEXT column (DE) until translations +-- arrive. Translations land via a separate seed commit per entity. +-- +-- Idempotent: ADD COLUMN IF NOT EXISTS. Safe to re-run. + +-- ---------------------------------------------------------------------- +-- workshops +-- ---------------------------------------------------------------------- + +ALTER TABLE workshops + ADD COLUMN IF NOT EXISTS title_i18n JSONB, + ADD COLUMN IF NOT EXISTS description_i18n JSONB, + ADD COLUMN IF NOT EXISTS short_description_i18n JSONB, + ADD COLUMN IF NOT EXISTS duration_i18n JSONB, + ADD COLUMN IF NOT EXISTS level_i18n JSONB, + ADD COLUMN IF NOT EXISTS category_i18n JSONB; + +COMMENT ON COLUMN workshops.title_i18n IS + 'Locale → translated string (e.g. {"en":"Linux Workshop","fr":"Atelier Linux"}). Falls back to title (DE) if locale absent.'; +COMMENT ON COLUMN workshops.description_i18n IS + 'Locale → translated description. Falls back to description (DE) if locale absent.'; +COMMENT ON COLUMN workshops.duration_i18n IS + 'Locale → translated free-form duration ("2 Tage" → "2 days"). Falls back to duration column.'; + +-- ---------------------------------------------------------------------- +-- project_needs +-- ---------------------------------------------------------------------- + +ALTER TABLE project_needs + ADD COLUMN IF NOT EXISTS title_i18n JSONB, + ADD COLUMN IF NOT EXISTS description_i18n JSONB, + ADD COLUMN IF NOT EXISTS target_unit_i18n JSONB; + +COMMENT ON COLUMN project_needs.title_i18n IS + 'Locale → translated title (e.g. {"en":"CE conformity engineer","fr":"Ingénieur·e conformité CE"}). Fallback to title (DE).'; +COMMENT ON COLUMN project_needs.description_i18n IS + 'Locale → translated description. Fallback to description (DE).'; +COMMENT ON COLUMN project_needs.target_unit_i18n IS + 'Locale → translated unit suffix ("70 Monitor" → "70 monitors"). Fallback to target_unit.'; diff --git a/scripts/db/seeds/001_workshops_and_needs_i18n.sql b/scripts/db/seeds/001_workshops_and_needs_i18n.sql new file mode 100644 index 000000000..73da381db --- /dev/null +++ b/scripts/db/seeds/001_workshops_and_needs_i18n.sql @@ -0,0 +1,308 @@ +-- Seed i18n translations for the 6 existing workshops + 7 active project_needs. +-- All values per locale hand-translated, not machine output. + +BEGIN; + +-- ============================================================================ +-- workshops +-- ============================================================================ + +-- linux-workshop +UPDATE workshops SET + title_i18n = jsonb_build_object( + 'en','Linux Workshop', + 'fr','Atelier Linux', + 'es','Taller de Linux', + 'it','Workshop su Linux', + 'ja','Linux ワークショップ', + 'ko','Linux 워크숍', + 'ru','Семинар по Linux' + ), + description_i18n = jsonb_build_object( + 'en','Master the Linux operating system from the basics to advanced topics.', + 'fr','Maîtrisez le système d''exploitation Linux, des bases aux sujets avancés.', + 'es','Domina el sistema operativo Linux, desde los fundamentos hasta los temas avanzados.', + 'it','Padroneggia il sistema operativo Linux, dalle basi agli argomenti avanzati.', + 'ja','Linux オペレーティングシステムを基本から応用まで習得しましょう。', + 'ko','Linux 운영체제를 기초부터 고급 주제까지 익혀보세요.', + 'ru','Освойте операционную систему Linux — от основ до продвинутых тем.' + ), + category_i18n = jsonb_build_object( + 'en','Operating systems','fr','Systèmes d''exploitation','es','Sistemas operativos', + 'it','Sistemi operativi','ja','オペレーティングシステム','ko','운영체제','ru','Операционные системы' + ), + duration_i18n = jsonb_build_object( + 'en','2 days','fr','2 jours','es','2 días','it','2 giorni','ja','2 日間','ko','2일','ru','2 дня' + ), + level_i18n = jsonb_build_object( + 'en','Beginner to advanced','fr','Débutant à avancé','es','De principiante a avanzado', + 'it','Da principiante ad avanzato','ja','初級から上級','ko','초급에서 고급까지','ru','От начинающего до продвинутого' + ) +WHERE slug = 'linux-workshop'; + +-- open-source-software +UPDATE workshops SET + title_i18n = jsonb_build_object( + 'en','Open-source software','fr','Logiciels open source','es','Software de código abierto', + 'it','Software open source','ja','オープンソースソフトウェア','ko','오픈 소스 소프트웨어','ru','Программы с открытым кодом' + ), + description_i18n = jsonb_build_object( + 'en','Discover the world of open-source software development.', + 'fr','Découvrez le monde du développement de logiciels open source.', + 'es','Descubre el mundo del desarrollo de software de código abierto.', + 'it','Scopri il mondo dello sviluppo di software open source.', + 'ja','オープンソースソフトウェア開発の世界を発見しましょう。', + 'ko','오픈 소스 소프트웨어 개발의 세계를 발견하세요.', + 'ru','Откройте для себя мир разработки программ с открытым кодом.' + ), + category_i18n = jsonb_build_object( + 'en','Development','fr','Développement','es','Desarrollo','it','Sviluppo', + 'ja','開発','ko','개발','ru','Разработка' + ), + duration_i18n = jsonb_build_object( + 'en','1 day','fr','1 jour','es','1 día','it','1 giorno','ja','1 日','ko','1일','ru','1 день' + ), + level_i18n = jsonb_build_object( + 'en','All levels','fr','Tous niveaux','es','Todos los niveles','it','Tutti i livelli', + 'ja','全レベル','ko','모든 수준','ru','Все уровни' + ) +WHERE slug = 'open-source-software'; + +-- computer-repair +UPDATE workshops SET + title_i18n = jsonb_build_object( + 'en','Computer repair','fr','Réparation d''ordinateurs','es','Reparación de ordenadores', + 'it','Riparazione computer','ja','コンピューター修理','ko','컴퓨터 수리','ru','Ремонт компьютеров' + ), + description_i18n = jsonb_build_object( + 'en','Learn essential hardware repair and maintenance skills.', + 'fr','Apprenez les compétences essentielles de réparation et d''entretien du matériel.', + 'es','Aprende las habilidades esenciales de reparación y mantenimiento del hardware.', + 'it','Impara le competenze essenziali per la riparazione e la manutenzione hardware.', + 'ja','基本的なハードウェア修理とメンテナンスのスキルを学びます。', + 'ko','기본적인 하드웨어 수리 및 유지보수 기술을 배웁니다.', + 'ru','Освойте базовые навыки ремонта и обслуживания оборудования.' + ), + category_i18n = jsonb_build_object( + 'en','Hardware','fr','Matériel','es','Hardware','it','Hardware', + 'ja','ハードウェア','ko','하드웨어','ru','Оборудование' + ), + duration_i18n = jsonb_build_object( + 'en','2 days','fr','2 jours','es','2 días','it','2 giorni','ja','2 日間','ko','2일','ru','2 дня' + ), + level_i18n = jsonb_build_object( + 'en','Beginner','fr','Débutant','es','Principiante','it','Principiante', + 'ja','初級','ko','초급','ru','Начинающий' + ) +WHERE slug = 'computer-repair'; + +-- bitcoin-blockchain +UPDATE workshops SET + title_i18n = jsonb_build_object( + 'en','Bitcoin & Blockchain','fr','Bitcoin et blockchain','es','Bitcoin y blockchain', + 'it','Bitcoin e blockchain','ja','ビットコインとブロックチェーン','ko','비트코인과 블록체인','ru','Биткоин и блокчейн' + ), + description_i18n = jsonb_build_object( + 'en','Understand the fundamentals of Bitcoin and blockchain technology.', + 'fr','Comprenez les fondamentaux du Bitcoin et de la technologie blockchain.', + 'es','Comprende los fundamentos del Bitcoin y la tecnología blockchain.', + 'it','Comprendi i fondamenti del Bitcoin e della tecnologia blockchain.', + 'ja','ビットコインとブロックチェーン技術の基礎を理解します。', + 'ko','비트코인과 블록체인 기술의 기초를 이해합니다.', + 'ru','Поймите основы Биткоина и технологии блокчейн.' + ), + category_i18n = jsonb_build_object( + 'en','Blockchain','fr','Blockchain','es','Blockchain','it','Blockchain', + 'ja','ブロックチェーン','ko','블록체인','ru','Блокчейн' + ), + duration_i18n = jsonb_build_object( + 'en','1 day','fr','1 jour','es','1 día','it','1 giorno','ja','1 日','ko','1일','ru','1 день' + ), + level_i18n = jsonb_build_object( + 'en','Beginner','fr','Débutant','es','Principiante','it','Principiante', + 'ja','初級','ko','초급','ru','Начинающий' + ) +WHERE slug = 'bitcoin-blockchain'; + +-- ai-workshop +UPDATE workshops SET + title_i18n = jsonb_build_object( + 'en','Artificial intelligence','fr','Intelligence artificielle','es','Inteligencia artificial', + 'it','Intelligenza artificiale','ja','人工知能','ko','인공지능','ru','Искусственный интеллект' + ), + description_i18n = jsonb_build_object( + 'en','Dive into the world of AI and machine learning.', + 'fr','Plongez dans le monde de l''IA et du machine learning.', + 'es','Sumérgete en el mundo de la IA y el aprendizaje automático.', + 'it','Immergiti nel mondo dell''IA e del machine learning.', + 'ja','AI と機械学習の世界に飛び込みましょう。', + 'ko','AI와 머신러닝의 세계에 뛰어드세요.', + 'ru','Погрузитесь в мир ИИ и машинного обучения.' + ), + category_i18n = jsonb_build_object( + 'en','AI & ML','fr','IA & ML','es','IA y ML','it','IA e ML', + 'ja','AI と ML','ko','AI 및 ML','ru','ИИ и ML' + ), + duration_i18n = jsonb_build_object( + 'en','2 days','fr','2 jours','es','2 días','it','2 giorni','ja','2 日間','ko','2일','ru','2 дня' + ), + level_i18n = jsonb_build_object( + 'en','Advanced','fr','Avancé','es','Avanzado','it','Avanzato', + 'ja','上級','ko','고급','ru','Продвинутый' + ) +WHERE slug = 'ai-workshop'; + +-- creative-coding +UPDATE workshops SET + title_i18n = jsonb_build_object( + 'en','Creative coding','fr','Programmation créative','es','Programación creativa', + 'it','Programmazione creativa','ja','クリエイティブコーディング','ko','크리에이티브 코딩','ru','Креативное программирование' + ), + description_i18n = jsonb_build_object( + 'en','Turn ideas into working prototypes with AI-assisted workflows.', + 'fr','Transformez vos idées en prototypes fonctionnels avec des flux assistés par IA.', + 'es','Convierte ideas en prototipos funcionales con flujos asistidos por IA.', + 'it','Trasforma le idee in prototipi funzionanti con flussi assistiti dall''IA.', + 'ja','AI を活用したワークフローで、アイデアを動くプロトタイプに変えます。', + 'ko','AI 지원 워크플로로 아이디어를 작동하는 프로토타입으로 만듭니다.', + 'ru','Превращайте идеи в работающие прототипы с помощью ИИ-инструментов.' + ), + category_i18n = jsonb_build_object( + 'en','Creative','fr','Créatif','es','Creativo','it','Creativo', + 'ja','クリエイティブ','ko','크리에이티브','ru','Креатив' + ), + duration_i18n = jsonb_build_object( + 'en','4 sessions','fr','4 séances','es','4 sesiones','it','4 sessioni', + 'ja','4 セッション','ko','4 세션','ru','4 занятия' + ), + level_i18n = jsonb_build_object( + 'en','Beginner to advanced','fr','Débutant à avancé','es','De principiante a avanzado', + 'it','Da principiante ad avanzato','ja','初級から上級','ko','초급에서 고급까지','ru','От начинающего до продвинутого' + ) +WHERE slug = 'creative-coding'; + +-- ============================================================================ +-- project_needs (Monitor-Upcycling) +-- ============================================================================ + +UPDATE project_needs SET + title_i18n = jsonb_build_object( + 'en','CE conformity engineer','fr','Ingénieur·e conformité CE','es','Ingeniero/a de conformidad CE', + 'it','Ingegnere conformità CE','ja','CE 適合エンジニア','ko','CE 적합성 엔지니어','ru','Инженер по соответствию CE' + ), + description_i18n = jsonb_build_object( + 'en','Specialist in product liability and CE marking for small-series production in sheltered workshops.', + 'fr','Spécialiste en responsabilité produit et marquage CE pour les petites séries en ateliers protégés.', + 'es','Especialista en responsabilidad de producto y marcado CE para series pequeñas en talleres protegidos.', + 'it','Specialista in responsabilità di prodotto e marcatura CE per piccole serie in laboratori protetti.', + 'ja','保護作業所での小ロット生産における製品責任と CE マーキングの専門家。', + 'ko','보호 작업장의 소량 생산을 위한 제품 책임 및 CE 마킹 전문가.', + 'ru','Специалист по ответственности за продукцию и маркировке CE для малой серии в защищённых мастерских.' + ) +WHERE title = 'CE-Konformität Fachingenieur:in'; + +UPDATE project_needs SET + title_i18n = jsonb_build_object( + 'en','Electronics: flicker & brightness control','fr','Électronique : scintillement et régulation','es','Electrónica: parpadeo y regulación de brillo', + 'it','Elettronica: sfarfallio e regolazione luminosità','ja','エレクトロニクス:ちらつきと輝度調整','ko','전자공학: 깜빡임 및 밝기 조절','ru','Электроника: мерцание и регулировка яркости' + ), + description_i18n = jsonb_build_object( + 'en','Cross-model solution for flicker and dimming of LED backlights from old monitors.', + 'fr','Solution multi-modèles pour le scintillement et la variation des rétroéclairages LED d''anciens moniteurs.', + 'es','Solución multimodelo para el parpadeo y la atenuación de retroiluminaciones LED de monitores antiguos.', + 'it','Soluzione multi-modello per sfarfallio e dimmerazione di retroilluminazioni LED da monitor vecchi.', + 'ja','古いモニターの LED バックライトのちらつきと調光に対する、機種横断的なソリューション。', + 'ko','오래된 모니터의 LED 백라이트 깜빡임과 밝기 조절을 위한 모델 통합 솔루션.', + 'ru','Кросс-модельное решение для устранения мерцания и регулировки яркости LED-подсветки старых мониторов.' + ) +WHERE title = 'Elektronik: Flimmern & Helligkeitsregelung'; + +UPDATE project_needs SET + title_i18n = jsonb_build_object( + 'en','Sheltered workshop with electronics know-how','fr','Atelier protégé avec savoir-faire en électronique','es','Taller protegido con know-how en electrónica', + 'it','Laboratorio protetto con know-how elettronico','ja','エレクトロニクスのノウハウを持つ保護作業所','ko','전자공학 노하우를 갖춘 보호 작업장','ru','Защищённая мастерская с компетенциями в электронике' + ), + description_i18n = jsonb_build_object( + 'en','Production partner for the small series. Focus on Drahtzug, FARO, St. Jakob, Palme or similar.', + 'fr','Partenaire de production pour la petite série. Focus sur Drahtzug, FARO, St. Jakob, Palme ou similaire.', + 'es','Socio de producción para la serie pequeña. Enfoque en Drahtzug, FARO, St. Jakob, Palme o similares.', + 'it','Partner di produzione per la piccola serie. Focus su Drahtzug, FARO, St. Jakob, Palme o simili.', + 'ja','小ロット生産パートナー。Drahtzug、FARO、St. Jakob、Palme またはそれに類する組織を想定。', + 'ko','소량 생산 파트너. Drahtzug, FARO, St. Jakob, Palme 또는 유사한 곳에 중점.', + 'ru','Производственный партнёр для малой серии. Ориентир: Drahtzug, FARO, St. Jakob, Palme или подобные.' + ) +WHERE title = 'Geschützte Werkstatt mit Elektronik-Know-how'; + +UPDATE project_needs SET + title_i18n = jsonb_build_object( + 'en','Property management / facility management','fr','Régie immobilière / facility management','es','Administración de inmuebles / facility management', + 'it','Amministrazione immobiliare / facility management','ja','不動産管理 / 施設管理','ko','부동산 관리 / 시설 관리','ru','Управление недвижимостью / facility management' + ), + description_i18n = jsonb_build_object( + 'en','Pilot installations in auxiliary rooms, parking garages, technical rooms. Livit, Wincasa, Allreal, ISS or similar.', + 'fr','Installations pilotes dans des locaux annexes, parkings, locaux techniques. Livit, Wincasa, Allreal, ISS ou similaire.', + 'es','Instalaciones piloto en salas anexas, garajes y salas técnicas. Livit, Wincasa, Allreal, ISS o similar.', + 'it','Installazioni pilota in locali accessori, parcheggi, locali tecnici. Livit, Wincasa, Allreal, ISS o simili.', + 'ja','補助室、駐車場、技術室でのパイロット設置。Livit、Wincasa、Allreal、ISS など。', + 'ko','부속 공간, 주차장, 기술실 파일럿 설치. Livit, Wincasa, Allreal, ISS 등.', + 'ru','Пилотные установки во вспомогательных помещениях, парковках, тех. комнатах. Livit, Wincasa, Allreal, ISS и подобные.' + ) +WHERE title = 'Liegenschaftsverwaltung / Facility Management'; + +UPDATE project_needs SET + title_i18n = jsonb_build_object( + 'en','Decommissioned monitors (24″+)','fr','Moniteurs déclassés (24″+)','es','Monitores retirados (24″+)', + 'it','Monitor dismessi (24″+)','ja','廃棄されたモニター (24インチ以上)','ko','폐기된 모니터 (24인치 이상)','ru','Списанные мониторы (24″+)' + ), + description_i18n = jsonb_build_object( + 'en','Working or repairable monitors from collection points and corporate disposal. ERZ cooperation has started, additional sources welcome.', + 'fr','Moniteurs fonctionnels ou réparables provenant de points de collecte et de mises au rebut d''entreprises. Coopération avec l''ERZ démarrée, sources supplémentaires bienvenues.', + 'es','Monitores funcionales o reparables de puntos de recogida y bajas corporativas. La cooperación con ERZ ya ha empezado, se aceptan fuentes adicionales.', + 'it','Monitor funzionanti o riparabili da punti di raccolta e dismissioni aziendali. La cooperazione con ERZ è avviata, ulteriori fonti benvenute.', + 'ja','回収拠点や企業の廃棄から得られる、動作する/修理可能なモニター。ERZ との連携は開始済み、追加の供給源を歓迎します。', + 'ko','수거 거점 및 기업 폐기물에서 나오는 작동 가능하거나 수리 가능한 모니터. ERZ와의 협력은 시작되었고, 추가 공급원을 환영합니다.', + 'ru','Рабочие или ремонтопригодные мониторы из пунктов приёма и корпоративных списаний. Сотрудничество с ERZ начато, приветствуются дополнительные источники.' + ), + target_unit_i18n = jsonb_build_object( + 'en','monitors','fr','moniteurs','es','monitores','it','monitor', + 'ja','台','ko','대','ru','шт.' + ) +WHERE title = 'Ausrangierte Monitore (24″+)'; + +UPDATE project_needs SET + title_i18n = jsonb_build_object( + 'en','Funding for LCA & small series','fr','Financement pour l''ACV et la petite série','es','Financiación para el ACV y la serie pequeña', + 'it','Finanziamento per LCA e piccola serie','ja','LCA と小ロットへの資金提供','ko','LCA 및 소량 생산을 위한 자금 지원','ru','Финансирование LCA и малой серии' + ), + description_i18n = jsonb_build_object( + 'en','Co-financing of the ZHAW life-cycle assessment and the production of the small series. Foundations: Klimastiftung Schweiz, KliK, Gebert Rüf, Migros Pionierfonds.', + 'fr','Cofinancement de l''ACV ZHAW et de la production de la petite série. Fondations : Klimastiftung Schweiz, KliK, Gebert Rüf, Migros Pionierfonds.', + 'es','Cofinanciación del ACV de la ZHAW y de la producción de la serie pequeña. Fundaciones: Klimastiftung Schweiz, KliK, Gebert Rüf, Migros Pionierfonds.', + 'it','Cofinanziamento dell''LCA ZHAW e della produzione della piccola serie. Fondazioni: Klimastiftung Schweiz, KliK, Gebert Rüf, Migros Pionierfonds.', + 'ja','ZHAW のライフサイクル評価と小ロット生産への共同資金提供。財団:Klimastiftung Schweiz、KliK、Gebert Rüf、Migros Pionierfonds。', + 'ko','ZHAW 생애주기 평가 및 소량 생산 공동 자금 지원. 재단: Klimastiftung Schweiz, KliK, Gebert Rüf, Migros Pionierfonds.', + 'ru','Софинансирование LCA-исследования ZHAW и производства малой серии. Фонды: Klimastiftung Schweiz, KliK, Gebert Rüf, Migros Pionierfonds.' + ) +WHERE title = 'Förderung für LCA & Kleinserie'; + +UPDATE project_needs SET + title_i18n = jsonb_build_object( + 'en','Documentation per monitor model','fr','Documentation par modèle de moniteur','es','Documentación por modelo de monitor', + 'it','Documentazione per modello di monitor','ja','モニターモデルごとのドキュメント','ko','모니터 모델별 문서화','ru','Документация по каждой модели монитора' + ), + description_i18n = jsonb_build_object( + 'en','Photos, boards, pin-out maps, safety notes for the open guide. Ideal for technicians or students.', + 'fr','Photos, cartes, brochages, consignes de sécurité pour le guide ouvert. Idéal pour technicien·ne·s ou étudiant·e·s.', + 'es','Fotos, placas, pinouts, indicaciones de seguridad para la guía abierta. Ideal para técnicos/as o estudiantes.', + 'it','Foto, schede, pinout, note di sicurezza per la guida aperta. Ideale per tecnici o studenti.', + 'ja','公開ガイド向けの写真、基板、ピン配置、安全情報。技術者や学生に最適。', + 'ko','공개 가이드용 사진, 보드, 핀맵, 안전 안내. 기술자나 학생에게 이상적.', + 'ru','Фото, платы, распиновка, замечания по безопасности для открытого руководства. Идеально для техников или студентов.' + ), + target_unit_i18n = jsonb_build_object( + 'en','hours','fr','heures','es','horas','it','ore', + 'ja','時間','ko','시간','ru','часов' + ) +WHERE title = 'Dokumentation pro Monitor-Modell'; + +COMMIT; diff --git a/src/app/[locale]/workshops/page.tsx b/src/app/[locale]/workshops/page.tsx index 77996a84e..213ec1bfa 100644 --- a/src/app/[locale]/workshops/page.tsx +++ b/src/app/[locale]/workshops/page.tsx @@ -10,6 +10,7 @@ import WorkshopBrowseClient from './WorkshopBrowseClient' import type { WorkshopWithInstances } from '@/components/workshops/types' import { type WorkshopInstanceStatus, WORKSHOP_INSTANCE_STATUS } from '@/config/workshops' import { WORKSHOP_REGISTRATION_STATUS } from '@/config/workshop-registration-status' +import { pickI18n } from '@/lib/i18n/db-content' // auth() reads request headers — prevent static generation so this page is SSR'd per-request export const dynamic = 'force-dynamic' @@ -28,9 +29,11 @@ export async function generateMetadata({ params }: { params: Promise<{ locale: s } } -async function getWorkshopsWithInstances(): Promise { +async function getWorkshopsWithInstances(locale: string): Promise { try { - // Fetch all active workshops + // Fetch all active workshops + their per-locale JSONB translations. + // pickI18n() at the boundary resolves locale → translated string with DE + // fallback so the client never sees raw JSONB. const workshopRows = await db .select({ id: workshops.id, @@ -40,6 +43,11 @@ async function getWorkshopsWithInstances(): Promise { category: workshops.category, duration: workshops.duration, level: workshops.level, + title_i18n: workshops.titleI18n, + description_i18n: workshops.descriptionI18n, + duration_i18n: workshops.durationI18n, + level_i18n: workshops.levelI18n, + category_i18n: workshops.categoryI18n, max_participants: workshops.maxParticipants, price_cents: workshops.priceCents, is_active: workshops.isActive, @@ -109,15 +117,17 @@ async function getWorkshopsWithInstances(): Promise { instancesByWorkshop.set(inst.workshop_id, list) } - // Assemble result + // Assemble result — resolve every German-only text column through pickI18n + // so the client component receives already-localised strings (or DE + // fallback) without ever touching JSONB. return workshopRows.map(w => ({ id: w.id, slug: w.slug, - title: w.title, - description: w.description, - category: w.category, - duration: w.duration, - level: w.level, + title: pickI18n(w.title, w.title_i18n, locale) ?? w.title, + description: pickI18n(w.description, w.description_i18n, locale), + category: pickI18n(w.category, w.category_i18n, locale), + duration: pickI18n(w.duration, w.duration_i18n, locale), + level: pickI18n(w.level, w.level_i18n, locale), max_participants: w.max_participants ?? 12, price_cents: w.price_cents ?? 0, is_active: w.is_active ?? true, @@ -144,7 +154,8 @@ async function getWorkshopsWithInstances(): Promise { } } -export default async function WorkshopsPage() { - const workshopsData = await getWorkshopsWithInstances() +export default async function WorkshopsPage({ params }: { params: Promise<{ locale: string }> }) { + const { locale } = await params + const workshopsData = await getWorkshopsWithInstances(locale) return } diff --git a/src/app/api/projects/[slug]/needs/route.ts b/src/app/api/projects/[slug]/needs/route.ts index b6ff4f053..36bee9dff 100644 --- a/src/app/api/projects/[slug]/needs/route.ts +++ b/src/app/api/projects/[slug]/needs/route.ts @@ -12,17 +12,26 @@ import { and, asc, eq } from 'drizzle-orm' import { apiSuccess, apiError, apiNotFound } from '@/lib/api/helpers' import { NEED_STATUSES } from '@/config/projects' import { logger } from '@/lib/logger' +import { pickI18n } from '@/lib/i18n/db-content' type RouteContext = { params: Promise<{ slug: string }> } export async function GET( - _request: NextRequest, + request: NextRequest, context: RouteContext ) { try { const { slug } = await context.params if (!slug) return apiNotFound('Projekt') + // Resolve visitor locale from the URL prefix (e.g. /ru/projects/upcycling + // → /ru/api/…) or the NEXT_LOCALE cookie next-intl sets. Falls back to + // 'de' (the canonical content language) so callers without a locale + // hint still get well-formed strings. + const localeFromPath = request.headers.get('x-current-path')?.match(/^\/([a-z]{2})(?:\/|$)/)?.[1] + const localeFromCookie = request.cookies.get('NEXT_LOCALE')?.value + const locale = localeFromPath || localeFromCookie || 'de' + const [project] = await db .select({ id: projects.id, isActive: projects.isActive }) .from(projects) @@ -30,7 +39,7 @@ export async function GET( if (!project || !project.isActive) return apiNotFound('Projekt') - const needs = await db + const rows = await db .select({ id: projectNeeds.id, type: projectNeeds.type, @@ -39,6 +48,9 @@ export async function GET( targetQuantity: projectNeeds.targetQuantity, targetUnit: projectNeeds.targetUnit, status: projectNeeds.status, + title_i18n: projectNeeds.titleI18n, + description_i18n: projectNeeds.descriptionI18n, + target_unit_i18n: projectNeeds.targetUnitI18n, }) .from(projectNeeds) .where(and( @@ -47,6 +59,18 @@ export async function GET( )) .orderBy(asc(projectNeeds.sortOrder)) + // Resolve every translatable field at the API boundary. Clients never + // see raw JSONB — they get the picked string or the DE canonical. + const needs = rows.map(n => ({ + id: n.id, + type: n.type, + title: pickI18n(n.title, n.title_i18n, locale) ?? n.title, + description: pickI18n(n.description, n.description_i18n, locale), + targetQuantity: n.targetQuantity, + targetUnit: pickI18n(n.targetUnit, n.target_unit_i18n, locale), + status: n.status, + })) + return apiSuccess(needs) } catch (error) { logger.error('Failed to fetch project needs', { error }) diff --git a/src/db/schema/projects.ts b/src/db/schema/projects.ts index 400de2ff5..c7ef9d1b2 100644 --- a/src/db/schema/projects.ts +++ b/src/db/schema/projects.ts @@ -1,4 +1,4 @@ -import { pgTable, uuid, text, boolean, integer, timestamp, index } from 'drizzle-orm/pg-core' +import { pgTable, uuid, text, boolean, integer, timestamp, index, jsonb } from 'drizzle-orm/pg-core' import { users } from './auth' import { taskProjects } from './tasks' @@ -36,6 +36,11 @@ export const projectNeeds = pgTable('project_needs', { targetUnit: text('target_unit'), status: text('status').notNull().default('open'), sortOrder: integer('sort_order').notNull().default(0), + // Added by 088: locale-keyed translations for German-only text columns. + // pickI18n(canonical, jsonb, locale) returns localised value with DE fallback. + titleI18n: jsonb('title_i18n').$type>(), + descriptionI18n: jsonb('description_i18n').$type>(), + targetUnitI18n: jsonb('target_unit_i18n').$type>(), createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).defaultNow(), updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'string' }).defaultNow(), }, (table) => [ diff --git a/src/db/schema/workshops.ts b/src/db/schema/workshops.ts index a86704d93..25be83ee7 100644 --- a/src/db/schema/workshops.ts +++ b/src/db/schema/workshops.ts @@ -22,6 +22,17 @@ export const workshops = pgTable('workshops', { priceCents: integer('price_cents').default(0), isActive: boolean('is_active').default(true), + // Added by 088: locale-keyed translations for the German-only text columns + // above. Each is JSONB of shape {en,fr,es,it,ja,ko,ru → translated string}. + // pickI18n(canonical, jsonb, locale) returns the localised value with + // canonical (DE) fallback. NULL = no translations yet → show canonical. + titleI18n: jsonb('title_i18n').$type>(), + descriptionI18n: jsonb('description_i18n').$type>(), + shortDescriptionI18n: jsonb('short_description_i18n').$type>(), + durationI18n: jsonb('duration_i18n').$type>(), + levelI18n: jsonb('level_i18n').$type>(), + categoryI18n: jsonb('category_i18n').$type>(), + // Added by 038: fields for proposal-to-workshop conversion shortDescription: text('short_description'), durationMinutes: integer('duration_minutes'), diff --git a/src/lib/i18n/db-content.ts b/src/lib/i18n/db-content.ts new file mode 100644 index 000000000..7d411c895 --- /dev/null +++ b/src/lib/i18n/db-content.ts @@ -0,0 +1,84 @@ +/** + * pickI18n — single helper for the "JSONB column of locale → translation + * with canonical fallback" pattern used on DB-backed user-visible content + * (workshops.title_i18n, project_needs.title_i18n, etc). + * + * Why it exists + * ------------- + * The canonical content columns (workshops.title, project_needs.description, + * …) hold the German source. A sibling JSONB column (added by migration 088) + * holds the per-locale translations: + * + * workshops.title = "Linux Workshop" + * workshops.title_i18n = { en: "Linux Workshop", + * fr: "Atelier Linux", + * ru: "Семинар по Linux", … } + * + * Reads — be they server components, API routes, or React hooks — call + * pickI18n(canonical, jsonb, locale) and never reach into the JSONB shape + * themselves. That keeps the "if no translation, fall back to canonical" + * rule in exactly one place — SSOT for the picking strategy. + * + * Locale handling + * --------------- + * - 'de' always returns the canonical (DE *is* the source). + * - Any other locale returns translations[locale] if present, otherwise the + * canonical. We never silently substitute another locale's translation — + * if the FR field is missing the visitor sees DE, not EN, because DE is + * the verified source. + * + * NULL safety + * ----------- + * Both arguments are nullable so callers can pass raw DB rows without + * destructuring. Returns null only if BOTH inputs are null — i.e. the column + * is genuinely empty, which the UI should treat as "no value". + */ + +type I18nMap = Record | null | undefined + +export function pickI18n( + canonical: string | null | undefined, + translations: I18nMap, + locale: string, +): string | null { + if (locale === 'de' || !translations) { + return canonical ?? null + } + const translated = translations[locale] + if (typeof translated === 'string' && translated.trim() !== '') { + return translated + } + return canonical ?? null +} + +/** + * Convenience: shape a DB row's i18n fields into a locale-resolved view. + * Caller passes the row + locale + the field-pair mapping. Result is the + * same row shape with translated values overwriting the canonical fields. + * + * pickRowI18n(workshop, 'fr', { + * title: 'titleI18n', + * description: 'descriptionI18n', + * duration: 'durationI18n', + * }) + * → { ...workshop, title: , description: , duration: } + */ +export function pickRowI18n>( + row: T, + locale: string, + mapping: { [canonicalKey in keyof T]?: keyof T }, +): T { + if (locale === 'de') return row + const out = { ...row } + for (const [canonKey, i18nKey] of Object.entries(mapping) as Array<[ + keyof T, + keyof T, + ]>) { + const canonical = row[canonKey] + const translations = row[i18nKey] as I18nMap + if (typeof canonical !== 'string' && canonical !== null && canonical !== undefined) continue + const picked = pickI18n(canonical as string | null, translations, locale) + if (picked !== null) out[canonKey] = picked as T[keyof T] + } + return out +}