Skip to content

armgit / spree

Public Imported from GitHub
0

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

18.9 KB
Raw Blame

Duties & Custom Fees

Status: Implemented for 6.0 (2026-08-14); the provider gem is 6.1 Target: Spree 6.0 (core plumbing) / 6.1 (landed-cost provider gem) Depends on: 6.0-6.1-split-adjustments.md (typed Fee/TaxLine rows — shipped), 6.0-tax-provider.md, 6.0-integrations-admin.md, 6.0-delivery-rate-provider.md (EasyPost provider gem) Author: Damian Legawiec Last updated: 2026-08-15

Shipped (2026-08-14): the whole 6.0 scope — hs_code/country_of_origin/customs_description on spree_variants (normalized + format-validated, admin API/CSV write paths, and both dashboard editors: the per-variant sheet and the bulk spreadsheet), duty fee kind, fees + fee_total on the Store API cart and order, the EasyPost customs declaration on both quotes and label purchases with an incoterm preference, and — after the tax-provider work reached main — duty fees excluded from the default taxable-item set.

Summary

Cross-border orders carry charges that are neither product price, delivery, nor sales tax: customs duties, brokerage and disbursement fees, and import VAT levied on top of the duty itself. Today Spree has no way to classify goods for customs (no HS code or country of origin anywhere), no way to show a shopper an itemized fee at checkout (the Store API exposes neither fees nor fee_total), and the EasyPost provider buys international labels with an empty customs declaration. This plan closes those gaps on top of the already-shipped typed Fee row: customs classification fields on the variant with the EasyPost customs declaration as their first consumer, a duty fee kind whose rows snapshot their calculation inputs, Store API visibility for fees, and a landed-cost estimation path that rides the existing Spree.adjusters registry + Spree::Integration credential surface rather than a new engine in core. A survey of the hosted market leader and the three OSS platforms (2026-08-14) shaped the design; the notable finding is that none of the OSS platforms has a usable duties story, and the hosted leader has no merchant-writable fee primitive at all — so finishing our fee surface is differentiation, not parity work.

