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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Let the operator manage a seller's team
Damian Legawiec2430db14c6e4
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex aac027cd23..bb66082baf 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -311,6 +311,7 @@ import type {Seller,SellerRequirement,SellerRequirementSubmission,+ SellerTeamMember,StockLevel,StockLocation,StockMovement,@@ -2456,6 +2457,34 @@ export class AdminClient {body: params,}),+ /**+ * Who runs this seller. The operator's view of what the seller panel+ * manages for itself — and the only way to repair a seller whose team has+ * locked itself out.+ */+ team: {+ list: (sellerId: string, options?: RequestOptions): Promise<{ data: SellerTeamMember[] }> =>+ this.request<{ data: SellerTeamMember[] }>('GET', `/sellers/${sellerId}/team`, options),++ /** Revokes a member's access. */+ remove: (sellerId: string, id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>('DELETE', `/sellers/${sellerId}/team/${id}`, options),+ },++ /** Offers to join this seller that nobody has accepted yet. */+ invitations: {+ list: (sellerId: string, options?: RequestOptions): Promise<{ data: Invitation[] }> =>+ this.request<{ data: Invitation[] }>('GET', `/sellers/${sellerId}/invitations`, options),++ /** Withdraws an offer. */+ remove: (sellerId: string, id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>('DELETE', `/sellers/${sellerId}/invitations/${id}`, options),++ /** Sends the email again; refused once the offer has lapsed. */+ resend: (sellerId: string, id: string, options?: RequestOptions): Promise<Invitation> =>+ this.request<Invitation>('PATCH', `/sellers/${sellerId}/invitations/${id}/resend`, options),+ },+/** What this seller submitted about the requirements, and its decisions. */requirementSubmissions: {list: (diff --git a/packages/admin-sdk/src/types/generated/SellerTeamMember.ts b/packages/admin-sdk/src/types/generated/SellerTeamMember.tsnew file mode 100644index 0000000000..42302c6f2d--- /dev/null+++ b/packages/admin-sdk/src/types/generated/SellerTeamMember.ts@@ -0,0 +1,16 @@+// Typelizer digest 7178e6a238cd4b61ef2d494bbbb2756d+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++interface SellerTeamMember {+ id: string;+ email: string;+ first_name: string | null;+ last_name: string | null;+ full_name: string | null;+ created_at: string;+ updated_at: string;+ avatar_url: string | null;+}++export default SellerTeamMember;diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.tsindex fa5750a79f..37fbc53635 100644--- a/packages/admin-sdk/src/types/generated/index.ts+++ b/packages/admin-sdk/src/types/generated/index.ts@@ -1,4 +1,4 @@-// Typelizer digest f6fb43d9d2c744ab64ce66d6aa31356b+// Typelizer digest cd6f30b505a5197901ec71bec46d0194//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { default as Address } from './Address'@@ -84,6 +84,7 @@ export type { default as SellerRequirement } from './SellerRequirement'export type { default as SellerRequirementStatus } from './SellerRequirementStatus'export type { default as SellerRequirementSubmission } from './SellerRequirementSubmission'export type { default as Seller } from './Seller'+export type { default as SellerTeamMember } from './SellerTeamMember'export type { default as SetupTask } from './SetupTask'export type { default as State } from './State'export type { default as StockLevel } from './StockLevel'diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.tsindex 54eb4d1eb2..aa0dd93b90 100644--- a/packages/admin-sdk/src/types/index.ts+++ b/packages/admin-sdk/src/types/index.ts@@ -93,6 +93,7 @@ export type { default as Seller } from './generated/Seller'export type { default as SellerRequirement } from './generated/SellerRequirement'export type { default as SellerRequirementStatus } from './generated/SellerRequirementStatus'export type { default as SellerRequirementSubmission } from './generated/SellerRequirementSubmission'+export type { default as SellerTeamMember } from './generated/SellerTeamMember'export type { default as SetupTask } from './generated/SetupTask'export type { default as State } from './generated/State'export type { default as StockLevel } from './generated/StockLevel'diff --git a/packages/dashboard/src/components/spree/sellers/seller-team-card.tsx b/packages/dashboard/src/components/spree/sellers/seller-team-card.tsxnew file mode 100644index 0000000000..8ea2907139--- /dev/null+++ b/packages/dashboard/src/components/spree/sellers/seller-team-card.tsx@@ -0,0 +1,151 @@+import type { Seller } from '@spree/admin-sdk'+import { Subject, usePermissions } from '@spree/dashboard-core'+import {+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardHeader,+ CardTitle,+ RowActions,+ useConfirm,+} from '@spree/dashboard-ui'+import { UserPlusIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'+import {+ useRemoveSellerTeamMember,+ useResendSellerInvitation,+ useRevokeSellerInvitation,+ useSellerInvitations,+ useSellerTeam,+} from '../../../hooks/use-sellers'++/**+ * Who runs this seller, and the offers nobody has accepted yet.+ *+ * The operator's view of what a seller manages in their own panel. It earns+ * its place here because the operator is the only one who can repair a seller+ * that has locked itself out — the last member gone, or an invitation sent to+ * the wrong address — which a seller by definition cannot do from inside.+ */+export function SellerTeamCard({ seller, onInvite }: { seller: Seller; onInvite: () => void }) {+ const { t } = useTranslation()+ const { permissions } = usePermissions()+ const confirm = useConfirm()++ const { data: team, isLoading: loadingTeam } = useSellerTeam(seller.id)+ const { data: invitations } = useSellerInvitations(seller.id)+ const removeMember = useRemoveSellerTeamMember(seller.id)+ const revokeInvitation = useRevokeSellerInvitation(seller.id)+ const resendInvitation = useResendSellerInvitation(seller.id)++ const canManage = permissions.can('update', Subject.Seller)+ const members = team?.data ?? []+ const pending = invitations?.data ?? []++ async function handleRemove(id: string, label: string) {+ const ok = await confirm({+ title: t('admin.sellers.team.remove_confirm.title'),+ message: t('admin.sellers.team.remove_confirm.message', { name: label }),+ variant: 'destructive',+ confirmLabel: t('admin.actions.remove'),+ })+ if (!ok) return+ await removeMember.mutateAsync(id).catch(() => undefined)+ }++ async function handleRevoke(id: string, label: string) {+ const ok = await confirm({+ title: t('admin.sellers.team.revoke_confirm.title'),+ message: t('admin.sellers.team.revoke_confirm.message', { email: label }),+ variant: 'destructive',+ confirmLabel: t('admin.sellers.team.revoke'),+ })+ if (!ok) return+ await revokeInvitation.mutateAsync(id).catch(() => undefined)+ }++ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.sellers.team.title')}</CardTitle>+ {canManage && (+ <CardAction>+ <Button variant="outline" size="sm" onClick={onInvite}>+ <UserPlusIcon className="size-4" />+ {t('admin.sellers.team.invite')}+ </Button>+ </CardAction>+ )}+ </CardHeader>+ <CardContent className="flex flex-col gap-4">+ {loadingTeam ? (+ <p className="text-muted-foreground text-sm">{t('admin.common.loading')}</p>+ ) : members.length === 0 && pending.length === 0 ? (+ <p className="text-muted-foreground text-sm">{t('admin.sellers.team.empty')}</p>+ ) : null}++ {members.map((member) => (+ <div key={member.id} className="flex items-center justify-between gap-3">+ <div className="min-w-0">+ <div className="truncate text-sm font-medium">{member.full_name || member.email}</div>+ {member.full_name && (+ <div className="truncate text-muted-foreground text-xs">{member.email}</div>+ )}+ </div>+ {canManage && (+ <RowActions+ actions={[+ {+ key: 'remove',+ label: t('admin.actions.remove'),+ destructive: true,+ disabled: removeMember.isPending,+ onSelect: () => handleRemove(member.id, member.full_name || member.email),+ },+ ]}+ />+ )}+ </div>+ ))}++ {pending.length > 0 && (+ <div className="flex flex-col gap-3 border-t border-border pt-4">+ <h3 className="text-muted-foreground text-xs font-medium">+ {t('admin.sellers.team.pending')}+ </h3>+ {pending.map((invitation) => (+ <div key={invitation.id} className="flex items-center justify-between gap-3">+ <div className="flex min-w-0 items-center gap-2">+ <span className="truncate text-sm">{invitation.email}</span>+ <Badge variant="secondary">{t('admin.sellers.team.invited')}</Badge>+ </div>+ {canManage && (+ <RowActions+ actions={[+ {+ key: 'resend',+ label: t('admin.sellers.team.resend'),+ disabled: resendInvitation.isPending,+ onSelect: () =>+ resendInvitation.mutateAsync(invitation.id).catch(() => undefined),+ },+ {+ key: 'revoke',+ label: t('admin.sellers.team.revoke'),+ destructive: true,+ disabled: revokeInvitation.isPending,+ onSelect: () => handleRevoke(invitation.id, invitation.email),+ },+ ]}+ />+ )}+ </div>+ ))}+ </div>+ )}+ </CardContent>+ </Card>+ )+}diff --git a/packages/dashboard/src/hooks/use-sellers.ts b/packages/dashboard/src/hooks/use-sellers.tsindex e1ea36818e..0ff8e9a991 100644--- a/packages/dashboard/src/hooks/use-sellers.ts+++ b/packages/dashboard/src/hooks/use-sellers.ts@@ -1,4 +1,5 @@import type {+ Invitation,ListParams,Seller,SellerApproveParams,@@ -143,3 +144,47 @@ export function useRejectSeller(id: string) {errorMessage: i18n.t('admin.sellers.messages.reject_failed'),})}++export function useSellerTeam(sellerId: string) {+ return useQuery({+ queryKey: useResourceKey('sellers', sellerId, 'team'),+ queryFn: () => adminClient.sellers.team.list(sellerId),+ })+}++export function useRemoveSellerTeamMember(sellerId: string) {+ return useResourceMutation<void, Error, string>({+ mutationFn: (id) => adminClient.sellers.team.remove(sellerId, id),+ invalidate: [+ ['sellers', sellerId, 'team'],+ ['sellers', sellerId],+ ],+ successMessage: i18n.t('admin.sellers.team.messages.removed'),+ errorMessage: i18n.t('admin.errors.failed_to_delete'),+ })+}++export function useSellerInvitations(sellerId: string) {+ return useQuery({+ queryKey: useResourceKey('sellers', sellerId, 'invitations'),+ queryFn: () => adminClient.sellers.invitations.list(sellerId),+ })+}++export function useRevokeSellerInvitation(sellerId: string) {+ return useResourceMutation<void, Error, string>({+ mutationFn: (id) => adminClient.sellers.invitations.remove(sellerId, id),+ invalidate: [['sellers', sellerId, 'invitations']],+ successMessage: i18n.t('admin.sellers.team.messages.invitation_revoked'),+ errorMessage: i18n.t('admin.errors.failed_to_delete'),+ })+}++export function useResendSellerInvitation(sellerId: string) {+ return useResourceMutation<Invitation, Error, string>({+ mutationFn: (id) => adminClient.sellers.invitations.resend(sellerId, id),+ invalidate: [['sellers', sellerId, 'invitations']],+ successMessage: i18n.t('admin.sellers.team.messages.invitation_resent'),+ errorMessage: i18n.t('admin.errors.failed_to_update'),+ })+}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 586db8074e..fc0d31be13 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -4232,6 +4232,28 @@"platform": "السوق يورّد الضريبة","seller": "البائع يورّد الضريبة"},+ "team": {+ "empty": "لا أحد يدير هذا البائع بعد.",+ "invite": "دعوة",+ "invited": "مدعو",+ "messages": {+ "invitation_resent": "تم إرسال الدعوة مرة أخرى",+ "invitation_revoked": "تم إلغاء الدعوة",+ "removed": "تمت إزالة عضو الفريق"+ },+ "pending": "دعوات معلقة",+ "remove_confirm": {+ "message": "سيفقد {{name}} الوصول إلى هذا البائع.",+ "title": "إزالة عضو الفريق؟"+ },+ "resend": "إعادة الإرسال",+ "revoke": "إلغاء",+ "revoke_confirm": {+ "message": "سيتوقف العرض المرسل إلى {{email}} عن العمل.",+ "title": "إلغاء الدعوة؟"+ },+ "title": "الفريق"+ },"team_column": "الفريق"},"settings": {diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 11e676ca31..596c3f0381 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -4213,6 +4213,28 @@"platform": "Marktplatz führt ab","seller": "Verkäufer führt ab"},+ "team": {+ "empty": "Diesen Verkäufer betreibt noch niemand.",+ "invite": "Einladen",+ "invited": "Eingeladen",+ "messages": {+ "invitation_resent": "Einladung erneut gesendet",+ "invitation_revoked": "Einladung widerrufen",+ "removed": "Teammitglied entfernt"+ },+ "pending": "Ausstehende Einladungen",+ "remove_confirm": {+ "message": "{{name}} verliert den Zugriff auf diesen Verkäufer.",+ "title": "Teammitglied entfernen?"+ },+ "resend": "Erneut senden",+ "revoke": "Widerrufen",+ "revoke_confirm": {+ "message": "Das an {{email}} gesendete Angebot wird ungültig.",+ "title": "Einladung widerrufen?"+ },+ "title": "Team"+ },"team_column": "Team"},"settings": {diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 9a3471024d..8edaf44cfa 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -4213,6 +4213,28 @@"platform": "Marketplace remits","seller": "Seller remits"},+ "team": {+ "empty": "Nobody runs this seller yet.",+ "invite": "Invite",+ "invited": "Invited",+ "messages": {+ "invitation_resent": "Invitation sent again",+ "invitation_revoked": "Invitation revoked",+ "removed": "Team member removed"+ },+ "pending": "Pending invitations",+ "remove_confirm": {+ "message": "{{name}} will lose access to this seller.",+ "title": "Remove team member?"+ },+ "resend": "Resend",+ "revoke": "Revoke",+ "revoke_confirm": {+ "message": "The offer sent to {{email}} will stop working.",+ "title": "Revoke invitation?"+ },+ "title": "Team"+ },"team_column": "Team"},"settings": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 3b430d875f..13a2c9b887 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -4213,6 +4213,28 @@"platform": "La place de marché reverse","seller": "Le vendeur reverse"},+ "team": {+ "empty": "Personne ne gère encore ce vendeur.",+ "invite": "Inviter",+ "invited": "Invité",+ "messages": {+ "invitation_resent": "Invitation renvoyée",+ "invitation_revoked": "Invitation révoquée",+ "removed": "Membre retiré"+ },+ "pending": "Invitations en attente",+ "remove_confirm": {+ "message": "{{name}} perdra l'accès à ce vendeur.",+ "title": "Retirer ce membre ?"+ },+ "resend": "Renvoyer",+ "revoke": "Révoquer",+ "revoke_confirm": {+ "message": "L'offre envoyée à {{email}} cessera de fonctionner.",+ "title": "Révoquer l'invitation ?"+ },+ "title": "Équipe"+ },"team_column": "Équipe"},"settings": {diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex a3bdd074d4..aa6f9cdcb5 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -4273,6 +4273,28 @@"platform": "Rozlicza marketplace","seller": "Rozlicza sprzedawca"},+ "team": {+ "empty": "Nikt jeszcze nie prowadzi tego sprzedawcy.",+ "invite": "Zaproś",+ "invited": "Zaproszony",+ "messages": {+ "invitation_resent": "Zaproszenie wysłane ponownie",+ "invitation_revoked": "Unieważniono zaproszenie",+ "removed": "Usunięto członka zespołu"+ },+ "pending": "Oczekujące zaproszenia",+ "remove_confirm": {+ "message": "{{name}} straci dostęp do tego sprzedawcy.",+ "title": "Usunąć członka zespołu?"+ },+ "resend": "Wyślij ponownie",+ "revoke": "Unieważnij",+ "revoke_confirm": {+ "message": "Oferta wysłana do {{email}} przestanie działać.",+ "title": "Unieważnić zaproszenie?"+ },+ "title": "Zespół"+ },"team_column": "Zespół"},"settings": {diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 6efe34e881..3413aea9a6 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -4206,6 +4206,28 @@"platform": "市场申报","seller": "卖家申报"},+ "team": {+ "empty": "尚无人管理该卖家。",+ "invite": "邀请",+ "invited": "已邀请",+ "messages": {+ "invitation_resent": "已再次发送邀请",+ "invitation_revoked": "已撤销邀请",+ "removed": "已移除团队成员"+ },+ "pending": "待接受的邀请",+ "remove_confirm": {+ "message": "{{name}} 将失去对该卖家的访问权限。",+ "title": "移除团队成员?"+ },+ "resend": "重新发送",+ "revoke": "撤销",+ "revoke_confirm": {+ "message": "发送给 {{email}} 的邀请将失效。",+ "title": "撤销邀请?"+ },+ "title": "团队"+ },"team_column": "团队"},"settings": {diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/sellers/$sellerId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/sellers/$sellerId.tsxindex a72d856798..2836f3caba 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/sellers/$sellerId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/sellers/$sellerId.tsx@@ -24,6 +24,7 @@ import { SellerInviteSheet } from '../../../../components/spree/sellers/seller-iimport { SellerOnboardingCard } from '../../../../components/spree/sellers/seller-onboarding-card'import { SellerSettlementCard } from '../../../../components/spree/sellers/seller-settlement-card'import { SellerStatusCard } from '../../../../components/spree/sellers/seller-status-card'+import { SellerTeamCard } from '../../../../components/spree/sellers/seller-team-card'import { useSellerOnboarding } from '../../../../hooks/use-seller-requirements'import {useApproveSeller,@@ -260,6 +261,7 @@ function SellerBody({ seller }: { seller: Seller }) {onEdit={() => setEditingProfile(true)}/><SellerOnboardingCard seller={seller} canEdit={canEdit} />+ <SellerTeamCard seller={seller} onInvite={() => setInviting(true)} /><Slot name="seller.form_main" context={{ seller, canEdit }} /></>}diff --git a/spree/api/app/controllers/spree/api/v3/admin/sellers/invitations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/sellers/invitations_controller.rbnew file mode 100644index 0000000000..386e3cfa30--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/sellers/invitations_controller.rb@@ -0,0 +1,77 @@+module Spree+ module Api+ module V3+ module Admin+ module Sellers+ # Offers to join one of the marketplace's sellers that nobody has+ # accepted yet.+ #+ # The operator's counterpart to the seller panel's own invitations+ # endpoint, and rooted the same way — at the seller's invitations, so+ # an id from another seller reads as missing rather than as denied.+ #+ # Creating one is the `invite` action on the seller itself; what is+ # here is the bookkeeping the operator needs when an offer went to+ # the wrong address or never arrived.+ class InvitationsController < Admin::BaseController+ scoped_resource :sellers++ before_action :set_seller+ before_action :set_invitation, only: [:destroy, :resend]++ # Pending only: an accepted invitation is a team member, which the+ # team endpoint lists.+ def index+ invitations = @seller.invitations.pending.order(created_at: :desc)++ render json: { data: invitations.map { |invitation| serialize(invitation) } }+ end++ def destroy+ @invitation.destroy+ head :no_content+ end++ # Sends the email again. The model refuses once the invitation has+ # expired, and says so rather than silently doing nothing.+ def resend+ if @invitation.expired?+ return render_error(+ code: ErrorHandler::ERROR_CODES[:processing_error],+ message: Spree.t(:invitation_expired),+ status: :unprocessable_content+ )+ end++ @invitation.resend!+ render json: serialize(@invitation)+ end++ protected++ def read_actions+ %w[index]+ end++ private++ def set_seller+ @seller = current_store.sellers.find_by_prefix_id!(params[:seller_id])+ authorize! :show, @seller+ end++ def set_invitation+ @invitation = @seller.invitations.pending.find_by_prefix_id!(params[:id])+ end++ def serialize(invitation)+ Spree.api.admin_invitation_serializer.new(+ invitation, params: { store: current_store }+ ).to_h+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/sellers/team_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/sellers/team_controller.rbnew file mode 100644index 0000000000..3ffe122440--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/sellers/team_controller.rb@@ -0,0 +1,64 @@+module Spree+ module Api+ module V3+ module Admin+ module Sellers+ # The people who run one of the marketplace's sellers.+ #+ # The operator's view of what the seller panel manages for itself. It+ # exists because the operator is the only one who can repair a seller+ # nobody can sign in to any more — the last member left, or the wrong+ # person was invited — which a seller by definition cannot do from+ # inside their own panel.+ #+ # Inviting is not here: it is the `invite` action on the seller+ # itself, which is a lifecycle workflow rather than bookkeeping on a+ # team.+ class TeamController < Admin::BaseController+ scoped_resource :sellers++ before_action :set_seller+ before_action :set_member, only: [:destroy]++ def index+ render json: { data: @seller.users.map { |member| serialize_member(member) } }+ end++ # Revokes a member's access. Unlike the seller's own panel this+ # does not insist on leaving one member behind: emptying the team+ # is a state only the operator can undo, and refusing it here+ # would leave them unable to remove somebody who should not have+ # access — the reason this endpoint exists.+ def destroy+ @seller.remove_user(@member)+ head :no_content+ end++ protected++ def read_actions+ %w[index]+ end++ private++ def set_seller+ @seller = current_store.sellers.find_by_prefix_id!(params[:seller_id])+ authorize! :show, @seller+ end++ def set_member+ @member = @seller.users.find_by_prefix_id!(params[:id])+ end++ def serialize_member(member)+ Spree.api.admin_seller_team_member_serializer.new(+ member, params: { store: current_store }+ ).to_h+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/seller_team_member_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/seller_team_member_serializer.rbnew file mode 100644index 0000000000..30887f1576--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/seller_team_member_serializer.rb@@ -0,0 +1,29 @@+module Spree+ module Api+ module V3+ module Admin+ # A person who runs one of the marketplace's sellers.+ #+ # Deliberately not `AdminUserSerializer`: its `roles` attribute keeps+ # only the roles held on the current *store*, and a seller's team hold+ # theirs on the seller — so every member would read as having none. The+ # role is not worth reporting anyway, since a seller's team all hold+ # the one seeded role that carries the whole seller vocabulary.+ class SellerTeamMemberSerializer < V3::BaseSerializer+ typelize email: :string,+ first_name: [:string, nullable: true],+ last_name: [:string, nullable: true],+ full_name: [:string, nullable: true],+ avatar_url: [:string, nullable: true]++ attributes :email, :first_name, :last_name, :full_name,+ created_at: :iso8601, updated_at: :iso8601++ attribute :avatar_url do |user|+ image_url_for(user.avatar)+ end+ end+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 67f9b14c55..7ce39279f4 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -462,6 +462,16 @@ Spree::Core::Engine.add_routes dopatch :reopen_onboardingend+ # Who runs this seller, and the offers nobody has accepted yet.+ # The operator is the only one who can repair a seller whose team+ # has locked itself out, which the seller's own panel cannot do.+ resources :team, only: [:index, :destroy], controller: 'sellers/team'+ resources :invitations, only: [:index, :destroy], controller: 'sellers/invitations' do+ member do+ patch :resend+ end+ end+# What this seller submitted about the requirements, and the# operator's decisions on it. Nested, because a submission means# nothing outside the seller it belongs to.diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex 2a1d58845e..cee8f6fa93 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -155,6 +155,7 @@ module Spreeadmin_company_contact_serializer: 'Spree::Api::V3::Admin::CompanyContactSerializer',admin_tax_exemption_certificate_serializer: 'Spree::Api::V3::Admin::TaxExemptionCertificateSerializer',admin_admin_user_serializer: 'Spree::Api::V3::Admin::AdminUserSerializer',+ admin_seller_team_member_serializer: 'Spree::Api::V3::Admin::SellerTeamMemberSerializer',seller_serializer: 'Spree::Api::V3::SellerSerializer',seller_profile_serializer: 'Spree::Api::V3::Seller::ProfileSerializer',seller_team_member_serializer: 'Spree::Api::V3::Seller::TeamMemberSerializer',diff --git a/spree/api/spec/controllers/spree/api/v3/admin/sellers/invitations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/sellers/invitations_controller_spec.rbnew file mode 100644index 0000000000..b8c1856de8--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/sellers/invitations_controller_spec.rb@@ -0,0 +1,73 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::Sellers::InvitationsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let(:seller) { create(:seller, store: store) }+ let(:invitation) do+ create(:invitation, resource: seller, role: seller.default_user_role, inviter: admin_user)+ end++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ it 'lists offers nobody has accepted' do+ invitation++ get :index, params: { seller_id: seller.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].map { |row| row['id'] }).to include(invitation.prefixed_id)+ end++ # An accepted invitation is a team member, which the team endpoint lists.+ it 'leaves out one that has been accepted' do+ invitation.update!(accepted_at: Time.current, status: 'accepted')++ get :index, params: { seller_id: seller.prefixed_id }, as: :json++ expect(json_response['data']).to be_empty+ end+ end++ describe 'DELETE #destroy' do+ it 'withdraws the offer' do+ delete :destroy, params: { seller_id: seller.prefixed_id, id: invitation.prefixed_id }, as: :json++ expect(response).to have_http_status(:no_content)+ expect(Spree::Invitation.find_by(id: invitation.id)).to be_nil+ end++ it 'refuses an invitation belonging to another seller' do+ other = create(:seller, store: store)+ stranger = create(:invitation, resource: other, role: other.default_user_role, inviter: admin_user)++ delete :destroy, params: { seller_id: seller.prefixed_id, id: stranger.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'PATCH #resend' do+ # The mail is sent by a subscriber on the event, so the event is what this+ # endpoint is responsible for raising.+ it 'sends the offer again' do+ invitation # created before the expectation, so its own event is not caught+ expect_any_instance_of(Spree::Invitation).to receive(:publish_event).with('invitation.resent')++ patch :resend, params: { seller_id: seller.prefixed_id, id: invitation.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ end++ it 'refuses once the offer has lapsed' do+ invitation.update_column(:expires_at, 1.day.ago)++ patch :resend, params: { seller_id: seller.prefixed_id, id: invitation.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/sellers/team_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/sellers/team_controller_spec.rbnew file mode 100644index 0000000000..8c93e2782c--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/sellers/team_controller_spec.rb@@ -0,0 +1,53 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::Sellers::TeamController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let(:seller) { create(:seller, store: store) }+ let(:member) { create(:admin_user) }++ before do+ request.headers.merge!(headers)+ seller.add_user(member)+ end++ describe 'GET #index' do+ it 'lists who runs the seller' do+ get :index, params: { seller_id: seller.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].find { |member_row| member_row['id'] == member.prefixed_id }+ expect(row['email']).to eq(member.email)+ end++ # A seller belonging to another marketplace is not this operator's to read,+ # and reads as missing rather than as denied.+ it 'refuses a seller from another store' do+ other = create(:seller, store: create(:store))++ get :index, params: { seller_id: other.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'DELETE #destroy' do+ it 'revokes a member' do+ delete :destroy, params: { seller_id: seller.prefixed_id, id: member.prefixed_id }, as: :json++ expect(response).to have_http_status(:no_content)+ expect(seller.reload.users).not_to include(member)+ end++ it 'refuses a member of another seller' do+ stranger = create(:admin_user)+ create(:seller, store: store).add_user(stranger)++ delete :destroy, params: { seller_id: seller.prefixed_id, id: stranger.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end+end