Skip to content

armgit / spree

Public Imported from GitHub
0

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

Give sellers their orders over the API

Damian Legawiecbc566dd1842f
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index 6e2b9af6a7..5a9cd0d1db 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -2,7 +2,9 @@ import type { ListParams, ListResponse, RequestFn, RequestOptions } from '@spree
import { transformListParams } from '@spree/sdk-core'
import type {
AuthTokens,
+ Fulfillment,
Invitation,
+ Order,
Product,
Profile,
RequirementStatus,
@@ -219,6 +221,62 @@ export class SellerClient {
this.request<void>('DELETE', `/products/${id}`, options),
}
+ /**
+ * What this seller has sold. A basket spanning several sellers is split
+ * into one order each, so these are the seller's own orders rather than a
+ * filtered view of somebody else's.
+ */
+ readonly orders = {
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<ListResponse<Order>> =>
+ this.request<ListResponse<Order>>('GET', '/orders', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ get: (id: string, options?: RequestOptions): Promise<Order> =>
+ this.request<Order>('GET', `/orders/${id}`, options),
+
+ /** Withdraws from an order this seller cannot fulfil. */
+ cancel: (
+ id: string,
+ params?: { notify_customer?: boolean },
+ options?: RequestOptions,
+ ): Promise<Order> =>
+ this.request<Order>('PATCH', `/orders/${id}/cancel`, { ...options, body: params }),
+
+ /** The parcels owed on one order. */
+ fulfillments: {
+ list: (orderId: string, options?: RequestOptions): Promise<{ data: Fulfillment[] }> =>
+ this.request<{ data: Fulfillment[] }>('GET', `/orders/${orderId}/fulfillments`, options),
+
+ get: (orderId: string, id: string, options?: RequestOptions): Promise<Fulfillment> =>
+ this.request<Fulfillment>('GET', `/orders/${orderId}/fulfillments/${id}`, options),
+
+ /**
+ * Ships the parcel. `items` narrows it to part of what the fulfillment
+ * holds, which splits the rest onto a new one.
+ */
+ fulfill: (
+ orderId: string,
+ id: string,
+ params?: {
+ tracking?: string
+ tracking_carrier?: string
+ notify_customer?: boolean
+ items?: Array<{ item_id: string; quantity: number }>
+ },
+ options?: RequestOptions,
+ ): Promise<Fulfillment> =>
+ this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/fulfill`, {
+ ...options,
+ body: params,
+ }),
+ },
+ }
+
/**
* Presigning for the documents onboarding asks for. Exchange the blob's
* metadata for an upload URL, PUT the file to it, then post the returned
diff --git a/packages/seller-sdk/src/types/generated/Fulfillment.ts b/packages/seller-sdk/src/types/generated/Fulfillment.ts
new file mode 100644
index 0000000000..59cf6483b2
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Fulfillment.ts
@@ -0,0 +1,23 @@
+// Typelizer digest 1c54efc582de5122eb1e857fb0f14d71
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {FulfillmentItem} from '@/types'
+
+type Fulfillment = {
+ id: string;
+ number: string;
+ status: string;
+ tracking: string | null;
+ tracking_url: string | null;
+ tracking_carrier: string | null;
+ tracking_status: string | null;
+ fulfilled_at: string;
+ created_at: string;
+ updated_at: string;
+ fulfillment_type: string | null;
+ delivery_method_name: string | null;
+ stock_location_name: string | null;
+ items: Array<FulfillmentItem>;
+}
+
+export default Fulfillment;
diff --git a/packages/seller-sdk/src/types/generated/FulfillmentItem.ts b/packages/seller-sdk/src/types/generated/FulfillmentItem.ts
new file mode 100644
index 0000000000..a0894b80c6
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/FulfillmentItem.ts
@@ -0,0 +1,14 @@
+// Typelizer digest 7988b9d8c443cf4ffa7d4451678da5d4
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type FulfillmentItem = {
+ id: string;
+ quantity: number;
+ line_item_id: string | null;
+ name: string | null;
+ sku: string | null;
+ options_text: string | null;
+}
+
+export default FulfillmentItem;
diff --git a/packages/seller-sdk/src/types/generated/Order.ts b/packages/seller-sdk/src/types/generated/Order.ts
new file mode 100644
index 0000000000..e9e98c3e6a
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Order.ts
@@ -0,0 +1,31 @@
+// Typelizer digest cc44b646cbe77e1e3454fa3625348cbb
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {OrderLineItem, Fulfillment, Address} from '@/types'
+
+type Order = {
+ id: string;
+ number: string;
+ email: string | null;
+ customer_note: string | null;
+ currency: string;
+ total_quantity: number;
+ status: string;
+ fulfillment_status: string | null;
+ payment_status: string | null;
+ completed_at: string;
+ created_at: string;
+ updated_at: string;
+ item_total: unknown;
+ display_item_total: unknown;
+ tax_total: unknown;
+ display_tax_total: unknown;
+ total: unknown;
+ display_total: unknown;
+ items: Array<OrderLineItem>;
+ fulfillments: Array<Fulfillment>;
+ shipping_address: Address;
+ billing_address: Address;
+}
+
+export default Order;
diff --git a/packages/seller-sdk/src/types/generated/OrderLineItem.ts b/packages/seller-sdk/src/types/generated/OrderLineItem.ts
new file mode 100644
index 0000000000..9d882da5ba
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/OrderLineItem.ts
@@ -0,0 +1,20 @@
+// Typelizer digest c36756c7df6d9fddfa747db960c36235
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type OrderLineItem = {
+ id: string;
+ name: string;
+ options_text: string | null;
+ quantity: number;
+ currency: string;
+ price: unknown;
+ display_price: unknown;
+ total: unknown;
+ display_total: unknown;
+ variant_id: string | null;
+ sku: string | null;
+ thumbnail_url: string | null;
+}
+
+export default OrderLineItem;
diff --git a/packages/seller-sdk/src/types/generated/index.ts b/packages/seller-sdk/src/types/generated/index.ts
index 4951a1d084..64eb1f2432 100644
--- a/packages/seller-sdk/src/types/generated/index.ts
+++ b/packages/seller-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 53306523edc4d3f2294f0a0ff019019b
+// Typelizer digest 2b7959b291060494f5dfb2020d7ac972
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -9,7 +9,11 @@ export type { default as OptionType } from './OptionType'
export type { default as OptionValue } from './OptionValue'
export type { default as PriceHistory } from './PriceHistory'
export type { default as Price } from './Price'
+export type { default as FulfillmentItem } from './FulfillmentItem'
+export type { default as Fulfillment } from './Fulfillment'
export type { default as Invitation } from './Invitation'
+export type { default as OrderLineItem } from './OrderLineItem'
+export type { default as Order } from './Order'
export type { default as Product } from './Product'
export type { default as Profile } from './Profile'
export type { default as RequirementCustomField } from './RequirementCustomField'
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb
new file mode 100644
index 0000000000..3cd350d6b1
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb
@@ -0,0 +1,109 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ module Orders
+ # Dispatching what a seller owes on one of their orders.
+ #
+ # Rooted at the order fetched through `current_seller.orders`, so a
+ # fulfillment on somebody else's order reads as missing rather than
+ # denied — and a seller can never ship against an order that is not
+ # theirs, whatever id they send.
+ #
+ # Fulfilling reuses the operator's workflow, so the customer email,
+ # the label purchase and the extension hooks all happen exactly as
+ # they do when the marketplace ships on the seller's behalf.
+ class FulfillmentsController < Seller::BaseController
+ include Spree::Api::V3::OrderLock
+
+ scoped_resource :fulfillments
+
+ before_action :set_order
+ before_action :set_fulfillment, only: [:show, :fulfill]
+
+ def index
+ render json: {
+ data: @order.fulfillments.map { |fulfillment| serialize(fulfillment) }
+ }
+ end
+
+ def show
+ render json: serialize(@fulfillment)
+ end
+
+ # PATCH /api/v3/seller/orders/:order_id/fulfillments/:id/fulfill
+ #
+ # Ships the parcel. `items` narrows it to part of what the
+ # fulfillment holds, which splits the rest onto a new one.
+ def fulfill
+ with_order_lock do
+ result = Spree.fulfillment_fulfill_workflow.call(
+ fulfillment: @fulfillment,
+ items: items_for_fulfill,
+ tracking: fulfill_params[:tracking],
+ tracking_carrier: fulfill_params[:tracking_carrier],
+ notify_customer: notify_customer?(fulfill_params[:notify_customer])
+ )
+
+ if result.success?
+ render json: serialize(result.value)
+ else
+ render_service_error(@fulfillment.errors.presence || result.error)
+ end
+ end
+ end
+
+ protected
+
+ def read_actions
+ %w[index show]
+ end
+
+ private
+
+ def set_order
+ @order = current_seller.orders.find_by_prefix_id!(params[:order_id])
+ authorize! :show, @order
+ end
+
+ def set_fulfillment
+ @fulfillment = @order.fulfillments.find_by_prefix_id!(params[:id])
+ authorize! :update, @fulfillment if action_name == 'fulfill'
+ end
+
+ def fulfill_params
+ @fulfill_params ||= params.permit(
+ :tracking, :tracking_carrier, :notify_customer, items: [:item_id, :quantity]
+ )
+ end
+
+ # The workflow addresses what to ship by line item, and the lookup
+ # runs through the order so an id from elsewhere cannot be shipped.
+ def items_for_fulfill
+ return if fulfill_params[:items].nil?
+
+ fulfill_params[:items].map do |item|
+ {
+ line_item: @order.line_items.find_by_prefix_id!(item[:item_id]),
+ quantity: Integer(item[:quantity].to_s, exception: false)
+ }
+ end
+ end
+
+ # Only an explicit false suppresses the email; an omitted flag
+ # keeps sending it, as the operator's endpoint does.
+ def notify_customer?(value)
+ !ActiveModel::Type::Boolean.new.cast(value).equal?(false)
+ end
+
+ def serialize(fulfillment)
+ Spree.api.seller_fulfillment_serializer.new(
+ fulfillment, params: { store: current_store }
+ ).to_h
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb
new file mode 100644
index 0000000000..b3118d4fc9
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb
@@ -0,0 +1,88 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # The orders placed with this seller.
+ #
+ # On a marketplace a basket spanning several sellers is split into one
+ # order each, so a seller's orders are their own rows — not a filtered
+ # view of somebody else's. The anchor roots `scope` in
+ # `current_seller.orders`, so an id belonging to another seller reads
+ # as missing rather than denied.
+ #
+ # Read and cancel only. Fulfilling is the fulfillments endpoint under
+ # the order, and everything that settles money with the customer —
+ # approving, resuming, refunds, payments — stays with the operator,
+ # who owns that relationship.
+ class OrdersController < Seller::ResourceController
+ include Spree::Api::V3::OrderLock
+
+ scoped_resource :orders
+
+ before_action :set_resource, only: [:show, :cancel]
+
+ # PATCH /api/v3/seller/orders/:id/cancel
+ #
+ # A seller withdrawing from an order they cannot fulfil. Restocking
+ # and any refund are the workflow's own concern, so a seller cannot
+ # cancel without the money and stock following.
+ def cancel
+ with_order_lock do
+ result = Spree.order_cancel_workflow.call(
+ order: @resource,
+ canceler: try_spree_current_user,
+ notify_customer: params[:notify_customer].to_b
+ )
+
+ if result.success?
+ render json: serialize_resource(@resource.reload)
+ else
+ render_service_error(@resource.errors.presence || result.error)
+ end
+ end
+ end
+
+ protected
+
+ def model_class
+ Spree::Order
+ end
+
+ def serializer_class
+ Spree.api.seller_order_serializer
+ end
+
+ def read_actions
+ %w[index show]
+ end
+
+ # A checkout still in flight is a draft carrying its cart; it is not
+ # yet anybody's order and must not appear in a seller's list.
+ def scope
+ base = super
+
+ base.where(cart_id: nil).or(base.where.not(status: 'draft'))
+ end
+
+ def collection_includes
+ [:line_items, :customer, :channel]
+ end
+
+ private
+
+ def set_resource
+ @resource = find_resource
+ @order = @resource # OrderLock reads this
+ authorize_resource!(@resource)
+ end
+
+ # Cancelling is a change to the order, so it needs the write key
+ # rather than a key of its own.
+ def authorize_resource!(resource = @resource, action = action_name.to_sym)
+ authorize!(action == :cancel ? :update : action, resource)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/fulfillment_item_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/fulfillment_item_serializer.rb
new file mode 100644
index 0000000000..3100779aec
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/seller/fulfillment_item_serializer.rb
@@ -0,0 +1,37 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # One line inside a parcel: what to pick and how many.
+ #
+ # `line_item_id` is what a partial dispatch names — the fulfill
+ # endpoint takes line items, so this is the id a panel sends back.
+ class FulfillmentItemSerializer < V3::BaseSerializer
+ typelize quantity: :number,
+ line_item_id: [:string, nullable: true],
+ name: [:string, nullable: true],
+ sku: [:string, nullable: true],
+ options_text: [:string, nullable: true]
+
+ attributes :quantity
+
+ attribute :line_item_id do |item|
+ item.line_item&.prefixed_id
+ end
+
+ attribute :name do |item|
+ item.line_item&.name
+ end
+
+ attribute :sku do |item|
+ item.variant&.sku
+ end
+
+ attribute :options_text do |item|
+ item.line_item&.options_text
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/fulfillment_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/fulfillment_serializer.rb
new file mode 100644
index 0000000000..649ddae0cd
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/seller/fulfillment_serializer.rb
@@ -0,0 +1,46 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # A parcel this seller owes on one of their orders.
+ #
+ # Declared rather than subclassed from the store's fulfillment, which
+ # nests delivery rates and the store's own stock location serializer —
+ # rate selection is a checkout concern, and the location a seller cares
+ # about is their own shelf, named here rather than expanded.
+ class FulfillmentSerializer < V3::BaseSerializer
+ typelize number: :string,
+ status: :string,
+ tracking: [:string, nullable: true],
+ tracking_url: [:string, nullable: true],
+ tracking_carrier: [:string, nullable: true],
+ tracking_status: [:string, nullable: true],
+ fulfillment_type: [:string, nullable: true],
+ delivery_method_name: [:string, nullable: true],
+ stock_location_name: [:string, nullable: true]
+
+ attributes :number, :status, :tracking, :tracking_url, :tracking_carrier,
+ :tracking_status,
+ fulfilled_at: :iso8601, created_at: :iso8601, updated_at: :iso8601
+
+ attribute :fulfillment_type do |fulfillment|
+ fulfillment.fulfillment_type.presence || (fulfillment.digital? ? 'digital' : 'shipping')
+ end
+
+ # How it travels and where it leaves from, as names rather than
+ # expanded records: a seller reads them, never edits them here.
+ attribute :delivery_method_name do |fulfillment|
+ fulfillment.delivery_method&.name
+ end
+
+ attribute :stock_location_name do |fulfillment|
+ fulfillment.stock_location&.name
+ end
+
+ many :fulfillment_items, key: :items,
+ resource: proc { Spree.api.seller_fulfillment_item_serializer }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/order_line_item_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/order_line_item_serializer.rb
new file mode 100644
index 0000000000..6e2b463572
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/seller/order_line_item_serializer.rb
@@ -0,0 +1,42 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # A line on one of this seller's orders — what to pick, how many, and
+ # what it sold for.
+ #
+ # Declared rather than subclassed from the store's line item: that one
+ # carries the associations a storefront needs (digital links, tax
+ # lines, the seller's own public profile), none of which help someone
+ # packing a box, and each of which would pull another serializer into
+ # this branch's generated types.
+ class OrderLineItemSerializer < V3::BaseSerializer
+ typelize name: :string,
+ sku: [:string, nullable: true],
+ options_text: [:string, nullable: true],
+ quantity: :number,
+ currency: :string,
+ variant_id: [:string, nullable: true],
+ thumbnail_url: [:string, nullable: true]
+
+ attributes :name, :options_text, :quantity, :currency
+
+ money_attributes :price, :display_price, :total, :display_total
+
+ attribute :variant_id do |line_item|
+ line_item.variant&.prefixed_id
+ end
+
+ # How a seller finds the item on their own shelf.
+ attribute :sku do |line_item|
+ line_item.variant&.sku
+ end
+
+ attribute :thumbnail_url do |line_item|
+ image_url_for(line_item.thumbnail)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/order_serializer.rb
new file mode 100644
index 0000000000..6a665f02bc
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/seller/order_serializer.rb
@@ -0,0 +1,44 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # An order placed with this seller.
+ #
+ # Built from the base rather than the store serializer: that one is
+ # written for the shopper who placed the order, and carries payments —
+ # how the customer paid the marketplace is not the seller's business,
+ # and what they are owed is the commission ledger, not this.
+ #
+ # The customer's contact details are here because the seller packs and
+ # posts the parcel, so they need the address and a way to reach the
+ # buyer about it.
+ class OrderSerializer < V3::BaseSerializer
+ typelize number: :string,
+ email: [:string, nullable: true],
+ customer_note: [:string, nullable: true],
+ currency: :string,
+ total_quantity: :number,
+ fulfillment_status: [:string, nullable: true],
+ payment_status: [:string, nullable: true],
+ status: :string
+
+ attributes :number, :email, :customer_note, :currency, :total_quantity,
+ :status, :fulfillment_status, :payment_status,
+ completed_at: :iso8601, created_at: :iso8601, updated_at: :iso8601
+
+ # What this seller is owed for the goods, and what the buyer paid for
+ # them. Deliberately not the whole money surface: gift cards, store
+ # credit and the payment breakdown belong to the marketplace.
+ money_attributes :item_total, :display_item_total,
+ :tax_total, :display_tax_total,
+ :total, :display_total
+
+ many :line_items, key: :items, resource: proc { Spree.api.seller_order_line_item_serializer }
+ many :fulfillments, resource: proc { Spree.api.seller_fulfillment_serializer }
+ one :shipping_address, resource: proc { Spree.api.address_serializer }
+ one :billing_address, resource: proc { Spree.api.address_serializer }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index a1c430a81f..2749dde2c1 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -730,6 +730,21 @@ Spree::Core::Engine.add_routes do
resources :products, only: [:index, :show, :create, :update, :destroy]
+ # What this seller has sold. Cancelling is a member action because it
+ # is a workflow with its own arguments, and fulfilling is nested: a
+ # parcel means nothing outside the order it belongs to.
+ resources :orders, only: [:index, :show] do
+ member do
+ patch :cancel
+ end
+
+ resources :fulfillments, only: [:index, :show], controller: 'orders/fulfillments' do
+ member do
+ patch :fulfill
+ end
+ end
+ end
+
resources :direct_uploads, only: [:create]
# No destroy: a location holds stock levels and is named on historical
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 2c3d075448..d4b895afc5 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -165,6 +165,10 @@ module Spree
seller_team_member_serializer: 'Spree::Api::V3::Seller::TeamMemberSerializer',
seller_invitation_serializer: 'Spree::Api::V3::Seller::InvitationSerializer',
seller_product_serializer: 'Spree::Api::V3::Seller::ProductSerializer',
+ seller_order_serializer: 'Spree::Api::V3::Seller::OrderSerializer',
+ seller_order_line_item_serializer: 'Spree::Api::V3::Seller::OrderLineItemSerializer',
+ seller_fulfillment_serializer: 'Spree::Api::V3::Seller::FulfillmentSerializer',
+ seller_fulfillment_item_serializer: 'Spree::Api::V3::Seller::FulfillmentItemSerializer',
seller_stock_location_serializer: 'Spree::Api::V3::Seller::StockLocationSerializer',
seller_requirement_custom_field_serializer: 'Spree::Api::V3::Seller::RequirementCustomFieldSerializer',
seller_tax_identifier_serializer: 'Spree::Api::V3::Seller::TaxIdentifierSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/orders/fulfillments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/orders/fulfillments_controller_spec.rb
new file mode 100644
index 0000000000..0df5b2b6f2
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/seller/orders/fulfillments_controller_spec.rb
@@ -0,0 +1,65 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Seller::Orders::FulfillmentsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Seller'
+
+ let(:seller_user) do
+ create(:admin_user, :without_admin_role).tap { |user| seller.add_user(user) }
+ end
+ let(:token) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ seller_user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_SELLER
+ )
+ end
+
+ let!(:order) { create(:order_ready_to_ship, store: store, seller: seller) }
+ let(:fulfillment) { order.fulfillments.first }
+
+ before do
+ request.headers['Authorization'] = "Bearer #{token}"
+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id
+ end
+
+ describe 'GET #index' do
+ it 'lists what the seller owes on the order' do
+ get :index, params: { order_id: order.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].map { |row| row['id'] }).to include(fulfillment.prefixed_id)
+ end
+
+ it "404s on another seller's order" do
+ other = create(:order_ready_to_ship, store: store, seller: create(:seller, :approved, store: store))
+
+ get :index, params: { order_id: other.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'PATCH #fulfill' do
+ it 'ships the parcel' do
+ patch :fulfill,
+ params: { order_id: order.prefixed_id, id: fulfillment.prefixed_id, tracking: 'TRACK-1' },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(fulfillment.reload).to be_fulfilled
+ expect(fulfillment.tracking).to eq('TRACK-1')
+ end
+
+ # Shipping through another seller's order must be unreachable whatever ids
+ # are sent, since the fulfillment is only ever found through the order.
+ it "404s on a fulfillment reached through someone else's order" do
+ other = create(:order_ready_to_ship, store: store, seller: create(:seller, :approved, store: store))
+ theirs = other.fulfillments.first
+
+ patch :fulfill, params: { order_id: order.prefixed_id, id: theirs.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(theirs.reload).not_to be_fulfilled
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/orders_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/orders_controller_spec.rb
new file mode 100644
index 0000000000..72bd77c298
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/seller/orders_controller_spec.rb
@@ -0,0 +1,82 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Seller::OrdersController, type: :controller do
+ render_views
+
+ include_context 'API v3 Seller'
+
+ let(:seller_user) do
+ create(:admin_user, :without_admin_role).tap { |user| seller.add_user(user) }
+ end
+ let(:token) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ seller_user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_SELLER
+ )
+ end
+
+ let!(:mine) { create(:completed_order_with_totals, store: store, seller: seller) }
+ let(:other_seller) { create(:seller, :approved, store: store) }
+ let!(:theirs) { create(:completed_order_with_totals, store: store, seller: other_seller) }
+
+ before do
+ request.headers['Authorization'] = "Bearer #{token}"
+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id
+ end
+
+ describe 'GET #index' do
+ it "lists only this seller's orders" do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ numbers = json_response['data'].map { |row| row['number'] }
+ expect(numbers).to include(mine.number)
+ expect(numbers).not_to include(theirs.number)
+ end
+
+ # A draft carrying its cart is a checkout still in flight; it is nobody's
+ # order yet and must not appear in a seller's list.
+ it 'leaves out a checkout still in flight' do
+ cart = create(:cart, store: store)
+ create(:order, store: store, seller: seller, status: 'draft', cart: cart)
+
+ get :index, as: :json
+
+ expect(json_response['data'].map { |row| row['status'] }).not_to include('draft')
+ end
+ end
+
+ describe 'GET #show' do
+ it 'renders what the seller needs to pack the parcel' do
+ get :show, params: { id: mine.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['number']).to eq(mine.number)
+ expect(json_response).to have_key('items')
+ expect(json_response).to have_key('shipping_address')
+ # How the customer paid the marketplace is not the seller's business.
+ expect(json_response).not_to have_key('payments')
+ end
+
+ it "404s on another seller's order" do
+ get :show, params: { id: theirs.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'PATCH #cancel' do
+ it 'withdraws from an order it cannot fulfil' do
+ patch :cancel, params: { id: mine.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(mine.reload).to be_canceled
+ end
+
+ it "404s on another seller's order" do
+ patch :cancel, params: { id: theirs.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(theirs.reload).not_to be_canceled
+ end
+ end
+end