Key Decisions (do not deviate without discussion)

  • A duty is a Fee with kind: 'duty', never a TaxLine and never a new table. Duties are a customs charge, not a sales tax — recording them as tax lines corrupts tax reporting and filings (the trap one OSS platform's percentage-only tax interface forces). The Fee row already rolls into fee_total/adjustment_total, participates in refund math, and is line-item- or order-level-scopable. Import VAT on a duty works today via TaxLine#fee_id — the same shape the hosted leader models as tax lines on its duty object.
  • Duty rows snapshot their calculation inputs in metadata (hs_code, country_of_origin, rate, provider identifier, estimate vs. guaranteed). Order history must not shift when the catalog is re-classified; the hosted leader's duty object snapshots identically rather than referencing the product.
  • Classification lives on the variant as plain columns (2026-08-14). The variant is our stock-keeping entity (weight, dimensions, cost price already live there), matching where both platforms that store customs data put it. Product-level fallback and custom-field modeling were both considered and rejected: fallback doubles the admin/CSV surface for the same declaration, and custom fields give untyped, unvalidated values invisible to typed serializers. Accepted trade-off: multi-variant products repeat the same values per variant; bulk editing and CSV import are the answer, not a second storage level.
  • Columns must ship with a consumer. One OSS platform has carried hs_code/origin_country columns for years that nothing reads — inert fields deliver nothing. Our first consumer is the EasyPost provider building a customs declaration (CustomsInfo/CustomsItems) for international label purchase; today it sends customs_info: null.
  • Core ships no duty calculation engine and no landed-cost guarantee. Guaranteed landed cost requires being importer of record — a service business, not a code path (even the hosted leader resells a merchant-of-record service for it). Estimation belongs to provider gems behind the existing extension points; core ships the data model, the fee kind, and the storefront visibility.
  • Duties enter the cart through Spree.adjusters (2026-08-14). A provider gem registers a Spree::Adjusters::Base subclass that writes/refreshes Fee(kind: 'duty') rows during recalculation — zero new machinery, and the two-pass ordering already puts fees before tax estimation so import VAT lands on the duty. Extending the tax provider was rejected (couples duty availability to the merchant's tax-engine choice and blurs the duty-is-not-tax boundary); a dedicated duty-provider contract was rejected as speculative machinery — per the service-workflows doctrine it graduates only when a real provider gem proves the need for estimate/commit/void lifecycle calls. Accepted trade-off: no commit/void lifecycle for customs transactions until then.
  • The internal tax provider excludes kind: 'duty' fees from its default taxing set (2026-08-14). Domestic sales tax stacked on a customs duty is wrong in most regimes and double-counts once a duties provider writes its own import-VAT TaxLine(fee_id: …) rows. Duty fees are taxed only by provider-written tax lines. Accepted trade-off: a kind-based special case inside TaxProvider::Internal; other fee kinds stay taxed as before.
  • Release split settled (2026-08-14): plumbing ships in 6.0, estimation in 6.1. 6.0 = variant customs fields, duty fee kind, Store API fee exposure, EasyPost customs declaration + shipping-terms (incoterm) option. 6.1 = the landed-cost provider gem and the Spree::Market shipping-terms setting. Everything-in-6.0 was rejected for schedule risk on the least-proven piece; everything-in-6.1 was rejected because 6.0 would otherwise ship international labels with empty customs declarations and keep every fee kind invisible to shoppers.
  • Fees become visible on the Store API (fees array + fee_total/display_fee_total on cart and order serializers). Itemized display is a legal expectation for cross-border charges and the delivery channel for every fee use case (surcharge, COD, handling) — currently the store serializers expose only aggregate adjustment totals.
  • Collecting duties at checkout must stay linked to duty-paid shipping. Charging the customer at checkout and then shipping under terms where the carrier collects again double-charges them. Any future "collect duties" toggle is scoped to methods/labels that support duty-paid terms; until a provider gem exists, duty fees are admin-written and the burden is on the merchant.
  • Shipping-terms selection (who is importer of record) is deferred to the provider-gem phase; its future home is a Spree::Market setting, not a global.

Design Details

1. Customs classification on the variant

New columns on spree_variants:

  • hs_code (string, nullable) — 6–13 digit Harmonized System code, digits only, validated by format when present. One global code; per-destination overrides are a provider-gem concern if ever needed.
  • country_of_origin (string, nullable) — ISO 3166-1 alpha-2.
  • customs_description (string, nullable) — plain-language contents description for the declaration; falls back to the product name.

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 that a variant attribute must be permitted in two places — the nested Admin::Products::VariantsController (which enumerates its own list) and the inline variants: [...] list on Admin::ProductsController. (It was three until Spree::PermittedAttributes was removed; see 6.0-permitted-attributes-removal.md.) 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

  • Spree::Fee::KINDS gains 'duty'.
  • Duty fees attach to line items when computed per item (the normal case — ad-valorem duty is per classified good) and may be order-level for lump-sum brokerage/disbursement charges (those may also use kind 'surcharge' with a label).
  • metadata on a duty row records the snapshot: hs_code, country_of_origin, rate, provider, guaranteed (boolean). Nothing reads these for money math — they are the audit trail.
  • Dashboard: the existing order fee card renders the new kind via the admin.orders.detail.adjustment_lines.fee_kind_duty key (all locale files); the add-fee dialog offers it. No new UI.

3. Store API fee exposure

  • Spree::Api::V3::CartSerializer and OrderSerializer gain fee_total / display_fee_total (money attributes, hide_prices-aware) and a fees association rendered with the existing store FeeSerializer (label, kind, amount, display_amount, line_item_id, fulfillment_id). Spree::Order was missing fee_total from its money_methods (Cart already had it) — added, or display_fee_total would not exist post-placement.
  • The admin cart and order serializers drop the inherited fees association rather than redeclaring it: fees reach the admin through their own /orders/:id/fees endpoint, which is also the write path, and an admin serializer must never render a store serializer.
  • Storefronts group and label fees themselves (e.g. one "Duties & import fees" line summing kind: 'duty' rows) — core provides itemized data, not presentation.
  • Full type pipeline follows (typelizer → Zod → integration specs → OpenAPI → SDK).

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.

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)

A duties provider gem ships the established pair:

  • Spree::Integrations::<Provider> — credentials, can_connect?, admin-managed via the integrations gallery.
  • A Spree::Adjusters::Base subclass registered in Spree.adjusters — during Carts::RecalculateTotals it reads the destination (ship address / market), each line's variant classification, and writes/refreshes line-scoped Fee(kind: 'duty') rows plus any import-VAT TaxLine(fee_id: …) rows carrying its provider_id.

The two-pass recalculate ordering already fits: adjusters persist fees before the tax provider estimates, so duty exists when import VAT is computed. Caching against external calls is the adjuster's responsibility (the same discipline the delivery-rate provider applies). If a provider needs post-placement lifecycle calls (commit/void on the customs transaction), that graduates it toward the tax-provider-style contract — decided when the first gem is built, not speculatively.

6. Tax providers and duty fees

The default taxable-item set lives on Spree::Purchase::Taxation#taxable_items (shared by Cart and Order) rather than inside one provider, so every provider inherits the duty exclusion when estimate is called without an explicit item list. A provider that does tax duties — import VAT is levied on the duty in most regimes — passes its own list, which stays supported and is covered by a spec.

Two things this method must keep doing, both learned the hard way:

  • Read through fresh scopes, never the cached associations. fees/line_items are typically already loaded (and empty) from record creation, and recalculation calls estimate immediately after adjusters have written fee rows. Reading the stale association silently leaves every fee untaxed. This bug predates the duty work — it was latent in the provider's own owner.fees.to_a — and Carts::RecalculateTotals guards the same hazard by resetting association caches before it runs.
  • Filter in SQL (where.not(kind: 'duty')), not in Ruby over a loaded collection, for the same reason.

internal_spec.rb covers this alongside the provider's other cases, and one of its examples fails if the association-staleness fix is reverted. That file had been skipped wholesale (xdescribe) by the countries-drop commit on the grounds that tax matching ran through the defunct Spree::Zone; the very next commit — the country_iso → country_code rename — removed that dependency, so the skip was stale and was lifted here, along with the identically-skipped promotion_tax_recalculation_spec.rb. Rate matching is now a plain country_code/state_code comparison (TaxRate.for_jurisdiction) with no zone involved; 56 examples covering the tax provider and the promotion/taxable-basis matrix are back in CI, verified stable across repeated full-suite runs.

Migration Path

  1. 6.0 — additive migration for the three spree_variants columns; duty kind + locale keys; store serializer fee exposure + type pipeline; EasyPost customs declaration. No data migration: all fields start empty, no existing rows change meaning.
  2. 6.1 — first landed-cost provider gem under spree/providers/; shipping-terms setting on Spree::Market if the gem needs it; per-destination HS codes only if a provider demands them.

Constraints on Current Work

  • New fee-producing code must write typed Fee rows through the adjusters registry or the order-locked fee services — never bespoke totals math (restates 6.0-6.1-split-adjustments.md).
  • Nothing outside a duty row's metadata snapshot may read variant classification for money math on an existing order — recalculation of a completed order must not re-derive duty from the live catalog.
  • Store-serializer work touching cart/order money fields should not assume fees stay hidden — fee_total and fees are becoming public surface.
  • The EasyPost provider must not require customs fields for domestic shipments; international-only, degrade like the carrier API does.

Open Questions

The four design questions raised by the draft (classification placement, duty write path, internal taxation of duty fees, release split) were all resolved on 2026-08-14 and moved to Key Decisions; the last of them shipped once the tax-provider work reached main (see below). What remains is deferred to the 6.1 provider-gem phase, with the gem as the unblocker: per-destination HS code overrides, the Spree::Market shipping-terms setting, and whether the adjuster path needs commit/void lifecycle calls.

References

  • docs/plans/6.0-6.1-split-adjustments.md — the Fee/TaxLine substrate this builds on (its manual-fee list already names customs as a fee use case)
  • docs/plans/6.0-tax-provider.md — provider/Integration pairing pattern, per-market provider selection
  • docs/plans/6.0-integrations-admin.md — credential surface for provider gems
  • docs/plans/6.0-delivery-rate-provider.md — EasyPost provider gem this extends with customs declarations
  • Platform survey 2026-08-14 (private session notes; per repository policy the survey itself stays out of the repo)