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
Expose seller requirements and onboarding on the Admin API
Damian Legawiec6ea16c5ac1ab
diff --git a/packages/admin-sdk/examples/seller_requirements/create.ts b/packages/admin-sdk/examples/seller_requirements/create.tsnew file mode 100644index 0000000000..52d3ff5e4e--- /dev/null+++ b/packages/admin-sdk/examples/seller_requirements/create.ts@@ -0,0 +1,22 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+// Asks every seller for a business registration before they can be approved.+// The wording is yours — `document` is one of the open-ended kinds, so a store+// can add as many as it needs, each with its own instructions.+const sellerRequirement = await client.sellerRequirements.create({+ type: 'document',+ name: 'Business registration',+ description: 'A copy of your certificate of incorporation.',+ required: true,+ preferences: { accepted_content_types: ['application/pdf'] },+})++// endregion:example++export { sellerRequirement }diff --git a/packages/admin-sdk/examples/seller_requirements/delete.ts b/packages/admin-sdk/examples/seller_requirements/delete.tsnew file mode 100644index 0000000000..dd84f8786b--- /dev/null+++ b/packages/admin-sdk/examples/seller_requirements/delete.ts@@ -0,0 +1,13 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+// Stops asking for this, and deletes what sellers submitted against it. To+// keep the record while pausing the ask, update it with `active: false`.+await client.sellerRequirements.delete('selreq_a1b2c3')++// endregion:examplediff --git a/packages/admin-sdk/examples/seller_requirements/list.ts b/packages/admin-sdk/examples/seller_requirements/list.tsnew file mode 100644index 0000000000..76ec9787aa--- /dev/null+++ b/packages/admin-sdk/examples/seller_requirements/list.ts@@ -0,0 +1,15 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+// The checklist in the order sellers work through it. `required` items block+// approval; the rest are shown as recommended.+const { data: sellerRequirements } = await client.sellerRequirements.list({ page: 1, limit: 25 })++// endregion:example++export { sellerRequirements }diff --git a/packages/admin-sdk/examples/seller_requirements/types.ts b/packages/admin-sdk/examples/seller_requirements/types.tsnew file mode 100644index 0000000000..2f1eb7a0a4--- /dev/null+++ b/packages/admin-sdk/examples/seller_requirements/types.ts@@ -0,0 +1,15 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+// What you can ask for, and the configuration each kind takes. A kind your own+// code registers server-side shows up here too.+const { data: requirementTypes } = await client.sellerRequirements.types()++// endregion:example++export { requirementTypes }diff --git a/packages/admin-sdk/examples/seller_requirements/update.ts b/packages/admin-sdk/examples/seller_requirements/update.tsnew file mode 100644index 0000000000..43c18c654d--- /dev/null+++ b/packages/admin-sdk/examples/seller_requirements/update.ts@@ -0,0 +1,17 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+// Asks for three products instead of one. Sellers who already met the old+// number see this return to their checklist.+const sellerRequirement = await client.sellerRequirements.update('selreq_a1b2c3', {+ preferences: { minimum_count: 3 },+})++// endregion:example++export { sellerRequirement }diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 6935a0ec87..3f840389fa 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -129,6 +129,7 @@ import type {CustomFieldDefinitionCreateParams,CustomFieldDefinitionUpdateParams,CustomFieldOwnerType,+ CustomFieldResourceType,CustomFieldUpdateParams,DeliveryMethodParams,DeliveryOriginGroupParams,@@ -205,9 +206,17 @@ import type {ReturnUpdateParams,RoleCreateParams,RoleUpdateParams,+ SellerApproveParams,SellerCreateParams,SellerInviteParams,+ SellerOnboarding,SellerRejectParams,+ SellerReopenOnboardingParams,+ SellerRequirementCreateParams,+ SellerRequirementReviewParams,+ SellerRequirementType,+ SellerRequirementUpdateParams,+ SellerRequirementWaiveParams,SellerSuspendParams,SellerUpdateParams,SetupCountries,@@ -296,6 +305,8 @@ import type {ReturnReason,Role,Seller,+ SellerRequirement,+ SellerRequirementSubmission,StockLevel,StockLocation,StockMovement,@@ -479,6 +490,17 @@ export class AdminClient {get: (id: string, options?: RequestOptions): Promise<CustomFieldDefinition> =>this.request<CustomFieldDefinition>('GET', `/custom_field_definitions/${id}`, options),+ /**+ * What a definition can be attached to. Comes from the server's registry,+ * so a resource an extension adds is offered without a dashboard release.+ */+ resourceTypes: (options?: RequestOptions): Promise<{ data: CustomFieldResourceType[] }> =>+ this.request<{ data: CustomFieldResourceType[] }>(+ 'GET',+ '/custom_field_definitions/resource_types',+ options,+ ),+create: (params: CustomFieldDefinitionCreateParams,options?: RequestOptions,@@ -2393,9 +2415,93 @@ export class AdminClient {invite: (id: string, params: SellerInviteParams, options?: RequestOptions): Promise<Seller> =>this.request<Seller>('POST', `/sellers/${id}/invite`, { ...options, body: params }),- /** Lets the seller trade — also the way back from suspended or rejected. */- approve: (id: string, options?: RequestOptions): Promise<Seller> =>- this.request<Seller>('PATCH', `/sellers/${id}/approve`, options),+ /**+ * Lets the seller trade — also the way back from suspended or rejected.+ * Refused while a required onboarding requirement is unmet, unless+ * `override_requirements` says the operator means it anyway.+ */+ approve: (+ id: string,+ params?: SellerApproveParams,+ options?: RequestOptions,+ ): Promise<Seller> =>+ this.request<Seller>('PATCH', `/sellers/${id}/approve`, { ...options, body: params }),++ /** Where this seller stands against the marketplace's checklist. */+ onboarding: (id: string, options?: RequestOptions): Promise<SellerOnboarding> =>+ this.request<SellerOnboarding>('GET', `/sellers/${id}/onboarding`, options),++ /** Sends a seller awaiting review back to onboarding, with a note. */+ reopenOnboarding: (+ id: string,+ params?: SellerReopenOnboardingParams,+ options?: RequestOptions,+ ): Promise<Seller> =>+ this.request<Seller>('PATCH', `/sellers/${id}/reopen_onboarding`, {+ ...options,+ body: params,+ }),++ /** What this seller submitted about the requirements, and its decisions. */+ requirementSubmissions: {+ list: (+ sellerId: string,+ params?: ListParams & Record<string, unknown>,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<SellerRequirementSubmission>> =>+ this.request<PaginatedResponse<SellerRequirementSubmission>>(+ 'GET',+ `/sellers/${sellerId}/requirement_submissions`,+ { ...options, params: params ? transformListParams(params) : undefined },+ ),++ get: (+ sellerId: string,+ id: string,+ options?: RequestOptions,+ ): Promise<SellerRequirementSubmission> =>+ this.request<SellerRequirementSubmission>(+ 'GET',+ `/sellers/${sellerId}/requirement_submissions/${id}`,+ options,+ ),++ accept: (+ sellerId: string,+ id: string,+ params?: SellerRequirementReviewParams,+ options?: RequestOptions,+ ): Promise<SellerRequirementSubmission> =>+ this.request<SellerRequirementSubmission>(+ 'PATCH',+ `/sellers/${sellerId}/requirement_submissions/${id}/accept`,+ { ...options, body: params },+ ),++ reject: (+ sellerId: string,+ id: string,+ params?: SellerRequirementReviewParams,+ options?: RequestOptions,+ ): Promise<SellerRequirementSubmission> =>+ this.request<SellerRequirementSubmission>(+ 'PATCH',+ `/sellers/${sellerId}/requirement_submissions/${id}/reject`,+ { ...options, body: params },+ ),++ /** Excuses this seller from one requirement the store asks of everyone. */+ waive: (+ sellerId: string,+ params: SellerRequirementWaiveParams,+ options?: RequestOptions,+ ): Promise<SellerRequirementSubmission> =>+ this.request<SellerRequirementSubmission>(+ 'POST',+ `/sellers/${sellerId}/requirement_submissions`,+ { ...options, body: params },+ ),+ },suspend: (id: string,@@ -2408,6 +2514,53 @@ export class AdminClient {this.request<Seller>('PATCH', `/sellers/${id}/reject`, { ...options, body: params }),}+ // ============================================+ // Seller onboarding requirements+ // ============================================++ /**+ * What this marketplace asks of a seller before it will let them trade.+ * Rows the operator composes from registered kinds — `types()` is what a+ * picker renders, and a marketplace's own kinds appear there as soon as+ * they are registered server-side.+ */+ readonly sellerRequirements = {+ list: (+ params?: ListParams & Record<string, unknown>,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<SellerRequirement>> =>+ this.request<PaginatedResponse<SellerRequirement>>('GET', '/seller_requirements', {+ ...options,+ params: params ? transformListParams(params) : undefined,+ }),++ get: (id: string, options?: RequestOptions): Promise<SellerRequirement> =>+ this.request<SellerRequirement>('GET', `/seller_requirements/${id}`, options),++ create: (+ params: SellerRequirementCreateParams,+ options?: RequestOptions,+ ): Promise<SellerRequirement> =>+ this.request<SellerRequirement>('POST', '/seller_requirements', { ...options, body: params }),++ update: (+ id: string,+ params: SellerRequirementUpdateParams,+ options?: RequestOptions,+ ): Promise<SellerRequirement> =>+ this.request<SellerRequirement>('PATCH', `/seller_requirements/${id}`, {+ ...options,+ body: params,+ }),++ delete: (id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>('DELETE', `/seller_requirements/${id}`, options),++ /** The kinds an operator can add, with each one's configuration shape. */+ types: (options?: RequestOptions): Promise<{ data: SellerRequirementType[] }> =>+ this.request<{ data: SellerRequirementType[] }>('GET', '/seller_requirements/types', options),+ }+// ============================================// Commissions (what the marketplace charges its sellers)// ============================================diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex 336e89251e..0aa50f3676 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -1,6 +1,8 @@// Request parameter types for Admin API endpoints// Based on the Admin API OpenAPI specification+import type { SellerRequirementStatus } from './types'+export interface StoreUpdateParams {name?: stringpreferred_admin_locale?: string@@ -1478,6 +1480,92 @@ export interface SellerRejectParams {reason?: string}+/**+ * Admitting a seller. `override_requirements` admits one whose onboarding+ * checklist is unfinished — the operator's deliberate exception, which the+ * seller.approved event records along with what was outstanding.+ */+export interface SellerApproveParams {+ override_requirements?: boolean+}++/** Sending a seller back to onboarding, with what they have to fix. */+export interface SellerReopenOnboardingParams {+ note?: string+}++/** A resource a custom field definition can be attached to. */+export interface CustomFieldResourceType {+ /** The value to send as `resource_type`. */+ resource_type: string+ /** What a merchant calls it, e.g. "Sellers". */+ name: string+}++/** One configured entry on the marketplace's seller onboarding checklist. */+export interface SellerRequirementCreateParams {+ /** The kind, from `sellerRequirements.types()` — e.g. `document`. */+ type: string+ /** Custom field definitions this requirement asks the seller to fill in. */+ custom_field_definition_ids?: string[]+ name?: string+ description?: string+ position?: number+ active?: boolean+ required?: boolean+ preferences?: Record<string, unknown>+ metadata?: Record<string, unknown>+}++/** `type` is absent: a saved row's kind never changes. */+export interface SellerRequirementUpdateParams {+ custom_field_definition_ids?: string[]+ name?: string+ description?: string+ position?: number+ active?: boolean+ required?: boolean+ preferences?: Record<string, unknown>+ metadata?: Record<string, unknown>+}++/** A requirement kind an operator can add, and the shape of its form. */+export interface SellerRequirementType {+ type: string+ name: string+ description: string+ allow_multiple: boolean+ accepts_submissions: boolean+ reviewed_by_operator: boolean+ /** Whether this store already has one — single-instance kinds only. */+ configured: boolean+ /** Whether the operator may add one now; the server owns the rule. */+ addable: boolean+ /** What a seller may upload, for kinds that collect a file. */+ accepted_content_types: string[]+ /** Association-backed config this kind takes beyond its preferences. */+ association_fields: string[]+ preference_schema: Array<Record<string, unknown>>+}++/** Excusing one seller from one requirement. */+export interface SellerRequirementWaiveParams {+ requirement_id: string+ review_note?: string+}++/** Accepting or rejecting what a seller submitted. */+export interface SellerRequirementReviewParams {+ review_note?: string+}++/** A seller's evaluated onboarding checklist. */+export interface SellerOnboarding {+ status: string+ progress: { done: number; total: number; percentage: number }+ requirements: SellerRequirementStatus[]+}+/*** One condition on a commission rate.*diff --git a/packages/admin-sdk/src/types/generated/Address.ts b/packages/admin-sdk/src/types/generated/Address.tsindex 2fcd5bd976..19d6ac2591 100644--- a/packages/admin-sdk/src/types/generated/Address.ts+++ b/packages/admin-sdk/src/types/generated/Address.ts@@ -1,4 +1,4 @@-// Typelizer digest 24044bb3f128587099bcfefc81083294+// Typelizer digest 0388d5f0fa8c020dca64662f8ab8168e//// DO NOT MODIFY: This file was automatically generated by Typelizer.@@ -27,6 +27,8 @@ interface Address {metadata: Record<string, unknown>;created_at: string;updated_at: string;+ latitude: number | null;+ longitude: number | null;customer_id: string | null;}diff --git a/packages/admin-sdk/src/types/generated/Seller.ts b/packages/admin-sdk/src/types/generated/Seller.tsindex 018dbe7b3e..8f1bb6f3b5 100644--- a/packages/admin-sdk/src/types/generated/Seller.ts+++ b/packages/admin-sdk/src/types/generated/Seller.ts@@ -1,4 +1,4 @@-// Typelizer digest 0c251a8daa6abea01005b8f5d58413b5+// Typelizer digest 9ea0fa57629e2cfbc989efe587510dc2//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {Address} from '@/types'@@ -28,6 +28,8 @@ interface Seller {sellable: boolean;products_count: number;users_count: number;+ onboarding_progress: { done: number; total: number; percentage: number };+ onboarding_complete: boolean;billing_address?: Address;returns_address?: Address;}diff --git a/packages/admin-sdk/src/types/generated/SellerRequirement.ts b/packages/admin-sdk/src/types/generated/SellerRequirement.tsnew file mode 100644index 0000000000..8a7e1458ac--- /dev/null+++ b/packages/admin-sdk/src/types/generated/SellerRequirement.ts@@ -0,0 +1,23 @@+// Typelizer digest 3150835ff7ae52b69992b3696edd8adb+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++interface SellerRequirement {+ id: string;+ position: number;+ active: boolean;+ required: boolean;+ metadata: Record<string, unknown> | null;+ created_at: string;+ updated_at: string;+ kind: string;+ name: string;+ description: string | null;+ preferences: Record<string, unknown>;+ custom_field_definition_ids: Array<string>;+ allow_multiple: boolean;+ accepts_submissions: boolean;+ reviewed_by_operator: boolean;+}++export default SellerRequirement;diff --git a/packages/admin-sdk/src/types/generated/SellerRequirementStatus.ts b/packages/admin-sdk/src/types/generated/SellerRequirementStatus.tsnew file mode 100644index 0000000000..9e20f0b0ad--- /dev/null+++ b/packages/admin-sdk/src/types/generated/SellerRequirementStatus.ts@@ -0,0 +1,19 @@+// Typelizer digest 4d0f2420eec1d6bc006dc2e20e6d6b4c+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.+import type {SellerRequirementSubmission} from '@/types'++interface SellerRequirementStatus {+ id: string;+ kind: string;+ name: string;+ description: string | null;+ required: boolean;+ position: number;+ status: string;+ action_url: string | null;+ blocking: boolean;+ submission?: SellerRequirementSubmission;+}++export default SellerRequirementStatus;diff --git a/packages/admin-sdk/src/types/generated/SellerRequirementSubmission.ts b/packages/admin-sdk/src/types/generated/SellerRequirementSubmission.tsnew file mode 100644index 0000000000..479488a0cc--- /dev/null+++ b/packages/admin-sdk/src/types/generated/SellerRequirementSubmission.ts@@ -0,0 +1,22 @@+// Typelizer digest 2f1071b838a272e08eed6d2905356259+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++interface SellerRequirementSubmission {+ id: string;+ status: string;+ note: string | null;+ review_note: string | null;+ reference: string | null;+ metadata: Record<string, unknown> | null;+ reviewed_at: string | null;+ created_at: string;+ updated_at: string;+ seller_id: string;+ requirement_id: string;+ requirement_name: string;+ file_url: string | null;+ file_name: string | null;+}++export default SellerRequirementSubmission;diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.tsindex 218f7d7658..17de3548c1 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 a8cb8ffe4383aa5294d51223946bdf4a+// Typelizer digest 7d7db5f9ff5c3c46e23f7b85fa3d86e2//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { default as Address } from './Address'@@ -79,6 +79,9 @@ export type { default as ReturnLineItem } from './ReturnLineItem'export type { default as ReturnReason } from './ReturnReason'export type { default as Return } from './Return'export type { default as Role } from './Role'+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 SetupTask } from './SetupTask'export type { default as State } from './State'diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.tsindex 15fdff6757..54eb4d1eb2 100644--- a/packages/admin-sdk/src/types/index.ts+++ b/packages/admin-sdk/src/types/index.ts@@ -90,6 +90,9 @@ export type { default as ReturnLineItem } from './generated/ReturnLineItem'export type { default as ReturnReason } from './generated/ReturnReason'export type { default as Role } from './generated/Role'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 SetupTask } from './generated/SetupTask'export type { default as State } from './generated/State'export type { default as StockLevel } from './generated/StockLevel'diff --git a/spree/api/app/controllers/spree/api/v3/admin/seller_requirement_submissions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/seller_requirement_submissions_controller.rbnew file mode 100644index 0000000000..4ab23c586a--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/seller_requirement_submissions_controller.rb@@ -0,0 +1,139 @@+module Spree+ module Api+ module V3+ module Admin+ # The operator's review queue: what sellers have submitted about the+ # marketplace's requirements, and the decisions on them.+ #+ # Each decision is its own member action because each is a workflow+ # carrying its own arguments — a rejection carries the reason the+ # seller needs in order to fix it — and because a status moved by+ # PATCH would skip the mail and the extension hooks.+ class SellerRequirementSubmissionsController < ResourceController+ scoped_resource :sellers++ before_action :set_resource, only: [:show, :accept, :reject, :download]++ # POST /api/v3/admin/sellers/:seller_id/requirement_submissions+ #+ # The operator excusing one seller from something the marketplace+ # asks of everyone. Creating anything else here would be the+ # operator submitting on the seller's behalf, which is what the+ # seller's own branch is for.+ def create+ authorize! :create, Spree::SellerRequirementSubmission++ result = Spree.seller_requirement_submission_waive_workflow.call(+ seller: seller,+ requirement: requirement_from_params,+ reviewed_by: try_spree_current_user,+ review_note: params[:review_note]+ )++ if result.success?+ render json: serialize_resource(result.value), status: :created+ else+ render_result_error(result)+ end+ end++ # PATCH /api/v3/admin/sellers/:seller_id/requirement_submissions/:id/accept+ def accept+ run_workflow(Spree.seller_requirement_submission_accept_workflow)+ end++ # PATCH /api/v3/admin/sellers/:seller_id/requirement_submissions/:id/reject+ def reject+ run_workflow(Spree.seller_requirement_submission_reject_workflow)+ end++ # GET /api/v3/admin/sellers/:seller_id/requirement_submissions/:id/download+ #+ # Served through the API rather than as a storage link: these are+ # business registrations and identity documents, so each read is+ # authorized instead of being open to anyone holding a URL.+ def download+ unless @resource.file.attached?+ return render_error(+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:validation_error],+ message: 'Submission has no attached file',+ status: :unprocessable_content+ )+ end++ send_data(+ @resource.file.download,+ filename: @resource.file.filename.to_s,+ type: @resource.file.content_type,+ disposition: 'attachment'+ )+ end++ protected++ def model_class+ Spree::SellerRequirementSubmission+ end++ def serializer_class+ Spree.api.admin_seller_requirement_submission_serializer+ end++ # The parent is set and authorized by the base controller, and the+ # scope hangs off it — so a submission belonging to another+ # marketplace is a 404 rather than a document.+ def parent_association+ :requirement_submissions+ end++ # The serializer reads each row's file and its seller, so both are+ # loaded with the page rather than per row.+ def collection_includes+ [:requirement, :reviewed_by, :seller, { file_attachment: :blob }]+ end++ def read_actions+ super + %w[download]+ end++ # Scope-fetched through the store, then filtered by what this role may+ # do with it: reading a seller is not licence to decide its+ # submissions, which `authorize_parent!` enforces per action.+ def set_parent+ @parent = current_store.sellers.+ accessible_by(current_ability, parent_ability_action).+ find_by_prefix_id!(params[:seller_id])+ authorize_parent!(@parent)+ end++ private++ def seller+ @parent+ end++ # Through the store's own requirements: an id from elsewhere is a+ # 404 here rather than a waiver written against another+ # marketplace's checklist.+ def requirement_from_params+ current_store.seller_requirements.find_by_prefix_id!(params[:requirement_id])+ end++ def run_workflow(workflow)+ result = workflow.call(+ submission: @resource,+ reviewed_by: try_spree_current_user,+ review_note: params[:review_note]+ )++ if result.success?+ render json: serialize_resource(result.value)+ else+ render_result_error(result)+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/seller_requirements_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/seller_requirements_controller.rbnew file mode 100644index 0000000000..a723c5be96--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/seller_requirements_controller.rb@@ -0,0 +1,111 @@+module Spree+ module Api+ module V3+ module Admin+ # What this marketplace asks of a seller before it will let them+ # trade (docs/plans/6.0-seller-onboarding-requirements.md).+ #+ # Under `write_sellers` rather than `settings`: who decides admission+ # is who admits, and a key that can approve sellers is the same key+ # that should be able to change what approval requires.+ class SellerRequirementsController < ResourceController+ include Spree::Api::V3::Admin::SubclassedResource++ scoped_resource :sellers++ subclassed_via -> { Spree.seller_requirements },+ unknown_type_error: 'unknown_seller_requirement_type'++ # GET /api/v3/admin/seller_requirements/types+ #+ # The kinds an operator can add, with the shape of each one's+ # configuration form. A marketplace's own kinds appear here the+ # moment they are registered, which is what keeps the picker from+ # being a hardcoded list in the dashboard.+ def types+ # `:read`, matching its place in `read_actions`: this lists the+ # kinds a marketplace has registered and nothing about any store,+ # so a staffer who can see the checklist can see what it is made+ # of. Asking for `:create` here 403s exactly those people.+ authorize! :read, model_class++ data = Spree.seller_requirements.map do |klass|+ {+ type: klass.api_type,+ name: klass.human_name,+ description: klass.human_description,+ allow_multiple: klass.allow_multiple?,+ accepts_submissions: klass.accepts_submissions?,+ reviewed_by_operator: klass.reviewed_by_operator?,+ # Whether the store already has one, and whether it may add+ # another — the uniqueness rule is the model's, so the picker+ # reads the answer rather than reimplementing it.+ configured: configured_types.include?(klass.to_s),+ addable: klass.allow_multiple? || configured_types.exclude?(klass.to_s),+ # What a seller may upload, for kinds that collect a file.+ # Told to the operator, never asked of them — the answer is+ # the same for every marketplace.+ accepted_content_types: klass.accepted_content_types,+ # Config a kind takes beyond its preferences — a reference+ # list gets its own picker, not a text box.+ association_fields: association_fields_for(klass),+ preference_schema: klass.serialized_preference_schema+ }+ end++ render json: { data: data }+ end++ protected++ def model_class+ Spree::SellerRequirement+ end++ def serializer_class+ Spree.api.admin_seller_requirement_serializer+ end++ # `type` is stripped before assignment by the subclassed-resource+ # flow, so a saved row's kind can never change — which matters+ # because its submissions answered the old one.+ def permitted_params+ params.permit(:type, :name, :description, :position, :active, :required,+ preferences: {}, metadata: {})+ end++ # `types` is read-only discovery — maps to the read scope.+ def read_actions+ super + %w[types]+ end++ private++ # `additional_permitted_attributes` entries are either bare symbols+ # or `{ custom_field_definition_ids: [] }` hashes; both reduce to+ # field names an editor can render a picker for.+ def association_fields_for(klass)+ return [] unless klass.respond_to?(:additional_permitted_attributes)++ klass.additional_permitted_attributes.flat_map do |attribute|+ attribute.is_a?(Hash) ? attribute.keys : attribute+ end.map(&:to_s)+ end++ def build_subclassed_resource(klass, attrs)+ current_store.seller_requirements.build(attrs.merge(type: klass.sti_name))+ end++ # `pluck` queries whether or not the association is already loaded,+ # so a warm `current_store` cannot leave this answering with a kind+ # the store no longer has. `reorder(nil)` because the association+ # orders by position, and PostgreSQL refuses SELECT DISTINCT with an+ # ORDER BY on a column it does not select.+ def configured_types+ @configured_types ||= current_store.seller_requirements.reorder(nil).distinct.pluck(:type)+ end+ end+ end+ end+ end+enddiff --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 d48da93670..c6ecd27f28 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@@ -16,7 +16,8 @@ module Spree# panel — managing sellers is the operator's job.scoped_resource :sellers- before_action :set_resource, only: [:show, :update, :destroy, :invite, :approve, :suspend, :reject]+ before_action :set_resource, only: [:show, :update, :destroy, :invite, :approve, :suspend, :reject,+ :onboarding, :reopen_onboarding]# POST /api/v3/admin/sellers/:id/invite#@@ -37,9 +38,43 @@ module Spreeendend+ # GET /api/v3/admin/sellers/:id/onboarding+ #+ # Where this seller stands against the marketplace's checklist. Its+ # own action rather than a field on the seller: evaluating it costs+ # a handful of queries per seller, which a list of twenty-five must+ # not pay for a column most operators are not looking at.+ def onboarding+ authorize_resource!(@resource, :show)++ requirements = Spree::Sellers::Requirements.new(@resource)++ render json: {+ status: @resource.status,+ progress: requirements.progress,+ requirements: serialize_requirement_statuses(requirements.statuses)+ }+ end+# PATCH /api/v3/admin/sellers/:id/approve+ #+ # `override_requirements` admits a seller whose checklist is not+ # finished — the operator's deliberate exception, which the event+ # records alongside what was outstanding.def approve- run_workflow(Spree.seller_approve_workflow, approver: try_spree_current_user)+ run_workflow(Spree.seller_approve_workflow,+ approver: try_spree_current_user,+ override_requirements: ActiveModel::Type::Boolean.new.cast(params[:override_requirements]))+ end++ # PATCH /api/v3/admin/sellers/:id/reopen_onboarding+ #+ # Sends a seller awaiting review back to onboarding with a note.+ # Distinct from reject, which turns them away.+ def reopen_onboarding+ run_workflow(Spree.seller_reopen_onboarding_workflow,+ note: params[:note],+ reopened_by: try_spree_current_user)end# PATCH /api/v3/admin/sellers/:id/suspend@@ -71,7 +106,18 @@ module Spree# catalog can run to thousands, so the serializer counts it in SQL# rather than materializing it just to measure it.def collection_includes- [:billing_address, :returns_address, :users]+ [:users]+ end++ # What the serializer's onboarding progress reads for every seller,+ # on the list and on the profile alike: the checklist's kinds look+ # at addresses, branding and the seller's own submissions, and the+ # requirements themselves hang off the store — one row shared by+ # every seller on the page, so it loads once. Applied to the scope+ # rather than the collection so a single-seller read gets it too.+ def scope_includes+ [:billing_address, :returns_address, :requirement_submissions,+ { store: :seller_requirements, logo_attachment: :blob, cover_photo_attachment: :blob }]end# Enumerated rather than borrowing the legacy global list, which@@ -104,8 +150,19 @@ module Spree)end+ # `onboarding` is a read of the seller — it changes nothing.+ def read_actions+ super + %w[onboarding]+ end+private+ def serialize_requirement_statuses(statuses)+ serializer = Spree.api.admin_seller_requirement_status_serializer++ statuses.map { |status| serializer.new(status, params: serializer_params).to_h }+ end+def run_workflow(workflow, **arguments)result = workflow.call(seller: @resource, **arguments)diff --git a/spree/api/app/serializers/spree/api/v3/admin/address_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/address_serializer.rbindex b1275210cb..074256c596 100644--- a/spree/api/app/serializers/spree/api/v3/admin/address_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/address_serializer.rb@@ -5,11 +5,24 @@ module Spreeclass AddressSerializer < V3::AddressSerializertypelize label: [:string, nullable: true],customer_id: [:string, nullable: true],+ latitude: [:number, nullable: true],+ longitude: [:number, nullable: true],metadata: 'Record<string, unknown>'attributes :label, :metadata,created_at: :iso8601, updated_at: :iso8601+ # Geocoded in the background after the address is saved, so both are+ # null until that job has run — a client showing a map has to cope+ # with an address it cannot place yet.+ attribute :latitude do |address|+ address.latitude&.to_f+ end++ attribute :longitude do |address|+ address.longitude&.to_f+ end+attribute :customer_id do |address|address.customer&.prefixed_idenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/seller_requirement_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/seller_requirement_serializer.rbnew file mode 100644index 0000000000..3f2e221024--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/seller_requirement_serializer.rb@@ -0,0 +1,68 @@+module Spree+ module Api+ module V3+ module Admin+ # A configured requirement, as the operator manages it. Admin-only:+ # what a marketplace asks of its sellers is between the operator and+ # the seller, and never appears on the store surface.+ class SellerRequirementSerializer < BaseSerializer+ typelize kind: :string, name: :string, description: [:string, nullable: true],+ position: :number, active: :boolean, required: :boolean,+ allow_multiple: :boolean, accepts_submissions: :boolean,+ reviewed_by_operator: :boolean,+ preferences: 'Record<string, unknown>',+ custom_field_definition_ids: [:string, multi: true],+ metadata: 'Record<string, unknown> | null'++ attributes :position, :active, :required, :metadata,+ created_at: :iso8601,+ updated_at: :iso8601++ # The kind, so a dashboard can key presentation off it without+ # parsing the Ruby class name.+ attribute :kind do |requirement|+ requirement.class.api_type+ end++ # What the seller sees — the operator's wording, or the kind's own.+ attribute :name do |requirement|+ requirement.display_name+ end++ attribute :description do |requirement|+ requirement.display_description+ end++ attribute :preferences do |requirement|+ requirement.serialized_preferences+ end++ # The definitions a requirement asks for, when its kind takes any.+ # Read through the association, so one the operator deleted is gone+ # rather than echoed back as an id nothing can address.+ attribute :custom_field_definition_ids do |requirement|+ if requirement.respond_to?(:custom_field_definition_prefixed_ids)+ requirement.custom_field_definition_prefixed_ids+ else+ []+ end+ end++ # Capabilities of the kind, so the operator's form knows whether to+ # offer a second row of it and whether sellers can submit anything.+ attribute :allow_multiple do |requirement|+ requirement.class.allow_multiple?+ end++ attribute :accepts_submissions do |requirement|+ requirement.class.accepts_submissions?+ end++ attribute :reviewed_by_operator do |requirement|+ requirement.class.reviewed_by_operator?+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/seller_requirement_status_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/seller_requirement_status_serializer.rbnew file mode 100644index 0000000000..1b5173d882--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/seller_requirement_status_serializer.rb@@ -0,0 +1,34 @@+module Spree+ module Api+ module V3+ module Admin+ # One line of a seller's onboarding checklist — a requirement+ # evaluated against them. A value object, so no id of its own: the+ # `id` here is the requirement it came from, which is what a caller+ # acts on.+ class SellerRequirementStatusSerializer+ include Alba::Resource+ include Typelizer::DSL++ typelize id: :string, kind: :string, name: :string,+ description: [:string, nullable: true],+ required: :boolean, position: :number, status: :string,+ blocking: :boolean, action_url: [:string, nullable: true]++ attributes :id, :kind, :name, :description, :required, :position, :status, :action_url++ # Whether this stands between the seller and approval. Serialized+ # rather than left to each client to derive, so the dashboard's+ # override warning and the approval gate cannot disagree.+ attribute :blocking do |status|+ status.blocking?+ end++ one :submission,+ resource: proc { Spree.api.admin_seller_requirement_submission_serializer },+ if: proc { |status| status.submission.present? }+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/seller_requirement_submission_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/seller_requirement_submission_serializer.rbnew file mode 100644index 0000000000..c4776785a9--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/seller_requirement_submission_serializer.rb@@ -0,0 +1,57 @@+module Spree+ module Api+ module V3+ module Admin+ # What a seller submitted about one requirement, and what was made of+ # it. The file is exposed as a URL rather than a blob id — it is what+ # the reviewer opens.+ class SellerRequirementSubmissionSerializer < BaseSerializer+ typelize status: :string, note: [:string, nullable: true],+ review_note: [:string, nullable: true],+ reference: [:string, nullable: true],+ reviewed_at: [:string, nullable: true],+ file_url: [:string, nullable: true],+ file_name: [:string, nullable: true],+ seller_id: :string, requirement_id: :string,+ requirement_name: :string,+ metadata: 'Record<string, unknown> | null'++ attributes :status, :note, :review_note, :reference, :metadata,+ reviewed_at: :iso8601,+ created_at: :iso8601,+ updated_at: :iso8601++ attribute :seller_id do |submission|+ submission.seller&.prefixed_id+ end++ attribute :requirement_id do |submission|+ submission.requirement&.prefixed_id+ end++ # The reviewer is looking at a queue of these and needs to know what+ # each one answers without fetching the requirement.+ attribute :requirement_name do |submission|+ submission.requirement&.display_name+ end++ # A path to this API's own download action rather than a storage+ # URL: these are identity documents, and the download is authorized+ # per request instead of being readable by anyone holding a link.+ attribute :file_url do |submission|+ next nil unless submission.file.attached?++ Spree::Core::Engine.routes.url_helpers.download_api_v3_admin_seller_requirement_submission_path(+ seller_id: submission.seller.prefixed_id,+ id: submission.prefixed_id+ )+ end++ attribute :file_name do |submission|+ submission.file.attached? ? submission.file.filename.to_s : nil+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/seller_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/seller_serializer.rbindex 8addca26e0..e8444bf847 100644--- a/spree/api/app/serializers/spree/api/v3/admin/seller_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/seller_serializer.rb@@ -16,6 +16,8 @@ module Spreedeleted_at: [:string, nullable: true],on_holiday: :boolean, sellable: :boolean,products_count: :number, users_count: :number,+ onboarding_progress: '{ done: number; total: number; percentage: number }',+ onboarding_complete: :boolean,metadata: 'Record<string, unknown> | null'attributes :status, :contact_email, :billing_email,@@ -41,18 +43,29 @@ module Spreeend# Saves the dashboard a request per row for the two counts its list- # and header show. `count`, not `size`: a seller's catalog is the one association here- # that can run to thousands of rows, and the list only ever renders- # the number. Costs one COUNT per row, which is cheaper than loading- # the catalog into memory to measure it.+ # and header show. Read off the seller, which memoizes the SQL count+ # so the minimum-products requirement asks the same question free.attribute :products_count do |seller|- seller.products.count+ seller.products_countendattribute :users_count do |seller|seller.users.sizeend+ # How far through the marketplace's checklist this seller is — what+ # the list's progress column and the profile's badge render. The+ # requirements themselves, with their submissions, stay on the+ # heavier `onboarding` action; a list of sellers needs the number,+ # not the rows behind it.+ attribute :onboarding_progress do |seller|+ seller.onboarding_progress+ end++ attribute :onboarding_complete do |seller|+ seller.onboarding_complete?+ end+one :billing_address,resource: proc { Spree.api.admin_address_serializer },if: proc { |seller| seller.billing_address.present? }diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 162a5e31a5..e0f90e4bac 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -147,7 +147,12 @@ Spree::Core::Engine.add_routes doend# Definitions are per resource type, not per instance.- resources :custom_field_definitions+ resources :custom_field_definitions do+ collection do+ # What a definition can be attached to, from the registry.+ get :resource_types+ end+ end# Translation discovery: the translatable-resources registry and the# store's supported locales. See docs/plans/5.5-6.0-resource-translations-api.md.@@ -436,6 +441,31 @@ Spree::Core::Engine.add_routes dopatch :approvepatch :suspendpatch :reject+ # Where the seller stands against the marketplace's checklist,+ # and the way back to onboarding when something has to be redone.+ get :onboarding+ patch :reopen_onboarding+ 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.+ resources :requirement_submissions, only: [:index, :show, :create],+ controller: 'seller_requirement_submissions' do+ member do+ patch :accept+ patch :reject+ get :download+ end+ end+ end++ # What this marketplace asks of a seller before it will let them+ # trade. Configuration, so it hangs off the store rather than a+ # seller.+ resources :seller_requirements do+ collection do+ get :typesendenddiff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex a518d53f79..6efb91bbf7 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -155,6 +155,9 @@ module Spreeadmin_admin_user_serializer: 'Spree::Api::V3::Admin::AdminUserSerializer',seller_serializer: 'Spree::Api::V3::SellerSerializer',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',+ admin_seller_requirement_status_serializer: 'Spree::Api::V3::Admin::SellerRequirementStatusSerializer',admin_commission_rate_serializer: 'Spree::Api::V3::Admin::CommissionRateSerializer',admin_commission_rule_serializer: 'Spree::Api::V3::Admin::CommissionRuleSerializer',admin_commission_line_serializer: 'Spree::Api::V3::Admin::CommissionLineSerializer',diff --git a/spree/api/spec/controllers/spree/api/v3/admin/seller_onboarding_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/seller_onboarding_spec.rbnew file mode 100644index 0000000000..b4a053786d--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/seller_onboarding_spec.rb@@ -0,0 +1,102 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::SellersController, 'onboarding', type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let(:seller) { create(:seller, :onboarding, store: store) }++ before do+ request.headers.merge!(headers)+ Spree::SellerRequirement.where(store_id: store.id).destroy_all+ end++ describe 'GET #onboarding' do+ it 'shows where the seller stands, in the operator’s order' do+ create(:accept_terms_requirement, store: store)+ create(:billing_address_requirement, store: store, required: false)++ get :onboarding, params: { id: seller.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['status']).to eq('onboarding')+ expect(json_response['progress']).to eq('done' => 0, 'total' => 2, 'percentage' => 0)++ rows = json_response['requirements']+ expect(rows.map { |r| r['kind'] }).to eq(%w[accept_terms billing_address])+ expect(rows.first['status']).to eq('incomplete')+ expect(rows.first['required']).to be true+ expect(rows.second['required']).to be false+ end++ it 'reflects what the seller has done' do+ create(:accept_terms_requirement, store: store)+ seller.update!(terms_accepted_at: Time.current)++ get :onboarding, params: { id: seller.prefixed_id }, as: :json++ expect(json_response['requirements'].first['status']).to eq('complete')+ expect(json_response['progress']['percentage']).to eq(100)+ end++ it 'carries the submission a reviewer has to look at' do+ requirement = create(:operator_review_requirement, store: store)+ create(:seller_requirement_submission, seller: seller, requirement: requirement, note: 'ready')++ get :onboarding, params: { id: seller.prefixed_id }, as: :json++ row = json_response['requirements'].first+ expect(row['status']).to eq('pending')+ expect(row['submission']['note']).to eq('ready')+ end+ end++ describe 'PATCH #approve' do+ it 'refuses while the checklist is unfinished' do+ create(:accept_terms_requirement, store: store)++ patch :approve, params: { id: seller.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(seller.reload).not_to be_approved+ end++ it 'admits the seller when the operator overrides deliberately' do+ create(:accept_terms_requirement, store: store)++ patch :approve, params: { id: seller.prefixed_id, override_requirements: true }, as: :json++ expect(response).to have_http_status(:ok)+ expect(seller.reload).to be_approved+ end++ it 'admits without an override once the checklist is done' do+ create(:accept_terms_requirement, store: store)+ seller.update!(terms_accepted_at: Time.current)++ patch :approve, params: { id: seller.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(seller.reload).to be_approved+ end+ end++ describe 'PATCH #reopen_onboarding' do+ it 'sends a seller awaiting review back with a note' do+ seller.update!(status: 'ready_for_review')++ patch :reopen_onboarding, params: { id: seller.prefixed_id, note: 'Returns address is a PO box' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(seller.reload).to be_onboarding+ expect(seller.metadata['onboarding_reopened_note']).to eq('Returns address is a PO box')+ end++ it 'refuses a seller who is not awaiting review' do+ patch :reopen_onboarding, params: { id: seller.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/seller_requirement_submissions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/seller_requirement_submissions_controller_spec.rbnew file mode 100644index 0000000000..acc57c900d--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/seller_requirement_submissions_controller_spec.rb@@ -0,0 +1,110 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::SellerRequirementSubmissionsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let(:seller) { create(:seller, :onboarding, store: store) }+ let(:requirement) { create(:operator_review_requirement, store: store, name: 'VAT number check') }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ it 'lists what this seller submitted' do+ submission = create(:seller_requirement_submission, seller: seller, requirement: requirement, note: 'PL123')++ get :index, params: { seller_id: seller.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].first+ expect(row['id']).to eq(submission.prefixed_id)+ expect(row['status']).to eq('pending')+ expect(row['note']).to eq('PL123')+ expect(row['requirement_name']).to eq('VAT number check')+ end++ it 'never shows another seller’s submissions' do+ other = create(:seller, store: store)+ create(:seller_requirement_submission, seller: other, requirement: requirement)++ get :index, params: { seller_id: seller.prefixed_id }, as: :json++ expect(json_response['data']).to be_empty+ end++ it '404s on a seller belonging to another marketplace' do+ elsewhere = create(:seller, store: create(:store))++ get :index, params: { seller_id: elsewhere.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'PATCH #accept' do+ it 'settles the requirement' do+ submission = create(:seller_requirement_submission, seller: seller, requirement: requirement)++ patch :accept, params: { seller_id: seller.prefixed_id, id: submission.prefixed_id,+ review_note: 'Checked against the register' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['status']).to eq('accepted')+ expect(submission.reload.review_note).to eq('Checked against the register')+ expect(requirement.satisfied?(seller)).to be true+ end+ end++ describe 'PATCH #reject' do+ it 'sends it back with a reason' do+ submission = create(:seller_requirement_submission, seller: seller, requirement: requirement)++ patch :reject, params: { seller_id: seller.prefixed_id, id: submission.prefixed_id,+ review_note: 'That number does not resolve' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['status']).to eq('rejected')+ expect(requirement.status_for(seller)).to eq('rejected')+ end+ end++ describe 'POST #create' do+ it 'waives a requirement for one seller' do+ post :create, params: { seller_id: seller.prefixed_id, requirement_id: requirement.prefixed_id,+ review_note: 'Verified offline' }, as: :json++ expect(response).to have_http_status(:created)+ expect(json_response['status']).to eq('waived')+ expect(requirement.satisfied?(seller)).to be true+ end++ it '404s on a requirement from another marketplace' do+ elsewhere = create(:document_requirement, store: create(:store))++ post :create, params: { seller_id: seller.prefixed_id, requirement_id: elsewhere.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'GET #download' do+ it 'serves the file the seller uploaded' do+ document = create(:document_requirement, store: store)+ submission = create(:seller_requirement_submission, :with_file, seller: seller, requirement: document)++ get :download, params: { seller_id: seller.prefixed_id, id: submission.prefixed_id }++ expect(response).to have_http_status(:ok)+ expect(response.headers['Content-Disposition']).to include('thinking-cat.jpg')+ end++ it 'refuses when there is nothing attached' do+ submission = create(:seller_requirement_submission, seller: seller, requirement: requirement)++ get :download, params: { seller_id: seller.prefixed_id, id: submission.prefixed_id }++ expect(response).to have_http_status(:unprocessable_content)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/seller_requirements_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/seller_requirements_controller_spec.rbnew file mode 100644index 0000000000..8fddade3eb--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/seller_requirements_controller_spec.rb@@ -0,0 +1,201 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::SellerRequirementsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ before do+ request.headers.merge!(headers)+ store.seller_requirements.destroy_all+ end++ describe 'GET #types' do+ it 'tells the operator what a document kind accepts rather than asking' do+ get :types, params: { format: :json }++ document = json_response['data'].find { |t| t['type'] == 'document' }+ expect(document['accepted_content_types']).to include('application/pdf', 'image/jpeg')+ # Nothing to configure — the list is fixed, so it is not a preference.+ expect(document['preference_schema']).to be_empty+ end++ it 'names the records a kind takes, so the picker is a picker' do+ get :types, params: { format: :json }++ custom_fields = json_response['data'].find { |t| t['type'] == 'required_custom_fields' }+ expect(custom_fields['association_fields']).to eq(['custom_field_definition_ids'])+ end++ it 'lists the kinds an operator can add, with their configuration shape' do+ get :types, params: { format: :json }++ expect(response).to have_http_status(:ok)+ types = json_response['data']+ expect(types.map { |t| t['type'] }).to include('accept_terms', 'document', 'operator_review')++ accept_terms = types.find { |t| t['type'] == 'accept_terms' }+ expect(accept_terms['name']).to eq('Accept terms')+ expect(accept_terms['allow_multiple']).to be false+ expect(accept_terms['preference_schema']).to be_an(Array)++ document = types.find { |t| t['type'] == 'document' }+ expect(document['allow_multiple']).to be true+ expect(document['reviewed_by_operator']).to be true+ end++ it 'says which single-instance kinds the store already has' do+ create(:accept_terms_requirement, store: store)++ get :types, params: { format: :json }++ accept_terms = json_response['data'].find { |t| t['type'] == 'accept_terms' }+ expect(accept_terms['configured']).to be true+ end++ it 'says what may still be added, so the picker does not restate the rule' do+ create(:accept_terms_requirement, store: store)+ create(:document_requirement, store: store, name: 'Business registration')++ get :types, params: { format: :json }++ types = json_response['data']+ # Answers one question, already asked — not addable again.+ expect(types.find { |t| t['type'] == 'accept_terms' }['addable']).to be false+ # Carries the operator's own wording, so a second one is meaningful.+ expect(types.find { |t| t['type'] == 'document' }['addable']).to be true+ expect(types.find { |t| t['type'] == 'billing_address' }['addable']).to be true+ end+ end++ describe 'GET #index' do+ it 'lists this store’s checklist in the operator’s order' do+ first = create(:accept_terms_requirement, store: store)+ second = create(:billing_address_requirement, store: store)++ get :index, params: { format: :json }++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].map { |r| r['kind'] }).to eq(%w[accept_terms billing_address])+ expect(json_response['data'].first['id']).to eq(first.prefixed_id)+ expect(second.reload.position).to be > first.reload.position+ end++ it 'never shows another marketplace’s checklist' do+ create(:accept_terms_requirement, store: create(:store))++ get :index, params: { format: :json }++ expect(json_response['data']).to be_empty+ end+ end++ describe 'POST #create' do+ it 'adds a requirement of the chosen kind' do+ post :create, params: { type: 'billing_address', format: :json }++ expect(response).to have_http_status(:created)+ expect(json_response['kind']).to eq('billing_address')+ expect(store.seller_requirements.reload.first).to be_a(Spree::SellerRequirements::BillingAddress)+ end++ it 'takes the operator’s own wording' do+ post :create, params: {+ type: 'document', name: 'Business registration',+ description: 'A copy of your certificate of incorporation',+ format: :json+ }++ expect(response).to have_http_status(:created)+ expect(json_response['name']).to eq('Business registration')+ expect(json_response['description']).to eq('A copy of your certificate of incorporation')+ end++ it 'attaches the custom fields the operator picked' do+ definition = create(:custom_field_definition, resource_type: 'Spree::Seller')++ post :create, params: {+ type: 'required_custom_fields',+ custom_field_definition_ids: [definition.prefixed_id],+ format: :json+ }++ expect(response).to have_http_status(:created)+ expect(json_response['custom_field_definition_ids']).to eq([definition.prefixed_id])+ expect(store.seller_requirements.reload.first.custom_field_definitions).to eq([definition])+ end++ it 'refuses a kind nobody registered' do+ post :create, params: { type: 'imaginary_check', format: :json }++ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'refuses a second row of a kind that answers one question' do+ create(:accept_terms_requirement, store: store)++ post :create, params: { type: 'accept_terms', format: :json }++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'PATCH #update' do+ let(:requirement) { create(:minimum_products_requirement, store: store) }++ it 'changes what the requirement asks for' do+ patch :update, params: { id: requirement.prefixed_id, preferences: { minimum_count: 5 }, format: :json }++ expect(response).to have_http_status(:ok)+ expect(requirement.reload.preferred_minimum_count).to eq(5)+ end++ it 'switches a requirement off without deleting it' do+ patch :update, params: { id: requirement.prefixed_id, active: false, format: :json }++ expect(requirement.reload.active).to be false+ end++ it 'makes a requirement optional' do+ patch :update, params: { id: requirement.prefixed_id, required: false, format: :json }++ expect(requirement.reload.required).to be false+ end++ it 'reorders the checklist' do+ first = create(:accept_terms_requirement, store: store)+ second = create(:billing_address_requirement, store: store)++ patch :update, params: { id: second.prefixed_id, position: 1, format: :json }++ expect(store.seller_requirements.reload.map(&:class)).to eq(+ [Spree::SellerRequirements::BillingAddress, Spree::SellerRequirements::AcceptTerms]+ )+ expect(first.reload.position).to be > second.reload.position+ end++ it 'never changes a saved row’s kind' do+ patch :update, params: { id: requirement.prefixed_id, type: 'accept_terms', format: :json }++ expect(requirement.reload).to be_a(Spree::SellerRequirements::MinimumProducts)+ end++ it '404s on another marketplace’s requirement' do+ other = create(:accept_terms_requirement, store: create(:store))++ patch :update, params: { id: other.prefixed_id, active: false, format: :json }++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'DELETE #destroy' do+ it 'drops a requirement the marketplace no longer asks for' do+ requirement = create(:accept_terms_requirement, store: store)++ delete :destroy, params: { id: requirement.prefixed_id, format: :json }++ expect(store.seller_requirements.reload).to be_empty+ end+ end+enddiff --git a/spree/api/spec/integration/spree/api/v3/admin/seller_requirements_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/seller_requirements_spec.rbnew file mode 100644index 0000000000..73a315583b--- /dev/null+++ b/spree/api/spec/integration/spree/api/v3/admin/seller_requirements_spec.rb@@ -0,0 +1,234 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'Admin Seller Requirements API', type: :request, swagger_doc: 'api-reference/admin.yaml' do+ include_context 'API v3 Admin'++ let(:Authorization) { "Bearer #{admin_jwt_token}" }+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }++ before { Spree::SellerRequirement.where(store_id: store.id).destroy_all }++ path '/api/v3/admin/seller_requirements' do+ get 'List seller requirements' do+ tags 'Seller Requirements'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ What this marketplace asks of a seller before it will let them trade,+ in the order sellers work through it.++ Each row is one configured requirement. `required` says whether it+ stands between the seller and approval — the others are shown as+ recommended and counted in their progress, but never block. `active`+ switches one off without losing how it was worded.+ DESC+ admin_scope :read, :sellers++ admin_sdk_example 'seller_requirements/list'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true+ parameter name: :page, in: :query, type: :integer, required: false+ parameter name: :limit, in: :query, type: :integer, required: false++ response '200', 'seller requirements found' do+ let!(:requirement) { create(:accept_terms_requirement, store: store) }++ schema type: :object,+ properties: {+ data: { type: :array, items: { '$ref' => '#/components/schemas/SellerRequirement' } },+ meta: { '$ref' => '#/components/schemas/PaginationMeta' }+ }++ run_test!+ end+ end++ post 'Add a seller requirement' do+ tags 'Seller Requirements'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Adds something the marketplace asks of its sellers.++ `type` comes from `GET /seller_requirements/types`, which also+ describes the configuration each kind takes. Most kinds answer one+ question and can be added once; the open-ended ones — a seller+ confirmation, a manual check, a document — carry the question in your+ own `name` and `description`, so a store may add as many as it needs.++ A kind that reads the seller's own data (their addresses, their+ products, whether they accepted the terms) needs nothing from the+ seller beyond doing it. The others wait for the seller to submit+ something, and the ones you review wait for you.+ DESC+ admin_scope :write, :sellers++ admin_sdk_example 'seller_requirements/create'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true+ parameter name: :body, in: :body, schema: {+ type: :object,+ required: %w[type],+ properties: {+ type: { type: :string, example: 'document',+ description: 'The kind, from `GET /seller_requirements/types`.' },+ name: { type: :string, example: 'Business registration',+ description: 'What the seller sees. Required for kinds that can be added more than ' \+ 'once, since the wording is the only thing telling them apart. Left ' \+ 'blank on the others, the kind names itself.' },+ description: { type: :string, example: 'A copy of your certificate of incorporation.',+ description: 'Instructions shown to the seller.' },+ required: { type: :boolean, example: true,+ description: 'Whether this blocks approval. Off means recommended.' },+ active: { type: :boolean, example: true },+ position: { type: :integer, example: 1, description: 'Place in the checklist.' },+ preferences: { type: :object, example: { accepted_content_types: ['application/pdf'] },+ description: 'Configuration for this kind, per its `preference_schema`.' }+ }+ }++ response '201', 'seller requirement created' do+ let(:body) { { type: 'document', name: 'Business registration', required: true } }++ schema '$ref' => '#/components/schemas/SellerRequirement'++ run_test!+ end++ response '422', 'kind is not registered' do+ let(:body) { { type: 'imaginary_check' } }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ end++ path '/api/v3/admin/seller_requirements/types' do+ get 'List seller requirement kinds' do+ tags 'Seller Requirements'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ The kinds you can add, and the shape of each one's configuration form.++ `configured` says the store already has this kind — meaningful only+ where `allow_multiple` is false. `accepts_submissions` says the seller+ records having done it rather than it being read from their data, and+ `reviewed_by_operator` says what they send waits for you.++ A marketplace that registers its own kind server-side sees it here+ without this endpoint changing.+ DESC+ admin_scope :read, :sellers++ admin_sdk_example 'seller_requirements/types'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true++ response '200', 'kinds found' do+ schema type: :object,+ properties: {+ data: {+ type: :array,+ items: {+ type: :object,+ properties: {+ type: { type: :string, example: 'document' },+ name: { type: :string, example: 'Document' },+ description: { type: :string, example: 'A file the seller uploads and you review' },+ allow_multiple: { type: :boolean, example: true },+ accepts_submissions: { type: :boolean, example: true },+ reviewed_by_operator: { type: :boolean, example: true },+ configured: { type: :boolean, example: false },+ addable: { type: :boolean, example: true,+ description: 'Whether the operator may add one now. The uniqueness ' \+ 'rule is the server\'s, so clients filter on this rather ' \+ 'than deriving it.' },+ preference_schema: { type: :array, items: { type: :object } }+ }+ }+ }+ }++ run_test!+ end+ end+ end++ path '/api/v3/admin/seller_requirements/{id}' do+ parameter name: :id, in: :path, type: :string, required: true++ patch 'Update a seller requirement' do+ tags 'Seller Requirements'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Changes how a requirement is worded, what it asks for, where it sits in+ the checklist, and whether it blocks approval.++ `type` is not accepted: a saved row's kind never changes, because+ anything a seller already submitted answered the old one.+ DESC+ admin_scope :write, :sellers++ admin_sdk_example 'seller_requirements/update'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true+ parameter name: :body, in: :body, schema: {+ type: :object,+ properties: {+ name: { type: :string, example: 'Proof of business registration' },+ description: { type: :string, example: 'A copy of your certificate of incorporation.' },+ required: { type: :boolean, example: false },+ active: { type: :boolean, example: true },+ position: { type: :integer, example: 2 },+ preferences: { type: :object, example: { minimum_count: 3 } }+ }+ }++ response '200', 'seller requirement updated' do+ let(:requirement) { create(:minimum_products_requirement, store: store) }+ let(:id) { requirement.prefixed_id }+ let(:body) { { preferences: { minimum_count: 3 } } }++ schema '$ref' => '#/components/schemas/SellerRequirement'++ run_test!+ end+ end++ delete 'Delete a seller requirement' do+ tags 'Seller Requirements'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Stops asking for this. Anything sellers already submitted against it+ goes too — to keep the record while pausing the ask, set `active` to+ false instead.+ DESC+ admin_scope :write, :sellers++ admin_sdk_example 'seller_requirements/delete'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true++ response '204', 'seller requirement deleted' do+ let(:requirement) { create(:accept_terms_requirement, store: store) }+ let(:id) { requirement.prefixed_id }++ run_test!+ end+ end+ end+end