Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Add admin avatar upload to profile settings (#14268)

Damian Legawiec15ca93b0fc66
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 8d8b2b32cb..56304c1ae0 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -64,6 +64,7 @@ export interface MeResponse {
first_name: string | null
last_name: string | null
selected_locale: string | null
+ avatar_url: string | null
}
permissions: PermissionRule[]
}
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index ca9298660f..95754538b3 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -610,6 +610,11 @@ export interface MeUpdateParams {
selected_locale?: string
first_name?: string
last_name?: string
+ /**
+ * ActiveStorage direct-upload signed id to set the avatar, or `null` to
+ * remove it. Omit to leave the current photo unchanged.
+ */
+ avatar?: string | null
}
export interface StockLocationCreateParams {
diff --git a/packages/admin-sdk/src/types/generated/AdminUser.ts b/packages/admin-sdk/src/types/generated/AdminUser.ts
index f58a6b5f9a..aa75a19938 100644
--- a/packages/admin-sdk/src/types/generated/AdminUser.ts
+++ b/packages/admin-sdk/src/types/generated/AdminUser.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 1d440ad9e82f7f1a1901abeaa93f3c76
+// Typelizer digest 7439aff943ee8a5ee7c804eece26afe2
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -11,6 +11,7 @@ interface AdminUser {
selected_locale: string | null;
created_at: string;
updated_at: string;
+ avatar_url: string | null;
roles: Array<{ id: string; name: string }>;
}
diff --git a/packages/dashboard-core/src/components/top-bar.tsx b/packages/dashboard-core/src/components/top-bar.tsx
index 9483afdab5..ee2a104585 100644
--- a/packages/dashboard-core/src/components/top-bar.tsx
+++ b/packages/dashboard-core/src/components/top-bar.tsx
@@ -1,6 +1,7 @@
import {
Avatar,
AvatarFallback,
+ AvatarImage,
Button,
DropdownMenu,
DropdownMenuContent,
@@ -139,6 +140,7 @@ function TopBarUser({ uiLocales }: { uiLocales: ReadonlyArray<{ code: string; na
className="flex items-center gap-2 rounded-lg p-1 transition-colors hover:bg-accent"
>
<Avatar className="size-7">
+ {user.avatar_url && <AvatarImage src={user.avatar_url} alt="" />}
<AvatarFallback className="bg-primary text-xs text-primary-foreground dark:bg-accent dark:text-foreground">
{initials}
</AvatarFallback>
@@ -148,6 +150,7 @@ function TopBarUser({ uiLocales }: { uiLocales: ReadonlyArray<{ code: string; na
<DropdownMenuContent align="end" className="w-56" sideOffset={8}>
<div className="flex items-center gap-2 p-1.5">
<Avatar className="size-8">
+ {user.avatar_url && <AvatarImage src={user.avatar_url} alt="" />}
<AvatarFallback className="bg-primary text-xs text-primary-foreground dark:bg-accent dark:text-foreground">
{initials}
</AvatarFallback>
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 875358fe69..aa546ff07f 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -756,6 +756,10 @@
"last_name": {
"label": "اسم العائلة"
},
+ "avatar": {
+ "label": "الصورة",
+ "help": "تظهر بجوار اسمك في جميع أنحاء لوحة الإدارة. الصور المربعة تبدو أفضل."
+ },
"selected_locale": {
"label": "اللغة",
"help": "اللغة المستخدمة في لوحة الإدارة. تؤثر فقط على ما تراه."
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index ea112f03d2..09823baab9 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -708,6 +708,10 @@
"last_name": {
"label": "Nachname"
},
+ "avatar": {
+ "label": "Foto",
+ "help": "Wird im gesamten Admin neben Ihrem Namen angezeigt. Quadratische Bilder sehen am besten aus."
+ },
"selected_locale": {
"label": "Sprache",
"help": "Sprache, die im gesamten Admin-Dashboard verwendet wird. Betrifft nur Ihre Ansicht."
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 526a17ef59..8dccb4f188 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -759,6 +759,10 @@
"last_name": {
"label": "Last name"
},
+ "avatar": {
+ "label": "Photo",
+ "help": "Shown next to your name across the admin. Square images look best."
+ },
"selected_locale": {
"label": "Language",
"help": "Language used across the admin dashboard. Only affects what you see."
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 043f60407b..aef98e473b 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -708,6 +708,10 @@
"last_name": {
"label": "Nom"
},
+ "avatar": {
+ "label": "Photo",
+ "help": "Affichée à côté de votre nom dans toute l'administration. Les images carrées sont recommandées."
+ },
"selected_locale": {
"label": "Langue",
"help": "Langue utilisée dans tout le tableau de bord d'administration. N'affecte que ce que vous voyez."
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 82722cdf67..9a352d67a3 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -708,6 +708,10 @@
"last_name": {
"label": "Nazwisko"
},
+ "avatar": {
+ "label": "Zdjęcie",
+ "help": "Wyświetlane obok Twojego imienia w całym panelu administracyjnym. Najlepiej wyglądają zdjęcia kwadratowe."
+ },
"selected_locale": {
"label": "Język",
"help": "Język używany w całym panelu administracyjnym. Wpływa tylko na to, co widzisz."
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 22c20eebb4..aa136fd37a 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -756,6 +756,10 @@
"last_name": {
"label": "姓氏"
},
+ "avatar": {
+ "label": "照片",
+ "help": "在管理后台中显示在您的姓名旁边。方形图片效果最佳。"
+ },
"selected_locale": {
"label": "语言",
"help": "管理后台使用的语言。仅影响您看到的界面。"
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/profile.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/profile.tsx
index 2e998ef4e5..11afd22213 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/profile.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/profile.tsx
@@ -1,6 +1,7 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { type MeResponse, SpreeError } from '@spree/admin-sdk'
import {
+ ImageUploadField,
i18n,
mapSpreeErrorsToForm,
PageHeader,
@@ -29,7 +30,7 @@ import {
useFormSubmitShortcut,
} from '@spree/dashboard-ui'
import { createFileRoute } from '@tanstack/react-router'
-import { useMemo } from 'react'
+import { useEffect, useMemo } from 'react'
import {
type Control,
Controller,
@@ -41,7 +42,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { useProfile, useUpdateProfile } from '@/hooks/use-profile'
import { getAvailableUiLocales } from '@/i18n-setup'
-import { type MeFormValues, meFormSchema } from '@/schemas/me'
+import { type MeFormValues, meFormSchema, meToForm, meToParams } from '@/schemas/me'
export const Route = createFileRoute('/_authenticated/$storeId/settings/profile')({
component: ProfilePage,
@@ -58,14 +59,6 @@ function currentUiLocale(): string {
return active && available.includes(active) ? active : 'en'
}
-function meToFormValues(me: MeResponse): MeFormValues {
- return {
- first_name: me.user.first_name ?? '',
- last_name: me.user.last_name ?? '',
- selected_locale: me.user.selected_locale || currentUiLocale(),
- }
-}
-
function ProfilePage() {
const { t } = useTranslation()
const { data: me, isLoading, error, refetch } = useProfile()
@@ -105,24 +98,43 @@ function ProfileForm({ me }: { me: MeResponse }) {
const form = useForm<MeFormValues>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
resolver: zodResolver(meFormSchema) as any,
- defaultValues: meToFormValues(me),
+ defaultValues: meToForm(me, currentUiLocale()),
})
+ // Re-baseline from the refetched profile after a save (e.g. to surface the
+ // newly-persisted avatar_url as the server image), unless the admin has
+ // unsaved edits in flight.
+ useEffect(() => {
+ if (form.formState.isDirty) return
+ form.reset(meToForm(me, currentUiLocale()))
+ }, [me, form])
+
+ // Release the picked avatar's object URL when it's replaced or the page
+ // unmounts. ImageUploadField hands the blob URL to the form (its caller), so
+ // the form owns revoking it — otherwise form.reset() (re-baseline above) or a
+ // navigate-away drops it without freeing the blob. Double-revokes (the field
+ // also revokes on replace/remove) are harmless no-ops.
+ const avatarPreviewUrl = form.watch('avatar_preview_url')
+ useEffect(() => {
+ if (!avatarPreviewUrl) return
+ return () => URL.revokeObjectURL(avatarPreviewUrl)
+ }, [avatarPreviewUrl])
+
const onSubmit = async (values: MeFormValues) => {
try {
- const updated = await updateMutation.mutateAsync({
- first_name: values.first_name || undefined,
- last_name: values.last_name || undefined,
- selected_locale: values.selected_locale || undefined,
- })
- // Reflect the new name/locale in the auth context (top-bar, etc.)
+ const updated = await updateMutation.mutateAsync(meToParams(values))
+ // Reflect the new name/locale/avatar in the auth context (top-bar, etc.)
// immediately instead of waiting for the next token refresh.
updateUser(updated.user)
toast.success(t('admin.messages.profile_updated'))
// Reset FIRST so the form is no longer dirty — otherwise the language
// switch below reloads the page while the `beforeunload` dirty-guard is
- // still armed, triggering the browser's "unsaved changes" prompt.
- form.reset(values)
+ // still armed, triggering the browser's "unsaved changes" prompt. Drop the
+ // consumed signed_id so a second save can't re-attach it, but KEEP
+ // avatar_cleared: forcing it false here would make the field fall back to
+ // the still-cached (stale) avatar_url and briefly re-show a just-removed
+ // photo. The re-hydrate effect resets it once the profile refetch lands.
+ form.reset({ ...values, avatar_signed_id: null })
// Apply a changed admin language by reloading in the new language.
const code = values.selected_locale
if (code && code !== i18n.language) switchLocale(code)
@@ -169,6 +181,22 @@ function ProfileForm({ me }: { me: MeResponse }) {
</CardHeader>
<CardContent>
<FieldGroup>
+ <ImageUploadField
+ square
+ serverUrl={me.user.avatar_url}
+ label={t('admin.fields.profile.avatar.label')}
+ help={t('admin.fields.profile.avatar.help')}
+ value={{
+ signedId: form.watch('avatar_signed_id'),
+ previewUrl: form.watch('avatar_preview_url'),
+ cleared: form.watch('avatar_cleared'),
+ }}
+ onChange={(next) => {
+ form.setValue('avatar_signed_id', next.signedId, { shouldDirty: true })
+ form.setValue('avatar_preview_url', next.previewUrl, { shouldDirty: true })
+ form.setValue('avatar_cleared', next.cleared, { shouldDirty: true })
+ }}
+ />
<Field>
<FieldLabel htmlFor="profile-email">
{t('admin.fields.profile.email.label')}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/staff.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/staff.tsx
index 7a3b7d53da..db59def6a1 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/staff.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/staff.tsx
@@ -4,6 +4,7 @@ import { getInitials, mapSpreeErrorsToForm, PageHeader } from '@spree/dashboard-
import {
Avatar,
AvatarFallback,
+ AvatarImage,
Badge,
Button,
Card,
@@ -199,6 +200,7 @@ function StaffRow({ member }: { member: AdminUser }) {
<TableCell>
<div className="flex items-center gap-3">
<Avatar className="size-8">
+ {member.avatar_url && <AvatarImage src={member.avatar_url} alt="" />}
<AvatarFallback className="bg-muted text-xs">{initials}</AvatarFallback>
</Avatar>
<div className="flex flex-col leading-tight">
diff --git a/packages/dashboard/src/schemas/me.ts b/packages/dashboard/src/schemas/me.ts
index 11048ee07f..cb07058cee 100644
--- a/packages/dashboard/src/schemas/me.ts
+++ b/packages/dashboard/src/schemas/me.ts
@@ -1,3 +1,4 @@
+import type { MeResponse, MeUpdateParams } from '@spree/admin-sdk'
import { z } from 'zod/v4'
// Profile form for the signed-in admin (PATCH /me). All fields optional —
@@ -5,10 +6,49 @@ import { z } from 'zod/v4'
// The admin-UI language options are NOT listed here: they're derived at render
// time from the dashboard's shipped locale bundles (see getAvailableUiLocales),
// which is what the SPA can actually display — not a backend list.
+//
+// The avatar is a small state machine: untouched (omit on save), uploaded
+// (send signed_id), or cleared (send null to purge). `avatar_signed_id` carries
+// a freshly direct-uploaded blob; `avatar_preview_url` is a transient object URL
+// for the just-picked file; `avatar_cleared` flags a removal of the persisted
+// photo.
export const meFormSchema = z.object({
first_name: z.string().nullable().optional(),
last_name: z.string().nullable().optional(),
selected_locale: z.string().nullable().optional(),
+ avatar_signed_id: z.string().nullable(),
+ avatar_preview_url: z.string().nullable(),
+ avatar_cleared: z.boolean(),
})
export type MeFormValues = z.infer<typeof meFormSchema>
+
+/** Hydrate the form from the current admin (PATCH /me response). */
+export function meToForm(me: MeResponse, fallbackLocale: string): MeFormValues {
+ return {
+ first_name: me.user.first_name ?? '',
+ last_name: me.user.last_name ?? '',
+ selected_locale: me.user.selected_locale || fallbackLocale,
+ avatar_signed_id: null,
+ avatar_preview_url: null,
+ avatar_cleared: false,
+ }
+}
+
+/** Map the form to the PATCH /me params (drops frontend-only fields). */
+export function meToParams(values: MeFormValues): MeUpdateParams {
+ return {
+ first_name: values.first_name || undefined,
+ last_name: values.last_name || undefined,
+ selected_locale: values.selected_locale || undefined,
+ ...avatarParam(values.avatar_signed_id, values.avatar_cleared),
+ }
+}
+
+// Three-state mapping: a fresh upload sends the signed_id, an explicit clear
+// sends null (purges the attachment), and an untouched field is omitted.
+function avatarParam(signedId: string | null, cleared: boolean) {
+ if (signedId) return { avatar: signedId }
+ if (cleared) return { avatar: null }
+ return {}
+}
diff --git a/spree/api/app/controllers/spree/api/v3/admin/admin_users_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/admin_users_controller.rb
index 4d09a51b23..931459e5fd 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/admin_users_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/admin_users_controller.rb
@@ -60,7 +60,7 @@ module Spree
end
def collection_includes
- [{ role_users: :role }]
+ [{ role_users: :role, avatar_attachment: :blob }]
end
# Restrict to users with a role assignment on the current store.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb
index d1ef6d4409..fd3ec17ea8 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb
@@ -27,11 +27,12 @@ module Spree
end
# PATCH /api/v3/admin/me
- # Self-service update of the signed-in admin's own profile. Currently
- # limited to `selected_locale` (the admin UI display language) — it
- # operates on `current_user` directly, so it needs no per-record
- # authorization. Distinct from PATCH /admin_users/:id, which is
- # store-scoped staff management of *other* users.
+ # Self-service update of the signed-in admin's own profile (display
+ # name, admin UI language, and avatar) — it operates on `current_user`
+ # directly, so it needs no per-record authorization. Distinct from
+ # PATCH /admin_users/:id, which is store-scoped staff management of
+ # *other* users. `avatar` accepts an ActiveStorage direct-upload
+ # signed id to set the photo, or `null` to remove it.
def update
if current_user.update(permitted_params)
render json: me_response
@@ -56,7 +57,7 @@ module Spree
end
def permitted_params
- params.permit(:selected_locale, :first_name, :last_name)
+ params.permit(:selected_locale, :first_name, :last_name, :avatar)
end
def me_response
diff --git a/spree/api/app/serializers/spree/api/v3/admin/admin_user_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/admin_user_serializer.rb
index 052ce26b5c..fc260994fd 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/admin_user_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/admin_user_serializer.rb
@@ -8,11 +8,16 @@ module Spree
last_name: [:string, nullable: true],
full_name: [:string, nullable: true],
selected_locale: [:string, nullable: true],
+ avatar_url: [:string, nullable: true],
roles: 'Array<{ id: string; name: string }>'
attributes :email, :first_name, :last_name, :full_name, :selected_locale,
created_at: :iso8601, updated_at: :iso8601
+ attribute :avatar_url do |user|
+ image_url_for(user.avatar)
+ end
+
# Roles assigned to this user *for the current store*. Each store
# gets its own role set via `Spree::RoleUser`, so this attribute is
# scoped against `current_store` rather than returning every role
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb
index 8337fe9e2b..966bc1e852 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb
@@ -66,6 +66,12 @@ RSpec.describe Spree::Api::V3::Admin::MeController, type: :controller do
expect(manage_all_rule).to be_present
end
+ it 'exposes the user avatar_url (null when no photo is attached)' do
+ subject
+ expect(json_response['user']).to have_key('avatar_url')
+ expect(json_response['user']['avatar_url']).to be_nil
+ end
+
it 'exposes the user selected_locale' do
subject
expect(json_response['user']).to have_key('selected_locale')
@@ -112,6 +118,59 @@ RSpec.describe Spree::Api::V3::Admin::MeController, type: :controller do
end
end
+ context 'with an avatar signed id' do
+ let(:blob) do
+ ActiveStorage::Blob.create_and_upload!(
+ io: File.open(Spree::Core::Engine.root.join('spec', 'fixtures', 'thinking-cat.jpg')),
+ filename: 'avatar.jpg',
+ content_type: 'image/jpeg'
+ )
+ end
+ let(:params) { { avatar: blob.signed_id } }
+
+ it 'attaches the avatar and returns its url' do
+ subject
+ expect(response).to have_http_status(:ok)
+ expect(admin_user.reload.avatar).to be_attached
+ expect(json_response['user']['avatar_url']).to be_present
+ end
+ end
+
+ context 'with a non-image avatar' do
+ let(:blob) do
+ ActiveStorage::Blob.create_and_upload!(
+ io: StringIO.new('<svg xmlns="http://www.w3.org/2000/svg"></svg>'),
+ filename: 'avatar.svg',
+ content_type: 'image/svg+xml'
+ )
+ end
+ let(:params) { { avatar: blob.signed_id } }
+
+ it 'rejects the upload with a validation error' do
+ subject
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(admin_user.reload.avatar).not_to be_attached
+ end
+ end
+
+ context 'clearing the avatar' do
+ before do
+ admin_user.avatar.attach(
+ io: File.open(Spree::Core::Engine.root.join('spec', 'fixtures', 'thinking-cat.jpg')),
+ filename: 'avatar.jpg',
+ content_type: 'image/jpeg'
+ )
+ end
+ let(:params) { { avatar: nil } }
+
+ it 'purges the avatar' do
+ subject
+ expect(response).to have_http_status(:ok)
+ expect(admin_user.reload.avatar).not_to be_attached
+ expect(json_response['user']['avatar_url']).to be_nil
+ end
+ end
+
context 'when authenticated via a secret API key (no Spree user)' do
let(:secret_api_key) { create(:api_key, :secret, store: store) }
let(:headers) { { 'x-spree-api-key' => secret_api_key.plaintext_token } }
diff --git a/spree/core/app/models/concerns/spree/admin_user_methods.rb b/spree/core/app/models/concerns/spree/admin_user_methods.rb
index 6fde5c25fd..f9f40732b6 100644
--- a/spree/core/app/models/concerns/spree/admin_user_methods.rb
+++ b/spree/core/app/models/concerns/spree/admin_user_methods.rb
@@ -33,6 +33,8 @@ module Spree
# Attachments
has_one_attached :avatar, service: Spree.public_storage_service_name
+ validates :avatar, content_type: Rails.application.config.active_storage.web_image_content_types
+
#
# Attributes
#