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
Share the duplicated seller and admin API code
Damian Legawiec06a8d73221d2
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/address_params.rb b/spree/api/app/controllers/concerns/spree/api/v3/address_params.rbnew file mode 100644index 0000000000..c28605435e--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/address_params.rb@@ -0,0 +1,17 @@+module Spree+ module Api+ module V3+ # The writable attributes of a nested address.+ #+ # One list rather than one per controller: an address is the same record+ # wherever it hangs, so a column added on one write path but missed on+ # another is dropped silently.+ module AddressParams+ ADDRESS_KEYS = [+ :first_name, :last_name, :company, :address1, :address2, :city,+ :postal_code, :zipcode, :phone, :country_code, :state_code, :state_name, :label+ ].freeze+ end+ end+ end+enddiff --git a/spree/api/app/controllers/concerns/spree/api/v3/direct_uploads.rb b/spree/api/app/controllers/concerns/spree/api/v3/direct_uploads.rbnew file mode 100644index 0000000000..47a5881286--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/direct_uploads.rb@@ -0,0 +1,35 @@+module Spree+ module Api+ module V3+ # Presigning for direct-to-storage uploads: a caller exchanges blob+ # metadata for an upload URL and gets back a signed id to reference when+ # it creates or updates a resource.+ #+ # Shared by the admin and seller branches because the exchange itself is+ # audience-neutral — a blob created here is attached to nothing. What+ # differs is the gate each branch puts in front of it, which stays on the+ # including controller as its `scoped_resource`.+ module DirectUploads+ extend ActiveSupport::Concern++ def create+ blob = ActiveStorage::Blob.create_before_direct_upload!(**blob_params)++ render json: {+ direct_upload: {+ url: blob.service_url_for_direct_upload,+ headers: blob.service_headers_for_direct_upload+ },+ signed_id: blob.signed_id+ }, status: :created+ end++ private++ def blob_params+ params.require(:blob).permit(:filename, :byte_size, :checksum, :content_type).to_h.symbolize_keys+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/concerns/spree/api/v3/permission_serialization.rb b/spree/api/app/controllers/concerns/spree/api/v3/permission_serialization.rbindex 7ba9868274..500873677e 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/permission_serialization.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/permission_serialization.rb@@ -34,13 +34,7 @@ module Spreeenddef 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+ rule.block.present? || rule.conditions.present?endendenddiff --git a/spree/api/app/controllers/concerns/spree/api/v3/seller/seller_context.rb b/spree/api/app/controllers/concerns/spree/api/v3/seller/seller_context.rbindex e7311679ad..a4e249efde 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/seller/seller_context.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/seller/seller_context.rb@@ -12,8 +12,8 @@ module Spree# all, which is an error rather than a default.## Included into both branch anchors (BaseController and- # ResourceController): they are parallel inheritance chains, so a- # concern on one is not on the other.+ # ResourceController) — parallel chains, so a concern on one is not on+ # the other.module SellerContextextend ActiveSupport::Concern@@ -36,18 +36,13 @@ module Spree# the caller belongs to.## @return [Spree::Seller, nil]+ # `||=` rather than a `defined?` memo on purpose: a nil must not+ # stick. The locale/currency chain reads `current_store` — and so+ # this — before authentication has run, and caching that first miss+ # would leave a controller which skips the context callback+ # (MeController) permanently seller-less even with a valid header.def current_seller- return @current_seller if defined?(@current_seller) && !@current_seller.nil?-- # Deliberately not memoising a nil: the locale/currency chain reads- # `current_store` — and so this — before authentication has run, and- # caching that first miss would leave a controller which skips the- # context callback (MeController) permanently without a seller even with- # a valid header.- resolved = resolve_current_seller- @current_seller = resolved if resolved-- resolved+ @current_seller ||= resolve_current_sellerend# Derived from the seller, so a seller can never widen their reach bydiff --git a/spree/api/app/controllers/spree/api/v3/admin/concerns/company_location_params.rb b/spree/api/app/controllers/spree/api/v3/admin/concerns/company_location_params.rbindex f09eafad56..3635031c2c 100644--- a/spree/api/app/controllers/spree/api/v3/admin/concerns/company_location_params.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/concerns/company_location_params.rb@@ -10,19 +10,14 @@ module Spree# Enumerated rather than borrowing the legacy global list, which# permits :id, :user_id and :deleted_at.- ADDRESS_KEYS = [- :first_name, :last_name, :company, :address1, :address2, :city,- :postal_code, :zipcode, :phone, :country_code, :state_code, :state_name, :label- ].freeze-protecteddef permitted_paramsparams.permit(:name,metadata: {},- billing_address: ADDRESS_KEYS,- shipping_address: ADDRESS_KEYS+ billing_address: Spree::Api::V3::AddressParams::ADDRESS_KEYS,+ shipping_address: Spree::Api::V3::AddressParams::ADDRESS_KEYS)endenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rbindex c7c611f04c..91fc8171e3 100644--- a/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rb@@ -3,6 +3,8 @@ module Spreemodule V3module Adminclass DirectUploadsController < Admin::BaseController+ include Spree::Api::V3::DirectUploads+# Direct uploads is a write-adjacent presigning helper: callers exchange# blob metadata for an upload URL, then reference the resulting# signed_id when creating/updating a resource (product media, customer@@ -14,25 +16,6 @@ module Spreescoped_resource :productsskip_before_action :authenticate_user-- # POST /api/v3/admin/direct_uploads- def create- blob = ActiveStorage::Blob.create_before_direct_upload!(**blob_params)-- render json: {- direct_upload: {- url: blob.service_url_for_direct_upload,- headers: blob.service_headers_for_direct_upload- },- signed_id: blob.signed_id- }, status: :created- end-- private-- def blob_params- params.require(:blob).permit(:filename, :byte_size, :checksum, :content_type).to_h.symbolize_keys- endendendenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rbindex 4dec9e4594..f3fc96dc90 100644--- a/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rb@@ -123,11 +123,6 @@ module Spree# Enumerated rather than borrowing the legacy global list, which# permits :id, :user_id and :deleted_at — the first of which would# reintroduce the address-by-id hole below.- ADDRESS_KEYS = [- :first_name, :last_name, :company, :address1, :address2, :city,- :postal_code, :zipcode, :phone, :country_code, :state_code, :state_name, :label- ].freeze-# The seller's own profile fields, plus the settlement and tax# configuration only the operator sets. `status` is absent by# design — see the class comment.@@ -145,7 +140,7 @@ module Spree:holiday_mode_until,:legal_name, :registration_number,metadata: {},- billing_address: ADDRESS_KEYS,+ billing_address: Spree::Api::V3::AddressParams::ADDRESS_KEYS,custom_fields: [:id, :custom_field_definition_id, :value, { value: [] }, { value: {} }]))enddiff --git a/spree/api/app/controllers/spree/api/v3/seller/direct_uploads_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/direct_uploads_controller.rbindex c4eb7f19c9..27ee184bd3 100644--- a/spree/api/app/controllers/spree/api/v3/seller/direct_uploads_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/direct_uploads_controller.rb@@ -11,26 +11,9 @@ module Spree# narrowest meaningful gate is the seller's own profile, which every# member of a seller's team holds.class DirectUploadsController < Seller::BaseController- scoped_resource :seller_profile-- # POST /api/v3/seller/direct_uploads- def create- blob = ActiveStorage::Blob.create_before_direct_upload!(**blob_params)-- render json: {- direct_upload: {- url: blob.service_url_for_direct_upload,- headers: blob.service_headers_for_direct_upload- },- signed_id: blob.signed_id- }, status: :created- end+ include Spree::Api::V3::DirectUploads- private-- def blob_params- params.require(:blob).permit(:filename, :byte_size, :checksum, :content_type).to_h.symbolize_keys- end+ scoped_resource :seller_profileendendenddiff --git a/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/products_controller.rbindex 8e90573608..d014a9c399 100644--- a/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb@@ -43,12 +43,6 @@ module Spree)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]enddiff --git a/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rbindex 59fe22d821..6eaf867af2 100644--- a/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb@@ -59,11 +59,6 @@ module Spree# Enumerated rather than borrowing the legacy global list, which# permits :id, :user_id and :deleted_at.- ADDRESS_KEYS = [- :first_name, :last_name, :company, :address1, :address2, :city,- :postal_code, :zipcode, :phone, :country_code, :state_code, :state_name, :label- ].freeze-# Accepting the marketplace's terms is a profile write, not an endpoint# of its own: `accept_terms: true` stamps the time, which is what the# AcceptTerms requirement reads.@@ -90,18 +85,12 @@ module Spree# verified that nobody has checked.def upsert_tax_identifier(attributes)kind = attributes[:kind].presence- value = attributes[:value]return if kind.blank?- identifier = current_seller.tax_identifiers.find_or_initialize_by(kind: kind)-- if value.blank?- identifier.destroy if identifier.persisted?- return- end+ value = attributes[:value]+ return current_seller.tax_identifiers.find_by(kind: kind)&.destroy if value.blank?- identifier.value = value- identifier.save+ current_seller.tax_identifiers.find_or_initialize_by(kind: kind).update(value: value)end# Narrowed to the definitions this marketplace's onboarding actually@@ -133,7 +122,7 @@ module Spree:legal_name, :registration_number,:logo, :square_logo, :cover_photo,tax_identifier: [:kind, :value],- billing_address: ADDRESS_KEYS,+ billing_address: Spree::Api::V3::AddressParams::ADDRESS_KEYS,custom_fields: [:id, :custom_field_definition_id, :value,{ value: [] }, { value: {} }]))diff --git a/spree/api/app/controllers/spree/api/v3/seller/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/resource_controller.rbindex 8cf4d86003..f839240dce 100644--- a/spree/api/app/controllers/spree/api/v3/seller/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/resource_controller.rb@@ -34,6 +34,20 @@ module Spreemodel_class.include?(Spree::TranslatableResource) ? base_scope.i18n : base_scopeend+ # A new record is this seller's, whatever the payload says, and its+ # store follows the seller rather than the request.+ def resource_scope+ return super if @parent.present?++ current_seller.public_send(seller_association)+ end++ def build_resource+ resource = super+ resource.store = current_store if resource.respond_to?(:store=)+ resource+ end+# The seller association this controller reads through, defaulting to# the model's plural name (`Spree::Product` -> `products`). Override# when the association is named differently.diff --git a/spree/api/app/controllers/spree/api/v3/seller/stock_locations_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/stock_locations_controller.rbindex 9400cc0b81..7dfca5561b 100644--- a/spree/api/app/controllers/spree/api/v3/seller/stock_locations_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/stock_locations_controller.rb@@ -49,11 +49,6 @@ module Spree:pickup_ready_in_minutes, :pickup_instructions)end-- # A new location is this seller's, and its store follows them.- def build_resource- current_seller.stock_locations.new(permitted_params.merge(store: current_store))- endendendenddiff --git a/spree/api/app/serializers/spree/api/v3/seller/requirement_status_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/requirement_status_serializer.rbindex 0321417ad3..6d49490dba 100644--- a/spree/api/app/serializers/spree/api/v3/seller/requirement_status_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/seller/requirement_status_serializer.rb@@ -28,7 +28,7 @@ module Spreeendattribute :accepted_content_types do |status|- status.requirement.class.requires_file? ? status.requirement.class.accepted_content_types : []+ status.requirement.accepted_content_typesendone :submission,@@ -37,7 +37,7 @@ module Spreemany :custom_fields,resource: proc { Spree.api.seller_requirement_custom_field_serializer },- if: proc { |status| status.respond_to?(:custom_fields) && status.custom_fields.any? } do |status|+ if: proc { |status| status.custom_fields.any? } do |status|status.custom_fieldsendenddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex df3242791c..67f9b14c55 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -666,46 +666,34 @@ Spree::Core::Engine.add_routes doget 'me', to: 'me#show'- # The seller's own record. Singular — there is exactly one seller in- # play and it is `current_seller`, never an id from the request.+ # Singular: the seller in play is always `current_seller`.resource :profile, only: [:show, :update], controller: 'profile'- # Who runs this seller. Inviting reuses the operator's workflow, so- # there is one invitation rail and one set of hooks.resources :team, only: [:index, :create, :destroy], controller: 'team'- # Offers not yet accepted. Creating one is hiring, so it lives on- # `team`; chasing or withdrawing one is bookkeeping on the offer.+ # Creating an invitation is hiring, so it lives on `team`; chasing or+ # withdrawing one is bookkeeping on the offer.resources :invitations, only: [:index, :destroy], controller: 'invitations' domember dopatch :resendendend- # 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]- # Presigning for the documents onboarding asks a seller to upload.resources :direct_uploads, only: [:create]- # Where this seller keeps stock, and so where their returns are sent.# No destroy: a location holds stock levels and is named on historical# fulfillments, so a seller retires one by deactivating it.resources :stock_locations, only: [:index, :show, :create, :update]- # Reference data for the panel's address forms — the same list the- # storefront serves, not narrowed to the marketplace's markets.resources :countries, only: [:index]- # What the marketplace asks of this seller. Singular: the checklist is- # always `current_seller`'s, never an id from the request.+ # Singular: the checklist is always `current_seller`'s.resource :onboarding, only: [:show], controller: 'onboarding' dopost :submit_for_reviewend- # Submissions are created against a requirement and read back through- # the seller who made them.resources :requirements, only: [] doresources :submissions, only: [:create], controller: 'requirement_submissions'enddiff --git a/spree/core/app/models/spree/seller_requirement_status.rb b/spree/core/app/models/spree/seller_requirement_status.rbindex 8ef0e9ddf3..5b9223dee1 100644--- a/spree/core/app/models/spree/seller_requirement_status.rb+++ b/spree/core/app/models/spree/seller_requirement_status.rb@@ -59,12 +59,12 @@ module Spree## @return [Array<Hash>] `{ definition:, custom_field: }` pairsdef custom_fields- return [] unless requirement.respond_to?(:custom_field_definitions)- return [] if seller.nil?+ return @custom_fields if defined?(@custom_fields)+ return @custom_fields = [] if seller.nil? || !requirement.respond_to?(:custom_field_definitions)answered = seller.custom_fields.index_by(&:custom_field_definition_id)- requirement.custom_field_definitions.map do |definition|+ @custom_fields = requirement.custom_field_definitions.map do |definition|{ definition: definition, custom_field: answered[definition.id] }endenddiff --git a/spree/core/app/models/spree/seller_requirement_submission.rb b/spree/core/app/models/spree/seller_requirement_submission.rbindex 4374bef134..c763eaf369 100644--- a/spree/core/app/models/spree/seller_requirement_submission.rb+++ b/spree/core/app/models/spree/seller_requirement_submission.rb@@ -43,22 +43,16 @@ module Spree#validate :requirement_belongs_to_sellers_store- # Sellers are the marketplace's lower-trust writers, and these files are- # opened by an operator on their own machine — so the bytes decide what a- # file is, not the header the uploader sent.+ # Sellers are the marketplace's lower-trust writers and an operator opens+ # these files on their own machine, so the bytes decide what a file is,+ # not the header the uploader sent. `spoofing_protection` is what makes+ # that true: without it a script named `certificate.pdf` passes.#- # `spoofing_protection` is what makes that true: without it the gem takes- # the declared type and filename at face value, and a script named- # `certificate.pdf` passes. With it, Marcel reads the magic bytes and the- # two must agree.- #- # The list belongs to the kind that asks for files, which already- # publishes it and whose value the seller API serializes so the panel's- # picker can hint it. Resolved in a lambda rather than referenced at- # class-definition time, which would pin the autoload order.+ # The accepted list comes from the requirement's own kind, the same value+ # the seller API serializes so the panel's picker can hint it.validates :file,content_type: {- in: ->(_record) { Spree::SellerRequirements::Document::ACCEPTED_CONTENT_TYPES },+ in: ->(record) { record.requirement&.accepted_content_types || [] },spoofing_protection: true},size: { less_than_or_equal_to: ->(_record) { Spree::Config.max_seller_document_upload_size } },diff --git a/spree/core/app/models/spree/stock_location.rb b/spree/core/app/models/spree/stock_location.rbindex 7706179b45..6ee4065047 100644--- a/spree/core/app/models/spree/stock_location.rb+++ b/spree/core/app/models/spree/stock_location.rb@@ -31,9 +31,9 @@ module Spree# that is not a marketplace.belongs_to :seller, class_name: 'Spree::Seller', optional: true, inverse_of: :stock_locations- # Name uniqueness is per owner rather than per store (see UniqueName, which- # this deliberately does not include): an operator and each of their sellers- # may each have a "Warehouse", which is what a marketplace looks like.+ # Per owner rather than per store, which is why UniqueName is not included+ # here: an operator and each of their sellers may each have a "Warehouse",+ # which is what a marketplace looks like.normalizes :name, with: ->(value) { value&.to_s&.squish&.presence }validates :name, presence: true,uniqueness: { case_sensitive: false, allow_blank: true,diff --git a/spree/core/app/workflows/spree/returns/create.rb b/spree/core/app/workflows/spree/returns/create.rbindex adfed9db2c..93fec794ae 100644--- a/spree/core/app/workflows/spree/returns/create.rb+++ b/spree/core/app/workflows/spree/returns/create.rb@@ -114,6 +114,7 @@ module Spreedef seller_returns_location@normalized_items.+ lazy.filter_map { |item| item[:fulfillment_item].line_item&.seller }.first&.returns_locationenddiff --git a/spree/core/app/workflows/spree/seller_requirement_submissions/create.rb b/spree/core/app/workflows/spree/seller_requirement_submissions/create.rbindex 17c0270a19..47cf4fa3e6 100644--- a/spree/core/app/workflows/spree/seller_requirement_submissions/create.rb+++ b/spree/core/app/workflows/spree/seller_requirement_submissions/create.rb@@ -10,31 +10,17 @@ module Spree## == Scanning an uploaded document#- # Hook `after_create` and reject what the scanner does not like:+ # A marketplace that runs a virus scanner hooks `after_create` and moves+ # the submission to `rejected` on a bad verdict. It must be `after_create`+ # rather than `validate`: at validate time the blob is built but not yet+ # uploaded, so there is nothing in storage to read. By `after_create` the+ # bytes are there and the submission is `pending`, a state no operator+ # acts on. A slow scanner does the same from a background job.#- # Spree.hooks.register('seller_requirement_submissions.create.after_create') do |workflow|- # submission = workflow.submission- # next unless submission.file.attached?- #- # verdict = MyScanner.scan(submission.file.download)- # if verdict.infected?- # submission.update!(status: 'rejected', review_note: 'Failed a virus scan.')- # end- # end- #- # `after_create` rather than `validate`, which is where a rejection would- # normally go: at validate time the blob is built but not yet uploaded, so- # there is nothing in storage for a scanner to read. By `after_create` the- # bytes are there, and the submission is `pending` — a state no operator- # acts on — so moving it to `rejected` settles it before anyone opens it.- # A scanner that answers slowly should do the same from a background job- # keyed on the submission.- #- # Core ships no scanner: which one a marketplace runs is a deployment- # decision, and the hook is the whole contract. What core does guarantee- # is that a file's *type* is decided by its bytes rather than the header- # the uploader sent, and that its size is bounded — see- # Spree::SellerRequirementSubmission.+ # Core ships no scanner — which one to run is a deployment decision. What+ # core does guarantee is that a file's type is decided by its bytes rather+ # than the uploader's header, and that its size is bounded (see+ # Spree::SellerRequirementSubmission).class Create < Spree::Workflowhooks :validate, :after_create@@ -86,13 +72,12 @@ module Spreeend# A document with nothing attached records a check nobody can repeat, so- # it is refused here rather than reaching a reviewer empty — and a file- # in a format the operator said they cannot open is refused with it,- # since the setting is shown to sellers as a promise.+ # it is refused here rather than reaching a reviewer empty.+ ## Only that a file is here at all. What the file *is* — its real type- # and its size — is the model's business, where the validation reads- # the bytes rather than the header the uploader sent; repeating a- # weaker version of that check here is how the two drift apart.+ # and its size — is the model's business, where the validation reads the+ # bytes rather than the uploader's header; repeating a weaker version of+ # that check here is how the two drift apart.def ensure_file_acceptablereturn unless requirement.class.requires_file?return if submission.file.attached?diff --git a/spree/core/db/migrate/20260820000001_add_seller_business_identity_and_stock_locations.rb b/spree/core/db/migrate/20260820000001_add_seller_business_identity_and_stock_locations.rbindex fa5f469130..8ede344b7e 100644--- a/spree/core/db/migrate/20260820000001_add_seller_business_identity_and_stock_locations.rb+++ b/spree/core/db/migrate/20260820000001_add_seller_business_identity_and_stock_locations.rb@@ -13,12 +13,5 @@ class AddSellerBusinessIdentityAndStockLocations < ActiveRecord::Migration[8.1]# is invoiced.add_column :spree_sellers, :legal_name, :stringadd_column :spree_sellers, :registration_number, :string-- # A fifth owner for the tax registration (docs/plans/6.0-tax-provider.md- # Phase 7). The seller's VAT number needs the validation verdict and the- # retained evidence the model already carries: EU reverse charge on the- # commission invoice has to stay defensible years after the registry that- # answered has moved on.- add_reference :spree_tax_identifiers, :seller, null: trueendend