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
Fix review findings on the duties work
Damian Legawiec9deb75058e2c
diff --git a/CLAUDE.md b/CLAUDE.mdindex 036d0e1b83..ad3a7ecc60 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -39,7 +39,7 @@ Active plans (6.0 target, work pending):- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Money lives in `Carts::RecalculateTotals` (single totals seam; the completed-order branch is the post-placement resum — rows re-summed, never regenerated), statuses in `Orders::UpdateStatuses` (refreshes each fulfillment's state, then rolls up); Order/CartUpdater are 6.1-removed warning shells. Shared Cart/Order surface lives in `Spree::Purchase::*` concerns; completion side effects (newsletter, account creation, risk) run in the sync `OrderPlacedSubscriber` on order.placed. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively — but hooks on flows already in the tier ship deliberately on the 6.0 boundary (2026-08-02), since hook keys are public API and moving one later is breaking. **New models get no state machine** — plain `status` string + inclusion validation, transitions through workflows; gateway I/O never in a save callback. Three hook families, contracts settled 2026-08-02: **lifecycle** (past tense, read-only), **validate** (handler calls `workflow.reject!(message)` to veto), **context** (`set_*_context`/`get_provider_data` — handler returns a hash, `run_hooks` deep-merges all handlers and returns it; last writer wins on collision). Phase 3 **shipped (2026-08-02)**: `run_hooks` returns the merged hash and `Workflow#reject!` is public API; `validate`/context/lifecycle hooks live on AddItem, Complete, Recalculate, RecalculateTotals, Cancel and Resume; `Fulfillments::Create`, `Payments::Capture`/`Refund`, `Payments::HandleWebhook` and `Carts::Merge` moved to `app/workflows/` (seams `fulfillment_create_workflow`, `payment_capture_workflow`, `payment_refund_workflow`, `payments_handle_webhook_workflow`, `cart_merge_workflow`; legacy names readable one release). **Customer registration (2026-08-05):** `Customers::Create` (seam `customer_create_workflow`, hooks `customers.create.validate`/`after_create`) is the single storefront customer-creation flow — self-registration + checkout account box (optional `order:` adopts addresses and links the order); absorbs `Orders::CreateUserAccount` (deprecated shell); admin create stays plain CRUD; token issuance stays in controllers; core sends NO welcome email — signup email is host-app code on `user.created` or the `after_create` hook. Payment workflows own the transaction boundary and guards — money movement stays in the model, called from an `external_step`. No workflows for plain CRUD. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.- `6.0-extendable-validations.md` — Workflow `validate` hooks are THE validation extension surface; **no generic model-validation registry** (design finalized 2026-08-13 — decorators stay the documented additive path, relaxing core rules = store preferences/predicate overrides). Ships: `Carts::UpsertItems` graduated to a workflow absorbing every non-increment item mutation (bulk payloads, PATCH quantity, DELETE = quantity 0; per-item `validate` with `AddItem`-compatible readers, shared item-application steps, ONE recalculate per batch; **partial-success on the storefront** — rejected items skip onto the cart's existing `warnings` array on 2xx, while the **order twin fails the whole batch**; no whole-batch veto; `SetQuantity`/`RemoveLineItem` → deprecated shells), `Products::Create`/`Update`/`Destroy` workflows (all write paths route through: Admin API v3, CSV importer, seeds; no standalone variant workflow), **rejections carry `ActiveModel::Errors`** (`Workflow#errors` + argument-less `reject!` rendering via `render_validation_error`; `reject!(message)` bridges to `:base`), `Spree.hooks.validate!` wired into boot, Address polish (document `Spree.validators.addresses` + removal API, `require_company` store preference). Address and cart creation get NO workflow (plain CRUD); custom-field value validation deferred to its own plan (Shopify-style per-definition rules, new-writes-only; `required` stays advisory). **Constraints now:** new item mutations route through `AddItem`/`UpsertItems`, new product write paths call the `Products::*` workflows, no hardcoded error codes at hook-bearing `render_service_error` call sites, clients must check `warnings` on storefront bulk-item 2xx responses. **Shipped 2026-08-13** (all four phases).- `6.0-store-scoped-configuration.md` — Move eight commerce-behavior globals (`auto_capture` + `auto_capture_on_dispatch` → one `capture_method` string; `allow_checkout_on_gateway_error` dropped, not moved — nothing reads it; `track_inventory_levels`, `stock_reservations_enabled`, `track_price_history`, `show_products_without_price`, `address_requires_phone`, `disable_sku_validation`) from `Spree::Config` to `Spree::Store` preferences. Store preference is **authoritative — no runtime fallback** (a fallback chain is what made `default_stock_reservation_ttl_minutes` silently unreachable); upgrade carries values over via `spree:store_settings:backfill_from_config`; globals are deprecated shells until 6.1. Storeless readers (`Address`, the product availability scope) use `Spree::Current.store` with a default fallback. Seven dead settings (`products_per_page`, `storefront_*_path`, …) get shells then deletion. **Capture timing is one vocabulary (2026-08-13):** `Spree::CaptureMethod` = `checkout | on_dispatch | manual` — a Store preference, overridable by a nullable `capture_method` **column** on PaymentMethod (null = inherit; a column, not a preference, since the payment-method preferences blob is per-provider gateway credentials); read `resolved_capture_method`, write `capture_method`; dispatch capture is decided per payment so a `manual` method is never charged by a dispatch; `spree:migrate_capture_methods` carries `auto_capture` over. **Constraints now:** no new `Spree::Config` reads of the movers; no new code against `auto_capture`/`auto_capture_on_dispatch` (deprecated on both models); new behavior flags are born on Store, never global; jobs that validate addresses or query the catalog must set `Spree::Current.store`.-- `6.0-duties-and-custom-fees.md` — Customs duties + shopper-visible custom fees on the shipped typed-`Fee` substrate (**6.0 scope implemented 2026-08-14**; 6.1 provider gem pending): a duty is a `Fee(kind: 'duty')` snapshotting its inputs (`hs_code`/`country_of_origin`/rate/provider) in `metadata` — never a TaxLine, never a new table; classification = three plain columns on `spree_variants` (`hs_code`, `country_of_origin` — **an ISO alpha-2 code, NEVER a country record id, since `spree_countries` is slated for removal**; `customs_description`) editable in both dashboard editors (variant sheet + bulk spreadsheet, sharing `normalize-customs.ts`) and shipped WITH their first consumer (EasyPost customs declaration + shipping-terms option on international labels — EasyPost declares, it never estimates); Store API cart/order serializers gain `fees` + `fee_total` (itemized shopper display is the point); duty estimation rides `Spree.adjusters` (provider gem writes duty fees + its own import-VAT `TaxLine(fee_id:)` rows) — no dedicated duty-provider contract unless a real gem proves the need; duty fees excluded from the default taxable-item set — `Spree::Purchase::Taxation#taxable_items` (shared Cart/Order) is the ONE definition every provider inherits, and it reads **fresh scopes, never the cached associations** (they load empty at record creation, so a Ruby-side `reject` over `fees` silently untaxes every fee — latent bug the duty work surfaced); a provider that does tax duties passes its own item list. 6.0 = plumbing; 6.1 = landed-cost provider gem + `Spree::Market` shipping-terms setting. **Constraints now:** never re-derive duty from the live catalog on an existing order (the metadata snapshot is authoritative); store-serializer money work must not assume fees stay hidden; EasyPost customs data is international-only, never required for domestic; admin cart/order serializers deliberately DROP the inherited `fees` association (admin reads/writes fees through `/orders/:id/fees`, and an admin serializer must never render a store serializer); variant write paths need the field in BOTH `PermittedAttributes` and the nested `Admin::Products::VariantsController` list. Still pending from the plan: excluding `kind: 'duty'` from `TaxProvider::Internal`'s fee taxing (blocked on that branch reaching main).+- `6.0-duties-and-custom-fees.md` — Customs duties + shopper-visible custom fees on the shipped typed-`Fee` substrate (**6.0 scope implemented 2026-08-14**; 6.1 provider gem pending): a duty is a `Fee(kind: 'duty')` snapshotting its inputs (`hs_code`/`country_of_origin`/rate/provider) in `metadata` — never a TaxLine, never a new table; classification = three plain columns on `spree_variants` (`hs_code`, `country_of_origin` — **an ISO alpha-2 code, NEVER a country record id, since `spree_countries` is slated for removal**; `customs_description`) editable in both dashboard editors (variant sheet + bulk spreadsheet, sharing `normalize-customs.ts`) and shipped WITH their first consumer (EasyPost customs declaration + shipping-terms option on international labels — EasyPost declares, it never estimates); Store API cart/order serializers gain `fees` + `fee_total` (itemized shopper display is the point); duty estimation rides `Spree.adjusters` (provider gem writes duty fees + its own import-VAT `TaxLine(fee_id:)` rows) — no dedicated duty-provider contract unless a real gem proves the need; duty fees excluded from the default taxable-item set — `Spree::Purchase::Taxation#taxable_items` (shared Cart/Order) is the ONE definition every provider inherits, and it reads **fresh scopes, never the cached associations** (they load empty at record creation, so a Ruby-side `reject` over `fees` silently untaxes every fee — latent bug the duty work surfaced); a provider that does tax duties passes its own item list. 6.0 = plumbing; 6.1 = landed-cost provider gem + `Spree::Market` shipping-terms setting. **Constraints now:** never re-derive duty from the live catalog on an existing order (the metadata snapshot is authoritative); store-serializer money work must not assume fees stay hidden; EasyPost customs data is international-only, never required for domestic; admin cart/order serializers deliberately DROP the inherited `fees` association (admin reads/writes fees through `/orders/:id/fees`, and an admin serializer must never render a store serializer); a new variant attribute must be permitted in THREE places or it is silently dropped on one write path — `PermittedAttributes`, the nested `Admin::Products::VariantsController`, AND the inline `variants: [...]` list on `Admin::ProductsController` (the last is what the dashboard's product Save actually hits; a spec on the nested controller proves nothing about it).- `6.0-store-scoped-custom-field-definitions.md` — Add `store_id` + persisted `filter_key` to `Spree::MetafieldDefinition` (today global and computed), making uniqueness `(store_id, resource_type, filter_key)` with a DB index. Deferred from the 5.6 custom-field search/sort/filter work (schema change, not patch-safe). **Until then:** `filter_key` is a computed method — no Ransack predicates or `where`/`order` against it; definitions are global; uniqueness rests on a `CONCAT` validation with no index behind it.- `6.0-opentelemetry.md` — First-class OpenTelemetry support (design finalized 2026-08-12; **phases 1–3 implemented same day** — core notifications + `spree/opentelemetry` gem + telemetry docs page; remaining: fast-follow spans, spree-starter Gemfile mention, collector smoke test): core emits a documented `ActiveSupport::Notifications` surface (NO OpenTelemetry dependency in core) + new optional top-level `spree_opentelemetry` gem (`spree/opentelemetry`) that boots the SDK from standard `OTEL_*` env vars (Saleor-style, no host initializer; `OTEL_SDK_DISABLED` kill switch), installs Rails auto-instrumentation, and translates Spree notifications into spans. Traces only in 6.0 (Ruby metrics/logs SDKs experimental; RED metrics via collector spanmetrics). First cut = commerce core four: workflows (`external_step` marks `external: true` → CLIENT spans; `outcome` payload key set inside the instrumented block), events dispatch, webhook delivery (+ outbound W3C `traceparent`), payment gateway boundary; provider bases/Meilisearch/imports/OIDC fast-follow. **Constraints now:** outbound network calls in workflows are always `external_step`, never `step`; never `rescue StandardError` around workflow execution (`FailureSignal`/`Halted` inherit `Exception`); notification payload keys are public API (additive only) and must be PII-safe; telemetry config is env-var deployment config — never `Spree::Config`, store preferences, or admin UI.diff --git a/docs/plans/6.0-duties-and-custom-fees.md b/docs/plans/6.0-duties-and-custom-fees.mdindex bd956199bd..db09ee5d2e 100644--- a/docs/plans/6.0-duties-and-custom-fees.md+++ b/docs/plans/6.0-duties-and-custom-fees.md@@ -38,7 +38,7 @@ New columns on `spree_variants`:`hs_code` is normalized to digits only and `country_of_origin` upcased, so a merchant pasting `6404.11` or `vn` stores the canonical value; the dashboard mirrors both normalizations client-side (`normalize-customs.ts`, shared by the variant edit sheet and the bulk editor) so a dotted tariff code pasted from a broker's spreadsheet is accepted rather than bounced by the format validation.-**`country_of_origin` stores an ISO 3166-1 alpha-2 code, never a country record id**, and every picker is bound to ISO accordingly (the edit sheet's `CountryCombobox`, the bulk editor's select cell). Customs classification has to outlive the `spree_countries` table — an id would dangle, a code will not. That table was **dropped on 2026-08-15** (`Spree::Country` is now reference data from the `countries` gem, `.by_iso` rather than `.find_by`), and this work needed no data change at all as a result. It is also what carriers expect on the declaration, so no lookup sits between the stored value and the EasyPost payload. Readers on `Spree::Variant` fall back to the product-type/product level only if a later plan adds it there — in 6.0 they are variant-local. Admin API v3 variant endpoints permit and serialize the three fields (admin serializer only — the Store API never exposes customs data); note the nested `Admin::Products::VariantsController` enumerates `permitted_params` itself rather than reading the shared allowlist, so both lists need the fields. CSV import columns follow. No validation requires them: customs data is optional until an international label or a duties provider needs it, at which point the consumer raises its own actionable error.+**`country_of_origin` stores an ISO 3166-1 alpha-2 code, never a country record id**, and every picker is bound to ISO accordingly (the edit sheet's `CountryCombobox`, the bulk editor's select cell). Customs classification has to outlive the `spree_countries` table — an id would dangle, a code will not. That table was **dropped on 2026-08-15** (`Spree::Country` is now reference data from the `countries` gem, `.by_iso` rather than `.find_by`), and this work needed no data change at all as a result. It is also what carriers expect on the declaration, so no lookup sits between the stored value and the EasyPost payload. Readers on `Spree::Variant` fall back to the product-type/product level only if a later plan adds it there — in 6.0 they are variant-local. Admin API v3 variant endpoints permit and serialize the three fields (admin serializer only — the Store API never exposes customs data); note that a variant attribute must be permitted in **three** places — the shared `PermittedAttributes`, the nested `Admin::Products::VariantsController` (which enumerates its own list), and the inline `variants: [...]` list on `Admin::ProductsController`. The last is the one the dashboard's product Save actually uses, and it was missed on the first pass: the nested-controller spec passed while every customs edit made through the product form was silently discarded. The inline-variants spec on the products controller now covers it. CSV import columns follow. No validation requires them: customs data is optional until an international label or a duties provider needs it, at which point the consumer raises its own actionable error.### 2. `duty` fee kind@@ -56,7 +56,9 @@ New columns on `spree_variants`:### 4. EasyPost customs declaration (first consumer)-The EasyPost fulfillment provider builds a customs declaration when origin and destination countries differ: one customs item per package line (description from `customs_description` → product name, quantity, value from the line's price, weight, `hs_code`, `origin_code` from `country_of_origin`), attached to the shipment at creation — EasyPost then produces the customs forms with the label. Missing weight or classification degrades exactly as EasyPost does (carrier-dependent — some accept declarations without HS codes); label-purchase errors surface loudly per the existing "label leads, fulfilled follows" doctrine. Contents type/restriction, customs signer, and the shipping-terms (incoterm) shipment option are `SpreeEasyPost::Integration` preferences; duty-paid billing is carrier-dependent and passes through as configuration. The incoterm preference is validated against EasyPost's enum and defaults to **DAP** (recipient pays on arrival) — `DDU` is not an accepted value despite being the common industry shorthand, and EasyPost's own default is DDP, which would silently bill the merchant for duties nobody collected. The declaration goes on rate quotes as well as label purchases, since international rates depend on declared contents. Note the boundary: EasyPost carries declarations and routes the carrier's actual duty bill under duty-paid terms — it estimates nothing, so it is a consumer of the classification fields, never a duties provider.+The EasyPost fulfillment provider builds a customs declaration when origin and destination countries differ: one customs item per package line (description from `customs_description` → product name, quantity, value from the line's price, weight, `hs_code`, `origin_code` from `country_of_origin`), attached to the shipment at creation — EasyPost then produces the customs forms with the label. Missing weight or classification degrades exactly as EasyPost does (carrier-dependent — some accept declarations without HS codes); label-purchase errors surface loudly per the existing "label leads, fulfilled follows" doctrine. Contents type/restriction, customs signer, and the shipping-terms (incoterm) shipment option are `SpreeEasyPost::Integration` preferences; duty-paid billing is carrier-dependent and passes through as configuration. The incoterm preference is validated against EasyPost's enum and defaults to **DAP** (recipient pays on arrival) — `DDU` is not an accepted value despite being the common industry shorthand, and EasyPost's own default is DDP, which would silently bill the merchant for duties nobody collected. The declaration goes on rate quotes as well as label purchases, since international rates depend on declared contents.++Three EasyPost contract details, each of which fails *silently* as "no international delivery options" if got wrong, since the rate provider swallows creation errors by design: **the declaration is certified only when a signer is configured** — EasyPost requires `customs_signer` whenever `customs_certify` is set, so certifying unconditionally would break every international quote for the default (signer-less) integration; **`customs_contents_type` is validated against EasyPost's enum minus `other`**, which additionally demands a free-text explanation nothing supplies; and **the US export exemption `NOEEI 30.37(a)` is claimed only for US-origin shipments declared in US dollars under $2,500** — above that the merchant owes a filing of their own, for a non-US origin the code is meaningless, and a non-dollar declaration cannot be compared against a dollar threshold without a conversion the code deliberately does not attempt. **Quote and label share one shipment builder** (`SpreeEasyPost.shipment_params`): the incoterm is a shipment property fixed at creation and not accepted on the buy call, so it must ride on the quote — a label bought against a quote created without it would silently ship under the carrier's default terms. Note the boundary: EasyPost carries declarations and routes the carrier's actual duty bill under duty-paid terms — it estimates nothing, so it is a consumer of the classification fields, never a duties provider.### 5. Landed-cost estimation path (provider gems, 6.1)diff --git a/packages/dashboard-core/src/components/country-combobox.tsx b/packages/dashboard-core/src/components/country-combobox.tsxindex e57e27b360..119f2bb4c8 100644--- a/packages/dashboard-core/src/components/country-combobox.tsx+++ b/packages/dashboard-core/src/components/country-combobox.tsx@@ -13,7 +13,7 @@ import {InputGroupAddon,useComboboxAnchor,} from '@spree/dashboard-ui'-import { useMemo, useState } from 'react'+import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { useCountries } from '../hooks/use-countries'import { useDisplayName } from '../hooks/use-display-name'@@ -23,15 +23,19 @@ export type CountryOption = { iso: string; iso3: string; name: string }/*** Resolves a country's display name in the admin UI language (keyed on the* stable ISO code), falling back to the API's backend-locale `name` when the- * runtime lacks coverage.- */-/**- * Localized country name with the API's own name as fallback. Exported so- * every country-labelled surface (pickers, grid cells) reads the same.+ * runtime lacks coverage. Exported so every country-labelled surface+ * (pickers, grid cells) reads the same.+ *+ * The resolver is referentially stable across renders — callers feed it into+ * `useMemo` deps, and a fresh closure each render would rebuild every derived+ * option list (and, downstream, every grid column) on each keystroke.*/export function useCountryDisplayName() {const displayName = useDisplayName('region')- return (country: CountryOption) => displayName(country.iso) ?? country.name+ return useCallback(+ (country: CountryOption) => displayName(country.iso) ?? country.name,+ [displayName],+ )}/**@@ -89,11 +93,14 @@ function CountryRow({ country, label }: { country: CountryOption; label: string* name + flag in the trigger and `<CountryRow>` in the dropdown.*/export function CountryCombobox({+ id,value,onValueChange,placeholder,disabled = false,}: {+ /** Forwarded to the text input so a `<FieldLabel htmlFor>` can target it. */+ id?: stringvalue: string | null | undefinedonValueChange: (iso: string) => voidplaceholder?: string@@ -126,6 +133,7 @@ export function CountryCombobox({filter={filter}><ComboboxInput+ id={id}placeholder={placeholder ?? t('admin.components.country_combobox.search_placeholder')}disabled={disabled}>diff --git a/packages/dashboard/src/components/spree/products/variant-edit-sheet.tsx b/packages/dashboard/src/components/spree/products/variant-edit-sheet.tsxindex 70524cf486..99f1cb9cfc 100644--- a/packages/dashboard/src/components/spree/products/variant-edit-sheet.tsx+++ b/packages/dashboard/src/components/spree/products/variant-edit-sheet.tsx@@ -297,6 +297,7 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Procontrol={form.control}render={({ field }) => (<CountryCombobox+ id={`variant-${variantIndex}-country-of-origin`}value={field.value ?? null}onValueChange={(iso) => field.onChange(iso || null)}/>diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rbindex 4212ccad2d..2040337cea 100644--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb@@ -238,6 +238,7 @@ module Spree:id, :sku, :barcode,:cost_price, :cost_currency,:weight, :height, :width, :depth, :weight_unit, :dimensions_unit,+ :hs_code, :country_of_origin, :customs_description,:track_inventory, :preorderable, :preorder_ships_at, :backorder_limit, :tax_category_id, :position,options: [:name, :value],prices: [:amount, :compare_at_amount, :currency],diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rbindex 1660795881..26e30689a5 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb@@ -767,6 +767,9 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller dooptions: [{ name: 'size', value: 'Small' }],weight: 0.3,track_inventory: true,+ hs_code: '6109.10',+ country_of_origin: 'bd',+ customs_description: 'Cotton t-shirt',prices: [{ currency: 'USD', amount: 34.99, compare_at_amount: 49.99 },{ currency: 'EUR', amount: 31.99 },@@ -808,6 +811,13 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller doexpect(small.weight.to_f).to eq(0.3)expect(small.option_values.first.presentation).to eq('Small')+ # Customs classification rides inline with the variant — this is the+ # path the dashboard's product Save uses, not the nested variants+ # endpoint — and lands normalized.+ expect(small.hs_code).to eq('610910')+ expect(small.country_of_origin).to eq('BD')+ expect(small.customs_description).to eq('Cotton t-shirt')+# Multi-currency prices on small variantexpect(small.prices.find_by(currency: 'USD').amount.to_f).to eq(34.99)expect(small.prices.find_by(currency: 'USD').compare_at_amount.to_f).to eq(49.99)diff --git a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rbindex 2d21c4760a..a09713e196 100644--- a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb+++ b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb@@ -149,6 +149,32 @@ RSpec.shared_examples 'a taxation host' doexpect(record.pre_tax_total).to eq(7)endend++ describe '#taxable_items' do+ # Both hosts own fees through the exactly-one owner FK, so the factory+ # needs the matching key.+ def owner_attributes+ record.is_a?(Spree::Cart) ? { cart: record, order: nil } : { order: record }+ end++ it 'withholds customs duties while keeping every other fee' do+ create(:fee, owner_attributes.merge(amount: 20, kind: 'duty', label: 'Import duty'))+ surcharge = create(:fee, owner_attributes.merge(amount: 5, kind: 'surcharge', label: 'Handling'))++ expect(record.taxable_items.grep(Spree::Fee)).to contain_exactly(surcharge)+ end++ # The associations load empty at record creation, and recalculation asks+ # for taxable items right after adjusters have written fees — so this must+ # read fresh, not from the cache, on both hosts.+ it 'sees fees written after the association was first loaded' do+ record.fees.load++ late = create(:fee, owner_attributes.merge(amount: 5, kind: 'handling', label: 'Late fee'))++ expect(record.taxable_items).to include(late)+ end+ endendRSpec.describe Spree::Purchase::Taxation dodiff --git a/spree/core/spec/models/spree/tax_provider/internal_spec.rb b/spree/core/spec/models/spree/tax_provider/internal_spec.rbindex 12550cb8e1..487fbdb0e4 100644--- a/spree/core/spec/models/spree/tax_provider/internal_spec.rb+++ b/spree/core/spec/models/spree/tax_provider/internal_spec.rb@@ -302,23 +302,4 @@ describe Spree::TaxProvider::Internal, type: :model doendend- describe '#taxable_items' do- let!(:duty) { create(:fee, order: order, amount: 20, kind: 'duty', label: 'Import duty') }-- it 'withholds duties while keeping every other fee' do- surcharge = create(:fee, order: order, amount: 5, kind: 'surcharge', label: 'Handling')-- expect(order.taxable_items.grep(Spree::Fee)).to contain_exactly(surcharge)- end-- # The associations load empty at record creation, so reading them rather- # than a fresh scope would leave every just-written fee untaxed.- it 'sees fees written after the association was first loaded' do- order.fees.load-- late = create(:fee, order: order, amount: 5, kind: 'handling', label: 'Late fee')-- expect(order.taxable_items).to include(late)- end- endenddiff --git a/spree/providers/easypost/app/models/spree_easypost/delivery_rate_provider.rb b/spree/providers/easypost/app/models/spree_easypost/delivery_rate_provider.rbindex c7adb5bdc3..fe66a086d0 100644--- a/spree/providers/easypost/app/models/spree_easypost/delivery_rate_provider.rb+++ b/spree/providers/easypost/app/models/spree_easypost/delivery_rate_provider.rb@@ -124,29 +124,12 @@ module SpreeEasyPost)end- # International rates depend on the declared contents, so the customs- # form goes on the quote as well as the label.+ # Built by the shared helper so a label bought against this quote carries+ # exactly the customs form and duty terms the quote was priced with.def shipment_params(package)- destination = package.owner.ship_address- params = {- from_address: address_params(package.stock_location),- to_address: address_params(destination),- parcel: parcel_params(package)- }-- customs_info = SpreeEasyPost.customs_info_params(- package, package.stock_location, destination, integration+ SpreeEasyPost.shipment_params(+ package, package.stock_location, package.owner.ship_address, integration, store)- params[:customs_info] = customs_info if customs_info.present?- params- end-- def address_params(source)- SpreeEasyPost.address_params(source)- end-- def parcel_params(package)- SpreeEasyPost.parcel_params(package, store)endendenddiff --git a/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rb b/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rbindex 7825a550a3..275380e12f 100644--- a/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rb+++ b/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rb@@ -126,25 +126,12 @@ module SpreeEasyPostnilend- # Adds the customs declaration and duty terms when the parcel crosses a- # border; a domestic shipment is created exactly as before.+ # Same builder the rate provider uses, so a re-quote is priced and labelled+ # under the same terms as the original quote.def shipment_params(integration, fulfillment, address)- package = fulfillment.to_package- params = {- from_address: address_params(fulfillment.stock_location),- to_address: address_params(address),- parcel: SpreeEasyPost.parcel_params(package, fulfillment.order&.store)- }-- customs_info = SpreeEasyPost.customs_info_params(- package, fulfillment.stock_location, address, integration+ SpreeEasyPost.shipment_params(+ fulfillment.to_package, fulfillment.stock_location, address, integration, fulfillment.order&.store)- return params if customs_info.nil?-- params[:customs_info] = customs_info- incoterm = integration.preferred_incoterm.presence- params[:options] = { incoterm: incoterm } if incoterm.present?- paramsenddef remember_purchase(fulfillment, shipment)@@ -157,10 +144,6 @@ module SpreeEasyPost)end- def address_params(source)- SpreeEasyPost.address_params(source)- end-def report(error, fulfillment)Rails.error.report(error, context: { fulfillment_id: fulfillment.id }, source: 'spree_easypost.fulfillment')enddiff --git a/spree/providers/easypost/app/models/spree_easypost/integration.rb b/spree/providers/easypost/app/models/spree_easypost/integration.rbindex e4ed059c6e..05d0766e6f 100644--- a/spree/providers/easypost/app/models/spree_easypost/integration.rb+++ b/spree/providers/easypost/app/models/spree_easypost/integration.rb@@ -22,8 +22,13 @@ module SpreeEasyPost# EasyPost rejects any other value outright, and a rejected shipment# create is a checkout with no delivery options at all.INCOTERMS = %w[CFR CIF CIP CPT DAT DAP DDP EXW FAS FCA FOB].freeze+ # EasyPost's contents enum minus `other`, which additionally demands a+ # free-text explanation nothing here supplies — offering it would only+ # produce a rejected declaration.+ CUSTOMS_CONTENTS_TYPES = %w[documents gift merchandise returned_goods sample dangerous_goods humanitarian_donation].freezevalidates :preferred_incoterm, inclusion: { in: INCOTERMS }, allow_blank: true+ validates :preferred_customs_contents_type, inclusion: { in: CUSTOMS_CONTENTS_TYPES }, allow_blank: true# EasyPost's own documentation example address — used only to prove the# key authenticates.diff --git a/spree/providers/easypost/lib/spree_easypost.rb b/spree/providers/easypost/lib/spree_easypost.rbindex b52a36ecad..380399bc35 100644--- a/spree/providers/easypost/lib/spree_easypost.rb+++ b/spree/providers/easypost/lib/spree_easypost.rb@@ -96,6 +96,11 @@ module SpreeEasyPostsource.try(:name)end+ # US export filings are waived below this declared value (NOEEI 30.37(a));+ # above it a shipment needs its own filing number, which only the merchant+ # can supply, so no exemption is claimed on its behalf.+ EEI_EXEMPTION_LIMIT_USD = 2_500+# Customs payload for an international shipment. Nil for domestic ones —# EasyPost rejects a customs form on a domestic label, and every carrier# treats "no customs_info" as the domestic case.@@ -105,6 +110,11 @@ module SpreeEasyPost# what they demand, and a rejected label carries the carrier's own message,# which is more actionable than a guess made here.#+ # The declaration is only certified when the integration names a signer:+ # EasyPost requires one whenever `customs_certify` is set, so certifying+ # without it would fail every international quote for an integration that+ # never configured a signer — the common case.+ ## @param package [Spree::Stock::Package]# @param origin [Spree::StockLocation, nil] where the parcel ships from# @param destination [Spree::Address, nil] where it is going@@ -116,14 +126,63 @@ module SpreeEasyPostitems = customs_items_params(package)return if items.empty?- {+ signer = integration&.preferred_customs_signer.presence+ params = {contents_type: integration&.preferred_customs_contents_type.presence || 'merchandise',restriction_type: 'none',- eel_pfc: 'NOEEI 30.37(a)',- customs_certify: true,- customs_signer: integration&.preferred_customs_signer.presence,+ eel_pfc: eel_pfc_for(items, origin),customs_items: items- }.compact_blank+ }+ params[:customs_certify] = true if signer+ params[:customs_signer] = signer+ params.compact_blank+ end++ # The full shipment-create payload, shared by quoting and label purchase so+ # the two can never diverge. Whatever is set here at quote time is what a+ # label bought against that quote carries — including the customs form and+ # the duty terms, which are shipment properties EasyPost fixes at creation+ # and does not accept on the buy call.+ #+ # @param package [Spree::Stock::Package]+ # @param origin [Spree::StockLocation, nil]+ # @param destination [Spree::Address, nil]+ # @param integration [SpreeEasyPost::Integration, nil]+ # @param store [Spree::Store, nil]+ # @return [Hash]+ def self.shipment_params(package, origin, destination, integration, store)+ params = {+ from_address: address_params(origin),+ to_address: address_params(destination),+ parcel: parcel_params(package, store)+ }++ customs_info = customs_info_params(package, origin, destination, integration)+ return params if customs_info.nil?++ params[:customs_info] = customs_info+ incoterm = integration&.preferred_incoterm.presence+ params[:options] = { incoterm: incoterm } if incoterm+ params+ end++ # The US export exemption, claimed only where it actually applies: a+ # US-origin shipment declared in US dollars under the filing threshold.+ # Anything else — a foreign origin, a non-dollar declaration, a value over+ # the limit — is left for the carrier to require rather than mis-declared+ # here. The threshold is a dollar figure, so a declaration in another+ # currency cannot be compared against it without a conversion this code+ # deliberately does not attempt.+ #+ # @param items [Array<Hash>] customs items with :value and :currency+ # @param origin [Spree::StockLocation, nil]+ # @return [String, nil]+ def self.eel_pfc_for(items, origin)+ return unless origin&.country_code == 'US'+ return unless items.all? { |item| item[:currency].to_s.upcase == 'USD' }++ declared_value = items.sum { |item| item[:value].to_f }+ 'NOEEI 30.37(a)' if declared_value < EEI_EXEMPTION_LIMIT_USDend# One customs item per package line. Quantity, value and weight always;diff --git a/spree/providers/easypost/spec/models/spree_easypost/customs_params_spec.rb b/spree/providers/easypost/spec/models/spree_easypost/customs_params_spec.rbindex 3bf64bc1ad..a449950c72 100644--- a/spree/providers/easypost/spec/models/spree_easypost/customs_params_spec.rb+++ b/spree/providers/easypost/spec/models/spree_easypost/customs_params_spec.rb@@ -42,10 +42,28 @@ RSpec.describe 'SpreeEasyPost customs params' doparams = SpreeEasyPost.customs_info_params(package, origin, foreign_destination)expect(params[:contents_type]).to eq('merchandise')- expect(params[:customs_certify]).to be trueexpect(params[:customs_items].size).to eq(1)end+ # EasyPost requires a signer whenever the declaration is certified, so an+ # integration without one must not certify — or every international quote+ # would fail for the default configuration.+ it 'does not certify the declaration when no signer is configured' do+ params = SpreeEasyPost.customs_info_params(package, origin, foreign_destination)++ expect(params).not_to have_key(:customs_certify)+ expect(params).not_to have_key(:customs_signer)+ end++ it 'certifies the declaration once a signer is named' do+ integration = SpreeEasyPost::Integration.new(store: store, preferences: { customs_signer: 'Jane Doe' })++ params = SpreeEasyPost.customs_info_params(package, origin, foreign_destination, integration)++ expect(params[:customs_certify]).to be true+ expect(params[:customs_signer]).to eq('Jane Doe')+ end+it 'carries the variant classification when the merchant recorded it' dovariant.update!(hs_code: '640411', country_of_origin: 'VN', customs_description: 'Leather footwear')@@ -91,6 +109,19 @@ RSpec.describe 'SpreeEasyPost customs params' doexpect(integration.errors[:preferred_incoterm]).to be_presentend+ it 'rejects a contents type EasyPost would refuse' do+ integration = SpreeEasyPost::Integration.new(store: store, preferences: { customs_contents_type: 'Merchandise' })++ expect(integration).not_to be_valid+ expect(integration.errors[:preferred_customs_contents_type]).to be_present+ end++ # `other` demands a free-text explanation nothing here supplies, so it is+ # deliberately not offered.+ it 'does not offer the contents type that needs an explanation' do+ expect(SpreeEasyPost::Integration::CUSTOMS_CONTENTS_TYPES).not_to include('other')+ end+it 'declares the line value and quantity' doline_item = order.line_items.first@@ -100,4 +131,55 @@ RSpec.describe 'SpreeEasyPost customs params' doexpect(item[:value]).to eq((line_item.price.to_f * line_item.quantity).round(2))endend++ describe '.eel_pfc_for' do+ let(:cheap) { [{ value: 100.0, currency: 'USD' }] }+ let(:dear) { [{ value: 3_000.0, currency: 'USD' }] }++ it 'claims the US export exemption for a low-value US-origin shipment' do+ expect(SpreeEasyPost.eel_pfc_for(cheap, origin)).to eq('NOEEI 30.37(a)')+ end++ # Above the filing threshold the merchant owes an export filing of their+ # own; claiming the exemption for them would be a misdeclaration.+ it 'claims nothing above the filing threshold' do+ expect(SpreeEasyPost.eel_pfc_for(dear, origin)).to be_nil+ end++ it 'claims nothing for a non-US origin — the code is a US regulation' do+ german_origin = create(:stock_location, country: Spree::Country.by_iso('DE'))++ expect(SpreeEasyPost.eel_pfc_for(cheap, german_origin)).to be_nil+ end++ # The threshold is a dollar figure; a euro declaration cannot be compared+ # against it without a conversion this code does not attempt.+ it 'claims nothing when the declaration is not in US dollars' do+ in_euros = [{ value: 100.0, currency: 'EUR' }]++ expect(SpreeEasyPost.eel_pfc_for(in_euros, origin)).to be_nil+ end+ end++ describe '.shipment_params' do+ let(:integration) do+ SpreeEasyPost::Integration.new(store: store, preferences: { incoterm: 'DDP', customs_signer: 'Jane Doe' })+ end++ it 'sets no customs form or duty terms on a domestic shipment' do+ params = SpreeEasyPost.shipment_params(package, origin, domestic_destination, integration, store)++ expect(params).not_to have_key(:customs_info)+ expect(params).not_to have_key(:options)+ end++ # The incoterm is a property of the shipment fixed at creation, so it has+ # to ride on the quote — a label bought against that quote cannot add it.+ it 'puts the configured incoterm on an international shipment at creation' do+ params = SpreeEasyPost.shipment_params(package, origin, foreign_destination, integration, store)++ expect(params[:customs_info]).to be_present+ expect(params[:options]).to eq(incoterm: 'DDP')+ end+ endend