From 1615888ce4fc27c525da9a05062ab7ebf81fa32d Mon Sep 17 00:00:00 2001 From: OlivierSchulbaum Date: Tue, 20 Oct 2026 11:16:47 +0200 Subject: [PATCH 1/4] New Crowdin updates (#537) * New translations es.json (Catalan) [ci skip] * New translations es.json (English) [ci skip] * New translations es.json (Catalan) [ci skip] * New translations es.json (English) [ci skip] * New translations es.json (Catalan) [ci skip] * New translations es.json (English) [ci skip] --- src/i18n/locales/ca.json | 158 ++++++++++++++++++++++++++------------- src/i18n/locales/en.json | 158 ++++++++++++++++++++++++++------------- 2 files changed, 210 insertions(+), 106 deletions(-) diff --git a/src/i18n/locales/ca.json b/src/i18n/locales/ca.json index fa194807..97ff6da9 100644 --- a/src/i18n/locales/ca.json +++ b/src/i18n/locales/ca.json @@ -14,7 +14,8 @@ }, "file": { "sizeTooLarge": "El fitxer {{ file }} supera la mida màxima ({{ max }})", - "unsupportedType": "Tipus de fitxer no permès: {{ file }}" + "unsupportedType": "Tipus de fitxer no permès: {{ file }}", + "uploadFailed": "No s'ha pogut pujar el fitxer" } }, "OAuth": { @@ -56,6 +57,12 @@ "max": "La data de llançament no pot ser posterior a {{ max }}" } }, + "review": { + "status": "L'estat de la revisió no és vàlid", + "comment": { + "max": "El missatge no pot superar els {{ max }} caràcters" + } + }, "errors": { "summary": { "title": "Corregeix els errors següents:" @@ -71,7 +78,9 @@ "search": { "bar": { "placeholder": "Cercar..." - } + }, + "noResults": "No s'han trobat resultats", + "removeItem": "Treu {{ label }}" }, "carousel": { "empty": "No hi ha articles per mostrar" @@ -94,7 +103,6 @@ "slug": "ID", "territory": "Territori", "dateUpdated": "Última actualització", - "budgetAmount": "Import", "gateway": "Passarel·la", "type": "Tipus", "checkout": { @@ -110,6 +118,9 @@ "userType": "Tipus d'usuari", "active": "Actiu", "userRoles": "Rols", + "reviewType": "Tipus de revisió", + "project": "Projecte", + "reviewer": "Assessor", "userTerritoryCountry": "Ubicació" }, "operator": { @@ -142,6 +153,10 @@ "active": { "true": "Actiu", "false": "Inactiu" + }, + "reviewType": { + "campaign": "Campanya", + "financial": "Finançament" } } }, @@ -182,8 +197,8 @@ } }, "reward": { - "byAtLeast": "Per {{ amount }}", - "byAtLeastOrMore": "Per {{ amount }} o més", + "forAtLeast": "Per {{ amount }}", + "forAtLeastOrMore": "Per {{ amount }} o més", "donation": "Donació", "unitsTotal": { "single": "Hi ha una unitat", @@ -197,7 +212,7 @@ "status": { "all": "Tots els estats", "in_draft": "Esborrany", - "to_campaign_review": "Pendent d'enviar a revisió", + "to_campaign_review": "A punt per a la revisió", "in_campaign_review": "En revisió", "in_campaign_review_to_change": "En revisió: requereix canvis", "in_campaign_review_to_review": "En revisió: pendent de revisar", @@ -206,12 +221,12 @@ "in_campaign": "En campanya", "campaign_failed": "Campanya fallida", "campaign_cancelled": "Campanya cancel·lada", - "to_funding_review": "Pendent de revisió de finançament", - "in_funding_review": "En revisió de finançament", - "in_funding_review_to_change": "En revisió de finançament: requereix canvis", - "in_funding_review_to_review": "En revisió de finançament: pendent de revisar", - "funding_review_rejected": "Rebutjat en revisió de finançament", - "to_funding": "Pendent de finançament", + "to_funding_review": "A punt per a la revisió financera", + "in_funding_review": "En revisió financera", + "in_funding_review_to_change": "En revisió financera: requereix canvis", + "in_funding_review_to_review": "En revisió financera: pendent de revisar", + "funding_review_rejected": "Rebutjat en la revisió financera", + "to_funding": "A punt per al finançament", "in_funding": "En finançament", "funding_paid": "Finançament pagat", "funded": "Finançats", @@ -311,6 +326,25 @@ "previous": "Pàgina anterior", "next": "Pàgina següent", "page": "Pàgina {{ page }}" + }, + "translationLanguages": { + "add": "Afegir traducció", + "remove": "Eliminar traducció", + "removeAll": "Eliminar totes les traduccions", + "addModal": { + "title": "Afegeix una traducció nova", + "description": "Cerca i tria l’idioma al qual vols traduir el contingut.", + "searchPlaceholder": "Cerca entre tots els idiomes…", + "submit": "Afegir" + }, + "removeModal": { + "title": "Vols eliminar aquesta traducció?", + "description": "La traducció s’eliminarà en desar." + }, + "removeAllModal": { + "title": "Vols eliminar totes les traduccions?", + "description": "Només es conservarà el text en {{language}}. Les altres traduccions s’eliminaran en desar." + } } }, "common": { @@ -720,8 +754,7 @@ }, "featuredPromoters": { "title": "Impulsors destacats", - "viewAll": "Veure'ls tots", - "projectsPromoted": "Projectes impulsats", + "projectsPromoted": "Projectes propis", "capitalRaised": "Capital recaptat", "promoterImage": "Foto de l'impulsor", "shareProfile": "Comparteix el perfil de {{name}}" @@ -1310,13 +1343,22 @@ "back": "Tornar a la revisió" }, "card": { - "activity": "{{ count }} xats. Darrera activitat {{ date }}" + "activity": "{{ count }} xats. Darrera activitat {{ date }}", + "activitySingular": "{{ count }} missatge. Darrera activitat {{ date }}" }, "chat": { "title": "{{ area }} · {{ project }}", "placeholder": "Escriu un missatge…", "send": "Enviar missatge", "empty": "Encara no hi ha missatges en aquesta conversa. Comença tu.", + "mdHelpTitle": "Format i dreceres de teclat", + "mdHelpBold": "**negreta** — Ctrl+B", + "mdHelpItalic": "_cursiva_ — Ctrl+I", + "mdHelpStrike": "~~ratllat~~ — Ctrl+Shift+S", + "mdHelpQuote": "> cita — Ctrl+Maj+Q", + "mdHelpLink": "[text](url) — enllaç", + "mdHelpImage": "![descripció](url) — imatge", + "mdHelpNote": "Selecciona el text i prem la drecera, o prem la drecera amb el cursor on vulguis escriure. Enter envia i Shift+Enter fa un salt de línia.", "today": "Avui", "yesterday": "Ahir", "day": "{{ date }}", @@ -1329,7 +1371,8 @@ "forbidden": "No tens permís per realitzar aquesta acció.", "notFound": "La revisió no existeix.", "areaNotFound": "L'àrea de risc no existeix.", - "statusNotUpdated": "No s'ha pogut actualitzar l'estat del projecte." + "statusNotUpdated": "No s'ha pogut actualitzar l'estat del projecte.", + "generic": "S'ha produït un error en realitzar l'operació." } }, "search": { @@ -1500,7 +1543,8 @@ "description": "Tria què es mostra a la portada.", "tabs": { "hero": "Heroi", - "highlights": "P. destacats" + "highlights": "P. destacats", + "featuredUsers": "Impulsors" }, "hero": { "title": "Heroi", @@ -1511,19 +1555,6 @@ "invalidTranslations": "Les traduccions enviades no són vàlides", "incompleteLanguages": "Falten camps obligatoris a: {{ languages }}" }, - "addTranslation": "Afegir traducció", - "addTranslationModal": { - "title": "Afegeix una nova traducció", - "description": "Cerca i tria l'idioma al qual vols traduir el contingut del hero", - "searchPlaceholder": "Cerca entre tots els idiomes…", - "submit": "Afegir" - }, - "removeTranslation": "Eliminar traducció", - "removeTranslationModal": { - "title": "Voleu eliminar aquesta traducció?", - "description": "La traducció s'eliminarà del formulari i no es desarà.", - "invalidUrl": "L'URL de l'enllaç no és vàlid" - }, "tabs": { "fields": "Nou", "history": "Registre" @@ -1599,6 +1630,21 @@ "submit": "Afegir" } } + }, + "featuredUsers": { + "title": "Impulsors", + "description": "Els que estan al capdavant de la nostra iniciativa, els més destacats.", + "selection": { + "title": "Selecciona els impulsors més destacats", + "empty": "Cerca un impulsor/a i destaca'l a la portada", + "add": "Afegeix impulsor", + "change": "Destaca un altre impulsor/a" + }, + "modal": { + "title": "Afegeix usuari", + "description": "Cerca i afegeix l'usuari que vulguis destacar a la portada", + "search": "Cerca un usuari" + } } }, "charges": { @@ -1965,7 +2011,11 @@ "title": "Ordena per", "options": { "handle-asc": "Nom d'usuari A–Z", - "handle-desc": "Nom d'usuari Z–A" + "handle-desc": "Nom d'usuari Z–A", + "dateCreated-desc": "Creació: més recents", + "dateCreated-asc": "Creació: més antics", + "dateUpdated-desc": "Actualització: més recents", + "dateUpdated-asc": "Actualització: més antics" } }, "itemsPerPage": { @@ -1989,11 +2039,6 @@ "individual": "Individual", "organization": "Organització" }, - "roles": { - "ROLE_USER": "Usuari", - "ROLE_ADMIN": "Administrador", - "ROLE_SUPER_ADMIN": "Superadministrador" - }, "details": { "id": "ID", "handle": "Usuari", @@ -2003,7 +2048,17 @@ "active": "Actiu", "totalCollected": "Total cobrat", "recentCharges": "Últims cobraments", - "noRecentCharges": "No s'han trobat cobraments recents" + "dateCreated": "Data d'alta", + "dateUpdated": "Última actualització", + "btns": { + "charges": "Veure cobraments", + "roles": "Actualitzar rols" + }, + "roles": { + "title": "Rols", + "placeholder": "Cerca o escriu un rol", + "save": "Desar rols" + } } } } @@ -2022,7 +2077,8 @@ "errors": { "forbidden": "No tens permisos per gestionar anuncis", "invalidUrl": "L'URL de l'anunci no és vàlida", - "invalidDateRange": "La data de fi no pot ser anterior a la d'inici" + "invalidDateRange": "La data de fi no pot ser anterior a la d'inici", + "incompleteLanguages": "Falten camps obligatoris a: {{languages}}" }, "tabs": { "fields": "Nous", @@ -2046,7 +2102,8 @@ "title": "Títol", "content": "Contingut", "publishedAt": "Data de publicació", - "endAt": "Data de finalització" + "endAt": "Data de finalització", + "translations": "Traduccions" }, "actions": { "view": "Veure" @@ -2085,7 +2142,6 @@ } }, "form": { - "addTranslation": "Afegir traducció", "titleSection": "Títol i subtítol", "titlePlaceholder": "Afegeix el títol", "subtitlePlaceholder": "Afegeix el subtítol", @@ -2105,18 +2161,7 @@ "newsletter": "Butlletí" }, "saveAndExit": "Desa i surt", - "publish": "Publica l'entrada", - "removeTranslation": "Eliminar traducció", - "translationModal": { - "title": "Afegeix una traducció nova", - "description": "Cerca i tria l'idioma al qual vols traduir aquesta entrada.", - "searchPlaceholder": "Cerca entre tots els idiomes…", - "submit": "Afegir" - }, - "removeTranslationModal": { - "title": "Eliminar aquesta traducció?", - "description": "La traducció s'eliminarà del formulari i no es desarà." - } + "publish": "Publica l'entrada" } } }, @@ -2131,6 +2176,7 @@ }, "table": { "headers": { + "id": "ID", "name": "Projecte", "promoter": "Promotor", "dateSubmitted": "Enviament a revisió", @@ -2145,7 +2191,7 @@ "dateRelease": "Llançament", "dateCreated": "Creació", "lastInteraction": "Última interacció", - "risk": "Risc", + "risk": "Riscos", "pendingMessages": "Missatges pendents", "minOptim": "Mínim - Òptim:", "lastModified": "Última modificació:", @@ -2156,6 +2202,12 @@ "advisory": "Assessorament del projecte", "assignAdvisor": "Assignar assessor", "annotations": "Anotacions" + }, + "modals": { + "assignAdvisor": { + "description": "Cerca i selecciona la persona assessora que acompanyarà aquest projecte en la revisió.", + "searchPlaceholder": "Cerca per nom o correu electrònic…" + } } } } diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 8ed2abb4..76acee3d 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -14,7 +14,8 @@ }, "file": { "sizeTooLarge": "{{ file }} exceeds the maximum size ({{ max }})", - "unsupportedType": "Unsupported file type: {{ file }}" + "unsupportedType": "Unsupported file type: {{ file }}", + "uploadFailed": "The file could not be uploaded" } }, "OAuth": { @@ -56,6 +57,12 @@ "max": "The launch date cannot be after {{ max }}" } }, + "review": { + "status": "The review status is invalid", + "comment": { + "max": "The message cannot exceed {{ max }} characters" + } + }, "errors": { "summary": { "title": "Correct the following errors:" @@ -71,7 +78,9 @@ "search": { "bar": { "placeholder": "Search..." - } + }, + "noResults": "No results found", + "removeItem": "Remove {{ label }}" }, "carousel": { "empty": "No items to display" @@ -94,7 +103,6 @@ "slug": "ID", "territory": "Territory", "dateUpdated": "Last updated", - "budgetAmount": "Amount", "gateway": "Gateway", "type": "Type", "checkout": { @@ -110,6 +118,9 @@ "userType": "User type", "active": "Active", "userRoles": "Roles", + "reviewType": "Review type", + "project": "Project", + "reviewer": "Advisor", "userTerritoryCountry": "Location" }, "operator": { @@ -142,6 +153,10 @@ "active": { "true": "Active", "false": "Inactive" + }, + "reviewType": { + "campaign": "Campaign", + "financial": "Funding" } } }, @@ -182,8 +197,8 @@ } }, "reward": { - "byAtLeast": "For {{ amount }}", - "byAtLeastOrMore": "For {{ amount }} or more", + "forAtLeast": "For {{ amount }}", + "forAtLeastOrMore": "For {{ amount }} or more", "donation": "Donation", "unitsTotal": { "single": "There is 1 unit", @@ -197,7 +212,7 @@ "status": { "all": "All statuses", "in_draft": "Draft", - "to_campaign_review": "Pending submission for review", + "to_campaign_review": "Ready for review", "in_campaign_review": "Under review", "in_campaign_review_to_change": "Under review: changes required", "in_campaign_review_to_review": "Under review: pending review", @@ -206,12 +221,12 @@ "in_campaign": "In campaign", "campaign_failed": "Failed campaign", "campaign_cancelled": "Cancelled campaign", - "to_funding_review": "Pending funding review", - "in_funding_review": "Under funding review", - "in_funding_review_to_change": "Under funding review: changes required", - "in_funding_review_to_review": "Under funding review: pending review", - "funding_review_rejected": "Rejected during funding review", - "to_funding": "Pending funding", + "to_funding_review": "Ready for funding review", + "in_funding_review": "In funding review", + "in_funding_review_to_change": "In funding review: requires changes", + "in_funding_review_to_review": "In funding review: pending review", + "funding_review_rejected": "Rejected in funding review", + "to_funding": "Ready for funding", "in_funding": "In funding", "funding_paid": "Funding paid", "funded": "Funded", @@ -311,6 +326,25 @@ "previous": "Previous page", "next": "Next page", "page": "Page {{ page }}" + }, + "translationLanguages": { + "add": "Add translation", + "remove": "Remove translation", + "removeAll": "Remove all translations", + "addModal": { + "title": "Add a new translation", + "description": "Search for and choose the language you want to translate the content into.", + "searchPlaceholder": "Search all languages…", + "submit": "Add" + }, + "removeModal": { + "title": "Remove this translation?", + "description": "The translation will be removed when you save." + }, + "removeAllModal": { + "title": "Remove all translations?", + "description": "Only the text in {{language}} will be kept. The other translations will be removed when you save." + } } }, "common": { @@ -720,8 +754,7 @@ }, "featuredPromoters": { "title": "Featured promoters", - "viewAll": "View all", - "projectsPromoted": "Projects promoted", + "projectsPromoted": "Own projects", "capitalRaised": "Capital raised", "promoterImage": "Promoter photo", "shareProfile": "Share {{name}}'s profile" @@ -1310,13 +1343,22 @@ "back": "Back to review" }, "card": { - "activity": "{{ count }} chats. Last activity {{ date }}" + "activity": "{{ count }} chats. Last activity {{ date }}", + "activitySingular": "{{ count }} message. Last activity {{ date }}" }, "chat": { "title": "{{ area }} · {{ project }}", "placeholder": "Write a message…", "send": "Send message", "empty": "There are no messages in this conversation yet. You start.", + "mdHelpTitle": "Formatting and keyboard shortcuts", + "mdHelpBold": "**bold** — Ctrl+B", + "mdHelpItalic": "_italic_ — Ctrl+I", + "mdHelpStrike": "~~strikethrough~~ — Ctrl+Shift+S", + "mdHelpQuote": "> quote — Ctrl+Shift+Q", + "mdHelpLink": "[text](url) — link", + "mdHelpImage": "![description](url) — image", + "mdHelpNote": "Select the text and press the shortcut, or press the shortcut with the cursor where you want to type. Enter sends and Shift+Enter adds a line break.", "today": "Today", "yesterday": "Yesterday", "day": "{{ date }}", @@ -1329,7 +1371,8 @@ "forbidden": "You do not have permission to perform this action.", "notFound": "The review does not exist.", "areaNotFound": "The risk area does not exist.", - "statusNotUpdated": "The project status could not be updated." + "statusNotUpdated": "The project status could not be updated.", + "generic": "An error occurred while performing the operation." } }, "search": { @@ -1500,7 +1543,8 @@ "description": "Choose what is displayed on the home page.", "tabs": { "hero": "Hero", - "highlights": "Featured Projects" + "highlights": "Featured Projects", + "featuredUsers": "Promoters" }, "hero": { "title": "Hero", @@ -1511,19 +1555,6 @@ "invalidTranslations": "The submitted translations are invalid", "incompleteLanguages": "Required fields are missing in: {{ languages }}" }, - "addTranslation": "Add translation", - "addTranslationModal": { - "title": "Add a new translation", - "description": "Search for and choose the language you want to translate the hero content into", - "searchPlaceholder": "Search all languages…", - "submit": "Add" - }, - "removeTranslation": "Remove translation", - "removeTranslationModal": { - "title": "Remove this translation?", - "description": "The translation will be removed from the form and will not be saved.", - "invalidUrl": "The link URL is invalid" - }, "tabs": { "fields": "New", "history": "History" @@ -1599,6 +1630,21 @@ "submit": "Add" } } + }, + "featuredUsers": { + "title": "Promoters", + "description": "Those leading our initiative, the most outstanding ones.", + "selection": { + "title": "Select the most outstanding promoters", + "empty": "Search for a promoter and feature them on the homepage", + "add": "Add promoter", + "change": "Feature another promoter" + }, + "modal": { + "title": "Add user", + "description": "Search for and add the user you want to feature on the homepage", + "search": "Search for a user" + } } }, "charges": { @@ -1965,7 +2011,11 @@ "title": "Order by", "options": { "handle-asc": "Username A–Z", - "handle-desc": "Username Z–A" + "handle-desc": "Username Z–A", + "dateCreated-desc": "Created: newest first", + "dateCreated-asc": "Created: oldest first", + "dateUpdated-desc": "Updated: newest first", + "dateUpdated-asc": "Updated: oldest first" } }, "itemsPerPage": { @@ -1989,11 +2039,6 @@ "individual": "Individual", "organization": "Organization" }, - "roles": { - "ROLE_USER": "User", - "ROLE_ADMIN": "Administrator", - "ROLE_SUPER_ADMIN": "Super Administrator" - }, "details": { "id": "ID", "handle": "User", @@ -2003,7 +2048,17 @@ "active": "Active", "totalCollected": "Total collected", "recentCharges": "Recent charges", - "noRecentCharges": "No recent charges found" + "dateCreated": "Registration date", + "dateUpdated": "Last updated", + "btns": { + "charges": "View charges", + "roles": "Update roles" + }, + "roles": { + "title": "Roles", + "placeholder": "Search or enter a role", + "save": "Save roles" + } } } } @@ -2022,7 +2077,8 @@ "errors": { "forbidden": "You do not have permission to manage ads", "invalidUrl": "The ad URL is invalid", - "invalidDateRange": "The end date cannot be earlier than the start date" + "invalidDateRange": "The end date cannot be earlier than the start date", + "incompleteLanguages": "Required fields are missing in: {{languages}}" }, "tabs": { "fields": "New", @@ -2046,7 +2102,8 @@ "title": "Title", "content": "Content", "publishedAt": "Publication date", - "endAt": "End date" + "endAt": "End date", + "translations": "Translations" }, "actions": { "view": "View" @@ -2085,7 +2142,6 @@ } }, "form": { - "addTranslation": "Add translation", "titleSection": "Title and subtitle", "titlePlaceholder": "Add the title", "subtitlePlaceholder": "Add the subtitle", @@ -2105,18 +2161,7 @@ "newsletter": "Newsletter" }, "saveAndExit": "Save and exit", - "publish": "Publish post", - "removeTranslation": "Remove translation", - "translationModal": { - "title": "Add a new translation", - "description": "Search for and choose the language you want to translate this post into.", - "searchPlaceholder": "Search all languages…", - "submit": "Add" - }, - "removeTranslationModal": { - "title": "Remove this translation?", - "description": "The translation will be removed from the form and will not be saved." - } + "publish": "Publish post" } } }, @@ -2131,6 +2176,7 @@ }, "table": { "headers": { + "id": "ID", "name": "Project", "promoter": "Promoter", "dateSubmitted": "Submitted for review", @@ -2145,7 +2191,7 @@ "dateRelease": "Launch", "dateCreated": "Creation", "lastInteraction": "Last interaction", - "risk": "Risk", + "risk": "Risks", "pendingMessages": "Pending messages", "minOptim": "Minimum - Optimum:", "lastModified": "Last modification:", @@ -2156,6 +2202,12 @@ "advisory": "Project advisory", "assignAdvisor": "Assign advisor", "annotations": "Annotations" + }, + "modals": { + "assignAdvisor": { + "description": "Search for and select the advisor who will support this project during the review.", + "searchPlaceholder": "Search by name or email…" + } } } } From 73c039fbeb97b6254d6070d1f2273b8ec742abb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Moreno=20C=C3=A1mara?= <139916751+Dayv1dDev@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:58:32 +0200 Subject: [PATCH 2/4] [fix] Display more descriptive error messages with floating Toast for register and login (#531) * fix: show descriptive errors in checkout login and register * feat: display checkout login and register errors in floating toast * fix: rely on API to detect duplicate email in register * fix: don't hardcode password length in register error mapping --- src/actions/register.ts | 153 ++++++++++++++++++++---- src/auth/grant.ts | 22 +++- src/components/checkout/Login.svelte | 39 +++--- src/components/checkout/Register.svelte | 24 ++-- src/i18n/locales/ca.json | 8 +- src/i18n/locales/en.json | 8 +- src/i18n/locales/es.json | 8 +- src/pages/api/session.ts | 45 +++++-- 8 files changed, 233 insertions(+), 74 deletions(-) diff --git a/src/actions/register.ts b/src/actions/register.ts index ce3f843a..dcd53055 100644 --- a/src/actions/register.ts +++ b/src/actions/register.ts @@ -9,12 +9,87 @@ import { } from "../openapi/client/index.ts"; import { zRegisterForm } from "../validation/registerValidation.ts"; +const DUPLICATE_EMAIL = /already in use|already exists|already registered|duplicate|taken/i; + +interface ApiViolation { + propertyPath?: string; + message?: string; +} + +function violationsOf(error: unknown): ApiViolation[] { + if (typeof error !== "object" || error === null) { + return []; + } + + const { violations } = error as { violations?: unknown }; + + return Array.isArray(violations) ? (violations as ApiViolation[]) : []; +} + +function isEmailInUse(error: unknown): boolean { + const fromViolations = violationsOf(error).some( + (violation) => + violation.propertyPath === "email" && DUPLICATE_EMAIL.test(violation.message ?? ""), + ); + + if (fromViolations) { + return true; + } + + return ( + typeof error === "object" && + error !== null && + "detail" in error && + DUPLICATE_EMAIL.test((error as { detail?: string | null }).detail ?? "") + ); +} + +/** + * Turns an API constraint violation into a descriptive, localized message. + */ +function violationMessage(violation: ApiViolation, t: (key: string) => string): string | undefined { + const { propertyPath, message = "" } = violation; + + switch (propertyPath) { + case "email": + return DUPLICATE_EMAIL.test(message) + ? t("pages.checkout.register.error.emailInUse") + : t("pages.checkout.register.form.validation.emailInvalid"); + case "password": + return /short/i.test(message) + ? t("pages.checkout.register.form.validation.password.minLength") + : t("pages.checkout.register.form.validation.passwordInvalid"); + case "taxId": + return t("pages.checkout.register.form.validation.taxIdInvalid"); + case "legalName": + case "firstName": + case "lastName": + return t("pages.checkout.register.form.validation.required"); + default: + return undefined; + } +} + +function apiErrorMessages(error: unknown, t: (key: string) => string): string[] { + return [ + ...new Set( + violationsOf(error) + .map((violation) => violationMessage(violation, t)) + .filter((message): message is string => Boolean(message)), + ), + ]; +} + export const register = defineAction({ accept: "form", input: zRegisterForm, handler: async (input, context) => { const { t } = context.locals; + // Tracks whether the account exists in the API, so post-creation + // failures can tell the user their account was created. + let accountCreated = false; + try { const { identifier, password, firstname, lastname, taxId, legalName } = input; @@ -30,6 +105,8 @@ export const register = defineAction({ throw error; } + accountCreated = true; + const userId = String(user.id); const auth = await passwordGrant({ identifier, password }); @@ -40,34 +117,31 @@ export const register = defineAction({ }); } - if (input.type === "individual") { - await apiUsersIdpersonPatch({ + const headers = auth.asHttpHeaders; + + const { error: personError } = await apiUsersIdpersonPatch({ + path: { id: userId }, + headers, + body: + input.type === "individual" + ? { taxId, firstName: firstname, lastName: lastname } + : { firstName: firstname, lastName: lastname }, + }); + + if (personError) { + throw personError; + } + + if (input.type === "organization") { + const { error: organizationError } = await apiUsersIdorganizationPatch({ path: { id: userId }, - headers: auth.asHttpHeaders, - body: { - taxId: taxId, - firstName: firstname, - lastName: lastname, - }, - }); - } else { - await apiUsersIdpersonPatch({ - path: { id: userId }, - headers: auth.asHttpHeaders, - body: { - firstName: firstname, - lastName: lastname, - }, + headers, + body: { taxId: taxId!, legalName: legalName! }, }); - await apiUsersIdorganizationPatch({ - path: { id: userId }, - headers: auth.asHttpHeaders, - body: { - taxId: taxId!, - legalName: legalName!, - }, - }); + if (organizationError) { + throw organizationError; + } } const session = await buildSession(auth); @@ -75,8 +149,37 @@ export const register = defineAction({ return { success: true }; } catch (error) { + if (error instanceof ActionError) { + throw error; + } + console.error("User register error:", error); + if (isEmailInUse(error)) { + throw new ActionError({ + code: "BAD_REQUEST", + message: t("pages.checkout.register.error.emailInUse"), + }); + } + + const details = apiErrorMessages(error, t); + + if (accountCreated) { + const message = t("pages.checkout.register.error.accountCreatedProfileFailed"); + + throw new ActionError({ + code: "BAD_REQUEST", + message: details.length > 0 ? `${message} ${details.join(" ")}` : message, + }); + } + + if (details.length > 0) { + throw new ActionError({ + code: "BAD_REQUEST", + message: details.join(" "), + }); + } + throw new ActionError({ code: "BAD_REQUEST", message: t("pages.checkout.register.error.unexpectedRegistration"), diff --git a/src/auth/grant.ts b/src/auth/grant.ts index b375791b..ca902ad8 100644 --- a/src/auth/grant.ts +++ b/src/auth/grant.ts @@ -1,6 +1,22 @@ import { withHttpHeaders } from "./token"; import { type OAuthToken } from "./types"; +/** + * Error thrown when the OAuth2 token endpoint rejects a grant request. + * It carries the OAuth2 error code (e.g. `invalid_grant`, `invalid_client`) so + * callers can map it to a descriptive, localized message instead of showing a + * generic error. + */ +export class OAuthError extends Error { + code?: string; + + constructor(token: OAuthToken) { + super(token.error_description ?? token.error ?? "OAuth error"); + this.name = "OAuthError"; + this.code = token.error; + } +} + export async function authorizationCode(args: { code: string; redirectUri: string; @@ -22,7 +38,7 @@ export async function authorizationCode(args: { if (oauth.error!) { console.error(oauth); - throw new Error(oauth.error_description); + throw new OAuthError(oauth); } return oauth; @@ -49,7 +65,7 @@ export async function passwordGrant(args: { if (oauth.error!) { console.error(oauth); - throw new Error(oauth.error_description); + throw new OAuthError(oauth); } return oauth; @@ -76,7 +92,7 @@ export async function refreshToken(token: OAuthToken): Promise { if (oauth.error!) { console.error(oauth); - throw new Error(oauth.error_description); + throw new OAuthError(oauth); } return oauth; diff --git a/src/components/checkout/Login.svelte b/src/components/checkout/Login.svelte index 3724f546..97a42785 100644 --- a/src/components/checkout/Login.svelte +++ b/src/components/checkout/Login.svelte @@ -1,8 +1,8 @@