Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(account): generated DiceBear avatars with style and background pickers
naveenkash1da86a68bb39
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex f02c115eb9..68579bd81d 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -3333,3 +3333,23 @@ of `salesInvoice`; backfilled by `20261006220901_sales-invoice-opportunity-backf**Rule:** A writer that turns triggers off does both halves itself: a null-`rowId` row per `CHANGE_LOGGED_TABLES` entry, and a null-`ids` broadcast on every `REALTIME_TABLES` topic of the company, inside the same transaction. When a stale client list is suspected, compare the ids in `window.clientCache.getQueryData(["live", companyId, name])` with the database before reading code.**Applies to:** `packages/jobs/src/inngest/functions/tasks/company-restore.ts` (`wipeAndLoad`); any new job that sets `session_replication_role`.++## A generated avatar is a seed, so the library version decides the face++**Context:** `user.avatarUrl` stores a generated avatar as `dicebear:<style>:<seed>[:<rrggbb>]` (`packages/utils/src/avatar.ts`). The browser draws it with DiceBear every time it renders (`packages/react/src/utils/generatedAvatar.ts`). Nothing about the picture is stored, only the seed.++**Problem:** A new DiceBear major version can draw a different face for the same seed. The move from version 9 to 10 (2026-10-08) changed every existing avatar, and nothing in the database showed it. A style removed from `GENERATED_AVATAR_STYLES` makes its stored values unparseable, so those avatars fall back to initials without an error.++**Rule:** Pin `@dicebear/core` and `@dicebear/styles` to exact versions, never a range. Treat a DiceBear upgrade as "every user's avatar may change", and compare renders of fixed seeds before and after. Only add to `GENERATED_AVATAR_STYLES`; the `Record` type of `STYLE_LOADERS` makes a style without a loader a type error.++**Applies to:** `packages/react/package.json` (DiceBear versions), `packages/utils/src/avatar.ts`, `packages/react/src/utils/generatedAvatar.ts`.++## A library that every page renders must not be imported statically++**Context:** `Avatar` (`@carbon/react`) is in the shell of every app. It renders generated avatars with `@dicebear/core`.++**Problem:** A static `import { Avatar, Style } from "@dicebear/core"` put about 156 KB minified (25 KB gzipped) into the main bundle of the ERP, MES and academy, on every page, whether or not a generated avatar was shown (found in self-review, 2026-10-08). Typecheck, tests and Biome all passed. Only a bundle measurement showed it.++**Rule:** In a component that every page renders, import a heavy library with `import()` at the point of first use, and keep only `import type` at the top of the file. Check with a split bundle: `npx esbuild <file> --bundle --splitting --format=esm --minify --outdir=/tmp/out '--external:@carbon/*' --external:react`. The entry file must stay small, and the library must be a separate chunk.++**Applies to:** `packages/react/src/**` components used in app shells (`Avatar`, `NavRail`, layout parts); any new dependency of `@carbon/react`.diff --git a/.ai/plans/2026-10-08-dicebear-avatars.md b/.ai/plans/2026-10-08-dicebear-avatars.mdnew file mode 100644index 0000000000..f2f835a7ca--- /dev/null+++ b/.ai/plans/2026-10-08-dicebear-avatars.md@@ -0,0 +1,188 @@+# Generated avatars (DiceBear Croodles Neutral) — implementation plan++**Spec:** .ai/specs/2026-10-08-dicebear-avatars.md+**Research:** N/A — skipped (not ERP-domain logic, clear request)+**Branch:** naveenkash/75pu7++## Progress+- [x] Task 1: Add the column default migration+- [x] Task 2: Add the generated-avatar string helpers to `@carbon/utils`+- [x] Task 3: Render generated avatars in the `@carbon/react` `Avatar`+- [x] Task 4: Pass generated values through the app `Avatar` wrappers+- [x] Task 5: Stop the invite flows from overwriting the default+- [x] Task 6: Check the avatar value in the profile action+- [x] Task 7: Add the picker and the new Remove behavior to the profile page+- [x] Task 8: Update docs and run the final gates++## Dependencies+Task 3 needs Task 2. Task 4 needs Task 2. Task 6 needs Task 2. Task 7 needs Tasks 2, 3 and 6. Tasks 1 and 5 are independent. Task 8 runs last.++## Execution notes (autonomous run)+- Do not commit. The user commits by hand.+- Do not apply the migration to the local database. The user applies it.++---++## Task 1: Add the column default migration++**Depends on:** none+**Files:**+- Create: `packages/database/supabase/migrations/{timestamp}_user-generated-avatar-default.sql`++**Steps:**+1. Run `pnpm db:migrate:new user-generated-avatar-default`.+2. Write this SQL into the new file:+ ```sql+ -- New users get a random DiceBear Croodles Neutral avatar. The value is+ -- rendered by @carbon/react Avatar (see packages/utils/src/avatar.ts).+ -- Existing rows are not changed.+ ALTER TABLE "user"+ ALTER COLUMN "avatarUrl"+ SET DEFAULT 'dicebear:croodles-neutral:' || gen_random_uuid()::text;+ ```++**Verify:**+```bash+ls packages/database/supabase/migrations | grep user-generated-avatar-default+# Expected: one file name+```++**Out of scope:** applying the migration; a backfill of existing rows.++## Task 2: Add the generated-avatar string helpers to `@carbon/utils`++**Depends on:** none+**Files:**+- Create: `packages/utils/src/avatar.ts`, `packages/utils/src/avatar.test.ts`+- Modify: `packages/utils/src/index.ts` — add `export * from "./avatar";`++**Steps:**+1. Export `GENERATED_AVATAR_STYLE = "croodles-neutral"`.+2. Export `GENERATED_AVATAR_PREFIX = "dicebear:croodles-neutral:"`.+3. Export `isGeneratedAvatar(value: string | null | undefined): value is string`. It is true when the value starts with the prefix and the seed matches `/^[A-Za-z0-9-]{1,64}$/`.+4. Export `parseGeneratedAvatar(value)`, which returns `{ style, seed }` or `null`.+5. Export `newGeneratedAvatar()`, which returns the prefix plus `crypto.randomUUID()`.+6. Write tests for a valid value, a storage path, `null`, an empty seed and a seed with `/`.+7. Run the license header fixer.++**Verify:**+```bash+pnpm --filter @carbon/utils exec vitest run src/avatar.test.ts+# Expected: all tests pass+```++## Task 3: Render generated avatars in the `@carbon/react` `Avatar`++**Depends on:** Task 2+**Files:**+- Modify: `packages/react/package.json` — add `@dicebear/core` `9.4.2` and `@dicebear/croodles-neutral` `9.4.2` to `dependencies`+- Create: `packages/react/src/utils/generatedAvatar.ts`, `packages/react/src/__tests__/generatedAvatar.test.ts`+- Modify: `packages/react/src/Avatar.tsx`++**Steps:**+1. Run `pnpm --filter @carbon/react add @dicebear/[email protected] @dicebear/[email protected]`.+2. In `generatedAvatar.ts`, export `generatedAvatarDataUri(value: string): string | undefined`.+3. Return `undefined` when `parseGeneratedAvatar(value)` is `null`.+4. Else call `createAvatar(croodlesNeutral, { seed, radius: 0 }).toDataUri()`. The SVG has no background.+5. Cache each result in a module-level `Map`, keyed by the value.+6. In `Avatar.tsx`, compute `imageSrc` with `useMemo`: the data URI for a generated value, else `src`.+7. Use `imageSrc` for the `<img>`. Keep the `onError` fallback.+ For a line-art avatar, add the classes `bg-white border-black/10`. For a color style, add `bg-muted border-transparent`.+8. Test: the same value gives the same string, the string starts with `data:image/svg+xml`, and a storage path gives `undefined`.++**Verify:**+```bash+pnpm --filter @carbon/react exec vitest run src/__tests__/generatedAvatar.test.ts+# Expected: all tests pass+```++**Out of scope:** the `@carbon/react` barrel (`src/index.tsx`).++## Task 4: Pass generated values through the app `Avatar` wrappers++**Depends on:** Task 2+**Files:**+- Modify: `apps/erp/app/components/Avatar.tsx`, `apps/mes/app/components/Avatar.tsx`, `apps/academy/app/components/Avatar.tsx`++**Steps:**+1. In each wrapper, if `isGeneratedAvatar(path)` is true, pass `path` as `src`.+2. Else keep the current `getStoragePath(bucket, path)` behavior.+3. In the ERP wrapper, keep `imageUrl` first.++**Verify:** Task 8 typechecks.++## Task 5: Stop the invite flows from overwriting the default++**Depends on:** none+**Files:**+- Modify: `apps/erp/app/modules/users/users.server.ts`++**Steps:**+1. Change the `createUser` parameter to `Omit<User, "fullName" | "avatarUrl">`.+2. Change the `insertUser` parameter to `Omit<User, "fullName" | "createdAt" | "avatarUrl">`.+3. Delete `avatarUrl: null` from the 3 `createUser` calls.+4. Delete `avatarUrl: null` from the `createConsoleOperator` insert.++**Verify:**+```bash+grep -n "avatarUrl: null" apps/erp/app/modules/users/users.server.ts+# Expected: no output+```++## Task 6: Check the avatar value in the profile action++**Depends on:** Task 2+**Files:**+- Modify: `apps/erp/app/routes/x+/account+/profile.tsx`++**Steps:**+1. In the `photo` intent, read `path` from the form.+2. If `isAllowedAvatarValue(userId, path)` is false, redirect with the flash "Invalid avatar path".+3. Read the current value with `getAccount`. Log a read error.+4. Save the new value with `updateAvatar`.+5. If the old value passes `isOwnAvatarUpload` and differs from the new one, delete it from the `avatars` bucket.+6. If the delete fails, log it and continue.+7. Remove the `null` branch and the "Removed avatar" message.++**Verify:** Task 8 typechecks.++## Task 7: Add the picker and the new Remove behavior to the profile page++**Depends on:** Tasks 2, 3, 6+**Files:**+- Create: `apps/erp/app/modules/account/ui/Profile/GeneratedAvatarPicker.tsx`+- Modify: `apps/erp/app/modules/account/ui/Profile/ProfilePhotoForm.tsx`+- Copy from (precedent): `apps/erp/app/modules/users/ui/components/RevokeInviteModal.tsx` (Modal shape)++**Steps:**+1. Build `GeneratedAvatarPicker` with props `isOpen`, `current`, `onClose`, `onSave(value)`.+2. Keep 12 options in state. The first is `current` when it is a generated value.+3. Shuffle replaces the other 11 with `newGeneratedAvatar()` values.+4. Render each option as a `button` with an `Avatar` (`size="lg"`, `src={value}`) in a 4-column grid.+5. Give the selected option a ring. Give each button an `aria-label` and `aria-pressed`.+6. Show the credit line with links to the Figma source and CC BY 4.0.+7. In `ProfilePhotoForm`, add a "Choose avatar" button that opens the picker.+8. On save, submit the value. The action deletes a replaced upload (Task 6).+9. Show Remove only for an uploaded photo. Remove submits `newGeneratedAvatar()`.+10. Show "Change" on the upload button when an uploaded photo exists, else "Upload".++**Verify:** Task 8 typechecks and lints.++## Task 8: Update docs and run the final gates++**Depends on:** Tasks 1–7+**Files:**+- Modify: `packages/react/AGENTS.md` — one line on generated avatar values++**Steps:**+1. Add the `Avatar` note to `packages/react/AGENTS.md`.+2. Run the gates below.++**Verify:**+```bash+pnpm --filter @carbon/checks license-headers+pnpm exec biome check packages/utils/src/avatar.ts packages/utils/src/avatar.test.ts packages/react/src/Avatar.tsx packages/react/src/utils/generatedAvatar.ts packages/react/src/__tests__/generatedAvatar.test.ts apps/erp/app/components/Avatar.tsx apps/mes/app/components/Avatar.tsx apps/academy/app/components/Avatar.tsx apps/erp/app/modules/users/users.server.ts apps/erp/app/routes/x+/account+/profile.tsx apps/erp/app/modules/account/ui/Profile+# Expected: no errors+pnpm exec turbo run typecheck --filter=@carbon/utils --filter=@carbon/react --filter=erp --filter=mes --filter=academy+# Expected: all tasks successful+```diff --git a/.ai/runs/2026-10-08-dicebear-avatars.md b/.ai/runs/2026-10-08-dicebear-avatars.mdnew file mode 100644index 0000000000..8b6fe12143--- /dev/null+++ b/.ai/runs/2026-10-08-dicebear-avatars.md@@ -0,0 +1,36 @@+# Feature run: Generated avatars (DiceBear Croodles Neutral)++- Date: 2026-10-08+- Mode: fully-autonomous+- Request: "i wanna implement the https://www.dicebear.com/introduction/ for the user so they can set it from this and can upload their own just like before, it will automatically create a randome avatar when new user signs up. and use Croodles Neutral from the dicebear"+- Phase plan: research [skip — not ERP-domain logic, and the request is clear] · spec [run — the change touches the DB, 3 apps, `@carbon/react` and the invite flows] · plan [run] · execute [run] · test [skip — the user chose no browser test and verifies by hand] · self-review [run]++## Decisions+- Plan approval gate: approved — every task maps to a spec criterion, and the plan has no schema change beyond one column default — 2026-10-08+- Picker location: ERP profile module, not `@carbon/react` — only the ERP uses it, and a barrel change is Ask-First in `packages/react/AGENTS.md` — 2026-10-08+- Mode and phases: fully autonomous, spec → plan → execute → self-review — user answer — 2026-10-08+- Avatar source: bundled `@dicebear/core@9` + `@dicebear/croodles-neutral@9`, not the HTTP API — user answer (this approves the new production dependencies) — 2026-10-08+- Existing users: no backfill. Only new users get a generated avatar — user answer — 2026-10-08+- Remove photo: switch to a new random generated avatar — user answer — 2026-10-08+- Commits: execute does NOT commit. The user's standing rule says "never commit without an explicit ask". The work stays uncommitted for review — 2026-10-08+- Local database: execute does NOT apply the migration. The user's standing rule says "no DB writes without asking". The column default does not change the generated types — 2026-10-08+- Avatar background: a color that contrasts with the theme, black on the light theme and white on the dark theme. This replaces the 5 pastel colors. `Avatar` applies it with `bg-white invert dark:invert-0` — user request — 2026-10-08+- Avatar styles: a style select with 10 styles (user request). DiceBear moves from 9 to 10, because Loops, Voxel Art, Voxel Bot and Planets exist only in version 10. New users keep Croodles Neutral — 2026-10-08+- Line-art avatars: black lines on white in both themes, no invert — user request — 2026-10-08+- Background color: user picks one per avatar with the ERP `ColorPicker`; stored as an optional `:<rrggbb>` value segment; dark backgrounds switch the neutral line styles to white ink — user request — 2026-10-08++## Phase log+- spec: written at `.ai/specs/2026-10-08-dicebear-avatars.md`. All 4 questions answered by the user before writing. STE-80 pass done.+- plan gate: auto-approved (autonomous mode). Plan at `.ai/plans/2026-10-08-dicebear-avatars.md`. STE-80 pass done.++- execute: Tasks 1–8 done, not committed. Gates: Biome clean on the changed files. Typecheck passes for `@carbon/utils`, `@carbon/react`, `erp`, `mes` and `academy`. Tests: `@carbon/utils` 611/611, `@carbon/react` 57/57, `@carbon/checks` 278/278. The DB invariants script did not run, because it needs `DATABASE_URL`.+- self-review: done. One stale doc line fixed (`account.mdx`). The other findings went to the user.+- self-review 2 (user asked to fix): 5 findings fixed. (1) The action now saves first, then deletes the replaced upload; the client deleted before the save. (2) The early "Photo removed" toast is gone. (3) The 5 picker strings are in the 13 `erp.po` catalogs, translated. (4) `Avatar` retries a new `src` after a failure. (5) `isAllowedAvatarValue` / `isOwnAvatarUpload` are in `@carbon/utils` with tests. Gates: Biome clean; typecheck passes for 6 tasks (`@carbon/utils`, `@carbon/react`, `erp`, `mes`, `academy`); tests `@carbon/utils` 614/614, `@carbon/react` 60/60. Not fixed: a database guard on `avatarUrl` (Ask-First, schema on `user`).+- styles: done. `@dicebear/[email protected]` + `@dicebear/[email protected]` replace the 9.4.2 packages. Each style is a lazy chunk. Gates: Biome clean on the changed files; typecheck passes for 6 tasks; tests `@carbon/utils` 616/616, `@carbon/react` 71/71; 3 new strings translated in 12 locales.++- background color: done. Gates: Biome clean on changed files; typecheck passes for 6 tasks; tests `@carbon/utils` 620/620, `@carbon/react` 74/74; 2 new strings translated in 12 locales.++- self-review 3 (user asked to fix the must-fix and suggestions): the DiceBear core loads lazily (renderer entry 2.5 KB in a split bundle); `generatedAvatarClassName` and `avatarSrc` extracted with tests; the order-dependent test isolated with `vi.resetModules`; the profile action has 6 tests (a delete-before-save mutation fails 4 of them). Docs: 2 lessons, both AGENTS notes, the spec.++## Outcome+- Uncommitted on `naveenkash/75pu7`. The migration is not applied. The user commits and applies it.diff --git a/.ai/specs/2026-10-08-dicebear-avatars.md b/.ai/specs/2026-10-08-dicebear-avatars.mdnew file mode 100644index 0000000000..97c9671da0--- /dev/null+++ b/.ai/specs/2026-10-08-dicebear-avatars.md@@ -0,0 +1,226 @@+# Generated avatars (DiceBear)++> Status: in-progress+> Author: naveenkash+> Date: 2026-10-08++## TLDR++Each new user gets a random generated avatar in the DiceBear "Croodles+Neutral" style. On the profile page, a user can choose one of 10 DiceBear+styles and pick an avatar in it, or upload a photo as before. `user.avatarUrl`+holds either a storage path (an uploaded photo) or a generated-avatar value+(`dicebear:<style>:<seed>`, with an optional `:<rrggbb>` background). A column default creates the value, so+every path that inserts a `user` row gets an avatar with no app code. The+avatar renders in the browser from the bundled DiceBear library. No request+goes to a third party.++## Overview diagram++```mermaid+flowchart LR+ subgraph Before+ B1["user row: avatarUrl null"] --> B2["Avatar wrapper"]+ B2 --> B3["initials on a color"]+ B4["avatarUrl = storage path"] --> B2+ B2 --> B5["public storage URL"]+ end+ subgraph After+ A1["user row: column default"]:::hot --> A2["Avatar wrapper"]:::hot+ A2 --> A3["DiceBear SVG data URI"]:::new+ A4["avatarUrl = storage path"] --> A2+ A2 --> A5["public storage URL"]+ A6["Profile: choose avatar"]:::new --> A1+ end+ classDef hot stroke-width:3px+ classDef new stroke-dasharray:4 3+```++## Problem Statement++A user without an uploaded photo shows initials on a colored circle. Most users+never upload a photo, so lists of people look the same and give no visual+identity. The request is:++1. Each new user gets a random avatar automatically.+2. A user can choose a different generated avatar.+3. A user can still upload a photo, as before.+4. New users get DiceBear "Croodles Neutral".+5. The user can choose from 10 styles: Croodles Neutral, Notionists,+ Notionists Neutral, Lorelei, Lorelei Neutral, Loops, Pixel Art, Voxel Art,+ Voxel Bot and Planets.++## Proposed Solution++### How a value is stored++`user.avatarUrl` keeps its type (`TEXT`, nullable). It now holds one of 3+values:++| Value | Example | Meaning |+|-------|---------|---------|+| A storage path | `5f0c…e1.webp` | An uploaded photo in the public `avatars` bucket (no change) |+| A generated-avatar value | `dicebear:croodles-neutral:0b6f…9a` | An avatar in that style from that seed. The style is one of `GENERATED_AVATAR_STYLES` |+| A generated-avatar value with a background | `dicebear:voxel-art:0b6f…9a:1e3a8a` | The same, on that background color (lowercase hex, no `#`). Without the segment the style uses its own background |+| `NULL` | — | An existing user with no avatar. Initials show, as before |++A storage path never contains `:`, because the upload names the file+`${userId}.${ext}`. So the prefix `dicebear:` cannot collide with a path.++### Where the code lives++| Unit | Location | Job |+|------|----------|-----|+| `GENERATED_AVATAR_STYLES`, `parseGeneratedAvatar`, `isGeneratedAvatar`, `newGeneratedAvatar(style?)`, `isAllowedAvatarValue` | `packages/utils/src/avatar.ts` (exported from `@carbon/utils`) | Pure string helpers. Server and client code use them. No DiceBear import |+| `STYLE_LOADERS`, `loadGeneratedAvatarStyle`, `generatedAvatarDataUri`, `useGeneratedAvatar`, `generatedAvatarClassName` | `packages/react/src/utils/generatedAvatar.ts` | Loads the DiceBear core and each style's JSON definition as separate chunks on first use. Renders `new Avatar(style, { seed }).toDataUri()` and caches the result per value. Picks the image classes per style |+| `Avatar` | `packages/react/src/Avatar.tsx` | If `src` is a generated-avatar value, renders the data URI. Shows a plain circle while the style loads |+| `GeneratedAvatarPicker` | `apps/erp/app/modules/account/ui/Profile/GeneratedAvatarPicker.tsx` | Modal with a style `Select`, a grid of generated options, a Shuffle button and the credit for the selected style. Each option is an `Avatar` with the value as `src`, so the `@carbon/react` barrel does not change |+| `avatarSrc` + app `Avatar` wrappers | `packages/utils/src/avatar.ts`, `apps/{erp,mes,academy}/app/components/Avatar.tsx` | `avatarSrc` passes a generated-avatar value through as `src` and turns a storage path into a URL. The 3 wrappers call it |++### Rendering options++`generatedAvatarDataUri` passes the `seed` to DiceBear. If the value has a+background, it also passes `backgroundColor`. If that background is dark+(`isDarkBackground`, by WCAG contrast), the 3 styles that draw lines straight+onto the background (Croodles Neutral, Notionists Neutral, Lorelei Neutral) get+white ink, so the face stays visible. Notionists and Lorelei paint a white face+first and need no change. A background never changes the face. Rendered+avatars sit in one cache, capped at 300 and evicted least recently used,+because a drag in the color picker makes a new value at each step.++A style definition is 10 KB to 370 KB of JSON, and `Avatar` renders on every+page. So `STYLE_LOADERS` imports each style with a dynamic `import()`, and the+bundler makes each one a separate chunk. The browser fetches a style the first+time it shows an avatar in that style. The DiceBear core (about 25 KB gzipped)+loads the same way, with the first style, so a page with no generated avatar+downloads none of it.++`useGeneratedAvatar` reads the state through `useSyncExternalStore`:++| State | When | `Avatar` shows |+|-------|------|----------------|+| `loading` | The server render, and the browser until the style arrives | A plain `bg-muted` circle. The initials do not flash |+| `ready` | The style is loaded | The data URI |+| `failed` | The style chunk did not load | The initials. The next avatar that mounts tries the load again |++The 10 styles fall into 2 groups. `generatedAvatarClassName` picks the classes:++| Group | Styles | Classes on the image | Light theme | Dark theme |+|-------|--------|----------------------|-------------|------------|+| Line art | Croodles Neutral, Notionists, Notionists Neutral, Lorelei, Lorelei Neutral | `bg-white border-black/10` | Black lines on white | Black lines on white |+| Color | Loops, Pixel Art, Voxel Art, Voxel Bot, Planets | `bg-muted border-transparent` | The style's own colors | The style's own colors |++Line-art avatars stay light in both themes (user request). Pixel Art has no+background of its own, so it shows on `bg-muted`.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Source of the artwork | Bundled `@dicebear/[email protected]` + `@dicebear/[email protected]` in `@carbon/react` | User answer. Works on self-hosted, offline and controlled-environment installs. No user data goes to a third party |+| DiceBear major version | 10, pinned exactly | Loops, Voxel Art, Voxel Bot and Planets exist only in version 10. A new major version can give a different face for the same seed, so the versions are exact, not ranges. `@dicebear/core@10` needs Node 22, which every workflow in the repo uses |+| Style list | Only ever add to `GENERATED_AVATAR_STYLES` | A removed style makes its existing values unparseable, and those avatars fall back to initials. The `Record` type of `STYLE_LOADERS` makes a style without a loader a type error |+| Where the value is stored | In `user.avatarUrl` with the `dicebear:` prefix | 26 migrations put `avatarUrl` into views and RPCs. A new column would need a change to each of them. The prefix needs none |+| How a new user gets a value | Column default on `user.avatarUrl` | One place covers all 6 insert paths: the `create_public_user` trigger, invites, console operators, `migrateUserToSso`, seed and bootstrap |+| Seed of the default | `gen_random_uuid()::text` | The request is a random avatar. A random seed does not reveal the user id. The client uses `crypto.randomUUID()` for the same format |+| Existing users | No backfill | User answer. They keep initials until they choose an avatar |+| Remove photo | Save a new random generated-avatar value | User answer. Every user who touches the profile ends with an avatar |+| Delete of the replaced photo | The profile action deletes the old upload AFTER it saves the new value. It deletes only a path that `isOwnAvatarUpload` accepts and that differs from the new value | If the save fails, `avatarUrl` still points at a file that exists. A failed delete only leaves an orphan file, so the action logs it. The same step also removes an old upload with a different file extension |+| Server check of the value | The `photo` intent accepts only a value that `isAllowedAvatarValue(userId, value)` accepts: a generated-avatar value, or `${userId}.<ext>` with no `/` | Today the action stores any string. The new check stops a user from storing a path to another user's file. Unit tests pin the helper |+| License credit | The picker shows the selected style's source, artist and license, with links | Croodles is CC BY 4.0, which requires attribution. The 9 other styles are CC0 1.0 and get the credit as a courtesy. The text comes from each style's DiceBear `meta`, so the ERP needs no DiceBear import |+| Invite upserts | Remove `avatarUrl: null` from `createUser` and `createConsoleOperator` | The upsert runs after the trigger. With `null` it overwrites the default |+| Multi-tenancy | No change | `user` is not company-scoped. No new table |+| RLS | No change | The "Users can modify themselves" UPDATE policy already covers `avatarUrl` |+| Service shape | `updateAvatar` keeps `client` first and returns `{ data, error }` | No new service function |+| Form pattern | No `ValidatedForm` | The photo intent is a `useSubmit` post today. The picker posts the same intent |+| Backward compatibility | `avatarUrl` keeps its type. Old storage paths render as before | Callers that pass `avatarUrl` as a raw `src` start to show generated avatars. Uploaded photos at those callers still fail to load, as today |++## Data Model Changes++One migration. It changes only the column default. It writes no rows.++```sql+ALTER TABLE "user"+ ALTER COLUMN "avatarUrl"+ SET DEFAULT 'dicebear:croodles-neutral:' || gen_random_uuid()::text;+```++The generated types do not change, because `avatarUrl` is already nullable and+optional on insert.++## API / Service Changes++- `apps/erp/app/routes/x+/account+/profile.tsx`, `intent=photo`: reject a+ missing `path`. Accept the path only if `isGeneratedAvatar(path)` is true or+ the path starts with `${userId}.`. Else flash "Invalid avatar path".+- `apps/erp/app/modules/users/users.server.ts`: `createUser` and `insertUser`+ take `Omit<User, "fullName" | "avatarUrl">`. The 3 invite calls and+ `createConsoleOperator` stop passing `avatarUrl: null`.++## UI Changes++Profile page, `ProfilePhotoForm` (`apps/erp/app/modules/account/ui/Profile/`):++| Control | Shows when | Action |+|---------|------------|--------|+| Avatar preview | Always | Renders the current value |+| Upload / Change | Always | No change: crop, upload, save the path |+| Choose avatar | Always | Opens a `Modal` with `GeneratedAvatarPicker`. Save submits the selected value |+| Remove | The value is an uploaded photo | Submits `newGeneratedAvatar()`. The action deletes the photo after the save |++`GeneratedAvatarPicker` opens on the style of the current value, or on Croodles+Neutral. A `Select` above the grid changes the style and deals 12 new options in+it. The options show in a 4-column grid. In the current value's style, the+first option is the current value. Shuffle replaces the other options with new+random seeds. A Background row (the ERP `ColorPicker`, empty = "Style+default", with a Reset button) sets one color for the whole grid. The+selected option has a ring. The credit line for the selected+style is under the grid.++## Acceptance Criteria++- [ ] After the migration, `INSERT INTO "user" ("id","email","firstName","lastName","about") VALUES (…)` gives a row whose `avatarUrl` starts with `dicebear:croodles-neutral:`.+- [ ] A new user from an employee invite has a `dicebear:croodles-neutral:` value after `createEmployeeAccount` returns.+- [ ] A user with a generated-avatar value sees a Croodles avatar in the ERP top-right menu, in the people lists and in the MES user menu.+- [ ] A user with an uploaded photo still sees the photo in the ERP.+- [ ] On the profile page, Choose avatar → select an option → Save shows the new avatar after the redirect.+- [ ] On the profile page, Remove on an uploaded photo deletes the file from the `avatars` bucket and shows a generated avatar.+- [ ] A post of `intent=photo` with `path=someone-else.webp` flashes "Invalid avatar path" and does not change the row.+- [ ] An existing user with `avatarUrl` `NULL` still sees initials.+- [ ] `packages/utils` unit tests cover `isGeneratedAvatar`, `parseGeneratedAvatar` and `newGeneratedAvatar`.+- [ ] `packages/react` unit tests show that `generatedAvatarDataUri` returns the same data URI for the same value and a `data:image/svg+xml` prefix.+- [ ] A `packages/react` unit test loads and renders each of the 10 styles from `@dicebear/styles`.+- [ ] A unit test of the profile action shows the save runs before the delete of the replaced upload, and a failed save deletes nothing.+- [ ] In the picker, a change of style shows 12 avatars in the new style, and Save stores a `dicebear:<style>:<seed>` value.++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| A list with many avatars generates many SVGs | Low | A module-level cache keys each data URI by value, so each value generates once per page load |+| A large style definition slows the first page | Low | Each style is its own chunk, fetched only when an avatar in that style shows. Notionists is the largest at 370 KB of JSON |+| The DiceBear core enlarges every page | Med | `Avatar` is in every app shell, and the core is about 25 KB gzipped. It is never imported statically: it loads with the first style (`import()`). A split bundle shows the renderer entry at 2.5 KB |+| Non-React code reads `avatarUrl` as a storage path | Low | A repo search finds no non-React reader. The Jira type and the workflow catalog list only the column name |+| An invite of an existing user overwrites the avatar | Low | `createUser` runs only on the new-user branch, and no longer sends `avatarUrl` |+| CC BY 4.0 credit missing | Med | The picker shows the credit. Self-review checks it |+| The default runs inside the GoTrue transaction | Low | `gen_random_uuid()` is built in and cannot fail |++## Open Questions++- [x] Should the avatar art come from the bundled library or the HTTP API? — **Answer:** the bundled library (user). This approves the 2 new production dependencies.+- [x] Do existing users with no avatar get a generated avatar? — **Answer:** no backfill. Only new users (user).+- [x] What does Remove do on an uploaded photo? — **Answer:** it saves a new random generated avatar (user).+- [x] Which pipeline mode? — **Answer:** fully autonomous, spec → plan → execute → self-review, no browser test (user).+- [x] Can a user set the background color? — **Answer:** yes, with a color picker; the default stays each style's own background (user).+- [x] Which styles can a user choose? — **Answer:** Croodles Neutral, Notionists, Notionists Neutral, Lorelei, Lorelei Neutral, Loops, Pixel Art, Voxel Art, Voxel Bot and Planets (user). New users keep Croodles Neutral.++## Changelog++- 2026-10-08: Spec written. All 4 questions answered by the user before writing.+- 2026-10-08: Background changed from 5 pastel colors to a color that contrasts with the theme: black on the light theme, white on the dark theme (user request). The `Avatar` component applies it with CSS.+- 2026-10-08: Self-review fixes. The action saves the new value, then deletes the replaced upload (it was the client, before the save). `isAllowedAvatarValue` and `isOwnAvatarUpload` moved into `@carbon/utils` with tests. `Avatar` retries a new `src` after an earlier one failed. The 5 picker strings are in the 13 `erp.po` catalogs.+- 2026-10-08: Style select added (user request): 10 styles. DiceBear moved from version 9 to 10, because 4 of the styles exist only in version 10. Each style loads as its own chunk. Line-art styles keep the theme invert; color styles keep their colors.+- 2026-10-08: Line-art avatars no longer invert on the light theme (user request). They are black lines on white in both themes.+- 2026-10-08: Background color picker added (user request). The value gains an optional `:<rrggbb>` segment; old values still parse. The avatar cache is now a capped LRU.+- 2026-10-08: Self-review 3 fixes. The DiceBear core loads with the first style, not on every page. `generatedAvatarClassName` and `avatarSrc` replace inline logic and have tests. The profile action has a test for the save-then-delete order. Two lessons added to `.ai/lessons.md`.+- 2026-10-08: Implemented (uncommitted). The picker lives in the ERP account module. The account reference doc (`docs/content/docs/reference/account.mdx`) describes the new Photo behavior.diff --git a/apps/academy/app/components/Avatar.tsx b/apps/academy/app/components/Avatar.tsxindex 139174a565..665ba5dcb2 100644--- a/apps/academy/app/components/Avatar.tsx+++ b/apps/academy/app/components/Avatar.tsx@@ -4,6 +4,7 @@import type { AvatarProps as AvatarBaseProps } from "@carbon/react";import { Avatar as AvatarBase } from "@carbon/react";+import { avatarSrc } from "@carbon/utils";import { forwardRef } from "react";import { getStoragePath } from "~/utils/path";@@ -14,7 +15,7 @@ type AvatarProps = AvatarBaseProps & {const Avatar = forwardRef<HTMLSpanElement, AvatarProps>(({ name, path, bucket = "avatars", ...props }, ref) => {- const imagePath = path ? getStoragePath(bucket, path) : undefined;+ const imagePath = avatarSrc(path, (value) => getStoragePath(bucket, value));return <AvatarBase src={imagePath} name={name} ref={ref} {...props} />;}diff --git a/apps/erp/app/components/Avatar.tsx b/apps/erp/app/components/Avatar.tsxindex be059e2b3b..4fd9fed1b2 100644--- a/apps/erp/app/components/Avatar.tsx+++ b/apps/erp/app/components/Avatar.tsx@@ -4,6 +4,7 @@import type { AvatarProps as AvatarBaseProps } from "@carbon/react";import { Avatar as AvatarBase } from "@carbon/react";+import { avatarSrc } from "@carbon/utils";import { forwardRef } from "react";import { getStoragePath } from "~/utils/path";@@ -15,11 +16,8 @@ type AvatarProps = AvatarBaseProps & {const Avatar = forwardRef<HTMLSpanElement, AvatarProps>(({ name, path, bucket = "avatars", imageUrl, ...props }, ref) => {- const finalImageUrl = imageUrl- ? imageUrl- : path- ? getStoragePath(bucket, path)- : undefined;+ const finalImageUrl =+ imageUrl || avatarSrc(path, (value) => getStoragePath(bucket, value));return <AvatarBase src={finalImageUrl} name={name} ref={ref} {...props} />;}diff --git a/apps/erp/app/components/ColorPicker.tsx b/apps/erp/app/components/ColorPicker.tsxindex b25af1c85f..05c2ec2e68 100644--- a/apps/erp/app/components/ColorPicker.tsx+++ b/apps/erp/app/components/ColorPicker.tsx@@ -29,11 +29,15 @@ const SWATCHES = [export function ColorPicker({value,- onChange+ onChange,+ placeholder}: {+ /** A hex color, or `""` for no color (pass `placeholder` to label it). */value: string;onChange: (value: string) => void;+ placeholder?: string;}) {+ const isEmpty = value === "";return (<Popover><PopoverTrigger asChild>@@ -42,18 +46,25 @@ export function ColorPicker({className="flex h-9 w-full items-center gap-2 rounded-md border border-input bg-background px-2 text-sm outline-none transition-colors focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"><span- className="size-5 shrink-0 rounded ring-1 ring-inset ring-black/10"- style={{ backgroundColor: value }}+ className={cn(+ "size-5 shrink-0 rounded ring-1 ring-inset ring-black/10",+ isEmpty && "bg-muted"+ )}+ style={isEmpty ? undefined : { backgroundColor: value }}/>- <span className="font-mono text-xs uppercase text-foreground">- {value}- </span>+ {isEmpty ? (+ <span className="text-xs text-muted-foreground">{placeholder}</span>+ ) : (+ <span className="font-mono text-xs uppercase text-foreground">+ {value}+ </span>+ )}</button></PopoverTrigger><PopoverContent align="start" className="w-[232px] p-3"><div className="flex flex-col gap-3"><HexColorPicker- color={value}+ color={isEmpty ? "#ffffff" : value}onChange={onChange}style={{ width: "100%", height: 150 }}/>diff --git a/apps/erp/app/modules/account/ui/Profile/GeneratedAvatarPicker.tsx b/apps/erp/app/modules/account/ui/Profile/GeneratedAvatarPicker.tsxnew file mode 100644index 0000000000..3cfcd7a754--- /dev/null+++ b/apps/erp/app/modules/account/ui/Profile/GeneratedAvatarPicker.tsx@@ -0,0 +1,321 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ Avatar,+ Button,+ cn,+ HStack,+ Modal,+ ModalBody,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@carbon/react";+import type { GeneratedAvatarStyle } from "@carbon/utils";+import {+ DEFAULT_GENERATED_AVATAR_STYLE,+ formatGeneratedAvatar,+ GENERATED_AVATAR_STYLES,+ isGeneratedAvatarStyle,+ newGeneratedAvatarSeed,+ normalizeAvatarBackground,+ parseGeneratedAvatar+} from "@carbon/utils";+import { Trans, useLingui } from "@lingui/react/macro";+import { useState } from "react";+import { LuShuffle } from "react-icons/lu";+import { ColorPicker } from "~/components/ColorPicker";++const OPTION_COUNT = 12;++const CC0 = {+ name: "CC0 1.0",+ url: "https://creativecommons.org/publicdomain/zero/1.0/"+};++// Proper names, so not translated. Credit comes from each style's DiceBear+// `meta`; Croodles (CC BY 4.0) requires it, the CC0 styles get it as courtesy.+const STYLE_INFO: Record<+ GeneratedAvatarStyle,+ {+ label: string;+ source: { name: string; url: string };+ creator: string;+ license: { name: string; url: string };+ }+> = {+ "croodles-neutral": {+ label: "Croodles Neutral",+ source: {+ name: "Croodles",+ url: "https://www.figma.com/community/file/966199982810283152"+ },+ creator: "vijay verma",+ license: {+ name: "CC BY 4.0",+ url: "https://creativecommons.org/licenses/by/4.0/"+ }+ },+ notionists: {+ label: "Notionists",+ source: {+ name: "Notionists",+ url: "https://heyzoish.gumroad.com/l/notionists"+ },+ creator: "Zoish",+ license: CC0+ },+ "notionists-neutral": {+ label: "Notionists Neutral",+ source: {+ name: "Notionists",+ url: "https://heyzoish.gumroad.com/l/notionists"+ },+ creator: "Zoish",+ license: CC0+ },+ lorelei: {+ label: "Lorelei",+ source: {+ name: "Lorelei",+ url: "https://www.figma.com/community/file/1198749693280469639"+ },+ creator: "Lisa Wischofsky",+ license: CC0+ },+ "lorelei-neutral": {+ label: "Lorelei Neutral",+ source: {+ name: "Lorelei Neutral",+ url: "https://www.figma.com/community/file/1198749693280469639"+ },+ creator: "Lisa Wischofsky",+ license: CC0+ },+ loops: {+ label: "Loops",+ source: { name: "Loops", url: "https://www.dicebear.com" },+ creator: "DiceBear",+ license: CC0+ },+ "pixel-art": {+ label: "Pixel Art",+ source: {+ name: "Pixel Art",+ url: "https://www.figma.com/community/file/1198754108850888330"+ },+ creator: "DiceBear",+ license: CC0+ },+ "voxel-art": {+ label: "Voxel Art",+ source: { name: "Voxel Art", url: "https://www.dicebear.com" },+ creator: "DiceBear",+ license: CC0+ },+ "voxel-bot": {+ label: "Voxel Bot",+ source: { name: "Voxel Bot", url: "https://www.dicebear.com" },+ creator: "DiceBear",+ license: CC0+ },+ planets: {+ label: "Planets",+ source: { name: "Planets", url: "https://www.dicebear.com" },+ creator: "DiceBear",+ license: CC0+ }+};++type GeneratedAvatarPickerProps = {+ current: string | null;+ onClose: () => void;+ onSave: (value: string) => void;+};++function randomSeeds(count: number) {+ return Array.from({ length: count }, () => newGeneratedAvatarSeed());+}++const GeneratedAvatarPicker = ({+ current,+ onClose,+ onSave+}: GeneratedAvatarPickerProps) => {+ const { t } = useLingui();+ const currentParsed = parseGeneratedAvatar(current);+ const currentGenerated = currentParsed ? current : null;++ const [style, setStyle] = useState<GeneratedAvatarStyle>(+ currentParsed?.style ?? DEFAULT_GENERATED_AVATAR_STYLE+ );+ // `null` = each style's own background.+ const [background, setBackground] = useState<string | null>(+ currentParsed?.background ?? null+ );++ // The grid holds seeds; style and background apply to all of them, so a new+ // color repaints the whole grid. In the current avatar's style its seed+ // stays first, so neither shuffling nor switching styles loses it.+ const seedsFor = (forStyle: GeneratedAvatarStyle) =>+ currentParsed && currentParsed.style === forStyle+ ? [currentParsed.seed, ...randomSeeds(OPTION_COUNT - 1)]+ : randomSeeds(OPTION_COUNT);++ const [seeds, setSeeds] = useState<string[]>(() => seedsFor(style));+ const [selectedSeed, setSelectedSeed] = useState<string | null>(+ currentParsed?.seed ?? null+ );++ const valueOf = (seed: string) =>+ formatGeneratedAvatar({ style, seed, background });+ const selected = selectedSeed ? valueOf(selectedSeed) : null;++ const changeStyle = (value: string) => {+ if (!isGeneratedAvatarStyle(value) || value === style) return;+ setStyle(value);+ setSeeds(seedsFor(value));+ setSelectedSeed(currentParsed?.style === value ? currentParsed.seed : null);+ };++ const shuffle = () => {+ setSeeds((previous) => {+ const keep = previous.filter(+ (seed) => seed === currentParsed?.seed || seed === selectedSeed+ );+ return [...keep, ...randomSeeds(OPTION_COUNT - keep.length)];+ });+ };++ const info = STYLE_INFO[style];++ return (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <ModalContent>+ <ModalHeader>+ <ModalTitle>+ <Trans>Choose avatar</Trans>+ </ModalTitle>+ <ModalDescription>+ <Trans>Pick a style and an avatar, or shuffle for new ones.</Trans>+ </ModalDescription>+ </ModalHeader>+ <ModalBody>+ <Select value={style} onValueChange={changeStyle}>+ <SelectTrigger aria-label={t`Avatar style`} className="mb-4">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {GENERATED_AVATAR_STYLES.map((option) => (+ <SelectItem key={option} value={option}>+ {STYLE_INFO[option].label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <div className="mb-4 flex items-center gap-2">+ <span className="shrink-0 text-sm text-muted-foreground">+ <Trans>Background</Trans>+ </span>+ <ColorPicker+ value={background ? `#${background}` : ""}+ onChange={(value) => {+ const color = normalizeAvatarBackground(value);+ if (color) setBackground(color);+ }}+ placeholder={t`Style default`}+ />+ {background && (+ <Button variant="ghost" onClick={() => setBackground(null)}>+ <Trans>Reset</Trans>+ </Button>+ )}+ </div>+ <div className="grid grid-cols-4 gap-3 justify-items-center">+ {seeds.map((seed, index) => {+ const isSelected = seed === selectedSeed;+ return (+ <button+ key={seed}+ type="button"+ aria-label={t`Avatar option ${index + 1}`}+ aria-pressed={isSelected}+ onClick={() => setSelectedSeed(seed)}+ className={cn(+ "rounded-full p-1 ring-2 ring-transparent transition-[box-shadow,transform] active:scale-[0.98] focus-visible:outline-none focus-visible:ring-ring",+ isSelected ? "ring-primary" : "hover:ring-border"+ )}+ >+ <Avatar size="lg" src={valueOf(seed)} />+ </button>+ );+ })}+ </div>+ <p className="mt-4 text-xs text-muted-foreground text-pretty">+ <Trans>+ Avatars from{" "}+ <a+ className="underline"+ href={info.source.url}+ target="_blank"+ rel="noreferrer"+ >+ {info.source.name}+ </a>{" "}+ by {info.creator}, licensed under{" "}+ <a+ className="underline"+ href={info.license.url}+ target="_blank"+ rel="noreferrer"+ >+ {info.license.name}+ </a>+ .+ </Trans>+ </p>+ </ModalBody>+ <ModalFooter>+ <HStack className="w-full justify-between">+ <Button+ variant="secondary"+ leftIcon={<LuShuffle />}+ onClick={shuffle}+ >+ <Trans>Shuffle</Trans>+ </Button>+ <HStack>+ <Button variant="ghost" onClick={onClose}>+ <Trans>Cancel</Trans>+ </Button>+ <Button+ isDisabled={!selected || selected === currentGenerated}+ onClick={() => {+ if (selected) onSave(selected);+ }}+ >+ <Trans>Save</Trans>+ </Button>+ </HStack>+ </HStack>+ </ModalFooter>+ </ModalContent>+ </Modal>+ );+};++export default GeneratedAvatarPicker;diff --git a/apps/erp/app/modules/account/ui/Profile/ProfilePhotoForm.tsx b/apps/erp/app/modules/account/ui/Profile/ProfilePhotoForm.tsxindex d8765ede37..33b99fae1d 100644--- a/apps/erp/app/modules/account/ui/Profile/ProfilePhotoForm.tsx+++ b/apps/erp/app/modules/account/ui/Profile/ProfilePhotoForm.tsx@@ -13,13 +13,16 @@ import {toast,VStack} from "@carbon/react";+import { isGeneratedAvatar, newGeneratedAvatar } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import type { ChangeEvent } from "react";+import { useState } from "react";import { useSubmit } from "react-router";import { Avatar } from "~/components";import { useUser } from "~/hooks";import { path } from "~/utils/path";import type { Account } from "../../types";+import GeneratedAvatarPicker from "./GeneratedAvatarPicker";const logger = getLogger("erp", "profilephotoform");@@ -34,6 +37,12 @@ const ProfilePhotoForm = ({ user }: ProfilePhotoFormProps) => {const { carbon } = useCarbon();const { company } = useUser();const submit = useSubmit();+ const [isPickerOpen, setIsPickerOpen] = useState(false);+ // `avatarUrl` is either an uploaded photo's storage path or a generated avatar.+ const uploadedPhotoPath =+ user.avatarUrl && !isGeneratedAvatar(user.avatarUrl)+ ? user.avatarUrl+ : null;const uploadImage = async (e: ChangeEvent<HTMLInputElement>) => {if (e.target.files && carbon) {@@ -82,28 +91,21 @@ const ProfilePhotoForm = ({ user }: ProfilePhotoFormProps) => {}};- const deleteImage = async () => {- if (carbon && user?.avatarUrl) {- const imageDelete = await carbon.storage- .from("avatars")- .remove([user.avatarUrl]);+ // The profile action deletes the replaced photo from storage after it saves+ // the new value, so neither of these touches storage.- if (imageDelete.error) {- const errorMessage =- imageDelete.error.message || "Failed to remove image";- toast.error(errorMessage);- return;- }+ // Removing a photo falls back to a new generated avatar, never to none.+ const removePhoto = () => submitAvatarUrl(newGeneratedAvatar());- toast.success(t`Photo removed successfully`);- submitAvatarUrl(null);- }+ const saveGeneratedAvatar = (value: string) => {+ setIsPickerOpen(false);+ submitAvatarUrl(value);};- const submitAvatarUrl = (avatarPath: string | null) => {+ const submitAvatarUrl = (avatarPath: string) => {const formData = new FormData();formData.append("intent", "photo");- if (avatarPath) formData.append("path", avatarPath);+ formData.append("path", avatarPath);submit(formData, {method: "post",action: path.to.profile,@@ -119,15 +121,25 @@ const ProfilePhotoForm = ({ user }: ProfilePhotoFormProps) => {name={user?.fullName ?? undefined}/><FileUpload accept="image/*" onChange={uploadImage}>- {user.avatarUrl ? t`Change` : t`Upload`}+ {uploadedPhotoPath ? t`Change` : t`Upload`}</FileUpload>+ <Button variant="secondary" onClick={() => setIsPickerOpen(true)}>+ <Trans>Choose avatar</Trans>+ </Button>- {user.avatarUrl && (- <Button variant="secondary" onClick={deleteImage}>+ {uploadedPhotoPath && (+ <Button variant="secondary" onClick={removePhoto}><Trans>Remove</Trans></Button>)}<Badge variant="outline">{t`${maxSizeMB}MB limit`}</Badge>+ {isPickerOpen && (+ <GeneratedAvatarPicker+ current={user.avatarUrl}+ onClose={() => setIsPickerOpen(false)}+ onSave={saveGeneratedAvatar}+ />+ )}</VStack>);};diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.tsindex f595090500..5951bf5bcb 100644--- a/apps/erp/app/modules/users/users.server.ts+++ b/apps/erp/app/modules/users/users.server.ts@@ -397,8 +397,7 @@ export async function createCustomerAccount(id: userId,email: email.toLowerCase(),firstName: firstName ?? "",- lastName: lastName ?? "",- avatarUrl: null+ lastName: lastName ?? ""});if (createCarbonUser.error) {@@ -570,8 +569,7 @@ export async function createEmployeeAccount(id: userId,email: email.toLowerCase(),firstName,- lastName,- avatarUrl: null+ lastName});if (createCarbonUser.error) {@@ -701,8 +699,7 @@ export async function createSupplierAccount(id: userId,email: email.toLowerCase(),firstName: firstName ?? "",- lastName: lastName ?? "",- avatarUrl: null+ lastName: lastName ?? ""});if (createCarbonUser.error) {@@ -762,9 +759,11 @@ export async function createSupplierAccount(return { success: true, code, userId, email };}+// `avatarUrl` is left to the column default (a generated avatar). The auth+// trigger has already inserted this row, and the upsert must not null it.async function createUser(client: SupabaseClient<Database>,- user: Omit<User, "fullName">+ user: Omit<User, "fullName" | "avatarUrl">) {const { data, error } = await insertUser(client, user);@@ -974,7 +973,7 @@ async function insertSupplierAccount(async function insertUser(client: SupabaseClient<Database>,- user: Omit<User, "fullName" | "createdAt">+ user: Omit<User, "fullName" | "createdAt" | "avatarUrl">) {return client.from("user").upsert([user]).select("*");}@@ -1021,7 +1020,6 @@ export async function createConsoleOperator(email: syntheticEmail,firstName,lastName,- avatarUrl: null,active: true,isConsoleOperator: true} as any)diff --git a/apps/erp/app/routes/x+/account+/profile.test.ts b/apps/erp/app/routes/x+/account+/profile.test.tsnew file mode 100644index 0000000000..d53c737f2e--- /dev/null+++ b/apps/erp/app/routes/x+/account+/profile.test.ts@@ -0,0 +1,122 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { requirePermissions } from "@carbon/auth/auth.server";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { getAccount, updateAvatar } from "~/modules/account";+import { action } from "./profile";++// The photo intent saves the new avatar value, then deletes the photo it+// replaced. The order is the point: deleting first and then failing the save+// left avatarUrl pointing at a file that no longer existed.++vi.mock("@lingui/core/macro", () => ({ msg: (value: unknown) => value }));+vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions: vi.fn() }));+vi.mock("@carbon/auth/session.server", () => ({+ flash: vi.fn(async () => ({}))+}));+vi.mock("@carbon/logger", () => ({+ getLogger: () => ({ error: vi.fn(), info: vi.fn(), warn: vi.fn() })+}));+vi.mock("@carbon/react", () => ({ VStack: () => null }));+vi.mock("~/modules/account/ui/Profile", () => ({ ProfileForm: () => null }));+vi.mock("~/modules/account", () => ({+ accountProfileValidator: {},+ getAccount: vi.fn(),+ updateAvatar: vi.fn(),+ updatePublicAccount: vi.fn()+}));++const USER_ID = "5f0c3d2a-1b2c-4d5e-8f90-123456789abc";+const GENERATED = "dicebear:voxel-art:3f2b8c4e-6a1d-4f7e-9b2c:1e3a8a";++const calls: string[] = [];+const remove = vi.fn(async (paths: string[]) => {+ calls.push(`remove:${paths.join(",")}`);+ return { error: null };+});++function postPhoto(path: string) {+ const body = new FormData();+ body.append("intent", "photo");+ body.append("path", path);+ return action({+ request: new Request("https://erp.example.com/x/account/profile", {+ method: "POST",+ body+ }),+ params: {},+ context: {}+ } as never);+}++async function run(path: string) {+ try {+ await postPhoto(path);+ } catch (thrown) {+ // The action ends with a thrown redirect, success or not.+ return thrown;+ }+ throw new Error("expected the action to throw a redirect");+}++describe("profile action, photo intent", () => {+ beforeEach(() => {+ calls.length = 0;+ vi.mocked(requirePermissions).mockResolvedValue({+ userId: USER_ID,+ client: { storage: { from: () => ({ remove }) } }+ } as never);+ vi.mocked(updateAvatar).mockImplementation((async (+ _client: unknown,+ _userId: string,+ value: string | null+ ) => {+ calls.push(`update:${value}`);+ return { error: null };+ }) as never);+ vi.mocked(getAccount).mockResolvedValue({+ data: { avatarUrl: `${USER_ID}.webp` },+ error: null+ } as never);+ remove.mockClear();+ });++ it("saves the generated avatar, THEN deletes the photo it replaced", async () => {+ await run(GENERATED);+ expect(calls).toEqual([`update:${GENERATED}`, `remove:${USER_ID}.webp`]);+ });++ it("keeps the photo when the save fails", async () => {+ vi.mocked(updateAvatar).mockResolvedValue({+ error: { message: "boom" }+ } as never);+ await run(GENERATED);+ expect(remove).not.toHaveBeenCalled();+ });++ it("deletes nothing when the previous avatar was generated", async () => {+ vi.mocked(getAccount).mockResolvedValue({+ data: { avatarUrl: "dicebear:croodles-neutral:abc" },+ error: null+ } as never);+ await run(GENERATED);+ expect(calls).toEqual([`update:${GENERATED}`]);+ });++ it("does not delete a photo the new upload overwrote in place", async () => {+ await run(`${USER_ID}.webp`);+ expect(calls).toEqual([`update:${USER_ID}.webp`]);+ });++ it("removes an old upload with a different extension", async () => {+ await run(`${USER_ID}.png`);+ expect(calls).toEqual([`update:${USER_ID}.png`, `remove:${USER_ID}.webp`]);+ });++ it("refuses another user's file and changes nothing", async () => {+ await run("someone-else.webp");+ expect(calls).toEqual([]);+ });+});diff --git a/apps/erp/app/routes/x+/account+/profile.tsx b/apps/erp/app/routes/x+/account+/profile.tsxindex e38dd868c0..fae143c0ca 100644--- a/apps/erp/app/routes/x+/account+/profile.tsx+++ b/apps/erp/app/routes/x+/account+/profile.tsx@@ -6,8 +6,13 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";+import { getLogger } from "@carbon/logger";import { VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";+import {+ isAllowedAvatarValue,+ isOwnAvatarUpload,+ redirect+} from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";@@ -21,6 +26,8 @@ import { ProfileForm } from "~/modules/account/ui/Profile";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";+const logger = getLogger("erp", "account-profile");+export const handle: Handle = {breadcrumb: msg`Profile`,to: path.to.profile@@ -76,32 +83,56 @@ export async function action({ request }: ActionFunctionArgs) {}if (formData.get("intent") === "photo") {- const photoPath = formData.get("path");- if (photoPath === null || typeof photoPath === "string") {- const avatarUpdate = await updateAvatar(client, userId, photoPath);- if (avatarUpdate.error) {- throw redirect(- path.to.profile,- await flash(- request,- error(avatarUpdate.error, "Failed to update avatar")- )- );- }+ const pathValue = formData.get("path");+ const photoPath = typeof pathValue === "string" ? pathValue : null;+ // A generated avatar, or the user's own upload. Anything else could point+ // at another user's file.+ if (!isAllowedAvatarValue(userId, photoPath)) {+ throw redirect(+ path.to.profile,+ await flash(request, error(null, "Invalid avatar path"))+ );+ }+ const previous = await getAccount(client, userId);+ if (previous.error) {+ logger.error("Failed to read the avatar being replaced", {+ userId,+ error: previous.error+ });+ }+ const avatarUpdate = await updateAvatar(client, userId, photoPath);+ if (avatarUpdate.error) {throw redirect(path.to.profile,await flash(request,- success(photoPath === null ? "Removed avatar" : "Updated avatar")+ error(avatarUpdate.error, "Failed to update avatar")));- } else {- throw redirect(- path.to.profile,- await flash(request, error(null, "Invalid avatar path"))- );}++ // Only after the new value is saved: drop the photo it replaced, so a+ // failed save never leaves avatarUrl pointing at a deleted file. A failed+ // delete only leaves an orphan file, so it is logged, not surfaced.+ const previousPath = previous.data?.avatarUrl;+ if (isOwnAvatarUpload(userId, previousPath) && previousPath !== photoPath) {+ const removal = await client.storage+ .from("avatars")+ .remove([previousPath]);+ if (removal.error) {+ logger.error("Failed to remove the replaced avatar photo", {+ userId,+ path: previousPath,+ error: removal.error+ });+ }+ }++ throw redirect(+ path.to.profile,+ await flash(request, success("Updated avatar"))+ );}return null;diff --git a/apps/mes/app/components/Avatar.tsx b/apps/mes/app/components/Avatar.tsxindex 139174a565..665ba5dcb2 100644--- a/apps/mes/app/components/Avatar.tsx+++ b/apps/mes/app/components/Avatar.tsx@@ -4,6 +4,7 @@import type { AvatarProps as AvatarBaseProps } from "@carbon/react";import { Avatar as AvatarBase } from "@carbon/react";+import { avatarSrc } from "@carbon/utils";import { forwardRef } from "react";import { getStoragePath } from "~/utils/path";@@ -14,7 +15,7 @@ type AvatarProps = AvatarBaseProps & {const Avatar = forwardRef<HTMLSpanElement, AvatarProps>(({ name, path, bucket = "avatars", ...props }, ref) => {- const imagePath = path ? getStoragePath(bucket, path) : undefined;+ const imagePath = avatarSrc(path, (value) => getStoragePath(bucket, value));return <AvatarBase src={imagePath} name={name} ref={ref} {...props} />;}diff --git a/docs/content/docs/reference/account.mdx b/docs/content/docs/reference/account.mdxindex b000bbf050..c8175334bd 100644--- a/docs/content/docs/reference/account.mdx+++ b/docs/content/docs/reference/account.mdx@@ -13,7 +13,7 @@ Profile information is visible to other users. The form warns: *"This informatio<Field name="First name / Last name" required>Your display name across Carbon.</Field><Field name="Phone">Optional.</Field><Field name="About">A short bio, capped at 160 characters.</Field>- <Field name="Photo">Your avatar; remove it to fall back to your initials.</Field>+ <Field name="Photo">Your avatar. Upload a photo, or pick a generated avatar with **Choose avatar**: choose a style (Croodles Neutral, Notionists, Lorelei, Loops, Pixel Art, Voxel Art, Voxel Bot, Planets and their neutral variants), then an avatar, and optionally a **Background** color (Reset returns to the style's own); Shuffle shows new ones. New users start with a random Croodles Neutral avatar, and removing an uploaded photo switches to a new one.</Field><Field name="Email">Shown but **read-only**. Your email is your sign-in identity, so changing it is handled outside these self-service settings.</Field></FieldTable>diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 9d83f8195c..01fb6d9e77 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -151783,6 +151783,8 @@ export default {type: "string"},avatarUrl: {+ default:+ "('dicebear:croodles-neutral:'::text || (gen_random_uuid())::text)",format: "text",type: "string"},diff --git a/packages/database/supabase/migrations/20261008113405_user-generated-avatar-default.sql b/packages/database/supabase/migrations/20261008113405_user-generated-avatar-default.sqlnew file mode 100644index 0000000000..7337044523--- /dev/null+++ b/packages/database/supabase/migrations/20261008113405_user-generated-avatar-default.sql@@ -0,0 +1,8 @@+-- New users get a random DiceBear Croodles Neutral avatar. The value is a+-- seed, not a storage path: @carbon/react's Avatar renders it in the browser+-- (see packages/utils/src/avatar.ts). A column default covers every path that+-- inserts a user row (the auth.users trigger, invites, console operators, SSO+-- migration, seeds). Existing rows are not changed.+ALTER TABLE "user"+ ALTER COLUMN "avatarUrl"+ SET DEFAULT 'dicebear:croodles-neutral:' || gen_random_uuid()::text;diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex 7b568f4b1a..f074b9fe03 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20261007171726",+ "schemaVersion": "20261008113405","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-07T18:06:45.508Z",+ "exportedAt": "2026-10-08T16:09:53.200Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 2d56019f6d..0f6f24269c 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -3415,9 +3415,22 @@ msgstr "Verfügbare Stunden"msgid "Available on the Business plan"msgstr "Im Business-Plan verfügbar"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "Avatar-Option {0}"++msgid "Avatar style"+msgstr "Avatar-Stil"+msgid "Avatar url"msgstr "Avatar-URL"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "Avatare aus <0>{0}</0> von {1}, lizenziert unter <1>{2}</1>."+msgid "Avg Days to Close"msgstr "Durchschn. Tage bis Abschluss"@@ -3433,6 +3446,9 @@ msgstr "Zurück zur Rückverfolgbarkeit"msgid "Backflush"msgstr "Retrograde Entnahme"+msgid "Background"+msgstr "Hintergrund"+msgid "Backup"msgstr "Sicherung"@@ -4402,6 +4418,9 @@ msgstr "Wählen Sie einen Lieferant für {0} beim Fertigungsauftrag aus"msgid "Choose another file"msgstr "Wählen Sie eine andere Datei"+msgid "Choose avatar"+msgstr "Avatar auswählen"+msgid "Choose how to add lines to this return."msgstr "Wählen Sie, wie Sie Positionen zu dieser Rückgabe hinzufügen möchten."@@ -14993,9 +15012,6 @@ msgstr "Telefon"msgid "Phone Number"msgstr "Telefonnummer"-msgid "Photo removed successfully"-msgstr "Foto erfolgreich entfernt"-msgid "Photo uploaded successfully"msgstr "Foto erfolgreich hochgeladen"@@ -15038,6 +15054,9 @@ msgstr "Wählen Sie einen Datensatztyp…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "Wählen Sie einen Schritt aus der Liste aus, um seine Details, Komponenten und Materialien zu bearbeiten."+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "Wählen Sie einen Stil und einen Avatar aus oder mischen Sie für neue."+msgid "Pick a target date to compare."msgstr "Wählen Sie ein Zieldatum zum Vergleich."@@ -19063,6 +19082,9 @@ msgstr "Dem Kunden auf der Rechnung angezeigt"msgid "Shown to the user when this rule fails."msgstr "Wird dem Benutzer angezeigt, wenn diese Regel fehlschlägt."+msgid "Shuffle"+msgstr "Mischen"+msgid "Sign in to Carbon"msgstr "Bei Carbon anmelden"@@ -19624,6 +19646,9 @@ msgstr "Stripe hat noch keinen Kunden für diesen Carbon-Kunden. Das Bestätigenmsgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe hat noch keinen Kunden für diesen Carbon-Kunden. Die Buchung wird einen auf Ihrem verbundenen Konto erstellen."+msgid "Style default"+msgstr "Standard des Stils"+msgid "Style of kanban output to show in the Kanban table"msgstr "Stil der Kanban-Ausgabe, die in der Kanban-Tabelle angezeigt werden soll"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 47d70cc63c..2c3ecfa340 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -3415,9 +3415,22 @@ msgstr "Available hours"msgid "Available on the Business plan"msgstr "Available on the Business plan"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "Avatar option {0}"++msgid "Avatar style"+msgstr "Avatar style"+msgid "Avatar url"msgstr "Avatar url"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgid "Avg Days to Close"msgstr "Avg Days to Close"@@ -3433,6 +3446,9 @@ msgstr "Back to traceability"msgid "Backflush"msgstr "Backflush"+msgid "Background"+msgstr "Background"+msgid "Backup"msgstr "Backup"@@ -4402,6 +4418,9 @@ msgstr "choose a supplier for {0} on the job"msgid "Choose another file"msgstr "Choose another file"+msgid "Choose avatar"+msgstr "Choose avatar"+msgid "Choose how to add lines to this return."msgstr "Choose how to add lines to this return."@@ -14993,9 +15012,6 @@ msgstr "Phone"msgid "Phone Number"msgstr "Phone Number"-msgid "Photo removed successfully"-msgstr "Photo removed successfully"-msgid "Photo uploaded successfully"msgstr "Photo uploaded successfully"@@ -15038,6 +15054,9 @@ msgstr "Pick a record type…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "Pick a step from the list to edit its details, components, and materials."+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "Pick a style and an avatar, or shuffle for new ones."+msgid "Pick a target date to compare."msgstr "Pick a target date to compare."@@ -19063,6 +19082,9 @@ msgstr "Shown to the customer on the invoice"msgid "Shown to the user when this rule fails."msgstr "Shown to the user when this rule fails."+msgid "Shuffle"+msgstr "Shuffle"+msgid "Sign in to Carbon"msgstr "Sign in to Carbon"@@ -19624,6 +19646,9 @@ msgstr "Stripe has no customer for this Carbon customer yet. Confirming will cremsgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgid "Style default"+msgstr "Style default"+msgid "Style of kanban output to show in the Kanban table"msgstr "Style of kanban output to show in the Kanban table"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex d111428d81..70aae2b7b2 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -3415,9 +3415,22 @@ msgstr "Horas disponibles"msgid "Available on the Business plan"msgstr "Disponible en el plan Business"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "Opción de avatar {0}"++msgid "Avatar style"+msgstr "Estilo de avatar"+msgid "Avatar url"msgstr "URL del avatar"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "Avatares de <0>{0}</0> por {1}, con licencia <1>{2}</1>."+msgid "Avg Days to Close"msgstr "Días promedio para cerrar"@@ -3433,6 +3446,9 @@ msgstr "Volver a trazabilidad"msgid "Backflush"msgstr "Consumo retroactivo"+msgid "Background"+msgstr "Fondo"+msgid "Backup"msgstr "Copia de seguridad"@@ -4402,6 +4418,9 @@ msgstr "elegir un proveedor para {0} en la orden de trabajo"msgid "Choose another file"msgstr "Elegir otro archivo"+msgid "Choose avatar"+msgstr "Elegir avatar"+msgid "Choose how to add lines to this return."msgstr "Elija cómo agregar líneas a esta devolución."@@ -14993,9 +15012,6 @@ msgstr "Teléfono"msgid "Phone Number"msgstr "Número de Teléfono"-msgid "Photo removed successfully"-msgstr "Foto eliminada correctamente"-msgid "Photo uploaded successfully"msgstr "Foto cargada exitosamente"@@ -15038,6 +15054,9 @@ msgstr "Elige un tipo de registro…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "Seleccione un paso de la lista para editar sus detalles, componentes y materiales."+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "Elige un estilo y un avatar, o mezcla para ver otros nuevos."+msgid "Pick a target date to compare."msgstr "Selecciona una fecha objetivo para comparar."@@ -19063,6 +19082,9 @@ msgstr "Se muestra al cliente en la factura"msgid "Shown to the user when this rule fails."msgstr "Mostrado al usuario cuando falla esta regla."+msgid "Shuffle"+msgstr "Mezclar"+msgid "Sign in to Carbon"msgstr "Inicie sesión en Carbon"@@ -19624,6 +19646,9 @@ msgstr "Stripe aún no tiene un Cliente para este Cliente de Carbon. Confirmar cmsgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe aún no tiene un cliente para este cliente de Carbon. La contabilización creará uno en su cuenta conectada."+msgid "Style default"+msgstr "Predeterminado del estilo"+msgid "Style of kanban output to show in the Kanban table"msgstr "Estilo de salida de kanban para mostrar en la tabla Kanban"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex fce339504b..9b181e7839 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -3415,9 +3415,22 @@ msgstr "Heures disponibles"msgid "Available on the Business plan"msgstr "Disponible sur le plan Business"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "Option d’avatar {0}"++msgid "Avatar style"+msgstr "Style d’avatar"+msgid "Avatar url"msgstr "URL de l'avatar"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "Avatars issus de <0>{0}</0> par {1}, sous licence <1>{2}</1>."+msgid "Avg Days to Close"msgstr "Jours moy. pour fermer"@@ -3433,6 +3446,9 @@ msgstr "Retour à la traçabilité"msgid "Backflush"msgstr "Post-consommation"+msgid "Background"+msgstr "Arrière-plan"+msgid "Backup"msgstr "Sauvegarde"@@ -4402,6 +4418,9 @@ msgstr "choisir un fournisseur pour {0} sur l'ordre de fabrication"msgid "Choose another file"msgstr "Choisir un autre fichier"+msgid "Choose avatar"+msgstr "Choisir un avatar"+msgid "Choose how to add lines to this return."msgstr "Choisissez comment ajouter des lignes à ce retour."@@ -14993,9 +15012,6 @@ msgstr "Téléphone"msgid "Phone Number"msgstr "Numéro de téléphone"-msgid "Photo removed successfully"-msgstr "Photo supprimée avec succès"-msgid "Photo uploaded successfully"msgstr "Photo téléchargée avec succès"@@ -15038,6 +15054,9 @@ msgstr "Choisir un type d'enregistrement…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "Sélectionnez une étape dans la liste pour modifier ses détails, ses composants et ses matières."+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "Choisissez un style et un avatar, ou mélangez pour en voir de nouveaux."+msgid "Pick a target date to compare."msgstr "Choisissez une date cible pour la comparer."@@ -19063,6 +19082,9 @@ msgstr "Affiché au client sur la facture"msgid "Shown to the user when this rule fails."msgstr "Affiché à l'utilisateur quand cette règle échoue."+msgid "Shuffle"+msgstr "Mélanger"+msgid "Sign in to Carbon"msgstr "Se connecter à Carbon"@@ -19624,6 +19646,9 @@ msgstr "Stripe n'a pas encore de client pour ce client Carbon. La confirmation emsgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe n'a pas encore de client pour ce client Carbon. La comptabilisation en créera un sur votre compte connecté."+msgid "Style default"+msgstr "Par défaut du style"+msgid "Style of kanban output to show in the Kanban table"msgstr "Style de sortie kanban à afficher dans le tableau Kanban"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 1bc3f1181c..d855cd1db6 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -3415,9 +3415,22 @@ msgstr "उपलब्ध घंटे"msgid "Available on the Business plan"msgstr "बिज़नेस प्लान पर उपलब्ध"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "अवतार विकल्प {0}"++msgid "Avatar style"+msgstr "अवतार शैली"+msgid "Avatar url"msgstr "अवतार url"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "<0>{0}</0> से अवतार, {1} द्वारा, <1>{2}</1> के तहत लाइसेंस प्राप्त।"+msgid "Avg Days to Close"msgstr "बंद करने के लिए औसत दिन"@@ -3433,6 +3446,9 @@ msgstr "ट्रेसेबिलिटी पर वापस जाएं"msgid "Backflush"msgstr "बैकफ्लश"+msgid "Background"+msgstr "पृष्ठभूमि"+msgid "Backup"msgstr "बैकअप"@@ -4402,6 +4418,9 @@ msgstr "जॉब पर {0} के लिए एक आपूर्तिकरmsgid "Choose another file"msgstr "दूसरी फ़ाइल चुनें"+msgid "Choose avatar"+msgstr "अवतार चुनें"+msgid "Choose how to add lines to this return."msgstr "इस रिटर्न में पंक्तियाँ कैसे जोड़ें, यह चुनें।"@@ -14993,9 +15012,6 @@ msgstr "फोन"msgid "Phone Number"msgstr "फोन नंबर"-msgid "Photo removed successfully"-msgstr "फ़ोटो सफलतापूर्वक हटा दी गई"-msgid "Photo uploaded successfully"msgstr "फ़ोटो सफलतापूर्वक अपलोड हो गई"@@ -15038,6 +15054,9 @@ msgstr "एक रिकॉर्ड प्रकार चुनें…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "सूची से एक चरण चुनें और उसके विवरण, घटक और सामग्री संपादित करें।"+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "एक शैली और एक अवतार चुनें, या नए अवतारों के लिए शफ़ल करें।"+msgid "Pick a target date to compare."msgstr "तुलना के लिए एक लक्ष्य तारीख चुनें।"@@ -19063,6 +19082,9 @@ msgstr "चालान पर ग्राहक को दिखाया जmsgid "Shown to the user when this rule fails."msgstr "जब यह नियम विफल हो तब उपयोगकर्ता को दिखाया जाता है।"+msgid "Shuffle"+msgstr "शफ़ल करें"+msgid "Sign in to Carbon"msgstr "Carbon में साइन इन करें"@@ -19624,6 +19646,9 @@ msgstr "Stripe के पास इस Carbon ग्राहक के लिmsgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe के पास इस Carbon ग्राहक के लिए अभी कोई ग्राहक नहीं है। पोस्टिंग आपके जुड़े खाते पर एक नया ग्राहक बना देगी।"+msgid "Style default"+msgstr "शैली का डिफ़ॉल्ट"+msgid "Style of kanban output to show in the Kanban table"msgstr "कानबान तालिका में दिखाने के लिए कानबान आउटपुट की शैली"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex d390932526..3e3ecf4a6d 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -3415,9 +3415,22 @@ msgstr "Ore disponibili"msgid "Available on the Business plan"msgstr "Disponibile nel piano Business"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "Opzione avatar {0}"++msgid "Avatar style"+msgstr "Stile avatar"+msgid "Avatar url"msgstr "URL avatar"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "Avatar da <0>{0}</0> di {1}, con licenza <1>{2}</1>."+msgid "Avg Days to Close"msgstr "Giorni medi per chiudere"@@ -3433,6 +3446,9 @@ msgstr "Torna alla tracciabilità"msgid "Backflush"msgstr "Backflush"+msgid "Background"+msgstr "Sfondo"+msgid "Backup"msgstr "Backup"@@ -4402,6 +4418,9 @@ msgstr "scegli un fornitore per {0} nell'ordine di produzione"msgid "Choose another file"msgstr "Scegli un altro file"+msgid "Choose avatar"+msgstr "Scegli avatar"+msgid "Choose how to add lines to this return."msgstr "Scegli come aggiungere righe a questo reso."@@ -14993,9 +15012,6 @@ msgstr "Telefono"msgid "Phone Number"msgstr "Numero di telefono"-msgid "Photo removed successfully"-msgstr "Foto rimossa con successo"-msgid "Photo uploaded successfully"msgstr "Foto caricata con successo"@@ -15038,6 +15054,9 @@ msgstr "Scegli un tipo di record…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "Seleziona un passo dall'elenco per modificare i dettagli, i componenti e i materiali."+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "Scegli uno stile e un avatar, o mescola per vederne di nuovi."+msgid "Pick a target date to compare."msgstr "Seleziona una data di destinazione da confrontare."@@ -19063,6 +19082,9 @@ msgstr "Mostrato al cliente sulla fattura"msgid "Shown to the user when this rule fails."msgstr "Mostrato all'utente quando questa regola fallisce."+msgid "Shuffle"+msgstr "Mescola"+msgid "Sign in to Carbon"msgstr "Accedi a Carbon"@@ -19624,6 +19646,9 @@ msgstr "Stripe non ha ancora un cliente per questo cliente Carbon. La conferma nmsgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe non ha ancora un cliente per questo cliente Carbon. La registrazione ne creerà uno sul tuo account collegato."+msgid "Style default"+msgstr "Predefinito dello stile"+msgid "Style of kanban output to show in the Kanban table"msgstr "Stile dell'output kanban da mostrare nella tabella Kanban"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex e422c8ca14..4af4b7376c 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -3415,9 +3415,22 @@ msgstr "利用可能時間"msgid "Available on the Business plan"msgstr "ビジネスプランで利用可能"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "アバターの候補 {0}"++msgid "Avatar style"+msgstr "アバターのスタイル"+msgid "Avatar url"msgstr "アバターURL"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "アバターは {1} による <0>{0}</0> のもので、<1>{2}</1> でライセンスされています。"+msgid "Avg Days to Close"msgstr "平均クローズ日数"@@ -3433,6 +3446,9 @@ msgstr "トレーサビリティに戻る"msgid "Backflush"msgstr "バックフラッシュ"+msgid "Background"+msgstr "背景"+msgid "Backup"msgstr "バックアップ"@@ -4402,6 +4418,9 @@ msgstr "製造指図上の{0}の仕入先を選択してください"msgid "Choose another file"msgstr "別のファイルを選択"+msgid "Choose avatar"+msgstr "アバターを選択"+msgid "Choose how to add lines to this return."msgstr "この返品に明細を追加する方法を選択してください。"@@ -14993,9 +15012,6 @@ msgstr "電話"msgid "Phone Number"msgstr "電話番号"-msgid "Photo removed successfully"-msgstr "写真が正常に削除されました"-msgid "Photo uploaded successfully"msgstr "写真が正常にアップロードされました"@@ -15038,6 +15054,9 @@ msgstr "レコード種類を選択..."msgid "Pick a step from the list to edit its details, components, and materials."msgstr "リストからステップを選択して、その詳細、コンポーネント、および材料を編集します"+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "スタイルとアバターを選ぶか、シャッフルして新しい候補を表示します。"+msgid "Pick a target date to compare."msgstr "比較するターゲット日を選択してください。"@@ -19063,6 +19082,9 @@ msgstr "請求書で顧客に表示されます"msgid "Shown to the user when this rule fails."msgstr "このルールが失敗したときにユーザーに表示されます。"+msgid "Shuffle"+msgstr "シャッフル"+msgid "Sign in to Carbon"msgstr "Carbonにサインイン"@@ -19624,6 +19646,9 @@ msgstr "StripeにはこのCarbon得意先用のカスタマーがまだありまmsgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "StripeにはこのCarbon得意先に対応する顧客がまだありません。転記すると、接続済みアカウント上に作成されます。"+msgid "Style default"+msgstr "スタイルの既定"+msgid "Style of kanban output to show in the Kanban table"msgstr "かんばんテーブルに表示するかんばん出力のスタイル"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 54f06767ab..d647240307 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -3415,9 +3415,22 @@ msgstr "가용 시간"msgid "Available on the Business plan"msgstr "Business 플랜에서 사용 가능"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "아바타 옵션 {0}"++msgid "Avatar style"+msgstr "아바타 스타일"+msgid "Avatar url"msgstr "아바타 URL"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "아바타 출처: {1}의 <0>{0}</0>, <1>{2}</1> 라이선스."+msgid "Avg Days to Close"msgstr "평균 마감 소요일"@@ -3433,6 +3446,9 @@ msgstr "추적성으로 돌아가기"msgid "Backflush"msgstr "백플러시"+msgid "Background"+msgstr "배경"+msgid "Backup"msgstr "백업"@@ -4402,6 +4418,9 @@ msgstr "작업 지시의 {0}에 대한 공급업체를 선택하세요"msgid "Choose another file"msgstr "다른 파일을 선택하세요"+msgid "Choose avatar"+msgstr "아바타 선택"+msgid "Choose how to add lines to this return."msgstr "이 반품에 라인을 추가하는 방법을 선택하세요."@@ -14993,9 +15012,6 @@ msgstr "전화번호"msgid "Phone Number"msgstr "전화번호"-msgid "Photo removed successfully"-msgstr "사진이 삭제되었습니다"-msgid "Photo uploaded successfully"msgstr "사진이 업로드되었습니다"@@ -15038,6 +15054,9 @@ msgstr "레코드 유형 선택…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "목록에서 단계를 선택하여 세부 사항, 구성 요소 및 자재를 편집하세요."+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "스타일과 아바타를 선택하거나 섞어서 새 아바타를 보세요."+msgid "Pick a target date to compare."msgstr "비교할 목표 날짜를 선택하세요."@@ -19063,6 +19082,9 @@ msgstr "송장에서 고객에게 표시"msgid "Shown to the user when this rule fails."msgstr "이 규칙이 실패할 때 사용자에게 표시됩니다."+msgid "Shuffle"+msgstr "섞기"+msgid "Sign in to Carbon"msgstr "Carbon에 로그인"@@ -19624,6 +19646,9 @@ msgstr "Stripe에는 아직 이 Carbon 고객을 위한 고객이 없습니다.msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "이 Carbon 고객에 대한 Stripe 고객이 아직 없습니다. 전기하면 연결된 계정에 생성됩니다."+msgid "Style default"+msgstr "스타일 기본값"+msgid "Style of kanban output to show in the Kanban table"msgstr "칸반 테이블에 표시할 칸반 출력 스타일"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 104f51c811..06dcd3104d 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -3415,9 +3415,22 @@ msgstr "Dostępne godziny"msgid "Available on the Business plan"msgstr "Dostępne w planie Business"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "Opcja awatara {0}"++msgid "Avatar style"+msgstr "Styl awatara"+msgid "Avatar url"msgstr "URL avatara"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "Awatary z <0>{0}</0> autorstwa {1}, na licencji <1>{2}</1>."+msgid "Avg Days to Close"msgstr "Średnia liczba dni do zamknięcia"@@ -3433,6 +3446,9 @@ msgstr "Powrót do identyfikowalności"msgid "Backflush"msgstr "Pobranie wsteczne"+msgid "Background"+msgstr "Tło"+msgid "Backup"msgstr "Kopia zapasowa"@@ -4402,6 +4418,9 @@ msgstr "wybierz dostawcę dla {0} na zleceniu produkcyjnym"msgid "Choose another file"msgstr "Wybierz inny plik"+msgid "Choose avatar"+msgstr "Wybierz awatar"+msgid "Choose how to add lines to this return."msgstr "Wybierz sposób dodania pozycji do tego zwrotu."@@ -14993,9 +15012,6 @@ msgstr "Telefon"msgid "Phone Number"msgstr "Numer telefonu"-msgid "Photo removed successfully"-msgstr "Zdjęcie usunięte pomyślnie"-msgid "Photo uploaded successfully"msgstr "Zdjęcie przesłane pomyślnie"@@ -15038,6 +15054,9 @@ msgstr "Wybierz typ rekordu…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "Wybierz krok z listy, aby edytować jego szczegóły, komponenty i materiały."+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "Wybierz styl i awatar lub przetasuj, aby zobaczyć nowe."+msgid "Pick a target date to compare."msgstr "Wybierz docelowy termin do porównania."@@ -19063,6 +19082,9 @@ msgstr "Wyświetlane klientowi na fakturze"msgid "Shown to the user when this rule fails."msgstr "Wyświetlane użytkownikowi, gdy ta reguła się nie powiedzie."+msgid "Shuffle"+msgstr "Przetasuj"+msgid "Sign in to Carbon"msgstr "Zaloguj się do Carbon"@@ -19624,6 +19646,9 @@ msgstr "Stripe nie ma jeszcze klienta dla tego klienta Carbon. Potwierdzenie spomsgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe nie ma jeszcze klienta dla tego klienta Carbon. Księgowanie utworzy go na twoim podłączonym koncie."+msgid "Style default"+msgstr "Domyślny dla stylu"+msgid "Style of kanban output to show in the Kanban table"msgstr "Styl wyjścia kanban do wyświetlenia w tabeli Kanban"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 6e30e40234..c27033a91f 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -3415,9 +3415,22 @@ msgstr "Horas Disponíveis"msgid "Available on the Business plan"msgstr "Disponível no plano Business"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "Opção de avatar {0}"++msgid "Avatar style"+msgstr "Estilo do avatar"+msgid "Avatar url"msgstr "URL do avatar"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "Avatares de <0>{0}</0> por {1}, licenciados sob <1>{2}</1>."+msgid "Avg Days to Close"msgstr "Dias Médios para Fechar"@@ -3433,6 +3446,9 @@ msgstr "Voltar para rastreabilidade"msgid "Backflush"msgstr "Baixa automática"+msgid "Background"+msgstr "Fundo"+msgid "Backup"msgstr "Backup"@@ -4402,6 +4418,9 @@ msgstr "escolher um fornecedor para {0} na ordem de produção"msgid "Choose another file"msgstr "Escolher outro arquivo"+msgid "Choose avatar"+msgstr "Escolher avatar"+msgid "Choose how to add lines to this return."msgstr "Escolha como adicionar linhas a esta devolução."@@ -14993,9 +15012,6 @@ msgstr "Telefone"msgid "Phone Number"msgstr "Número de Telefone"-msgid "Photo removed successfully"-msgstr "Foto removida com sucesso"-msgid "Photo uploaded successfully"msgstr "Foto enviada com sucesso"@@ -15038,6 +15054,9 @@ msgstr "Escolha um tipo de registro…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "Selecione uma etapa da lista para editar seus detalhes, componentes e materiais."+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "Escolha um estilo e um avatar, ou embaralhe para ver novos."+msgid "Pick a target date to compare."msgstr "Escolha uma data de destino para comparar."@@ -19063,6 +19082,9 @@ msgstr "Mostrado ao cliente na fatura"msgid "Shown to the user when this rule fails."msgstr "Mostrado ao usuário quando esta regra falha."+msgid "Shuffle"+msgstr "Embaralhar"+msgid "Sign in to Carbon"msgstr "Entrar no Carbon"@@ -19624,6 +19646,9 @@ msgstr "Stripe não tem um cliente para este cliente do Carbon ainda. Confirmarmsgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe ainda não tem um cliente para este cliente do Carbon. A Contabilização criará um na sua conta conectada."+msgid "Style default"+msgstr "Padrão do estilo"+msgid "Style of kanban output to show in the Kanban table"msgstr "Estilo de saída do kanban para mostrar na tabela Kanban"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 83854fd9dd..8ad629f802 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -3415,9 +3415,22 @@ msgstr "Доступные часы"msgid "Available on the Business plan"msgstr "Доступно в плане Business"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "Вариант аватара {0}"++msgid "Avatar style"+msgstr "Стиль аватара"+msgid "Avatar url"msgstr "URL аватара"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "Аватары из <0>{0}</0> от {1}, лицензия <1>{2}</1>."+msgid "Avg Days to Close"msgstr "Среднее количество дней до закрытия"@@ -3433,6 +3446,9 @@ msgstr "Вернуться к прослеживаемости"msgid "Backflush"msgstr "Ретроградное списание"+msgid "Background"+msgstr "Фон"+msgid "Backup"msgstr "Резервная копия"@@ -4402,6 +4418,9 @@ msgstr "выберите поставщика для {0} в производстmsgid "Choose another file"msgstr "Выбрать другой файл"+msgid "Choose avatar"+msgstr "Выбрать аватар"+msgid "Choose how to add lines to this return."msgstr "Выберите, как добавить строки в этот возврат."@@ -14993,9 +15012,6 @@ msgstr "Телефон"msgid "Phone Number"msgstr "Номер телефона"-msgid "Photo removed successfully"-msgstr "Фото успешно удалено"-msgid "Photo uploaded successfully"msgstr "Фото успешно загружено"@@ -15038,6 +15054,9 @@ msgstr "Выберите тип записи…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "Выберите шаг из списка, чтобы изменить его детали, компоненты и материалы."+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "Выберите стиль и аватар или перемешайте, чтобы увидеть новые."+msgid "Pick a target date to compare."msgstr "Выберите целевую дату для сравнения."@@ -19063,6 +19082,9 @@ msgstr "Показано покупателю на счет-фактуре"msgid "Shown to the user when this rule fails."msgstr "Показано пользователю при ошибке этого правила."+msgid "Shuffle"+msgstr "Перемешать"+msgid "Sign in to Carbon"msgstr "Войти в Carbon"@@ -19624,6 +19646,9 @@ msgstr "В Stripe еще нет покупателя для этого покуmsgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe еще не имеет покупателя для этого покупателя Carbon. Проведение создаст его на вашем подключенном счете."+msgid "Style default"+msgstr "По умолчанию для стиля"+msgid "Style of kanban output to show in the Kanban table"msgstr "Стиль вывода канбана для отображения в таблице Канбана"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 4be6997c99..d24ead75c0 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -3415,9 +3415,22 @@ msgstr "Kullanılabilir saatler"msgid "Available on the Business plan"msgstr "Business planında kullanılabilir"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "Avatar seçeneği {0}"++msgid "Avatar style"+msgstr "Avatar stili"+msgid "Avatar url"msgstr "Avatar URL'si"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "Avatarlar {1} tarafından <0>{0}</0> kaynağından alınmıştır, <1>{2}</1> ile lisanslanmıştır."+msgid "Avg Days to Close"msgstr "Kapatma Ortalama Günler"@@ -3433,6 +3446,9 @@ msgstr "İzlenebilirliğe geri dön"msgid "Backflush"msgstr "Geriye dönük tüketim"+msgid "Background"+msgstr "Arka plan"+msgid "Backup"msgstr "Yedek"@@ -4402,6 +4418,9 @@ msgstr "İş emirde {0} için bir tedarikçi seçin"msgid "Choose another file"msgstr "Başka bir dosya seç"+msgid "Choose avatar"+msgstr "Avatar seç"+msgid "Choose how to add lines to this return."msgstr "Bu iade için satırları nasıl ekleyeceğinizi seçin."@@ -14993,9 +15012,6 @@ msgstr "Telefon"msgid "Phone Number"msgstr "Telefon Numarası"-msgid "Photo removed successfully"-msgstr "Fotoğraf başarıyla kaldırıldı"-msgid "Photo uploaded successfully"msgstr "Fotoğraf başarıyla yüklendi"@@ -15038,6 +15054,9 @@ msgstr "Bir kayıt türü seçin…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "Ayrıntılarını, bileşenlerini ve malzemelerini düzenlemek için listeden bir adım seçin."+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "Bir stil ve bir avatar seçin veya yenilerini görmek için karıştırın."+msgid "Pick a target date to compare."msgstr "Karşılaştırma için hedef bir tarih seçin."@@ -19063,6 +19082,9 @@ msgstr "Müşteriye faturada gösterilir"msgid "Shown to the user when this rule fails."msgstr "Bu kural başarısız olduğunda kullanıcıya gösterilir."+msgid "Shuffle"+msgstr "Karıştır"+msgid "Sign in to Carbon"msgstr "Carbon'a giriş yapın"@@ -19624,6 +19646,9 @@ msgstr "Stripe'ın henüz bu Carbon müşterisi için bir müşterisi yok. Onaymsgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Bu Carbon müşterisi için Stripe'da henüz müşteri yok. Muhasebeleştirme, bağlı hesabınızda bir tane oluşturacak."+msgid "Style default"+msgstr "Stil varsayılanı"+msgid "Style of kanban output to show in the Kanban table"msgstr "Kanban tablosunda gösterilecek kanban çıktısı stili"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex d53521dfca..41cab0d164 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -3415,9 +3415,22 @@ msgstr "可用小时数"msgid "Available on the Business plan"msgstr "在商业计划中可用"+#. placeholder {0}: index + 1+msgid "Avatar option {0}"+msgstr "头像选项 {0}"++msgid "Avatar style"+msgstr "头像风格"+msgid "Avatar url"msgstr "头像网址"+#. placeholder {0}: info.source.name+#. placeholder {1}: info.creator+#. placeholder {2}: info.license.name+msgid "Avatars from <0>{0}</0> by {1}, licensed under <1>{2}</1>."+msgstr "头像来自 {1} 的 <0>{0}</0>,采用 <1>{2}</1> 许可。"+msgid "Avg Days to Close"msgstr "平均关闭天数"@@ -3433,6 +3446,9 @@ msgstr "返回可追溯性"msgid "Backflush"msgstr "倒冲"+msgid "Background"+msgstr "背景"+msgid "Backup"msgstr "备份"@@ -4402,6 +4418,9 @@ msgstr "为工单上的{0}选择供应商"msgid "Choose another file"msgstr "选择另一个文件"+msgid "Choose avatar"+msgstr "选择头像"+msgid "Choose how to add lines to this return."msgstr "选择如何向此退货添加行。"@@ -14993,9 +15012,6 @@ msgstr "电话"msgid "Phone Number"msgstr "电话号码"-msgid "Photo removed successfully"-msgstr "照片已成功删除"-msgid "Photo uploaded successfully"msgstr "照片上传成功"@@ -15038,6 +15054,9 @@ msgstr "选择记录类型…"msgid "Pick a step from the list to edit its details, components, and materials."msgstr "从列表中选择一个步骤以编辑其详细信息、组件和原材料。"+msgid "Pick a style and an avatar, or shuffle for new ones."+msgstr "选择一种风格和一个头像,或随机生成新的头像。"+msgid "Pick a target date to compare."msgstr "选择一个目标日期进行比较。"@@ -19063,6 +19082,9 @@ msgstr "在发票上向客户显示"msgid "Shown to the user when this rule fails."msgstr "当此规则失败时向用户显示。"+msgid "Shuffle"+msgstr "随机"+msgid "Sign in to Carbon"msgstr "登录 Carbon"@@ -19624,6 +19646,9 @@ msgstr "Stripe还没有为此Carbon客户创建对应的客户。确认将在您msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."msgstr "Stripe还没有该Carbon客户对应的客户。过账将在您的连接账户上创建一个。"+msgid "Style default"+msgstr "风格默认"+msgid "Style of kanban output to show in the Kanban table"msgstr "看板输出在看板表中显示的样式"diff --git a/packages/react/AGENTS.md b/packages/react/AGENTS.mdindex af8c9e9772..a5945ecb62 100644--- a/packages/react/AGENTS.md+++ b/packages/react/AGENTS.md@@ -49,6 +49,7 @@ import { Button, Card, HStack, VStack, IconButton, cn } from "@carbon/react";- **Data**: `Table` (TanStack), chart components via sub-exports (`@carbon/react/Chart`)- **Rich text**: `@carbon/react/Editor` and `@carbon/react/RichText` (wraps `@carbon/tiptap`)- **Error boundary**: `@carbon/react/ErrorBoundary` — `RouteErrorBoundary` (exported as `ErrorBoundary` from a module layout so a failed loader shows inside the app shell; it shows the status code and, for a 4xx, the message the server threw — `routeErrorCopy` — so throw a `Response` whose body says what was wrong. A 5xx or thrown `Error` gets generic copy) and `RootErrorBoundary` (drop-in root `ErrorBoundary` for RR v7 that maps 404 / other HTTP / thrown `Error` to a styled screen) plus its parts (`ErrorScreen`, `GlitchHeading`, `StatusReadout`, `MagneticLink`, `NoiseOverlay`). Wrap it in the app's `Document` and pass `env` so `window.env` is set (the client crashes hydration otherwise). Copy is intentionally hardcoded English, not i18n.+- **Avatar**: `src` may be a URL or a generated-avatar value from `user.avatarUrl` (`dicebear:<style>:<seed>[:<rrggbb>]`; the styles and value helpers are in `@carbon/utils` `avatar.ts`). It renders that in the browser with DiceBear 10 (`utils/generatedAvatar.ts`). Nothing from DiceBear is imported statically — the core (about 25 KB gzipped) and each style's JSON definition load with `import()` the first time an avatar needs them (`STYLE_LOADERS`, typed `Record<GeneratedAvatarStyle, …>` so a new style without a loader fails typecheck); keep it that way, `Avatar` is in every app shell. `useGeneratedAvatar` reads the state through `useSyncExternalStore`: `loading` on the server and until the chunks arrive (a plain `bg-muted` circle, no initials flash), `failed` falls back to initials. `generatedAvatarClassName(style)` picks the image classes: line-art styles on white (`bg-white`) in both themes, color styles on `bg-muted`. A value's optional background goes to DiceBear as `backgroundColor`; on a dark one (`isDarkBackground`, WCAG contrast) the styles that draw lines straight onto the background (`INK_OPTIONS`: Croodles Neutral, Notionists Neutral, Lorelei Neutral) get white ink. Rendered avatars sit in one LRU cache capped at `MAX_CACHED_AVATARS`, since a picker drag produces a new value per step. The app `Avatar` wrappers turn a stored value into `src` with `avatarSrc` (`@carbon/utils`); new users get a Croodles Neutral avatar from the column default- **Polish**: shadows over borders, `tabular-nums` for dynamic numbers, `active:scale-[0.98]` on pressables, `text-balance`/`text-pretty` for text wrapping## Cross-Referencesdiff --git a/packages/react/package.json b/packages/react/package.jsonindex 381cab6f05..3d67a5f5c9 100644--- a/packages/react/package.json+++ b/packages/react/package.json@@ -8,6 +8,8 @@"@carbon/tiptap": "workspace:*","@carbon/utils": "workspace:*","@base-ui/react": "1.6.0",+ "@dicebear/core": "10.7.0",+ "@dicebear/styles": "10.6.0","@radix-ui/react-accordion": "1.2.12","@radix-ui/react-avatar": "1.1.11","@radix-ui/react-checkbox": "1.3.3",diff --git a/packages/react/src/Avatar.tsx b/packages/react/src/Avatar.tsxindex 28708cf366..26c386e7dc 100644--- a/packages/react/src/Avatar.tsx+++ b/packages/react/src/Avatar.tsx@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source."use client";-import { getColorByValue } from "@carbon/utils";+import { getColorByValue, parseGeneratedAvatar } from "@carbon/utils";import type { VariantProps } from "class-variance-authority";import { cva } from "class-variance-authority";import type {@@ -18,10 +18,15 @@ import {createContext,forwardRef,useContext,+ useMemo,useState} from "react";import { cn } from "./utils/cn";+import {+ generatedAvatarClassName,+ useGeneratedAvatar+} from "./utils/generatedAvatar";export const avatarVariants = cva("flex flex-shrink-0 overflow-hidden rounded-full items-center justify-center font-medium transition-transform duration-200 ease-in-out",@@ -58,22 +63,50 @@ const Avatar = forwardRef<HTMLSpanElement, AvatarProps>(({ className, name, src, size, children, ...props }, ref) => {const isGroup = !!useAvatarGroupContext()?.limit;const avatarInitials = getInitials(name ?? "");- const [error, setError] = useState(false);+ // `src` may be a generated-avatar value from `user.avatarUrl` rather than a URL.+ const generated = useMemo(() => parseGeneratedAvatar(src), [src]);+ const generatedState = useGeneratedAvatar(generated ? src : undefined);+ const imageSrc = !generated+ ? src+ : generatedState.status === "ready"+ ? generatedState.src+ : undefined;+ // Remember which source failed, so a new `src` (a changed avatar) is tried.+ const [failedSrc, setFailedSrc] = useState<string>();+ const error = imageSrc !== undefined && imageSrc === failedSrc;const colorValue = getColorByValue(name ?? "", "light");const background = colorValue?.background;const color = colorValue?.color;- return src && !error ? (+ // A generated avatar whose style is still loading (or the server render):+ // a plain circle, so the initials do not flash before the avatar. A style+ // that failed to load falls through to the initials.+ if (generated && generatedState.status === "loading") {+ return (+ <span+ className={cn(+ avatarVariants({ size, isGroup }),+ "bg-muted",+ className+ )}+ {...props}+ ref={ref}+ />+ );+ }++ return imageSrc && !error ? (<imgclassName={cn(avatarVariants({ size, isGroup }),"object-cover bg-muted-foreground border border-muted",+ generated && generatedAvatarClassName(generated.style),className)}alt={name ?? "avatar"}- src={src}- onError={() => setError(true)}+ src={imageSrc}+ onError={() => setFailedSrc(imageSrc)}/>) : (<spandiff --git a/packages/react/src/__tests__/Avatar.test.tsx b/packages/react/src/__tests__/Avatar.test.tsxnew file mode 100644index 0000000000..b90b737290--- /dev/null+++ b/packages/react/src/__tests__/Avatar.test.tsx@@ -0,0 +1,35 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";++import { Avatar } from "../Avatar";++describe("Avatar", () => {+ it("renders a generated avatar as a plain placeholder on the server", () => {+ // The style loads in the browser; the server render (and hydration) shows+ // a neutral circle, never the initials, so nothing flashes.+ const html = renderToStaticMarkup(+ <Avatar name="Jane Doe" src="dicebear:croodles-neutral:seed-one" />+ );+ expect(html).not.toContain("<img");+ expect(html).not.toContain("JD");+ expect(html).toContain("bg-muted");+ });++ it("renders a URL as it is, without the generated-avatar styling", () => {+ const html = renderToStaticMarkup(+ <Avatar name="Jane Doe" src="https://example.com/avatars/jane.webp" />+ );+ expect(html).toContain('src="https://example.com/avatars/jane.webp"');+ expect(html).not.toContain("bg-white");+ });++ it("falls back to initials with no source", () => {+ const html = renderToStaticMarkup(<Avatar name="Jane Doe" />);+ expect(html).not.toContain("<img");+ expect(html).toContain("JD");+ });+});diff --git a/packages/react/src/__tests__/generatedAvatar.test.ts b/packages/react/src/__tests__/generatedAvatar.test.tsnew file mode 100644index 0000000000..3ee1ff06e8--- /dev/null+++ b/packages/react/src/__tests__/generatedAvatar.test.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { GENERATED_AVATAR_STYLES } from "@carbon/utils";+import { describe, expect, it, vi } from "vitest";+import {+ generatedAvatarClassName,+ generatedAvatarDataUri,+ isDarkBackground,+ loadGeneratedAvatarStyle+} from "../utils/generatedAvatar";++const svgOf = (uri: string | undefined) =>+ decodeURIComponent((uri ?? "").replace(/^data:image\/svg\+xml;[^,]*,/, ""));++describe("generatedAvatarDataUri", () => {+ it("renders nothing until the value's style has loaded", async () => {+ // A fresh copy of the module, so no other test has loaded a style yet.+ vi.resetModules();+ const fresh = await import("../utils/generatedAvatar");+ const value = "dicebear:planets:seed-before-load";+ expect(fresh.generatedAvatarDataUri(value)).toBeUndefined();+ await fresh.loadGeneratedAvatarStyle("planets");+ expect(+ fresh.generatedAvatarDataUri(value)?.startsWith("data:image/svg+xml")+ ).toBe(true);+ });++ it.each(GENERATED_AVATAR_STYLES)("loads and renders %s", async (style) => {+ await loadGeneratedAvatarStyle(style);+ const uri = generatedAvatarDataUri(`dicebear:${style}:seed-one`);+ expect(uri?.startsWith("data:image/svg+xml")).toBe(true);+ });++ it("is deterministic per seed and differs between seeds", async () => {+ await loadGeneratedAvatarStyle("croodles-neutral");+ const first = generatedAvatarDataUri("dicebear:croodles-neutral:seed-two");+ const again = generatedAvatarDataUri("dicebear:croodles-neutral:seed-two");+ const other = generatedAvatarDataUri(+ "dicebear:croodles-neutral:seed-three"+ );+ expect(again).toBe(first);+ expect(other).not.toBe(first);+ });++ it("differs between styles for the same seed", async () => {+ await loadGeneratedAvatarStyle("croodles-neutral");+ await loadGeneratedAvatarStyle("lorelei");+ expect(generatedAvatarDataUri("dicebear:lorelei:seed-two")).not.toBe(+ generatedAvatarDataUri("dicebear:croodles-neutral:seed-two")+ );+ });++ it("returns undefined for an uploaded photo path", () => {+ expect(+ generatedAvatarDataUri("5f0c3d2a-1b2c-4d5e-8f90-123456789abc.webp")+ ).toBeUndefined();+ });++ describe("background color", () => {+ it("paints the chosen background", async () => {+ await loadGeneratedAvatarStyle("voxel-art");+ const svg = svgOf(+ generatedAvatarDataUri("dicebear:voxel-art:seed-bg:3b82f6")+ );+ expect(svg.toLowerCase()).toContain("#3b82f6");+ });++ it("switches line ink to white on a dark background", async () => {+ await loadGeneratedAvatarStyle("croodles-neutral");+ const dark = svgOf(+ generatedAvatarDataUri("dicebear:croodles-neutral:seed-ink:111827")+ ).toLowerCase();+ const light = svgOf(+ generatedAvatarDataUri("dicebear:croodles-neutral:seed-ink:fde68a")+ ).toLowerCase();+ expect(dark).toContain("#ffffff");+ expect(light).toContain("#000000");+ expect(light).not.toContain("#ffffff");+ });++ it("classifies backgrounds by contrast", () => {+ expect(isDarkBackground("000000")).toBe(true);+ expect(isDarkBackground("1e3a8a")).toBe(true);+ expect(isDarkBackground("ffffff")).toBe(false);+ expect(isDarkBackground("ffd5dc")).toBe(false);+ });+ });++ describe("generatedAvatarClassName", () => {+ it("puts line-art styles on white in both themes", () => {+ for (const style of [+ "croodles-neutral",+ "notionists",+ "notionists-neutral",+ "lorelei",+ "lorelei-neutral"+ ] as const) {+ expect(generatedAvatarClassName(style)).toBe(+ "bg-white border-black/10"+ );+ }+ });++ it("leaves color styles on the muted background, never inverted", () => {+ for (const style of [+ "loops",+ "pixel-art",+ "voxel-art",+ "voxel-bot",+ "planets"+ ] as const) {+ const className = generatedAvatarClassName(style);+ expect(className).toBe("bg-muted border-transparent");+ expect(className).not.toContain("invert");+ }+ });+ });+});diff --git a/packages/react/src/utils/generatedAvatar.ts b/packages/react/src/utils/generatedAvatar.tsnew file mode 100644index 0000000000..fdbbba3f24--- /dev/null+++ b/packages/react/src/utils/generatedAvatar.ts@@ -0,0 +1,238 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { getLogger } from "@carbon/logger";+import type { GeneratedAvatarStyle } from "@carbon/utils";+import { parseGeneratedAvatar } from "@carbon/utils";+import type { Style } from "@dicebear/core";+import { useEffect, useSyncExternalStore } from "react";++const log = getLogger("react", "generated-avatar");++// One loader per style. A style definition is 10–370 KB of JSON and the Avatar+// renders on every page, so each style is its own chunk, fetched the first time+// an avatar in that style is shown. `Record` makes a style in+// GENERATED_AVATAR_STYLES without a loader a type error.+const STYLE_LOADERS: Record<GeneratedAvatarStyle, () => Promise<unknown>> = {+ "croodles-neutral": () => import("@dicebear/styles/croodles-neutral.json"),+ notionists: () => import("@dicebear/styles/notionists.json"),+ "notionists-neutral": () =>+ import("@dicebear/styles/notionists-neutral.json"),+ lorelei: () => import("@dicebear/styles/lorelei.json"),+ "lorelei-neutral": () => import("@dicebear/styles/lorelei-neutral.json"),+ loops: () => import("@dicebear/styles/loops.json"),+ "pixel-art": () => import("@dicebear/styles/pixel-art.json"),+ "voxel-art": () => import("@dicebear/styles/voxel-art.json"),+ "voxel-bot": () => import("@dicebear/styles/voxel-bot.json"),+ planets: () => import("@dicebear/styles/planets.json")+};++/**+ * Styles drawn as black lines on a transparent background. `Avatar` puts them+ * on white in both themes. The rest are full color with their own background.+ */+const LINE_ART_STYLES: ReadonlySet<GeneratedAvatarStyle> = new Set([+ "croodles-neutral",+ "notionists",+ "notionists-neutral",+ "lorelei",+ "lorelei-neutral"+]);++function isLineArtStyle(style: GeneratedAvatarStyle) {+ return LINE_ART_STYLES.has(style);+}++/**+ * The classes `Avatar` puts on a generated avatar's image. Line-art styles are+ * black lines on transparent, so they sit on white in both themes; color+ * styles keep their own colors. A chosen background paints over either.+ */+export function generatedAvatarClassName(style: GeneratedAvatarStyle) {+ return isLineArtStyle(style)+ ? "bg-white border-black/10"+ : "bg-muted border-transparent";+}++/**+ * The line-color options of the styles that draw lines straight onto the+ * background. On a dark background they switch to white so the face stays+ * visible. Notionists and Lorelei paint a white face first, so they need none.+ */+const INK_OPTIONS: Partial<Record<GeneratedAvatarStyle, readonly string[]>> = {+ "croodles-neutral": ["inkColor"],+ "notionists-neutral": ["inkColor"],+ "lorelei-neutral": ["eyebrowsColor", "eyesColor", "mouthColor", "noseColor"]+};++function channel(hex: string, offset: number) {+ const value = Number.parseInt(hex.slice(offset, offset + 2), 16) / 255;+ return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;+}++/** True when white text reads better than black on `rrggbb` (WCAG contrast). */+export function isDarkBackground(hex: string) {+ const luminance =+ 0.2126 * channel(hex, 0) ++ 0.7152 * channel(hex, 2) ++ 0.0722 * channel(hex, 4);+ return 1.05 / (luminance + 0.05) > (luminance + 0.05) / 0.05;+}++function backgroundOptions(+ style: GeneratedAvatarStyle,+ background: string | null+): Record<string, string[]> {+ if (!background) return {};+ const options: Record<string, string[]> = {+ backgroundColor: [`#${background}`]+ };+ if (isDarkBackground(background)) {+ for (const option of INK_OPTIONS[style] ?? [])+ options[option] = ["#ffffff"];+ }+ return options;+}++// The DiceBear core is about 156 KB minified (25 KB gzipped) and `Avatar` is+// in every app shell, so it is never imported statically: it loads with the+// first style an avatar needs. Keep every runtime use behind `core`.+type DiceBearCore = typeof import("@dicebear/core");+let core: DiceBearCore | undefined;++const styles = new Map<GeneratedAvatarStyle, Style>();+const pending = new Map<GeneratedAvatarStyle, Promise<void>>();+const failed = new Set<GeneratedAvatarStyle>();++export type GeneratedAvatarState =+ | { status: "ready"; src: string }+ | { status: "loading" }+ | { status: "failed" };++type ReadyState = Extract<GeneratedAvatarState, { status: "ready" }>;++// Rendered avatars, keyed by value. A list of people renders the same few+// avatars many times, so each is generated once. Least recently used first: a+// picker drag or shuffle produces a new value per step, so the cache is capped+// rather than kept for the whole session. One state object per value keeps+// `useSyncExternalStore`'s snapshot stable.+const MAX_CACHED_AVATARS = 300;+const rendered = new Map<string, ReadyState>();++function remember(value: string, state: ReadyState) {+ rendered.delete(value);+ rendered.set(value, state);+ if (rendered.size > MAX_CACHED_AVATARS) {+ const oldest = rendered.keys().next().value;+ if (oldest !== undefined) rendered.delete(oldest);+ }+}++function renderReadyState(value: string): ReadyState | undefined {+ const cached = rendered.get(value);+ if (cached) {+ remember(value, cached);+ return cached;+ }++ const parsed = parseGeneratedAvatar(value);+ if (!parsed) return undefined;+ const style = styles.get(parsed.style);+ // A loaded style implies a loaded core; the check keeps the types honest.+ if (!style || !core) return undefined;++ const state: ReadyState = {+ status: "ready",+ src: new core.Avatar(style, {+ seed: parsed.seed,+ ...backgroundOptions(parsed.style, parsed.background)+ }).toDataUri()+ };+ remember(value, state);+ return state;+}++const listeners = new Set<() => void>();++function notify() {+ for (const listener of listeners) listener();+}++function subscribe(listener: () => void) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++/** Loads a style's definition once. Safe to call repeatedly. */+export function loadGeneratedAvatarStyle(+ style: GeneratedAvatarStyle+): Promise<void> {+ if (styles.has(style)) return Promise.resolve();+ const inFlight = pending.get(style);+ if (inFlight) return inFlight;+ failed.delete(style);++ const load = Promise.all([import("@dicebear/core"), STYLE_LOADERS[style]()])+ .then(([dicebear, module]) => {+ core = dicebear;+ const definition = (module as { default?: unknown }).default ?? module;+ styles.set(style, new dicebear.Style(definition));+ notify();+ })+ .catch((error) => {+ // Avatars in this style fall back to initials; the next one to mount+ // tries the load again.+ log.error("Failed to load avatar style", { style, error });+ failed.add(style);+ notify();+ })+ .finally(() => {+ pending.delete(style);+ });+ pending.set(style, load);+ return load;+}++/**+ * The SVG data URI for a generated-avatar value (`dicebear:<style>:<seed>`),+ * or `undefined` when the value is not one, or its style has not loaded yet.+ */+export function generatedAvatarDataUri(value: string): string | undefined {+ return renderReadyState(value)?.src;+}++const LOADING: GeneratedAvatarState = { status: "loading" };+const FAILED: GeneratedAvatarState = { status: "failed" };++function readState(value: string): GeneratedAvatarState {+ const ready = renderReadyState(value);+ if (ready) return ready;+ const style = parseGeneratedAvatar(value)?.style;+ return style && failed.has(style) ? FAILED : LOADING;+}++/**+ * The state of a generated-avatar value, loading its style on first use. It is+ * `loading` on the server, so the server render and hydration agree. Pass+ * `undefined` when the value is not a generated avatar (hooks cannot be+ * conditional); the result is then meaningless.+ */+export function useGeneratedAvatar(+ value: string | undefined+): GeneratedAvatarState {+ const state = useSyncExternalStore(+ subscribe,+ () => (value ? readState(value) : LOADING),+ () => LOADING+ );++ const style = value ? parseGeneratedAvatar(value)?.style : undefined;+ useEffect(() => {+ if (style) loadGeneratedAvatarStyle(style);+ }, [style]);++ return state;+}diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.mdindex 5163cc6370..7c76a28b59 100644--- a/packages/utils/AGENTS.md+++ b/packages/utils/AGENTS.md@@ -52,6 +52,7 @@ pnpm --filter @carbon/utils typecheck| `rental-invoice-plan` | Invoice automation's pure planner: `planRentalInvoices` (one combined invoice under `Draft Only`, else rent + a held charges invoice; holds for early-return credits and re-bills of a voided invoice), `effectiveInvoiceAutomation`, the hold messages, and the `InvoiceAutomation` type. Used by the `create-rental-invoices` server function and the invoice automation job || `async` | The `async` object: `Promise.all`, `Promise.allSettled` and `items.map` with a limit on how many run at once (`DEFAULT_CONCURRENCY`, 8, unless `{ concurrency }` says otherwise). `map(items, mapper)` follows p-map, `all(tasks)` and `allSettled(tasks)` take FUNCTIONS (a promise is already running) and keep the tuple's types, `limit(n)` follows p-limit. After a failure `map` / `all` start nothing further. Database calls inside a request need no limit of their own — the client `requirePermissions` returns has at most 8 in flight. `background(task, onError)` is fire-and-forget with a required error handler. `onBackground(hook)` registers what keeps the process alive for that work — both apps register Vercel's `waitUntil` in `entry.server.tsx` — so use `background` (never a bare unawaited promise) for anything a request leaves running || `errors` | `getErrorMessage(error, fallback)` — the error's own message, else the caller's copy (server functions leave `message` empty for data-layer failures so the fallback wins); `isUniqueViolation(error)` / `isForeignKeyViolation(error)` — the Postgres SQLSTATE checks (23505 / 23503) on a Supabase result or a thrown Kysely error; `getDatabaseErrorMessage(error, fallback, { duplicate?, referenced? })` — the caller's copy for the constraint Postgres named |+| `avatar` | Generated-avatar values in `user.avatarUrl` (`dicebear:<style>:<seed>[:<rrggbb>]` — the optional background is lowercase hex without `#`, absent = the style's own): `GENERATED_AVATAR_STYLES` (only ever add — a removed style's existing avatars fall back to initials), `parseGeneratedAvatar`, `formatGeneratedAvatar`, `isGeneratedAvatar`, `newGeneratedAvatar(style?, background?)`, `normalizeAvatarBackground` (picker input → stored form), `avatarSrc(value, toUrl)` (a stored value → an `<img>` `src`, used by every app's `Avatar` wrapper), and what a user may store (`isOwnAvatarUpload`, `isAllowedAvatarValue`). Rendering lives in `@carbon/react` || `arrays` | Array manipulation, grouping, deduplication || `bom` | Bill of Materials traversal and level computation || `date` | Date formatting, parsing, range helpers (uses `@internationalized/date`); `HOUR_MS`/`DAY_MS` millisecond constants for instant arithmetic |diff --git a/packages/utils/src/avatar.test.ts b/packages/utils/src/avatar.test.tsnew file mode 100644index 0000000000..446bec3dcb--- /dev/null+++ b/packages/utils/src/avatar.test.ts@@ -0,0 +1,175 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ avatarSrc,+ formatGeneratedAvatar,+ GENERATED_AVATAR_STYLES,+ isAllowedAvatarValue,+ isGeneratedAvatar,+ isOwnAvatarUpload,+ newGeneratedAvatar,+ normalizeAvatarBackground,+ parseGeneratedAvatar+} from "./avatar";++describe("generated avatars", () => {+ it("parses a generated value into its style and seed", () => {+ expect(+ parseGeneratedAvatar("dicebear:croodles-neutral:0b6f2c1e-9a")+ ).toEqual({+ style: "croodles-neutral",+ seed: "0b6f2c1e-9a",+ background: null+ });+ });++ it("does not treat an uploaded photo path as generated", () => {+ expect(isGeneratedAvatar("5f0c3d2a-1b2c-4d5e-8f90-123456789abc.webp")).toBe(+ false+ );+ });++ it("rejects empty, missing and malformed seeds", () => {+ expect(isGeneratedAvatar(null)).toBe(false);+ expect(isGeneratedAvatar(undefined)).toBe(false);+ expect(isGeneratedAvatar("dicebear:croodles-neutral:")).toBe(false);+ expect(isGeneratedAvatar("dicebear:croodles-neutral:a/b")).toBe(false);+ expect(+ isGeneratedAvatar(`dicebear:croodles-neutral:${"a".repeat(65)}`)+ ).toBe(false);+ expect(isGeneratedAvatar("dicebear:")).toBe(false);+ expect(isGeneratedAvatar("dicebear:croodles-neutral")).toBe(false);+ });++ it("accepts every supported style and nothing else", () => {+ for (const style of GENERATED_AVATAR_STYLES) {+ expect(parseGeneratedAvatar(`dicebear:${style}:abc`)).toEqual({+ style,+ seed: "abc",+ background: null+ });+ expect(isGeneratedAvatar(newGeneratedAvatar(style))).toBe(true);+ }+ // A DiceBear style we do not ship.+ expect(isGeneratedAvatar("dicebear:adventurer:abc")).toBe(false);+ });++ it("creates the default style when no style is given", () => {+ expect(parseGeneratedAvatar(newGeneratedAvatar())?.style).toBe(+ "croodles-neutral"+ );+ });++ it("creates a new random value each call", () => {+ const first = newGeneratedAvatar();+ const second = newGeneratedAvatar();+ expect(isGeneratedAvatar(first)).toBe(true);+ expect(isGeneratedAvatar(second)).toBe(true);+ expect(first).not.toBe(second);+ });++ it("accepts the format the column default writes", () => {+ // 'dicebear:croodles-neutral:' || gen_random_uuid()::text+ expect(+ isGeneratedAvatar(+ "dicebear:croodles-neutral:3f2b8c4e-6a1d-4f7e-9b2c-5d8e1a0f7c63"+ )+ ).toBe(true);+ });++ describe("what a user may store", () => {+ const userId = "5f0c3d2a-1b2c-4d5e-8f90-123456789abc";++ it("accepts the user's own upload", () => {+ expect(isOwnAvatarUpload(userId, `${userId}.webp`)).toBe(true);+ expect(isAllowedAvatarValue(userId, `${userId}.png`)).toBe(true);+ });++ it("accepts a generated avatar", () => {+ expect(isAllowedAvatarValue(userId, newGeneratedAvatar())).toBe(true);+ });++ it("rejects another user's file, folders, a bare id and empty values", () => {+ expect(isAllowedAvatarValue(userId, "someone-else.webp")).toBe(false);+ expect(isAllowedAvatarValue(userId, `${userId}./../x.webp`)).toBe(false);+ expect(isAllowedAvatarValue(userId, `tmp/${userId}.webp`)).toBe(false);+ expect(isAllowedAvatarValue(userId, `${userId}.`)).toBe(false);+ expect(isAllowedAvatarValue(userId, userId)).toBe(false);+ expect(isAllowedAvatarValue(userId, "")).toBe(false);+ expect(isAllowedAvatarValue(userId, null)).toBe(false);+ });+ });++ describe("background color", () => {+ it("parses an optional background segment", () => {+ expect(parseGeneratedAvatar("dicebear:voxel-art:seed-1:3b82f6")).toEqual({+ style: "voxel-art",+ seed: "seed-1",+ background: "3b82f6"+ });+ });++ it("rejects a malformed background or extra segments", () => {+ expect(isGeneratedAvatar("dicebear:voxel-art:seed-1:#3b82f6")).toBe(+ false+ );+ expect(isGeneratedAvatar("dicebear:voxel-art:seed-1:3B82F6")).toBe(false);+ expect(isGeneratedAvatar("dicebear:voxel-art:seed-1:abc")).toBe(false);+ expect(isGeneratedAvatar("dicebear:voxel-art:seed-1:")).toBe(false);+ expect(isGeneratedAvatar("dicebear:voxel-art:seed-1:3b82f6:x")).toBe(+ false+ );+ });++ it("normalizes picker input to lowercase rrggbb", () => {+ expect(normalizeAvatarBackground("#3B82F6")).toBe("3b82f6");+ expect(normalizeAvatarBackground("#abc")).toBe("aabbcc");+ expect(normalizeAvatarBackground("3b82f6")).toBe("3b82f6");+ expect(normalizeAvatarBackground("#12345")).toBeNull();+ expect(normalizeAvatarBackground("red")).toBeNull();+ expect(normalizeAvatarBackground("")).toBeNull();+ expect(normalizeAvatarBackground(null)).toBeNull();+ });++ it("round-trips through format and parse", () => {+ const avatar = {+ style: "planets" as const,+ seed: "seed-2",+ background: "ffd5dc"+ };+ expect(parseGeneratedAvatar(formatGeneratedAvatar(avatar))).toEqual(+ avatar+ );+ expect(formatGeneratedAvatar({ ...avatar, background: null })).toBe(+ "dicebear:planets:seed-2"+ );+ expect(newGeneratedAvatar("loops", "#FFF")).toMatch(+ /^dicebear:loops:[0-9a-f-]+:ffffff$/+ );+ });+ });++ describe("avatarSrc", () => {+ const toUrl = (path: string) =>+ `https://storage.example.com/avatars/${path}`;++ it("passes a generated avatar through untouched", () => {+ const value = "dicebear:planets:seed-1:1e3a8a";+ expect(avatarSrc(value, toUrl)).toBe(value);+ });++ it("turns an uploaded photo's path into a URL", () => {+ expect(avatarSrc("user-1.webp", toUrl)).toBe(+ "https://storage.example.com/avatars/user-1.webp"+ );+ });++ it("returns undefined for no avatar", () => {+ expect(avatarSrc(null, toUrl)).toBeUndefined();+ expect(avatarSrc("", toUrl)).toBeUndefined();+ });+ });+});diff --git a/packages/utils/src/avatar.ts b/packages/utils/src/avatar.tsnew file mode 100644index 0000000000..b49cadfef6--- /dev/null+++ b/packages/utils/src/avatar.ts@@ -0,0 +1,156 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/**+ * `user.avatarUrl` holds either a path in the public `avatars` bucket (an+ * uploaded photo) or a generated-avatar value: `dicebear:<style>:<seed>`, with+ * an optional `:<rrggbb>` background (none = the style's own). The+ * `@carbon/react` Avatar renders a generated value with DiceBear in the+ * browser. The column default (migration `20261008113405`) writes the default+ * style in the same format, so the two must change together.+ *+ * Every style here needs a loader in `@carbon/react`'s `generatedAvatar.ts`.+ * Removing a style stops existing values in it from rendering (they fall back+ * to initials), so only ever add.+ */+export const GENERATED_AVATAR_STYLES = [+ "croodles-neutral",+ "notionists",+ "notionists-neutral",+ "lorelei",+ "lorelei-neutral",+ "loops",+ "pixel-art",+ "voxel-art",+ "voxel-bot",+ "planets"+] as const;++export type GeneratedAvatarStyle = (typeof GENERATED_AVATAR_STYLES)[number];++export const DEFAULT_GENERATED_AVATAR_STYLE: GeneratedAvatarStyle =+ "croodles-neutral";++const GENERATED_AVATAR_PREFIX = "dicebear:";+const SEED_PATTERN = /^[A-Za-z0-9-]{1,64}$/;++export function isGeneratedAvatarStyle(+ value: string+): value is GeneratedAvatarStyle {+ return (GENERATED_AVATAR_STYLES as readonly string[]).includes(value);+}++export type GeneratedAvatar = {+ style: GeneratedAvatarStyle;+ seed: string;+ /** Lowercase `rrggbb` without `#`, or `null` for the style's own background. */+ background: string | null;+};++const BACKGROUND_PATTERN = /^[0-9a-f]{6}$/;++/**+ * A background color as the value stores it: lowercase `rrggbb` without `#`.+ * Accepts `#abc`, `#AABBCC` or the same without `#`; anything else is `null`.+ */+export function normalizeAvatarBackground(+ input: string | null | undefined+): string | null {+ if (!input) return null;+ let hex = input.trim().replace(/^#/, "").toLowerCase();+ if (/^[0-9a-f]{3}$/.test(hex)) {+ hex = hex+ .split("")+ .map((digit) => digit + digit)+ .join("");+ }+ return BACKGROUND_PATTERN.test(hex) ? hex : null;+}++/**+ * Parses `dicebear:<style>:<seed>` or `dicebear:<style>:<seed>:<rrggbb>`. The+ * background segment is optional, so every value written before it existed+ * (and the column default) still parses.+ */+export function parseGeneratedAvatar(+ value: string | null | undefined+): GeneratedAvatar | null {+ if (!value?.startsWith(GENERATED_AVATAR_PREFIX)) return null;+ const parts = value.slice(GENERATED_AVATAR_PREFIX.length).split(":");+ if (parts.length < 2 || parts.length > 3) return null;+ const [style = "", seed = "", background] = parts;+ if (!isGeneratedAvatarStyle(style) || !SEED_PATTERN.test(seed)) return null;+ if (background !== undefined && !BACKGROUND_PATTERN.test(background)) {+ return null;+ }+ return { style, seed, background: background ?? null };+}++export function isGeneratedAvatar(+ value: string | null | undefined+): value is string {+ return parseGeneratedAvatar(value) !== null;+}++export function formatGeneratedAvatar({+ style,+ seed,+ background+}: GeneratedAvatar): string {+ const color = normalizeAvatarBackground(background);+ return `${GENERATED_AVATAR_PREFIX}${style}:${seed}${color ? `:${color}` : ""}`;+}++export function newGeneratedAvatarSeed(): string {+ return crypto.randomUUID();+}++export function newGeneratedAvatar(+ style: GeneratedAvatarStyle = DEFAULT_GENERATED_AVATAR_STYLE,+ background: string | null = null+): string {+ return formatGeneratedAvatar({+ style,+ seed: newGeneratedAvatarSeed(),+ background+ });+}++/**+ * The `src` for a stored avatar value. A generated avatar passes through as+ * it is (the `@carbon/react` Avatar renders it); an uploaded photo's path+ * becomes a URL through `toUrl`. Every app's `Avatar` wrapper uses this.+ */+export function avatarSrc(+ value: string | null | undefined,+ toUrl: (path: string) => string+): string | undefined {+ if (!value) return undefined;+ return isGeneratedAvatar(value) ? value : toUrl(value);+}++/**+ * An uploaded photo lives at the root of the public `avatars` bucket, named+ * `${userId}.<ext>` (the bucket's write policy requires the user's id as the+ * filename prefix).+ */+export function isOwnAvatarUpload(+ userId: string,+ value: string | null | undefined+): value is string {+ return (+ !!value &&+ value.length > userId.length + 1 &&+ value.startsWith(`${userId}.`) &&+ !value.includes("/")+ );+}++/** What a user may store in their own `user.avatarUrl`. */+export function isAllowedAvatarValue(+ userId: string,+ value: string | null | undefined+): value is string {+ return isGeneratedAvatar(value) || isOwnAvatarUpload(userId, value);+}diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex cdb56fdd1b..f72e2f7def 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -12,6 +12,7 @@ export * from "./address";export * from "./arrays";export * from "./assembly-units";export * from "./async";+export * from "./avatar";export * from "./balloons";export * from "./bank";export * from "./batch-compatibility";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c13f9d2dfd..07b3f623cf 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3333,6 +3333,12 @@ importers:'@carbon/utils':specifier: workspace:*version: link:../utils+ '@dicebear/core':+ specifier: 10.7.0+ version: 10.7.0+ '@dicebear/styles':+ specifier: 10.6.0+ version: 10.6.0'@internationalized/date':specifier: 'catalog:'version: 3.12.0@@ -4711,6 +4717,13 @@ packages:vite:optional: true+ '@dicebear/[email protected]':+ resolution: {integrity: sha512-JUOzKOd8RUByJJo8ZL+C7YE/pvEsWewfpbWUmR8OIQZWv/PvUQHnohdevySC3icyyxe6EIU/8B/rQgA42us1QA==}+ engines: {node: '>=22.0.0'}++ '@dicebear/[email protected]':+ resolution: {integrity: sha512-KhxbEVI+z8TaenX58+ZhIRFBt7adggu/F+8g6ZYLu43H2/lgLuWA3Kg8vHBrCVWdfTTTt1p2wUhQomIkkypTuQ==}+'@dnd-kit/[email protected]':resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==}peerDependencies:@@ -18601,6 +18614,10 @@ snapshots:'@devframes/hub-ui': 1.1.0(@devframes/[email protected](@devframes/[email protected])([email protected]([email protected]))([email protected]))(@devframes/[email protected](@devframes/[email protected](@devframes/[email protected])([email protected]([email protected]))([email protected]))([email protected]))([email protected])vite: 8.3.1(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ '@dicebear/[email protected]': {}++ '@dicebear/[email protected]': {}+'@dnd-kit/[email protected]([email protected])':dependencies:react: 18.3.1