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.

Prove the seller CRUD anchor, and make <Can> work on the panel

Damian Legawiec4ef7ee0fa6e3
diff --git a/packages/seller-dashboard/src/api-client.ts b/packages/seller-dashboard/src/api-client.ts
index 6c6025e856..0b474fce52 100644
--- a/packages/seller-dashboard/src/api-client.ts
+++ b/packages/seller-dashboard/src/api-client.ts
@@ -46,10 +46,11 @@ export function createSellerApiClient({
fetchPermissions: async () => {
const response = await sellerClient().me()
- // The seller API grants capability by key alone — there are no CanCanCan
- // rules to report, and an empty list is the correct answer rather than a
- // missing one.
- return { rules: [], keys: response.permission_keys ?? [] }
+ // Both shapes, exactly as the operator's dashboard receives them. The
+ // framework's `<Can>` reads CanCanCan rules; the key list is what the
+ // API's own gate enforces. Dropping the rules here (an earlier version
+ // did) left every `<Can>` on the panel answering false — silently.
+ return { rules: response.permissions ?? [], keys: response.permission_keys ?? [] }
},
})
diff --git a/packages/seller-sdk/src/index.ts b/packages/seller-sdk/src/index.ts
index e48bd90a0d..d320398b2f 100644
--- a/packages/seller-sdk/src/index.ts
+++ b/packages/seller-sdk/src/index.ts
@@ -6,7 +6,13 @@ export { SpreeError } from '@spree/sdk-core'
// both names so hosts can say what they mean.
export type { Client, Client as SellerApiClient, SellerClientConfig } from './client'
export { createSellerClient } from './client'
-export type { MeResponse, ProfileUpdateParams, SellerAddressParams } from './seller-client'
+export type {
+ MeResponse,
+ PermissionRule,
+ ProductParams,
+ ProfileUpdateParams,
+ SellerAddressParams,
+} from './seller-client'
// Client class, for advanced use and subclassing
export { SellerClient } from './seller-client'
export type * from './types'
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index 7051adff15..bb33d703ae 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -1,5 +1,6 @@
-import type { RequestFn, RequestOptions } from '@spree/sdk-core'
-import type { AuthTokens, Invitation, Profile, SellerSummary, TeamMember } from './types'
+import type { ListParams, ListResponse, RequestFn, RequestOptions } from '@spree/sdk-core'
+import { transformListParams } from '@spree/sdk-core'
+import type { AuthTokens, Invitation, Product, Profile, SellerSummary, TeamMember } from './types'
/**
* Resource methods for the Spree Seller API — the marketplace seller panel.
@@ -131,12 +132,75 @@ export class SellerClient {
revoke: (id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/invitations/${id}`, options),
}
+
+ /**
+ * The seller's own catalog — products they own outright. Every call is
+ * rooted in the seller server-side, so an id belonging to another seller
+ * is a 404. Variants listed against shared master-catalog products are a
+ * separate surface.
+ */
+ readonly products = {
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<ListResponse<Product>> =>
+ this.request<ListResponse<Product>>('GET', '/products', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ get: (id: string, options?: RequestOptions): Promise<Product> =>
+ this.request<Product>('GET', `/products/${id}`, options),
+
+ create: (params: ProductParams, options?: RequestOptions): Promise<Product> =>
+ this.request<Product>('POST', '/products', { ...options, body: params }),
+
+ update: (id: string, params: ProductParams, options?: RequestOptions): Promise<Product> =>
+ this.request<Product>('PATCH', `/products/${id}`, { ...options, body: params }),
+
+ delete: (id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/products/${id}`, options),
+ }
+}
+
+/** The fields a seller may set on their own product. */
+export interface ProductParams {
+ name?: string
+ description?: string
+ slug?: string
+ status?: string
+ meta_title?: string
+ meta_description?: string
+ meta_keywords?: string
+ product_type_id?: string
+ tags?: string[]
+ category_ids?: string[]
+ metadata?: Record<string, unknown>
+ prices?: Array<{ amount: string | number; compare_at_amount?: string | number; currency: string }>
}
/** What `/seller/me` answers. */
+/**
+ * One CanCanCan rule, in the shape the panels' `<Can>` reads. Identical to
+ * the Admin API's, on purpose: the framework's permission model is one
+ * implementation, so its input has to be too.
+ */
+export interface PermissionRule {
+ /** true for `can`, false for `cannot` */
+ allow: boolean
+ /** Action names, e.g. ["read", "update"] or ["manage"] */
+ actions: string[]
+ /** Subject class names, e.g. ["Spree::Product"] or ["all"] */
+ subjects: string[]
+ /** The rule carries per-record conditions the API will still enforce. */
+ has_conditions: boolean
+}
+
export interface MeResponse {
user: TeamMember
sellers: SellerSummary[]
+ /** Empty until a seller is named — capability is per seller. */
+ permissions: PermissionRule[]
permission_keys: string[]
}
diff --git a/packages/seller-sdk/src/types/generated/Category.ts b/packages/seller-sdk/src/types/generated/Category.ts
new file mode 100644
index 0000000000..9315544bfe
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Category.ts
@@ -0,0 +1,30 @@
+// Typelizer digest 4a4eaa6142cd8caa6149e5771b9afcfc
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {CustomField} from '@/types'
+
+type Category = {
+ id: string;
+ name: string;
+ permalink: string;
+ position: number;
+ depth: number;
+ meta_title: string | null;
+ meta_description: string | null;
+ meta_keywords: string | null;
+ children_count: number;
+ parent_id: string | null;
+ description: string;
+ description_html: string;
+ image_url: string | null;
+ square_image_url: string | null;
+ is_root: boolean;
+ is_child: boolean;
+ is_leaf: boolean;
+ parent?: Category;
+ children?: Array<Category>;
+ ancestors?: Array<Category>;
+ custom_fields?: Array<CustomField>;
+}
+
+export default Category;
diff --git a/packages/seller-sdk/src/types/generated/CustomField.ts b/packages/seller-sdk/src/types/generated/CustomField.ts
new file mode 100644
index 0000000000..7359ba30c0
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/CustomField.ts
@@ -0,0 +1,15 @@
+// Typelizer digest 56b576d6ef0d9c0fb9565241c1a2e115
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type CustomField = {
+ id: string;
+ label: string;
+ /** @deprecated Use `field_type` instead. The legacy `type` field returns the Ruby STI class name (e.g. `Spree::CustomFields::ShortText`) and will be removed in a future minor. */
+ type: string;
+ field_type: 'short_text' | 'long_text' | 'rich_text' | 'number' | 'boolean' | 'json';
+ key: string;
+ value: any;
+}
+
+export default CustomField;
diff --git a/packages/seller-sdk/src/types/generated/Media.ts b/packages/seller-sdk/src/types/generated/Media.ts
new file mode 100644
index 0000000000..0cbf3331c0
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Media.ts
@@ -0,0 +1,24 @@
+// Typelizer digest a5e3fc9471b70defb20d943d458ef05d
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type Media = {
+ id: string;
+ product_id: string | null;
+ variant_ids: Array<string>;
+ position: number;
+ alt: string | null;
+ media_type: string;
+ focal_point_x: number | null;
+ focal_point_y: number | null;
+ external_video_url: string | null;
+ original_url: string | null;
+ mini_url: string | null;
+ small_url: string | null;
+ medium_url: string | null;
+ large_url: string | null;
+ xlarge_url: string | null;
+ og_image_url: string | null;
+}
+
+export default Media;
diff --git a/packages/seller-sdk/src/types/generated/OptionType.ts b/packages/seller-sdk/src/types/generated/OptionType.ts
new file mode 100644
index 0000000000..ab7b3db154
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/OptionType.ts
@@ -0,0 +1,13 @@
+// Typelizer digest 8034387e53b965dc346fbebd5860ea34
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type OptionType = {
+ id: string;
+ name: string;
+ label: string;
+ position: number;
+ kind: string;
+}
+
+export default OptionType;
diff --git a/packages/seller-sdk/src/types/generated/OptionValue.ts b/packages/seller-sdk/src/types/generated/OptionValue.ts
new file mode 100644
index 0000000000..7a84b067ac
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/OptionValue.ts
@@ -0,0 +1,17 @@
+// Typelizer digest d53b83174a583e30bf1ab4530fb76b80
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type OptionValue = {
+ id: string;
+ option_type_id: string;
+ name: string;
+ label: string;
+ position: number;
+ color_code: string | null;
+ option_type_name: string;
+ option_type_label: string;
+ image_url: string | null;
+}
+
+export default OptionValue;
diff --git a/packages/seller-sdk/src/types/generated/Price.ts b/packages/seller-sdk/src/types/generated/Price.ts
new file mode 100644
index 0000000000..5e9bf42a18
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Price.ts
@@ -0,0 +1,17 @@
+// Typelizer digest 7a116315f0ab746b716e9f89137a67f0
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type Price = {
+ id: string;
+ amount: string | null;
+ amount_in_cents: number | null;
+ compare_at_amount: string | null;
+ compare_at_amount_in_cents: number | null;
+ currency: string | null;
+ display_amount: string | null;
+ display_compare_at_amount: string | null;
+ price_list_id: string | null;
+}
+
+export default Price;
diff --git a/packages/seller-sdk/src/types/generated/PriceHistory.ts b/packages/seller-sdk/src/types/generated/PriceHistory.ts
new file mode 100644
index 0000000000..b1e1a526af
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/PriceHistory.ts
@@ -0,0 +1,14 @@
+// Typelizer digest 82799fb1cdb9d1035174afc6b1613ca8
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type PriceHistory = {
+ id: string;
+ amount: string;
+ amount_in_cents: number;
+ currency: string;
+ display_amount: string;
+ recorded_at: string;
+}
+
+export default PriceHistory;
diff --git a/packages/seller-sdk/src/types/generated/Product.ts b/packages/seller-sdk/src/types/generated/Product.ts
new file mode 100644
index 0000000000..87aebd1eeb
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Product.ts
@@ -0,0 +1,44 @@
+// Typelizer digest c0326d387820c104eb404426c885e2d3
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {Price, PriceHistory, Seller, Media, Variant, OptionType, OptionValue, Category, CustomField} from '@/types'
+
+type Product = {
+ id: string;
+ name: string;
+ slug: string;
+ meta_title: string | null;
+ meta_description: string | null;
+ meta_keywords: string | null;
+ variant_count: number;
+ available_on: string | null;
+ preorder_ships_at: string | null;
+ purchasable: boolean;
+ preorder: boolean;
+ in_stock: boolean;
+ backorderable: boolean;
+ available: boolean;
+ description: string | null;
+ description_html: string | null;
+ default_variant_id: string;
+ thumbnail_url: string | null;
+ tags: Array<string>;
+ price: Price;
+ original_price: Price | null;
+ seller_id: string | null;
+ seller?: Seller;
+ primary_media?: Media;
+ media?: Array<Media>;
+ variants?: Array<Variant>;
+ default_variant?: Variant;
+ option_types?: Array<OptionType>;
+ option_values?: Array<OptionValue>;
+ categories?: Array<Category>;
+ custom_fields?: Array<CustomField>;
+ prior_price?: PriceHistory | null;
+ status: string;
+ created_at: string;
+ updated_at: string;
+}
+
+export default Product;
diff --git a/packages/seller-sdk/src/types/generated/Seller.ts b/packages/seller-sdk/src/types/generated/Seller.ts
new file mode 100644
index 0000000000..6a93a4a9a7
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Seller.ts
@@ -0,0 +1,16 @@
+// Typelizer digest 857b5dc686d0fd5e0adb37a28883d302
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type Seller = {
+ id: string;
+ name: string;
+ slug: string;
+ about: string;
+ about_html: string;
+ logo_url: string | null;
+ square_logo_url: string | null;
+ cover_photo_url: string | null;
+}
+
+export default Seller;
diff --git a/packages/seller-sdk/src/types/generated/Variant.ts b/packages/seller-sdk/src/types/generated/Variant.ts
new file mode 100644
index 0000000000..0a0fdb0095
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Variant.ts
@@ -0,0 +1,32 @@
+// Typelizer digest 38bbefbdf6fa332789331b0ded11a43e
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {Price, PriceHistory, Media, OptionValue, CustomField} from '@/types'
+
+type Variant = {
+ id: string;
+ product_id: string;
+ sku: string | null;
+ options_text: string;
+ track_inventory: boolean;
+ media_count: number;
+ preorder_ships_at: string | null;
+ thumbnail_url: string | null;
+ purchasable: boolean;
+ in_stock: boolean;
+ backorderable: boolean;
+ preorder: boolean;
+ weight: number | null;
+ height: number | null;
+ width: number | null;
+ depth: number | null;
+ price: Price;
+ original_price: Price | null;
+ primary_media?: Media;
+ media?: Array<Media>;
+ option_values: Array<OptionValue>;
+ custom_fields?: Array<CustomField>;
+ prior_price?: PriceHistory | null;
+}
+
+export default Variant;
diff --git a/packages/seller-sdk/src/types/generated/index.ts b/packages/seller-sdk/src/types/generated/index.ts
index f055630176..059b57c18c 100644
--- a/packages/seller-sdk/src/types/generated/index.ts
+++ b/packages/seller-sdk/src/types/generated/index.ts
@@ -1,7 +1,17 @@
-// Typelizer digest 8ec41eedc9512a04635310303372ff56
+// Typelizer digest c91458a759831a127619fdc0158cbfaa
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
+export type { default as Category } from './Category'
+export type { default as CustomField } from './CustomField'
+export type { default as Media } from './Media'
+export type { default as OptionType } from './OptionType'
+export type { default as OptionValue } from './OptionValue'
+export type { default as PriceHistory } from './PriceHistory'
+export type { default as Price } from './Price'
export type { default as Invitation } from './Invitation'
+export type { default as Product } from './Product'
export type { default as Profile } from './Profile'
export type { default as TeamMember } from './TeamMember'
+export type { default as Seller } from './Seller'
+export type { default as Variant } from './Variant'
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/permission_serialization.rb b/spree/api/app/controllers/concerns/spree/api/v3/permission_serialization.rb
new file mode 100644
index 0000000000..7ba9868274
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/permission_serialization.rb
@@ -0,0 +1,48 @@
+module Spree
+ module Api
+ module V3
+ # Turns a CanCanCan ability into the flat, JSON-safe shape the panels'
+ # `<Can>` reads. Shared by every `/me` endpoint — the admin and seller
+ # branches answer different audiences, but the frontend permission model
+ # is one implementation, so its input has to be too.
+ #
+ # - Rule order is preserved so the frontend matcher can apply
+ # CanCanCan's "last matching rule wins" semantics.
+ # - Per-record conditions are NOT serialized (they often reference
+ # scopes or blocks that don't translate to JSON). The frontend
+ # receives `has_conditions: true` as a hint that the action might be
+ # denied at the per-record level — in practice the SPA shows the
+ # action optimistically and handles 403 from the API.
+ module PermissionSerialization
+ extend ActiveSupport::Concern
+
+ private
+
+ def serialize_permissions(ability)
+ ability.send(:rules).map do |rule|
+ {
+ allow: rule.base_behavior,
+ actions: Array(rule.actions).map(&:to_s),
+ subjects: Array(rule.subjects).map { |subject| subject.is_a?(Class) ? subject.name : subject.to_s },
+ has_conditions: rule_has_conditions?(rule)
+ }
+ end
+ end
+
+ def serialize_permission_keys(ability)
+ ability.respond_to?(:permission_keys) ? ability.permission_keys : []
+ end
+
+ def rule_has_conditions?(rule)
+ return true if rule.block.present?
+
+ conditions = rule.conditions
+ return false if conditions.nil?
+ return !conditions.empty? if conditions.respond_to?(:empty?)
+
+ true
+ end
+ end
+ end
+ end
+end
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 3bf68c8d56..31ef85ab6f 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
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class MeController < Admin::BaseController
+ include Spree::Api::V3::PermissionSerialization
+
skip_scope_check!
before_action :require_current_user!
@@ -68,41 +70,6 @@ module Spree
}
end
- # The flat expanded catalog keys the user holds on the current store —
- # the same currency the key gate enforces and the role editor grants.
- def serialize_permission_keys(ability)
- ability.respond_to?(:permission_keys) ? ability.permission_keys : []
- end
-
- # Serializes CanCanCan's rules into a flat, JSON-safe list of permission rules.
- #
- # - Rule order is preserved so the frontend matcher can apply
- # CanCanCan's "last matching rule wins" semantics.
- # - Per-record conditions are NOT serialized (they often reference
- # scopes or blocks that don't translate to JSON). The frontend
- # receives `has_conditions: true` as a hint that the action might
- # be denied at the per-record level — in practice the SPA shows
- # the action optimistically and handles 403 from the API.
- def serialize_permissions(ability)
- ability.send(:rules).map do |rule|
- {
- allow: rule.base_behavior,
- actions: Array(rule.actions).map(&:to_s),
- subjects: Array(rule.subjects).map { |s| s.is_a?(Class) ? s.name : s.to_s },
- has_conditions: rule_has_conditions?(rule)
- }
- end
- end
-
- def rule_has_conditions?(rule)
- return true if rule.block.present?
- conditions = rule.conditions
- return false if conditions.nil?
- return !conditions.empty? if conditions.respond_to?(:empty?)
-
- true
- end
-
def admin_user_serializer
Spree.api.admin_admin_user_serializer
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/me_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/me_controller.rb
index 00e7f5e608..c2a320fda6 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/me_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/me_controller.rb
@@ -10,6 +10,8 @@ module Spree
# is chosen. Sending the header still narrows `permission_keys` to that
# seller.
class MeController < Seller::BaseController
+ include Spree::Api::V3::PermissionSerialization
+
skip_scope_check!
skip_before_action :set_current_seller_context
before_action :require_current_user!
@@ -24,7 +26,12 @@ module Spree
{
user: Spree.api.seller_team_member_serializer.new(current_user, params: serializer_params).to_h,
sellers: serialized_sellers,
- permission_keys: permission_keys
+ # Both shapes, exactly as the admin `/me`: the panel's `<Can>`
+ # reads CanCanCan rules, the key gate reads keys. Sending only
+ # keys left `<Can>` answering false for everything on the seller
+ # panel — silently, since nothing gated on it yet.
+ permissions: serialize_permissions(seller_ability),
+ permission_keys: serialize_permission_keys(seller_ability)
}
end
@@ -35,12 +42,13 @@ module Spree
end
# Empty until a seller is named: capability is per seller, so there is
- # no meaningful answer spanning all of them.
- def permission_keys
- return [] if current_seller.nil?
+ # no meaningful answer spanning all of them. A bare ability (no
+ # resource) serializes to nothing rather than raising, so the panel
+ # can call `/me` before choosing a seller.
+ def seller_ability
+ return Spree::Ability.new(nil) if current_seller.nil?
- ability = current_ability
- ability.respond_to?(:permission_keys) ? ability.permission_keys : []
+ current_ability
end
def serializer_params
diff --git a/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb
new file mode 100644
index 0000000000..8e90573608
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb
@@ -0,0 +1,59 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # A seller's own products.
+ #
+ # The first consumer of `Seller::ResourceController`, and the shape
+ # every seller-side collection follows: the anchor roots `scope` in
+ # `current_seller.products`, so listing, finding, updating and
+ # deleting can only ever touch this seller's rows — a product id that
+ # belongs to another seller is a 404, not a 403, since the caller
+ # cannot tell whether it exists.
+ #
+ # Owned products only. Variants a seller lists against a shared
+ # master-catalog product are a separate surface (the shared catalog
+ # phase) and do not belong to this seller through `products`.
+ #
+ # What a seller may change is narrower than the operator's set:
+ # `tax_category_id` and `delivery_profile_id` are marketplace
+ # configuration and stay with the operator, as does `promotionable`.
+ class ProductsController < Seller::ResourceController
+ scoped_resource :products
+
+ protected
+
+ def model_class
+ Spree::Product
+ end
+
+ def serializer_class
+ Spree.api.seller_product_serializer
+ end
+
+ def permitted_params
+ params.permit(
+ :name, :description, :slug, :status,
+ :meta_title, :meta_description, :meta_keywords,
+ :product_type_id,
+ tags: [],
+ category_ids: [],
+ metadata: {},
+ prices: [:amount, :compare_at_amount, :currency]
+ )
+ end
+
+ # A new product is this seller's, whatever the payload says — the
+ # anchor's scope makes it findable, and the store follows the seller.
+ def build_resource
+ current_seller.products.new(permitted_params.merge(store: current_store))
+ end
+
+ def collection_includes
+ [:default_variant, :primary_media]
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/address_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/address_serializer.rb
deleted file mode 100644
index 4cbf38545a..0000000000
--- a/spree/api/app/serializers/spree/api/v3/seller/address_serializer.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-module Spree
- module Api
- module V3
- module Seller
- # A seller's own address, as they see it.
- #
- # Identical to the storefront's — an address is an address — but it
- # lives in this namespace so the seller SDK generates its own type
- # rather than importing one from a package it does not depend on.
- class AddressSerializer < V3::AddressSerializer
- end
- end
- end
- end
-end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/product_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/product_serializer.rb
new file mode 100644
index 0000000000..1bb2b79618
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/seller/product_serializer.rb
@@ -0,0 +1,25 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # A seller's own product, as they manage it.
+ #
+ # Extends the store serializer, NOT the admin one, deliberately. The
+ # admin serializer's nested associations (`variants`, `channels`,
+ # `product_publications`) render through admin serializers that carry
+ # operator data — cost prices, publication state, internal metadata —
+ # and a seller must not read those even on their own product. The
+ # store serializer's nested pieces are all customer-safe, so building
+ # up from there means nothing leaks by inheritance.
+ #
+ # On top of the public view, a seller needs `status` (their product may
+ # be a draft the storefront cannot see yet) and timestamps.
+ class ProductSerializer < V3::ProductSerializer
+ typelize status: :string
+
+ attributes :status, created_at: :iso8601, updated_at: :iso8601
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb
index 4e0544fbc1..b8711ca838 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb
@@ -47,11 +47,11 @@ module Spree
end
one :billing_address,
- resource: proc { Spree.api.seller_address_serializer },
+ resource: proc { Spree.api.address_serializer },
if: proc { |seller| seller.billing_address.present? }
one :returns_address,
- resource: proc { Spree.api.seller_address_serializer },
+ resource: proc { Spree.api.address_serializer },
if: proc { |seller| seller.returns_address.present? }
end
end
diff --git a/spree/api/config/initializers/typelizer.rb b/spree/api/config/initializers/typelizer.rb
index a081890124..ccbe24a6de 100644
--- a/spree/api/config/initializers/typelizer.rb
+++ b/spree/api/config/initializers/typelizer.rb
@@ -55,15 +55,42 @@ Rails.application.config.after_initialize do
}
end
- # Seller SDK — the seller panel's own branch. Keyed on the `::Seller::`
- # namespace exactly as admin is on `::Admin::`, which is why seller
- # serializers must live there and nowhere else.
+ # Seller SDK — the seller panel's own branch.
+ #
+ # Emits every `::Seller::` serializer PLUS the store-level serializers a
+ # seller serializer nests. Seller serializers extend store ones (a
+ # seller's product renders its media, variants and categories through the
+ # public shapes — those are exactly what a seller may see of their own
+ # record), so the referenced types have to exist in this package too. Admin
+ # avoids the same problem by shipping an admin twin of every store
+ # serializer it references; the seller branch is deliberately thinner and
+ # borrows the store shapes as-is.
+ #
+ # Store-level names are emitted only when a seller serializer reaches
+ # them — the `store_nested_for_seller` set — so this package does not
+ # grow into a second copy of the whole store SDK.
+ store_nested_for_seller = %w[
+ Address Category CustomField Media OptionType OptionValue
+ Price PriceHistory Seller Variant
+ ].to_set
+
config.writer(:seller) do |c|
c.output_dir = api_root.join('../../packages/seller-sdk/src/types/generated')
- c.reject_class = ->(serializer:) { !serializer.name.to_s.include?('::Seller::') }
+ c.reject_class = ->(serializer:) {
+ name = serializer.name.to_s
+ # Everything on the seller branch is in.
+ next false if name.include?('::Seller::')
+ # Nothing from the admin branch, ever.
+ next true if name.include?('::Admin::')
+
+ # A store-level serializer is in only if a seller serializer nests it.
+ bare = name.sub(/\ASpree::Api::V3::/, '').sub(/Serializer\z/, '')
+ !store_nested_for_seller.include?(bare)
+ }
c.serializer_name_mapper = ->(serializer) {
serializer.name.to_s
.sub(/\ASpree::Api::V3::Seller::/, '')
+ .sub(/\ASpree::Api::V3::/, '')
.sub(/Serializer\z/, '')
}
end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 28a0a342d9..f4e2fd502b 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -681,6 +681,10 @@ Spree::Core::Engine.add_routes do
patch :resend
end
end
+
+ # A seller's own catalog. The first collection on this branch, and the
+ # shape every later one follows — rooted in the seller by the anchor.
+ resources :products, only: [:index, :show, :create, :update, :destroy]
end
# Webhooks (outside of store namespace — no API key authentication)
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 66857daff1..36cf88a327 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -157,9 +157,9 @@ module Spree
admin_admin_user_serializer: 'Spree::Api::V3::Admin::AdminUserSerializer',
seller_serializer: 'Spree::Api::V3::SellerSerializer',
seller_profile_serializer: 'Spree::Api::V3::Seller::ProfileSerializer',
- seller_address_serializer: 'Spree::Api::V3::Seller::AddressSerializer',
seller_team_member_serializer: 'Spree::Api::V3::Seller::TeamMemberSerializer',
seller_invitation_serializer: 'Spree::Api::V3::Seller::InvitationSerializer',
+ seller_product_serializer: 'Spree::Api::V3::Seller::ProductSerializer',
admin_seller_serializer: 'Spree::Api::V3::Admin::SellerSerializer',
admin_seller_requirement_serializer: 'Spree::Api::V3::Admin::SellerRequirementSerializer',
admin_seller_requirement_submission_serializer: 'Spree::Api::V3::Admin::SellerRequirementSubmissionSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/me_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/me_controller_spec.rb
index 657a7a9239..9676da11d1 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/me_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/me_controller_spec.rb
@@ -40,4 +40,25 @@ RSpec.describe Spree::Api::V3::Seller::MeController, type: :controller do
expect(json_response['permission_keys']).to include('write_seller_profile', 'write_products')
end
+
+ # The panel's `<Can>` reads CanCanCan rules, not keys — same code as the
+ # operator's dashboard. Sending only keys left every `<Can>` answering false
+ # on the seller panel, silently.
+ it 'serializes CanCanCan rules so the panel can gate on them' do
+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id
+
+ get :show, as: :json
+
+ rules = json_response['permissions']
+ expect(rules).to be_present
+ expect(rules).to include(
+ a_hash_including('allow' => true, 'subjects' => include('Spree::Product'))
+ )
+ end
+
+ it 'serializes no rules until a seller is named' do
+ get :show, as: :json
+
+ expect(json_response['permissions']).to eq([])
+ end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb
new file mode 100644
index 0000000000..1af1441470
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb
@@ -0,0 +1,134 @@
+require 'spec_helper'
+
+# The first collection on the seller branch, so this doubles as the proof that
+# `Seller::ResourceController` roots everything in the seller. Every later
+# collection (orders, returns) inherits exactly this behaviour.
+RSpec.describe Spree::Api::V3::Seller::ProductsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Seller'
+
+ let(:seller_user) do
+ create(:admin_user, :without_admin_role).tap { |user| seller.add_user(user) }
+ end
+ let(:token) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ seller_user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_SELLER
+ )
+ end
+
+ let!(:mine) { create(:product, name: 'My Lamp', seller: seller, store: store) }
+ let(:other_seller) { create(:seller, :approved, store: store) }
+ let!(:theirs) { create(:product, name: 'Their Lamp', seller: other_seller, store: store) }
+ let!(:first_party) { create(:product, name: 'Marketplace Lamp', store: store) }
+
+ before do
+ request.headers['Authorization'] = "Bearer #{token}"
+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id
+ end
+
+ describe 'GET #index' do
+ it "lists only this seller's products" do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ names = json_response['data'].pluck('name')
+ expect(names).to include('My Lamp')
+ expect(names).not_to include('Their Lamp', 'Marketplace Lamp')
+ end
+
+ it 'exposes status, which the storefront serializer withholds' do
+ get :index, as: :json
+
+ expect(json_response['data'].first).to include('status')
+ end
+ end
+
+ describe 'GET #show' do
+ it 'returns their own product' do
+ get :show, params: { id: mine.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['name']).to eq('My Lamp')
+ end
+
+ # 404, not 403: the caller cannot tell whether the id exists at all.
+ it "404s on another seller's product" do
+ get :show, params: { id: theirs.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it '404s on a first-party product' do
+ get :show, params: { id: first_party.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'POST #create' do
+ it 'creates the product as this seller, whatever the payload says' do
+ post :create,
+ params: { name: 'New Lamp', status: 'draft', seller_id: other_seller.prefixed_id },
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ product = Spree::Product.find_by(name: 'New Lamp')
+ expect(product.seller).to eq(seller)
+ expect(product.store).to eq(store)
+ end
+ end
+
+ describe 'PATCH #update' do
+ it 'edits their own product' do
+ patch :update, params: { id: mine.prefixed_id, name: 'Renamed Lamp' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(mine.reload.name).to eq('Renamed Lamp')
+ end
+
+ it "cannot edit another seller's product" do
+ patch :update, params: { id: theirs.prefixed_id, name: 'Hijacked' }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(theirs.reload.name).to eq('Their Lamp')
+ end
+
+ # Marketplace configuration stays with the operator.
+ it 'ignores tax and delivery configuration' do
+ other_tax = create(:tax_category)
+
+ patch :update, params: { id: mine.prefixed_id, tax_category_id: other_tax.prefixed_id }, as: :json
+
+ expect(mine.reload.tax_category).not_to eq(other_tax)
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it "cannot delete another seller's product" do
+ delete :destroy, params: { id: theirs.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(theirs.reload).to be_present
+ end
+ end
+
+ # A member whose role lacks the products key is refused by the gate before
+ # the scope is even consulted.
+ context 'without write_products' do
+ let(:narrow_role) { create(:role, name: 'Viewer', resource: seller, permissions: %w[read_products]) }
+ let(:seller_user) do
+ create(:admin_user, :without_admin_role).tap { |user| seller.add_user(user, narrow_role) }
+ end
+
+ it 'can read' do
+ get :index, as: :json
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'cannot write' do
+ patch :update, params: { id: mine.prefixed_id, name: 'Nope' }, as: :json
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+end