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 inventory operations on the Admin API
Łukasz Adamczyk81dae3ffd9cc
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/receivable_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/receivable_actions.rbnew file mode 100644index 0000000000..4ae1e6517d--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/receivable_actions.rb@@ -0,0 +1,129 @@+module Spree+ module Api+ module V3+ module Admin+ # What a stock transfer and a purchase order have in common as+ # endpoints: line items resolved out of a flat payload, and statuses+ # moved one named action at a time+ # (docs/plans/6.0-inventory-operations.md).+ #+ # Every id a payload names is resolved through the store — or through+ # the document itself, for its own lines — so an id belonging to+ # another tenant answers 404 rather than being acted on. That is also+ # why nothing here assigns a `*_id` from the payload: `permitted_params`+ # decodes prefixed ids into primary keys, and a decoded key carries no+ # evidence of whose record it is.+ module ReceivableActions+ extend ActiveSupport::Concern++ # A payload whose `items` is not a list. Raised out of the params+ # helper so it cannot be mistaken for a workflow rejection, and+ # answered as the client mistake it is rather than a 500.+ class InvalidItems < StandardError; end++ included do+ rescue_from InvalidItems, with: :render_invalid_items+ end++ protected++ # Runs one of the document's status workflows and renders the result.+ def run_transition(workflow, **arguments)+ result = workflow.call(workflow_record_key => @resource, **arguments)++ if result.success?+ render json: serialize_resource(result.value)+ else+ render_result_error(result)+ end+ end++ # @return [Symbol] the keyword this document's workflows take it under+ def workflow_record_key+ raise NotImplementedError, "#{self.class} must implement #workflow_record_key"+ end++ # The lines a create or update named, or nil when the payload said+ # nothing about them — which on an update means "leave them alone".+ #+ # @param attribute_keys [Array<Symbol>] the per-line attributes this+ # document accepts beyond the variant (`:quantity_shipped`,+ # `:quantity_ordered`, `:unit_cost`)+ # @return [Array<Hash>, nil]+ def items_from_params(*attribute_keys)+ sent = sent_items([:variant_id, *attribute_keys])+ return nil if sent.nil?++ sent.map do |item|+ attributes = { variant: variants_scope.find_by_prefix_id!(item[:variant_id]) }+ attribute_keys.each { |key| attributes[key] = item[key] if item.key?(key.to_s) }+ attributes+ end+ end++ # What the warehouse counted, resolved through the document itself,+ # so a line from another transfer or order cannot be received here.+ #+ # An omitted `items` means "receive it all as expected". Naming an+ # empty list — or an explicit `null`, the same statement — means the+ # caller named no lines, and must not fall through to receive-all.+ #+ # @param keys [Array<Symbol>] the per-line keys to permit+ # @return [Array<Hash>, nil]+ def items_for_receive(keys)+ sent = sent_items(keys)+ return nil if sent.nil?++ sent.map do |item|+ {+ item: @resource.items.find_by_prefix_id!(item[:id]),+ quantity_received: item[:quantity_received],+ discrepancy_reason: item[:discrepancy_reason]+ }+ end+ end++ # Any of the store's warehouses the caller may see, or nil when the+ # payload did not name one.+ #+ # @return [Spree::StockLocation, nil]+ def stock_location_from(key)+ id = params[key]+ return nil if id.blank?++ current_store.stock_locations.accessible_by(current_ability, :show).find_by_prefix_id!(id)+ end++ def variants_scope+ current_store.variants.accessible_by(current_ability, :show)+ end++ def render_invalid_items+ errors = ActiveModel::Errors.new(@resource || model_class.new)+ errors.add(:items, :invalid)+ render_validation_error(errors)+ end++ private++ # Raw `params`, not `permitted_params`: the latter decodes anything+ # shaped like a prefixed id into a primary key, and these lines are+ # looked up by prefixed id precisely so their scope is checked.+ #+ # The list-ness is checked before `permit`, which silently drops a+ # scalar `items` — leaving a client typo indistinguishable from "no+ # lines named", and answering 201 to a payload nobody meant.+ def sent_items(keys)+ return nil unless params.key?(:items)++ raw = params[:items]+ return [] if raw.nil?+ raise InvalidItems unless raw.is_a?(Array)++ params.permit(items: keys)[:items] || []+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/purchase_orders_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/purchase_orders_controller.rbnew file mode 100644index 0000000000..2b947b4d27--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/purchase_orders_controller.rb@@ -0,0 +1,143 @@+module Spree+ module Api+ module V3+ module Admin+ # Goods bought from a supplier.+ #+ # Ordered units never count toward availability: nothing here touches+ # `count_on_hand` until `receive` runs, because a merchant who has+ # ordered stock does not have it.+ #+ # Each status change is its own member action rather than a PATCH that+ # mass-assigns `status`, because receiving carries the quantities the+ # warehouse counted.+ class PurchaseOrdersController < ResourceController+ include Spree::Api::V3::Admin::ReceivableActions++ scoped_resource :purchasing++ # The base registers this for show/update/destroy; a second+ # `before_action :set_resource` replaces that registration rather than+ # adding to it, so those three are listed again here.+ before_action :set_resource, only: [:show, :update, :destroy, :mark_ordered, :receive, :cancel]++ # DELETE /api/v3/admin/purchase_orders/:id+ #+ # Only a draft. Once the order has gone to the supplier it is a+ # matter of record between two businesses, and is cancelled rather+ # than deleted.+ def destroy+ return super if @resource.draft?++ render_error(+ code: 'invalid_status',+ message: Spree.t('purchase_order.errors.only_draft_can_be_deleted'),+ status: :unprocessable_content+ )+ end++ # PATCH /api/v3/admin/purchase_orders/:id/mark_ordered+ def mark_ordered+ run_transition(Spree.purchase_order_mark_ordered_workflow)+ end++ # PATCH /api/v3/admin/purchase_orders/:id/receive+ def receive+ run_transition(Spree.purchase_order_receive_workflow,+ items: items_for_receive([:id, :quantity_received]),+ received_by: try_spree_current_user)+ end++ # PATCH /api/v3/admin/purchase_orders/:id/cancel+ def cancel+ run_transition(Spree.purchase_order_cancel_workflow,+ reason: params[:reason],+ canceler: try_spree_current_user)+ end++ protected++ def model_class+ Spree::PurchaseOrder+ end++ def serializer_class+ Spree.api.admin_purchase_order_serializer+ end++ def collection_includes+ [:supplier, :destination_location, { items: :variant }]+ end++ def create_workflow+ Spree.purchase_order_create_workflow+ end++ def update_workflow+ Spree.purchase_order_update_workflow+ end++ def workflow_record_key+ :purchase_order+ end++ def create_workflow_arguments+ {+ store: current_store,+ supplier: supplier_from_params,+ destination_location: stock_location_from(:destination_location_id),+ items: items_from_params(:quantity_ordered, :unit_cost) || [],+ currency: params[:currency],+ expected_at: params[:expected_at],+ reference: params[:reference],+ notes: params[:notes],+ created_by: try_spree_current_user+ }+ end++ def update_workflow_arguments+ {+ purchase_order: @resource,+ attributes: editable_attributes,+ items: items_from_params(:quantity_ordered, :unit_cost)+ }+ end++ # The supplier and the warehouse are resolved through the store+ # instead, since an id the payload names has to be proved to belong+ # here.+ def resource_permitted_attributes+ [:currency, :expected_at, :reference, :notes, { metadata: {} }]+ end++ def editable_attributes+ attributes = permitted_params.to_h.symbolize_keys+ attributes[:supplier] = supplier_from_params if params.key?(:supplier_id)+ if params.key?(:destination_location_id)+ attributes[:destination_location] = stock_location_from(:destination_location_id)+ end+ attributes+ end++ def scope_includes+ [{ items: :variant }]+ end++ private++ # Read through `current_store` rather than the model constant: a+ # supplier id belonging to another store must 404, which no ability+ # check would catch.+ #+ # @return [Spree::Supplier, nil]+ def supplier_from_params+ return nil if params[:supplier_id].blank?++ current_store.suppliers.accessible_by(current_ability, :show).+ find_by_prefix_id!(params[:supplier_id])+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rbindex eb3ebbb40f..80282be359 100644--- a/spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rb@@ -2,38 +2,65 @@ module Spreemodule Apimodule V3module Admin- # Inventory movement between stock locations, or seller → location- # for receives. Pass `source_location_id` for transfers; omit it to- # record an external receive.+ # Stock moving between two of the merchant's own warehouses.+ #+ # `create` persists a draft; nothing moves until the transfer is marked+ # in transit. Receiving from a supplier is a+ # {Spree::Api::V3::Admin::PurchaseOrdersController} order, not a+ # transfer with a missing source.+ #+ # Every status change is its own member action rather than a PATCH that+ # mass-assigns `status`, because each one is a workflow with its own+ # arguments — receiving carries the quantities the warehouse counted,+ # cancelling carries what happens to units already in flight.class StockTransfersController < ResourceController+ include Spree::Api::V3::Admin::ReceivableActions+scoped_resource :stock- def create- authorize!(:create, model_class)-- stock_locations = Spree::StockLocation.accessible_by(current_ability, :show)- destination = stock_locations.find_by_prefix_id!(params[:destination_location_id])- source = params[:source_location_id].present? ?- stock_locations.find_by_prefix_id!(params[:source_location_id]) : nil-- variants_map = build_variants_map- if variants_map.empty?- return render_error(- code: 'invalid_variants',- message: Spree.t('stock_transfer.errors.must_have_variant'),- status: :unprocessable_content- )- end+ # The base registers this for show/update/destroy; a second+ # `before_action :set_resource` replaces that registration rather than+ # adding to it, so those three are listed again here.+ before_action :set_resource, only: [:show, :update, :destroy, :mark_ready, :mark_in_transit, :receive, :cancel]- @resource = source ?- Spree::StockTransfer.new(reference: params[:reference]).tap { |t| t.transfer(source, destination, variants_map) } :- Spree::StockTransfer.new(reference: params[:reference]).tap { |t| t.receive(destination, variants_map) }+ # DELETE /api/v3/admin/stock_transfers/:id+ #+ # A draft is the only transfer a merchant may throw away: past that+ # it describes a box that physically exists, which is cancelled+ # rather than deleted.+ def destroy+ return super if @resource.draft?- if @resource.persisted?- render json: serialize_resource(@resource), status: :created- else- render_validation_error(@resource.errors)- end+ render_error(+ code: 'invalid_status',+ message: Spree.t('stock_transfer.errors.only_draft_can_be_deleted'),+ status: :unprocessable_content+ )+ end++ # PATCH /api/v3/admin/stock_transfers/:id/mark_ready+ def mark_ready+ run_transition(Spree.stock_transfer_mark_ready_workflow)+ end++ # PATCH /api/v3/admin/stock_transfers/:id/mark_in_transit+ def mark_in_transit+ run_transition(Spree.stock_transfer_mark_in_transit_workflow, force: params[:force].to_b)+ end++ # PATCH /api/v3/admin/stock_transfers/:id/receive+ def receive+ run_transition(Spree.stock_transfer_receive_workflow,+ items: items_for_receive([:id, :quantity_received, :discrepancy_reason]),+ received_by: try_spree_current_user)+ end++ # PATCH /api/v3/admin/stock_transfers/:id/cancel+ def cancel+ run_transition(Spree.stock_transfer_cancel_workflow,+ on_in_transit: params[:on_in_transit],+ reason: params[:reason],+ canceler: try_spree_current_user)endprotected@@ -47,27 +74,64 @@ module Spreeenddef collection_includes- [:source_location, :destination_location]+ [:source_location, :destination_location, { items: :variant }]+ end++ def create_workflow+ Spree.stock_transfer_create_workflowend- private+ def update_workflow+ Spree.stock_transfer_update_workflow+ end- # Variants the merchant doesn't have access to are dropped silently;- # if the resulting map is empty the action surfaces a 422- # `invalid_variants` so callers can distinguish "nothing supplied"- # from "all variants were rejected." A single SELECT covers any- # number of variants instead of N round-trips.- def build_variants_map- entries = params.permit(variants: [:variant_id, :quantity]).fetch(:variants, [])- quantities_by_id = entries.each_with_object({}) do |entry, hash|- decoded = Spree::PrefixedId.decode_prefixed_id(entry[:variant_id])- hash[decoded.to_i] = entry[:quantity].to_i if decoded- end+ def workflow_record_key+ :stock_transfer+ end++ def create_workflow_arguments+ {+ store: current_store,+ source_location: stock_location_from(:source_location_id),+ destination_location: stock_location_from(:destination_location_id),+ items: items_from_params(:quantity_shipped) || [],+ reference: params[:reference],+ notes: params[:notes],+ created_by: try_spree_current_user+ }+ end- current_store.variants.accessible_by(current_ability, :update).where(id: quantities_by_id.keys).each_with_object({}) do |variant, acc|- quantity = quantities_by_id[variant.id]- acc[variant] = quantity if quantity&.positive?+ def update_workflow_arguments+ {+ stock_transfer: @resource,+ attributes: editable_attributes,+ items: items_from_params(:quantity_shipped)+ }+ end++ # Only what mass assignment may safely carry. The two warehouses are+ # resolved through the store instead, since an id the payload names+ # has to be proved to belong here.+ def resource_permitted_attributes+ [:reference, :notes, { metadata: {} }]+ end++ # A transfer's status transitions are its own actions, so `update`+ # only ever edits the document — and its two ends are objects the+ # store handed us, never ids the payload asserted.+ def editable_attributes+ attributes = permitted_params.to_h.symbolize_keys+ attributes[:source_location] = stock_location_from(:source_location_id) if params.key?(:source_location_id)+ if params.key?(:destination_location_id)+ attributes[:destination_location] = stock_location_from(:destination_location_id)end+ attributes+ end++ # The listing and the detail page both read a transfer's totals off+ # its lines.+ def scope_includes+ [{ items: :variant }]endendenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/suppliers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/suppliers_controller.rbnew file mode 100644index 0000000000..eb509625a8--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/suppliers_controller.rb@@ -0,0 +1,30 @@+module Spree+ module Api+ module V3+ module Admin+ # The merchant's supplier address book. Buying goods in is its own+ # permission resource: `write_stock` moves the stock you have, and must+ # not also mean "may place orders with suppliers".+ class SuppliersController < ResourceController+ scoped_resource :purchasing++ protected++ def model_class+ Spree::Supplier+ end++ def serializer_class+ Spree.api.admin_supplier_serializer+ end++ def resource_permitted_attributes+ [:name, :contact_name, :email, :phone, :notes,+ :address1, :address2, :city, :state_name, :state_code,+ :country_code, :postal_code, { metadata: {} }]+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/purchase_order_item_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/purchase_order_item_serializer.rbnew file mode 100644index 0000000000..a911896f1b--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/purchase_order_item_serializer.rb@@ -0,0 +1,65 @@+module Spree+ module Api+ module V3+ module Admin+ # One SKU on a purchase order, with the price the merchant agreed to.+ class PurchaseOrderItemSerializer < V3::BaseSerializer+ typelize quantity_ordered: :number,+ quantity_received: :number,+ outstanding: :number,+ unit_cost: :string,+ display_unit_cost: :string,+ total_cost: :string,+ display_total_cost: :string,+ currency: 'string | null',+ purchase_order_id: 'string | null',+ variant_id: 'string | null',+ variant_name: 'string | null',+ variant_sku: 'string | null',+ options_text: 'string | null'++ attributes :quantity_ordered, :quantity_received, :outstanding, :currency,+ created_at: :iso8601, updated_at: :iso8601++ # Money on the wire is a decimal string: a float would round the+ # merchant's own figure.+ attribute :unit_cost do |item|+ item.unit_cost&.to_s+ end++ attribute :total_cost do |item|+ item.total_cost.to_s+ end++ attribute :display_unit_cost do |item|+ item.display_unit_cost.to_s+ end++ attribute :display_total_cost do |item|+ item.display_total_cost.to_s+ end++ attribute :purchase_order_id do |item|+ Spree::PurchaseOrder.prefixed_id_for(item.purchase_order_id)+ end++ attribute :variant_id do |item|+ item.variant&.prefixed_id+ end++ attribute :variant_name do |item|+ item.variant&.product&.name+ end++ attribute :variant_sku do |item|+ item.variant&.sku+ end++ attribute :options_text do |item|+ item.variant&.options_text+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/purchase_order_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/purchase_order_serializer.rbnew file mode 100644index 0000000000..11abd75fb9--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/purchase_order_serializer.rb@@ -0,0 +1,75 @@+module Spree+ module Api+ module V3+ module Admin+ # Goods bought from a supplier. Admin-only — a purchase order is what+ # the merchant owes and expects, which no customer ever sees.+ class PurchaseOrderSerializer < V3::BaseSerializer+ typelize number: :string,+ status: :string,+ currency: :string,+ reference: 'string | null',+ notes: 'string | null',+ supplier_id: 'string | null',+ destination_location_id: 'string | null',+ expected_at: 'string | null',+ items_count: :number,+ quantity_ordered_total: :number,+ quantity_received_total: :number,+ subtotal: :string,+ display_subtotal: :string,+ editable: :boolean,+ metadata: 'Record<string, unknown>'++ attributes :number, :status, :currency, :reference, :notes, :metadata,+ :items_count, :quantity_received_total,+ ordered_at: :iso8601, received_at: :iso8601,+ created_at: :iso8601, updated_at: :iso8601++ # A calendar date, not an instant: the day a supplier promised, which+ # means the same day in every timezone. `yyyy-mm-dd`, which is what+ # the dashboard's date-only picker both sends and reads. The+ # `:iso8601` type is for instants and would ask a Date for+ # millisecond precision it has no argument for.+ attribute :expected_at do |purchase_order|+ purchase_order.expected_at&.iso8601+ end++ # Named for the merchant's own vocabulary — a purchase order orders,+ # a transfer ships — over the concern's neutral `quantity_expected`.+ attribute :quantity_ordered_total, &:quantity_expected_total++ attribute :editable, &:editable?++ attribute :subtotal do |purchase_order|+ purchase_order.subtotal.to_s+ end++ attribute :display_subtotal do |purchase_order|+ purchase_order.display_subtotal.to_s+ end++ attribute :supplier_id do |purchase_order|+ purchase_order.supplier&.prefixed_id+ end++ attribute :destination_location_id do |purchase_order|+ purchase_order.destination_location&.prefixed_id+ end++ many :items,+ resource: proc { Spree.api.admin_purchase_order_item_serializer },+ if: proc { expand?('items') }++ one :supplier,+ resource: proc { Spree.api.admin_supplier_serializer },+ if: proc { expand?('supplier') }++ one :destination_location,+ resource: proc { Spree.api.admin_stock_location_serializer },+ if: proc { expand?('destination_location') }+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/stock_movement_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/stock_movement_serializer.rbindex 05b851e93d..2715c6d503 100644--- a/spree/api/app/serializers/spree/api/v3/admin/stock_movement_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/stock_movement_serializer.rb@@ -5,7 +5,10 @@ module Spreeclass StockMovementSerializer < V3::StockMovementSerializertypelize order_id: [:string, nullable: true], fulfillment_id: [:string, nullable: true],return_id: [:string, nullable: true], exchange_id: [:string, nullable: true],- stock_transfer_id: [:string, nullable: true]+ stock_transfer_id: [:string, nullable: true],+ purchase_order_id: [:string, nullable: true],+ unit_cost: [:string, nullable: true],+ display_unit_cost: [:string, nullable: true]# The cause. Exactly which keys are set follows from the kind — a# dispatch carries its fulfillment and its order, a transfer carries@@ -29,6 +32,21 @@ module Spreeattribute :stock_transfer_id do |movement|Spree::StockTransfer.prefixed_id_for(movement.stock_transfer_id)end++ attribute :purchase_order_id do |movement|+ Spree::PurchaseOrder.prefixed_id_for(movement.purchase_order_id)+ end++ # What the units cost, on the rows where that means something: a+ # purchase. Null on a transfer or a return — moving stock the+ # merchant already owns is not buying it.+ attribute :unit_cost do |movement|+ movement.unit_cost&.to_s+ end++ attribute :display_unit_cost do |movement|+ movement.display_unit_cost&.to_s+ endendendenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/stock_transfer_item_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/stock_transfer_item_serializer.rbnew file mode 100644index 0000000000..8fae76499e--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/stock_transfer_item_serializer.rb@@ -0,0 +1,44 @@+module Spree+ module Api+ module V3+ module Admin+ # One SKU on a stock transfer: how many left, how many arrived, and+ # what happened to the difference.+ class StockTransferItemSerializer < V3::BaseSerializer+ typelize quantity_shipped: :number,+ quantity_received: :number,+ outstanding: :number,+ discrepancy_reason: 'string | null',+ stock_transfer_id: 'string | null',+ variant_id: 'string | null',+ variant_name: 'string | null',+ variant_sku: 'string | null',+ options_text: 'string | null'++ attributes :quantity_shipped, :quantity_received, :outstanding, :discrepancy_reason,+ created_at: :iso8601, updated_at: :iso8601++ attribute :stock_transfer_id do |item|+ Spree::StockTransfer.prefixed_id_for(item.stock_transfer_id)+ end++ attribute :variant_id do |item|+ item.variant&.prefixed_id+ end++ attribute :variant_name do |item|+ item.variant&.product&.name+ end++ attribute :variant_sku do |item|+ item.variant&.sku+ end++ attribute :options_text do |item|+ item.variant&.options_text+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/stock_transfer_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/stock_transfer_serializer.rbindex 4d09c4e5f6..4bfd44c38f 100644--- a/spree/api/app/serializers/spree/api/v3/admin/stock_transfer_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/stock_transfer_serializer.rb@@ -2,26 +2,32 @@ module Spreemodule Apimodule V3module Admin- # Inventory movement between two stock locations (or external →- # location for receives). The originating location is `nil` for- # receives (seller stock arriving) and present for transfers.- class StockTransferSerializer < V3::BaseSerializer- typelize number: :string,- reference: [:string, nullable: true],- source_location_id: [:string, nullable: true],- destination_location_id: [:string, nullable: true],+ # Stock moving between two of the merchant's own warehouses. The trip+ # has a middle: `shipped_at` is when the units left the source,+ # `received_at` when the destination finished counting them in.+ class StockTransferSerializer < V3::StockTransferSerializer+ typelize status: :string,+ notes: 'string | null',+ items_count: :number,+ quantity_shipped_total: :number,+ quantity_received_total: :number,+ editable: :boolean,metadata: 'Record<string, unknown>'- attributes :number, :reference, :metadata,- created_at: :iso8601, updated_at: :iso8601+ attributes :status, :notes, :metadata,+ :items_count, :quantity_received_total,+ shipped_at: :iso8601, received_at: :iso8601, deleted_at: :iso8601- attribute :source_location_id do |stock_transfer|- stock_transfer.source_location&.prefixed_id- end+ # Named for the merchant's own vocabulary — a transfer ships, a+ # purchase order orders — over the concern's neutral+ # `quantity_expected`.+ attribute :quantity_shipped_total, &:quantity_expected_total- attribute :destination_location_id do |stock_transfer|- stock_transfer.destination_location&.prefixed_id- end+ attribute :editable, &:editable?++ many :items,+ resource: proc { Spree.api.admin_stock_transfer_item_serializer },+ if: proc { expand?('items') }one :source_location,resource: proc { Spree.api.admin_stock_location_serializer },diff --git a/spree/api/app/serializers/spree/api/v3/admin/supplier_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/supplier_serializer.rbnew file mode 100644index 0000000000..2c84d02b0e--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/supplier_serializer.rb@@ -0,0 +1,35 @@+module Spree+ module Api+ module V3+ module Admin+ # Admin-only: who the merchant buys from is never a storefront+ # concern.+ class SupplierSerializer < V3::BaseSerializer+ typelize name: :string,+ contact_name: 'string | null',+ email: 'string | null',+ phone: 'string | null',+ notes: 'string | null',+ address1: 'string | null',+ address2: 'string | null',+ city: 'string | null',+ state_name: 'string | null',+ state_code: 'string | null',+ country_code: 'string | null',+ postal_code: 'string | null',+ purchase_orders_count: :number,+ metadata: 'Record<string, unknown>'++ attributes :name, :contact_name, :email, :phone, :notes,+ :address1, :address2, :city, :state_name, :state_code,+ :country_code, :postal_code, :metadata,+ created_at: :iso8601, updated_at: :iso8601, deleted_at: :iso8601++ attribute :purchase_orders_count do |supplier|+ supplier.purchase_orders.size+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/purchase_order_event_serializer.rb b/spree/api/app/serializers/spree/api/v3/purchase_order_event_serializer.rbnew file mode 100644index 0000000000..b4374aea8a--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/purchase_order_event_serializer.rb@@ -0,0 +1,11 @@+module Spree+ module Api+ module V3+ # Payload of the purchase_order.* events. Purchase orders have no+ # storefront serializer, so the event shape is declared here rather than+ # found by convention.+ class PurchaseOrderEventSerializer < Admin::PurchaseOrderSerializer+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/stock_transfer_serializer.rb b/spree/api/app/serializers/spree/api/v3/stock_transfer_serializer.rbindex 03ce022431..f5efacb9aa 100644--- a/spree/api/app/serializers/spree/api/v3/stock_transfer_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/stock_transfer_serializer.rb@@ -4,13 +4,13 @@ module Spreemodule Apimodule V3class StockTransferSerializer < BaseSerializer- # `type` is not exposed: Spree::StockTransfer has no STI subclasses, so- # the column is a legacy vestige that is always nil. The admin- # serializer already omits it.- typelize number: [:string, nullable: true],+ # Both warehouses are required now: receiving from a supplier is a+ # Spree::PurchaseOrder, not a transfer with a missing source+ # (docs/plans/6.0-inventory-operations.md).+ typelize number: :string,reference: [:string, nullable: true],- source_location_id: [:string, nullable: true],- destination_location_id: [:string, nullable: true]+ source_location_id: :string,+ destination_location_id: :stringattributes :number, :reference,created_at: :iso8601, updated_at: :iso8601diff --git a/spree/api/app/serializers/spree/api/v3/supplier_event_serializer.rb b/spree/api/app/serializers/spree/api/v3/supplier_event_serializer.rbnew file mode 100644index 0000000000..089150fea9--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/supplier_event_serializer.rb@@ -0,0 +1,11 @@+module Spree+ module Api+ module V3+ # Payload of the supplier.* events. Suppliers have no storefront+ # serializer — a customer never sees who the merchant buys from — so the+ # event shape is declared here rather than found by convention.+ class SupplierEventSerializer < Admin::SupplierSerializer+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex f22aca626a..78c2f0047e 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -429,7 +429,24 @@ Spree::Core::Engine.add_routes doendendresources :stock_movements, only: [:index, :show]- resources :stock_transfers, only: [:index, :show, :create, :destroy]+ resources :stock_transfers do+ member do+ patch :mark_ready+ patch :mark_in_transit+ patch :receive+ patch :cancel+ end+ end++ # Purchasing+ resources :suppliers+ resources :purchase_orders do+ member do+ patch :mark_ordered+ patch :receive+ patch :cancel+ end+ end# Payment Methodsresources :delivery_methods dodiff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex d01ef05d7a..b9bd48028c 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -134,6 +134,10 @@ module Spreeadmin_stock_level_serializer: 'Spree::Api::V3::Admin::StockLevelSerializer',admin_stock_movement_serializer: 'Spree::Api::V3::Admin::StockMovementSerializer',admin_stock_transfer_serializer: 'Spree::Api::V3::Admin::StockTransferSerializer',+ admin_stock_transfer_item_serializer: 'Spree::Api::V3::Admin::StockTransferItemSerializer',+ admin_supplier_serializer: 'Spree::Api::V3::Admin::SupplierSerializer',+ admin_purchase_order_serializer: 'Spree::Api::V3::Admin::PurchaseOrderSerializer',+ admin_purchase_order_item_serializer: 'Spree::Api::V3::Admin::PurchaseOrderItemSerializer',admin_shipment_serializer: 'Spree::Api::V3::Admin::FulfillmentSerializer',admin_fulfillment_serializer: 'Spree::Api::V3::Admin::FulfillmentSerializer',admin_fulfillment_item_serializer: 'Spree::Api::V3::Admin::FulfillmentItemSerializer',diff --git a/spree/api/spec/controllers/spree/api/v3/admin/purchase_orders_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/purchase_orders_controller_spec.rbnew file mode 100644index 0000000000..e5a40edd03--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/purchase_orders_controller_spec.rb@@ -0,0 +1,248 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::PurchaseOrdersController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let(:store) { Spree::Store.default }+ let!(:supplier) { create(:supplier, store: store, name: 'Acme Wholesale') }+ let!(:destination_location) { create(:stock_location, store: store, name: 'Brooklyn') }+ let(:variant) { create(:variant) }++ before { request.headers.merge!(headers) }++ def create_draft(quantity: 100, unit_cost: 12.5)+ Spree::PurchaseOrders::Create.call(+ store: store, supplier: supplier, destination_location: destination_location,+ items: [{ variant: variant, quantity_ordered: quantity, unit_cost: unit_cost }]+ ).value+ end++ def on_hand+ destination_location.stock_level(variant.id)&.count_on_hand.to_i+ end++ describe 'GET #index' do+ let!(:purchase_order) { create_draft }++ it 'returns the store’s purchase orders with their totals' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].find { |po| po['id'] == purchase_order.prefixed_id }+ expect(row).to include(+ 'status' => 'draft', 'items_count' => 1, 'quantity_ordered_total' => 100,+ 'quantity_received_total' => 0, 'subtotal' => '1250.0', 'editable' => true+ )+ expect(row['supplier_id']).to eq(supplier.prefixed_id)+ end++ it "never lists another store's purchase orders" do+ other_store = create(:store)+ foreign = Spree::PurchaseOrders::Create.call(+ store: other_store, supplier: create(:supplier, store: other_store),+ destination_location: create(:stock_location, store: other_store),+ items: [{ variant: create(:product, store: other_store).default_variant,+ quantity_ordered: 1, unit_cost: 1 }]+ ).value++ get :index, as: :json++ expect(json_response['data'].map { |po| po['id'] }).not_to include(foreign.prefixed_id)+ end++ it 'filters by status so the dashboard can show only what is outstanding' do+ ordered = create_draft+ Spree::PurchaseOrders::MarkOrdered.call(purchase_order: ordered)++ get :index, params: { q: { status_eq: 'ordered' } }, as: :json++ expect(json_response['data'].map { |po| po['id'] }).to eq([ordered.prefixed_id])+ end+ end++ describe 'POST #create' do+ let(:params) do+ {+ supplier_id: supplier.prefixed_id,+ destination_location_id: destination_location.prefixed_id,+ expected_at: '2026-10-01',+ reference: 'SUP-8891',+ items: [{ variant_id: variant.prefixed_id, quantity_ordered: 100, unit_cost: '12.50' }]+ }+ end++ it 'drafts the order without touching availability' do+ expect { post :create, params: params, as: :json }.to change(Spree::PurchaseOrder, :count).by(1)++ expect(response).to have_http_status(:created)+ expect(json_response).to include('status' => 'draft', 'reference' => 'SUP-8891',+ 'currency' => store.default_currency)+ expect(json_response['number']).to start_with('PO')+ expect(on_hand).to eq(0)+ end++ it 'accepts a foreign currency' do+ post :create, params: params.merge(currency: 'EUR'), as: :json++ expect(json_response['currency']).to eq('EUR')+ end++ it "returns 404 for another store's supplier" do+ foreign_supplier = create(:supplier, store: create(:store))++ post :create, params: params.merge(supplier_id: foreign_supplier.prefixed_id), as: :json++ expect(response).to have_http_status(:not_found)+ end++ it "returns 404 for another store's warehouse" do+ foreign_location = create(:stock_location, store: create(:store))++ post :create, params: params.merge(destination_location_id: foreign_location.prefixed_id), as: :json++ expect(response).to have_http_status(:not_found)+ end++ it "returns 404 for another store's variant" do+ foreign_variant = create(:product, store: create(:store)).default_variant++ post :create, params: params.merge(+ items: [{ variant_id: foreign_variant.prefixed_id, quantity_ordered: 1, unit_cost: '1' }]+ ), as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'PATCH #update' do+ let!(:purchase_order) { create_draft }++ it 'replaces the lines of a draft' do+ other_variant = create(:variant)++ patch :update, params: {+ id: purchase_order.prefixed_id, reference: 'SUP-9000',+ items: [{ variant_id: other_variant.prefixed_id, quantity_ordered: 4, unit_cost: '3.00' }]+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['reference']).to eq('SUP-9000')+ line = purchase_order.reload.items.sole+ expect(line.variant).to eq(other_variant)+ expect(line.quantity_ordered).to eq(4)+ expect(line.unit_cost).to eq(3)+ end++ it 'refuses to rewrite an order already placed with the supplier' do+ Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order)++ patch :update, params: { id: purchase_order.prefixed_id, reference: 'too late' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'the lifecycle actions' do+ let!(:purchase_order) { create_draft }++ it 'places the order with the supplier' do+ patch :mark_ordered, params: { id: purchase_order.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response).to include('status' => 'ordered', 'editable' => false)+ expect(json_response['ordered_at']).to be_present+ expect(on_hand).to eq(0)+ end++ it 'books in what the supplier actually delivered' do+ patch :mark_ordered, params: { id: purchase_order.prefixed_id }, as: :json+ item = purchase_order.reload.items.sole++ patch :receive, params: {+ id: purchase_order.prefixed_id, items: [{ id: item.prefixed_id, quantity_received: 60 }]+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response).to include('status' => 'partially_received',+ 'quantity_received_total' => 60)+ expect(on_hand).to eq(60)+ end++ it 'records what the units cost on the movement that landed them' do+ patch :mark_ordered, params: { id: purchase_order.prefixed_id }, as: :json+ patch :receive, params: { id: purchase_order.prefixed_id }, as: :json++ movement = purchase_order.reload.stock_movements.sole+ expect(movement.unit_cost).to eq(12.5)+ expect(movement.purchase_order).to eq(purchase_order)+ end++ it 'refuses to receive an order that has not been placed' do+ patch :receive, params: { id: purchase_order.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(on_hand).to eq(0)+ end++ it "returns 404 for a line belonging to another order" do+ patch :mark_ordered, params: { id: purchase_order.prefixed_id }, as: :json+ foreign_item = create_draft.items.sole++ patch :receive, params: {+ id: purchase_order.prefixed_id, items: [{ id: foreign_item.prefixed_id, quantity_received: 1 }]+ }, as: :json++ expect(response).to have_http_status(:not_found)+ end++ it 'cancels what is outstanding and leaves received units on the shelf' do+ patch :mark_ordered, params: { id: purchase_order.prefixed_id }, as: :json+ item = purchase_order.reload.items.sole+ patch :receive, params: {+ id: purchase_order.prefixed_id, items: [{ id: item.prefixed_id, quantity_received: 60 }]+ }, as: :json++ patch :cancel, params: { id: purchase_order.prefixed_id, reason: 'Supplier went under' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['status']).to eq('canceled')+ expect(on_hand).to eq(60)+ end+ end++ describe 'DELETE #destroy' do+ let!(:purchase_order) { create_draft }++ it 'throws a draft away' do+ expect { delete :destroy, params: { id: purchase_order.prefixed_id }, as: :json }.+ to change(Spree::PurchaseOrder, :count).by(-1)++ expect(response).to have_http_status(:no_content)+ end++ it 'refuses to delete an order already placed' do+ Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order)++ delete :destroy, params: { id: purchase_order.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('invalid_status')+ end+ end++ describe 'expanding the document' do+ let!(:purchase_order) { create_draft }++ it 'returns the lines with their costs when asked' do+ get :show, params: { id: purchase_order.prefixed_id, expand: 'items,supplier' }, as: :json++ expect(response).to have_http_status(:ok)+ line = json_response['items'].sole+ expect(line).to include('quantity_ordered' => 100, 'unit_cost' => '12.5',+ 'display_unit_cost' => '$12.50', 'outstanding' => 100)+ expect(json_response['supplier']['name']).to eq('Acme Wholesale')+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rbindex c9916061b6..d8a18aaf78 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb@@ -5,20 +5,25 @@ RSpec.describe Spree::Api::V3::Admin::StockTransfersController, type: :controlleinclude_context 'API v3 Admin authenticated'- let!(:source_location) { create(:stock_location_with_items, name: 'Source') }- let!(:destination_location) { create(:stock_location, name: 'Destination') }+ let(:store) { Spree::Store.default }+ let!(:source_location) { create(:stock_location, store: store, name: 'Source') }+ let!(:destination_location) { create(:stock_location, store: store, name: 'Destination') }let(:variant) { create(:variant) }before dorequest.headers.merge!(headers)- source_location.stock_level_or_create(variant).update!(count_on_hand: 50)- destination_location.stock_level_or_create(variant)+ source_location.restock(variant, 50)+ end++ def create_draft(quantity: 5)+ Spree::StockTransfers::Create.call(+ store: store, source_location: source_location, destination_location: destination_location,+ items: [{ variant: variant, quantity_shipped: quantity }]+ ).valueenddescribe 'GET #index' do- let!(:transfer) do- Spree::StockTransfer.new.tap { |t| t.transfer(source_location, destination_location, variant => 5) }- end+ let!(:transfer) { create_draft }it 'returns stock transfers' doget :index, as: :json@@ -27,29 +32,53 @@ RSpec.describe Spree::Api::V3::Admin::StockTransfersController, type: :controlleexpect(json_response['data'].map { |t| t['id'] }).to include(transfer.prefixed_id)end+ it 'reports the lifecycle columns the dashboard lists on' do+ get :index, as: :json++ row = json_response['data'].find { |t| t['id'] == transfer.prefixed_id }+ expect(row).to include(+ 'status' => 'draft', 'items_count' => 1,+ 'quantity_shipped_total' => 5, 'quantity_received_total' => 0, 'editable' => true+ )+ end++ # The table carried no store until 6.0, which left this endpoint reading+ # every tenant's transfers.+ it 'never lists another store’s transfers' do+ other_store = create(:store)+ other_location = create(:stock_location, store: other_store)+ foreign = Spree::StockTransfers::Create.call(+ store: other_store, source_location: other_location,+ destination_location: create(:stock_location, store: other_store),+ items: [{ variant: create(:product, store: other_store).default_variant, quantity_shipped: 1 }]+ ).value++ get :index, as: :json++ expect(json_response['data'].map { |t| t['id'] }).not_to include(foreign.prefixed_id)+ end+# The dashboard's search box sends this one predicate for both columns, so# a whitelist that covers only `number` would silently return every row.context 'searching by number or reference' dolet!(:referenced) do- Spree::StockTransfer.new(reference: 'PO-4471').tap do |t|- t.transfer(source_location, destination_location, variant => 1)- end+ Spree::StockTransfers::Create.call(+ store: store, source_location: source_location,+ destination_location: destination_location, reference: 'PO-4471',+ items: [{ variant: variant, quantity_shipped: 1 }]+ ).valueendit 'matches on the reference' doget :index, params: { q: { number_or_reference_cont: 'PO-4471' } }, as: :json- expect(response).to have_http_status(:ok)- ids = json_response['data'].map { |t| t['id'] }- expect(ids).to eq([referenced.prefixed_id])+ expect(json_response['data'].map { |t| t['id'] }).to eq([referenced.prefixed_id])endit 'matches on the number' doget :index, params: { q: { number_or_reference_cont: transfer.number } }, as: :json- expect(response).to have_http_status(:ok)- ids = json_response['data'].map { |t| t['id'] }- expect(ids).to eq([transfer.prefixed_id])+ expect(json_response['data'].map { |t| t['id'] }).to eq([transfer.prefixed_id])endendend@@ -59,50 +88,201 @@ RSpec.describe Spree::Api::V3::Admin::StockTransfersController, type: :controlle{source_location_id: source_location.prefixed_id,destination_location_id: destination_location.prefixed_id,- variants: [{ variant_id: variant.prefixed_id, quantity: 5 }]+ reference: 'Weekly restock',+ items: [{ variant_id: variant.prefixed_id, quantity_shipped: 5 }]}end- it 'transfers stock between locations' do+ # The 5.x endpoint moved stock the instant it was called. It now records a+ # plan, which is the whole point of the lifecycle.+ it 'persists a draft without moving any stock' doexpect { post :create, params: base_params, as: :json }.to change(Spree::StockTransfer, :count).by(1)expect(response).to have_http_status(:created)- expect(source_location.stock_level(variant).reload.count_on_hand).to eq(45)- expect(destination_location.stock_level(variant).reload.count_on_hand).to eq(5)+ expect(json_response).to include('status' => 'draft', 'reference' => 'Weekly restock')+ expect(source_location.stock_level(variant.id).reload.count_on_hand).to eq(50)+ expect(destination_location.stock_level(variant.id)&.count_on_hand.to_i).to eq(0)end- it 'receives from external seller when source is omitted' do- post :create, params: base_params.except(:source_location_id), as: :json+ it 'returns 422 for a line with no quantity' do+ post :create, params: base_params.merge(items: [{ variant_id: variant.prefixed_id, quantity_shipped: 0 }]),+ as: :json- expect(response).to have_http_status(:created)- expect(destination_location.stock_level(variant).reload.count_on_hand).to eq(5)+ expect(response).to have_http_status(:unprocessable_content)end- it 'returns 422 when variants is empty' do- post :create, params: base_params.merge(variants: []), as: :json+ it 'returns 404 when the destination location is unknown' do+ post :create, params: base_params.merge(destination_location_id: 'sloc_unknown'), as: :json- expect(response).to have_http_status(:unprocessable_content)- expect(json_response['error']['code']).to eq('invalid_variants')+ expect(response).to have_http_status(:not_found)end- it 'returns 404 when destination location is unknown' do- post :create, params: base_params.merge(destination_location_id: 'sloc_unknown'), as: :json+ # An id resolved through the model constant would accept another store's+ # warehouse; read through current_store it is simply not there.+ it "returns 404 for another store's warehouse" do+ foreign_location = create(:stock_location, store: create(:store))++ post :create, params: base_params.merge(destination_location_id: foreign_location.prefixed_id), as: :jsonexpect(response).to have_http_status(:not_found)end- it "drops variants belonging to another store and surfaces invalid_variants" do+ it "returns 404 for another store's variant" doforeign_variant = create(:product, store: create(:store)).default_variantexpect dopost :create, params: base_params.merge(- variants: [{ variant_id: foreign_variant.prefixed_id, quantity: 5 }]+ items: [{ variant_id: foreign_variant.prefixed_id, quantity_shipped: 5 }]), as: :jsonend.not_to change(Spree::StockTransfer, :count)+ expect(response).to have_http_status(:not_found)+ end++ it 'refuses a payload whose items is not a list' do+ post :create, params: base_params.merge(items: 'five'), as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'PATCH #update' do+ let!(:transfer) { create_draft }++ it 'replaces the lines of a draft' do+ other_variant = create(:variant)++ patch :update, params: {+ id: transfer.prefixed_id, reference: 'Second attempt',+ items: [{ variant_id: other_variant.prefixed_id, quantity_shipped: 2 }]+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['reference']).to eq('Second attempt')+ line = transfer.reload.items.sole+ expect(line.variant).to eq(other_variant)+ expect(line.quantity_shipped).to eq(2)+ end++ it 'refuses to rewrite a transfer the warehouse is acting on' do+ Spree::StockTransfers::MarkReady.call(stock_transfer: transfer)++ patch :update, params: { id: transfer.prefixed_id, reference: 'too late' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end++ # Moving both ends at once would satisfy the same-store validation while+ # leaving the transfer on this store's books.+ it "returns 404 when moving a transfer onto another store's warehouses" do+ other_store = create(:store)++ patch :update, params: {+ id: transfer.prefixed_id,+ source_location_id: create(:stock_location, store: other_store).prefixed_id,+ destination_location_id: create(:stock_location, store: other_store).prefixed_id+ }, as: :json++ expect(response).to have_http_status(:not_found)+ expect(transfer.reload.source_location).to eq(source_location)+ end+ end++ describe 'the lifecycle actions' do+ let!(:transfer) { create_draft(quantity: 10) }++ it 'marks a draft ready to ship' do+ patch :mark_ready, params: { id: transfer.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response).to include('status' => 'ready_to_ship', 'editable' => false)+ end++ it 'takes the units off the source shelf when the van leaves' do+ patch :mark_in_transit, params: { id: transfer.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['status']).to eq('in_transit')+ expect(json_response['shipped_at']).to be_present+ expect(source_location.stock_level(variant.id).reload.count_on_hand).to eq(40)+ expect(destination_location.stock_level(variant.id)&.count_on_hand.to_i).to eq(0)+ end++ it 'receives what actually arrived and records the shortfall' do+ patch :mark_in_transit, params: { id: transfer.prefixed_id }, as: :json+ item = transfer.reload.items.sole++ patch :receive, params: {+ id: transfer.prefixed_id,+ items: [{ id: item.prefixed_id, quantity_received: 8, discrepancy_reason: 'damaged_in_transit' }]+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response).to include('status' => 'partially_received',+ 'quantity_received_total' => 8)+ expect(destination_location.stock_level(variant.id).reload.count_on_hand).to eq(8)+ expect(item.reload.discrepancy_reason).to eq('damaged_in_transit')+ end++ it 'receives everything when the payload names no lines' do+ patch :mark_in_transit, params: { id: transfer.prefixed_id }, as: :json++ patch :receive, params: { id: transfer.prefixed_id }, as: :json++ expect(json_response['status']).to eq('received')+ expect(destination_location.stock_level(variant.id).reload.count_on_hand).to eq(10)+ end++ it "returns 404 for a line belonging to another transfer" do+ patch :mark_in_transit, params: { id: transfer.prefixed_id }, as: :json+ foreign_item = create_draft.items.sole++ patch :receive, params: {+ id: transfer.prefixed_id, items: [{ id: foreign_item.prefixed_id, quantity_received: 1 }]+ }, as: :json++ expect(response).to have_http_status(:not_found)+ end++ it 'refuses to cancel an in-transit transfer without a decision' do+ patch :mark_in_transit, params: { id: transfer.prefixed_id }, as: :json++ patch :cancel, params: { id: transfer.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(transfer.reload).to be_in_transit+ end++ it 'puts the units back when the merchant says they came home' do+ patch :mark_in_transit, params: { id: transfer.prefixed_id }, as: :json++ patch :cancel, params: { id: transfer.prefixed_id, on_in_transit: 'restock' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['status']).to eq('canceled')+ expect(source_location.stock_level(variant.id).reload.count_on_hand).to eq(50)+ end+ end++ describe 'DELETE #destroy' do+ let!(:transfer) { create_draft }++ it 'throws a draft away' do+ expect { delete :destroy, params: { id: transfer.prefixed_id }, as: :json }.+ to change(Spree::StockTransfer, :count).by(-1)++ expect(response).to have_http_status(:no_content)+ end++ # Past draft the transfer describes a box that physically exists.+ it 'refuses to delete a transfer that has shipped' do+ Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer)++ delete :destroy, params: { id: transfer.prefixed_id }, as: :json+expect(response).to have_http_status(:unprocessable_content)- expect(json_response['error']['code']).to eq('invalid_variants')+ expect(json_response['error']['code']).to eq('invalid_status')endendenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/suppliers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/suppliers_controller_spec.rbnew file mode 100644index 0000000000..b3da4395a8--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/suppliers_controller_spec.rb@@ -0,0 +1,117 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::SuppliersController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let(:store) { Spree::Store.default }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ let!(:supplier) { create(:supplier, store: store, name: 'Acme Wholesale') }++ it 'returns the store’s suppliers' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].map { |s| s['name'] }).to include('Acme Wholesale')+ end++ it "never lists another store's suppliers" do+ foreign = create(:supplier, store: create(:store))++ get :index, as: :json++ expect(json_response['data'].map { |s| s['id'] }).not_to include(foreign.prefixed_id)+ end++ it 'omits soft-deleted suppliers' do+ supplier.destroy++ get :index, as: :json++ expect(json_response['data'].map { |s| s['id'] }).not_to include(supplier.prefixed_id)+ end+ end++ describe 'POST #create' do+ let(:params) do+ {+ name: 'Acme Wholesale',+ contact_name: 'Dana Okafor',+ email: '[email protected]',+ phone: '555-0100',+ address1: '1 Warehouse Way',+ city: 'Brooklyn',+ state_code: 'NY',+ country_code: 'US',+ postal_code: '11201'+ }+ end++ it 'creates a supplier against the current store' do+ expect { post :create, params: params, as: :json }.to change(Spree::Supplier, :count).by(1)++ expect(response).to have_http_status(:created)+ expect(json_response).to include('name' => 'Acme Wholesale', 'email' => '[email protected]',+ 'city' => 'Brooklyn', 'country_code' => 'US')+ expect(Spree::Supplier.last.store).to eq(store)+ end++ it 'returns 422 without a name' do+ post :create, params: params.except(:name), as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'returns 422 for a name already in use in this store' do+ create(:supplier, store: store, name: 'Acme Wholesale')++ post :create, params: params, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'PATCH #update' do+ let!(:supplier) { create(:supplier, store: store) }++ it 'edits the supplier' do+ patch :update, params: { id: supplier.prefixed_id, contact_name: 'Sam Reyes' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['contact_name']).to eq('Sam Reyes')+ end++ it "returns 404 for another store's supplier" do+ foreign = create(:supplier, store: create(:store))++ patch :update, params: { id: foreign.prefixed_id, contact_name: 'Sam Reyes' }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'DELETE #destroy' do+ let!(:supplier) { create(:supplier, store: store) }++ it 'soft-deletes the supplier' do+ delete :destroy, params: { id: supplier.prefixed_id }, as: :json++ expect(response).to have_http_status(:no_content)+ expect(supplier.reload.deleted_at).to be_present+ end++ # The purchasing history has to keep naming who it was with.+ it 'refuses while purchase orders still point at it' do+ create(:purchase_order, store: store, supplier: supplier)++ delete :destroy, params: { id: supplier.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(supplier.reload.deleted_at).to be_nil+ end+ end+enddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 5c9c803719..daf62ba9a7 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -603,12 +603,12 @@ en:spree/store:one: Storeother: Stores- spree/supplier:- one: Supplier- other: Suppliersspree/store_credit:one: Store Creditother: Store Credits+ spree/supplier:+ one: Supplier+ other: Suppliersspree/tax_category:one: Tax Categoryother: Tax Categories@@ -1054,11 +1054,11 @@ en:delivery_zone_postal_definition_required: postal code member requires a prefix or a from/to rangedelivery_zone_prefix_and_range_exclusive: cannot be combined with a from/to rangedelivery_zone_range_inverted: must be greater than or equal to postal_code_from- duplicate_variant: cannot list the same variant twicedelivery_zone_range_not_supported: postal code ranges are not supported for this country — use prefixesdiscount_has_no_effect: discount would have no effect on this orderdiscount_value_must_be_positive: discount value must be a positive numberdiscount_value_type_invalid: value_type must be flat or percent+ duplicate_variant: cannot list the same variant twiceexactly_one_adjustable: must be attached to exactly one adjustableexactly_one_of_cart_or_order: must belong to exactly one of cart or orderexactly_one_of_line_item_or_fulfillment: must be charged against exactly one of a line item or a fulfillment@@ -1087,8 +1087,8 @@ en:profile_does_not_accept_provider: "%{provider} deliveries cannot join the %{profile} profile"promotion_discount_not_editable: promotion discounts are managed by recalculation and cannot be editedrate_provider_requires_shipping: "%{provider} quotes shipments, so this method must ship to an address"- received_exceeds_expected: cannot be more than the %{expected} expectedrate_provider_unavailable: is not available for this store — connect its integration first+ received_exceeds_expected: cannot be more than the %{expected} expectedsame_as_inviter: cannot be the same as the inviterseller_delivery_method_not_shareable: only the marketplace's own delivery methods can be shared with sellersseller_delivery_method_provider: a seller's delivery method prices its own rates and is fulfilled by hand — carrier accounts belong to the marketplace@@ -1619,14 +1619,14 @@ en:purchase_order:errors:already_closed: This purchase order has already been received or cancelled- invalid_received_quantity: 'Received quantity for %{variant} must be between what was already- received and the %{ordered} ordered'+ invalid_received_quantity: Received quantity for %{variant} must be between what was already received and the %{ordered} ordereditem_not_on_order: One of the lines does not belong to this purchase ordermust_have_variant: You must add at least one variantno_items_received: No units were receivednot_draft: Only a draft purchase order can be marked as orderednot_editable: Only a draft purchase order can be editednot_ordered: Only a purchase order that has been placed can be received+ only_draft_can_be_deleted: Only a draft purchase order can be deleted — cancel it insteadqty: Qtyquantity: Quantityquery: Query@@ -1885,11 +1885,9 @@ en:stock_transfer:errors:already_closed: This transfer has already been completed or cancelled- in_transit_resolution_required: Choose whether the units come back to the source warehouse- or are written off+ in_transit_resolution_required: Choose whether the units come back to the source warehouse or are written offinvalid_quantity: Every variant must move a quantity above zero- invalid_received_quantity: 'Received quantity for %{variant} must be between what was already- received and the %{shipped} shipped'+ invalid_received_quantity: Received quantity for %{variant} must be between what was already received and the %{shipped} shippeditem_not_on_transfer: One of the lines does not belong to this transferlocations_in_different_stores: must belong to the same store as the source locationmust_have_variant: You must add at least one variant@@ -1898,6 +1896,7 @@ en:not_editable: Only a draft transfer can be editednot_in_transit: Only a transfer in transit can be receivednot_shippable: Only a draft or ready-to-ship transfer can be marked in transit+ only_draft_can_be_deleted: Only a draft transfer can be deleted — cancel it insteadsame_location: cannot be the same as the destination locationvariants_unavailable: Some variants are not available on %{stock}stop: Stop