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
Added internal VAT validator (#14499)
Damian Legawiec74c38b2a6ee4
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex d0f848e7b8..45c60652d3 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -28274,7 +28274,7 @@ paths:data:- id: txi_UkLWZg9DAJkind: eu_vat- value: DE123456789+ value: DE100000008validation_status:validation_evidence:source:@@ -28323,11 +28323,11 @@ paths:// A business registration outranks the buyer's own when the sale is for that business.const registration = await client.companies.taxIdentifiers.create('comp_UkLWZg9DAJ', {kind: 'eu_vat',- value: 'DE123456789',+ value: 'DE100000008',})- lang: bashlabel: Spree CLI- source: spree api post /companies/{company_id}/tax_identifiers -d '{"kind":"eu_vat","value":"DE123456789"}'+ source: spree api post /companies/{company_id}/tax_identifiers -d '{"kind":"eu_vat","value":"DE100000008"}'parameters: []responses:'201':@@ -28355,7 +28355,7 @@ paths:example:error:code: validation_error- message: Kind has already been taken+ message: Registration type has already been takendetails:kind:- has already been taken@@ -28440,7 +28440,8 @@ paths:example:error:code: tax_id_not_validatable- message: No validator is registered for tax identifier kind 'eu_vat'+ message: No registry validator is installed for tax identifier kind+ 'eu_vat'"/api/v3/admin/companies":get:summary: List companiesdiff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yamlindex 76abaa0175..70148b74ce 100644--- a/docs/api-reference/seller.yaml+++ b/docs/api-reference/seller.yaml@@ -12769,8 +12769,8 @@ paths:example:data:- id: prod_UkLWZg9DAJ- name: Product 1353250- slug: product-1353250+ name: Product 1363250+ slug: product-1363250meta_title:meta_description:meta_keywords:@@ -13009,8 +13009,8 @@ paths:application/json:example:id: prod_UkLWZg9DAJ- name: Product 1386710- slug: product-1386710+ name: Product 1396710+ slug: product-1396710meta_title:meta_description:meta_keywords:@@ -13087,7 +13087,7 @@ paths:example:id: prod_UkLWZg9DAJname: Hand-thrown mug, large- slug: product-1418212+ slug: product-1428212meta_title:meta_description:meta_keywords:@@ -13224,7 +13224,6 @@ paths:- EUR- GBPproducts_count: 0- tax_identifiers: []schema:"$ref": "#/components/schemas/Profile"'403':@@ -13251,10 +13250,6 @@ paths:`slug`, since a seller renaming their own storefront address would breakevery link pointing at it.- `tax_identifier` holds one registration per kind: re-sending a kind- corrects the number, and an empty value removes it. A changed number- drops its validation verdict, because that answer was about the old one.-`accept_terms: true` stamps the moment the seller accepted themarketplace's terms, which is what the matching onboarding requirementreads. One-way — sending `false` does not unmake the stamp.@@ -13301,7 +13296,6 @@ paths:- EUR- GBPproducts_count: 0- tax_identifiers: []schema:"$ref": "#/components/schemas/Profile"'422':@@ -13360,15 +13354,6 @@ paths:accept_terms:type: booleandescription: Stamps acceptance of the marketplace terms- tax_identifier:- type: object- properties:- kind:- type: string- example: eu_vat- value:- type: string- example: PL1234567890billing_address:type: objectadditionalProperties: true@@ -14029,10 +14014,10 @@ paths:application/json:example:direct_upload:- url: http://www.example.com/rails/active_storage/disk/eyJfcmFpbHMiOnsiZGF0YSI6eyJrZXkiOiJuem5oOGdra3VxendvbDc1ODBxNHNwZmpmMjVxIiwiY29udGVudF90eXBlIjoiYXBwbGljYXRpb24vcGRmIiwiY29udGVudF9sZW5ndGgiOjUxMjM0LCJjaGVja3N1bSI6IlZqaHowNGxRdUVHdXY0bkR2aHNhTlE9PSIsInNlcnZpY2VfbmFtZSI6InRlc3QifSwiZXhwIjoiMjAyNi0wMS0xNVQxMjowNTowMC4wMDBaIiwicHVyIjoiYmxvYl90b2tlbiJ9fQ==--4739345b3df1958ee78bbd4119ff0e6d4f7c0a79+ url: http://www.example.com/rails/active_storage/disk/eyJfcmFpbHMiOnsiZGF0YSI6eyJrZXkiOiJuem5oOGdra3VxendvbDc1ODBxNHNwZmpmMjVxIiwiY29udGVudF90eXBlIjoiYXBwbGljYXRpb24vcGRmIiwiY29udGVudF9sZW5ndGgiOjUxMjM0LCJjaGVja3N1bSI6IlZqaHowNGxRdUVHdXY0bkR2aHNhTlE9PSIsInNlcnZpY2VfbmFtZSI6InRlc3QifSwiZXhwIjoiMjAyNi0wMS0xNVQxMjowNTowMC4wMDBaIiwicHVyIjoiYmxvYl90b2tlbiJ9fQ==--ec01546e3fc6ebad1b6d0564981d279619e5b061headers:Content-Type: application/pdf- signed_id: eyJfcmFpbHMiOnsiZGF0YSI6MSwicHVyIjoiYmxvYl9pZCJ9fQ==--f728cc8f2cc6dc935156331dc163f31d2e271174+ signed_id: eyJfcmFpbHMiOnsiZGF0YSI6MSwicHVyIjoiYmxvYl9pZCJ9fQ==--389837f16b7b8cde04c6aea7d0e8d4bc3ac5e2e7schema:"$ref": "#/components/schemas/DirectUploadResponse"requestBody:@@ -14296,8 +14281,8 @@ paths:- id: fi_UkLWZg9DAJquantity: 1line_item_id: li_UkLWZg9DAJ- name: Product 1289315- sku: SKU-160+ name: Product 1299315+ sku: SKU-161options_text: ''schema:type: object@@ -14366,8 +14351,8 @@ paths:- id: fi_UkLWZg9DAJquantity: 1line_item_id: li_UkLWZg9DAJ- name: Product 129961- sku: SKU-161+ name: Product 130961+ sku: SKU-162options_text: ''schema:"$ref": "#/components/schemas/Fulfillment"@@ -14467,7 +14452,7 @@ paths:display_total: "$110.00"items:- id: li_UkLWZg9DAJ- name: Product 13095+ name: Product 13195options_text: ''quantity: 1currency: USD@@ -14476,7 +14461,7 @@ paths:total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ- sku: SKU-162+ sku: SKU-163thumbnail_url:fulfillments:- id: ful_UkLWZg9DAJ@@ -14496,8 +14481,8 @@ paths:- id: fi_UkLWZg9DAJquantity: 1line_item_id: li_UkLWZg9DAJ- name: Product 13095- sku: SKU-162+ name: Product 13195+ sku: SKU-163options_text: ''shipping_address:id: addr_gbHJdmfrXB@@ -14616,7 +14601,7 @@ paths:display_total: "$110.00"items:- id: li_UkLWZg9DAJ- name: Product 1319755+ name: Product 1329755options_text: ''quantity: 1currency: USD@@ -14625,7 +14610,7 @@ paths:total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ- sku: SKU-163+ sku: SKU-164thumbnail_url:fulfillments:- id: ful_UkLWZg9DAJ@@ -14645,8 +14630,8 @@ paths:- id: fi_UkLWZg9DAJquantity: 1line_item_id: li_UkLWZg9DAJ- name: Product 1319755- sku: SKU-163+ name: Product 1329755+ sku: SKU-164options_text: ''shipping_address:id: addr_gbHJdmfrXB@@ -14754,7 +14739,7 @@ paths:display_total: "$110.00"items:- id: li_UkLWZg9DAJ- name: Product 1346554+ name: Product 1356554options_text: ''quantity: 1currency: USD@@ -14763,7 +14748,7 @@ paths:total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ- sku: SKU-166+ sku: SKU-167thumbnail_url:fulfillments:- id: ful_UkLWZg9DAJ@@ -14783,8 +14768,8 @@ paths:- id: fi_UkLWZg9DAJquantity: 1line_item_id: li_UkLWZg9DAJ- name: Product 1346554- sku: SKU-166+ name: Product 1356554+ sku: SKU-167options_text: ''shipping_address:id: addr_gbHJdmfrXB@@ -14841,6 +14826,201 @@ paths:notify_customer:type: booleandescription: Email the customer about the cancellation+ "/api/v3/seller/tax_identifiers":+ get:+ summary: List tax registrations+ tags:+ - Tax Identifiers+ security:+ - bearer_auth: []+ description: |+ The seller's own registrations — the numbers the marketplace's+ commission invoice is made out to, and what makes EU reverse charge on+ that fee possible.++ A collection rather than a single field: a business trading in more+ than one regime holds a registration in each, and they are not+ alternatives. One per kind.+ parameters:+ - name: X-Spree-Seller-Id+ in: header+ required: true+ schema:+ type: string+ responses:+ '200':+ description: registrations returned+ content:+ application/json:+ example:+ data:+ - id: txi_UkLWZg9DAJ+ kind: eu_vat+ value: DE100000008+ validation_status:+ validated_at:+ meta:+ page: 1+ limit: 25+ count: 1+ pages: 1+ from: 1+ to: 1+ in: 1+ previous:+ next:+ post:+ summary: Add a tax registration+ tags:+ - Tax Identifiers+ security:+ - bearer_auth: []+ description: |+ `kind` names the regime — `eu_vat`, `gb_vat`, and whatever else a+ validator is registered for. Any string is accepted; what a kind means+ is decided by its validator, and a kind nothing is registered for is+ stored and used as entered.++ A number a registered validator refuses is rejected outright rather+ than stored, so a typo cannot reach an invoice.+ parameters:+ - name: X-Spree-Seller-Id+ in: header+ required: true+ schema:+ type: string+ responses:+ '201':+ description: registration recorded+ content:+ application/json:+ example:+ id: txi_UkLWZg9DAJ+ kind: eu_vat+ value: DE100000008+ validation_status:+ validated_at:+ '422':+ description: the number is not valid for its regime+ content:+ application/json:+ example:+ error:+ code: validation_error+ message: Number does not look like a valid EU VAT registration+ details:+ value:+ - does not look like a valid EU VAT registration+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ kind:+ type: string+ example: eu_vat+ value:+ type: string+ example: DE100000008+ required:+ - kind+ - value+ "/api/v3/seller/tax_identifiers/{id}":+ parameters:+ - name: id+ in: path+ required: true+ schema:+ type: string+ patch:+ summary: Correct a tax registration+ tags:+ - Tax Identifiers+ security:+ - bearer_auth: []+ description: |+ A changed number drops its validation verdict, because that answer was+ about the old one.+ parameters:+ - name: X-Spree-Seller-Id+ in: header+ required: true+ schema:+ type: string+ responses:+ '200':+ description: registration corrected+ content:+ application/json:+ example:+ id: txi_UkLWZg9DAJ+ kind: eu_vat+ value: DE100000016+ validation_status:+ validated_at:+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ kind:+ type: string+ example: eu_vat+ value:+ type: string+ example: DE100000016+ delete:+ summary: Remove a tax registration+ tags:+ - Tax Identifiers+ security:+ - bearer_auth: []+ parameters:+ - name: X-Spree-Seller-Id+ in: header+ required: true+ schema:+ type: string+ responses:+ '204':+ description: registration removed+ "/api/v3/seller/tax_identifiers/{id}/validate":+ parameters:+ - name: id+ in: path+ required: true+ schema:+ type: string+ post:+ summary: Re-check a registration against its registry+ tags:+ - Tax Identifiers+ security:+ - bearer_auth: []+ description: |+ A registry answers "valid now", so a number verified last year may have+ been deregistered since. Refused when no registry validator is+ installed for the kind — core format-checks EU VAT numbers but asks no+ registry, so a stock install answers 422 here rather than queueing a+ check nobody can answer.+ parameters:+ - name: X-Spree-Seller-Id+ in: header+ required: true+ schema:+ type: string+ responses:+ '422':+ description: no registry validator is installed for this kind+ content:+ application/json:+ example:+ error:+ code: tax_id_not_validatable+ message: No registry validator is installed for tax identifier kind+ 'eu_vat'servers:- url: http://{defaultHost}variables:@@ -16459,10 +16639,6 @@ components:type: stringproducts_count:type: number- tax_identifiers:- type: array- items:- "$ref": "#/components/schemas/TaxIdentifier"billing_address:"$ref": "#/components/schemas/Address"returns_address:@@ -16492,7 +16668,6 @@ components:- default_currency- supported_currencies- products_count- - tax_identifiersx-typelizer: trueRequirementCustomField:type: objectdiff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.mdindex 7723117908..26cf688fd0 100644--- a/docs/plans/6.0-tax-provider.md+++ b/docs/plans/6.0-tax-provider.md@@ -302,7 +302,21 @@ CustomerGroup link; roles, approval workflows, purchase limits and invoicing. Co- **The address is an input, never the owner.** A tax ID identifies the legal entity, not a location; Spree addresses are cloned/deduplicated value records and a bad host for identity data (Magento's address-level columns are the cautionary precedent). The billing address's existing `company` field pairs with the ID on invoices — no duplicate field.- **Validation belongs to the identifier, not to a tax provider.** A registration number is checked against a registry chosen by its **kind** — an EU VAT number against the EU's verification service, a UK one against the UK's, an Australian one against Australia's — whichever engine happens to price the merchant's orders. Nothing about it is a market decision: a customer saves a tax ID on a profile, long before any order or market exists. Hanging validation off `TaxProvider` would force an arbitrary provider choice (a US sales-tax engine asked to check an EU VAT number, or an EU market on Internal declining to validate while a connected Avalara sits unused), so **`validate_tax_id` is deliberately not on the provider contract**.- **The seam is a registry keyed by kind**, empty by default — core ships **no registry client** for any jurisdiction:+ **The registry is keyed by kind**, and core ships exactly one entry: a **format-only** validator for `eu_vat`. Core ships **no registry client** for any jurisdiction.++ That split follows the cost, not the jurisdiction. Checking a VAT number's *shape* is arithmetic — the check digits are published in the directive, they are the same for every installation, and the check needs no credentials, no network and no configuration. Leaving it out means a stock install accepts `DE123` as a German VAT number and stores it, which is how a typo reaches an invoice. It is the same reasoning that already puts postal codes on `validates_zipcode`, phone numbers on `phonelib` and carrier numbers on `tracking_number`, and core takes the same route here: `valvat` as a dependency, wrapped in `Spree::TaxIdentifiers::Validator::EuVat`.++ Checking whether that number is *registered* is a call to somebody's government — slow, periodically down, and jurisdiction-specific — so it stays out, exactly as before.++ Three consequences worth stating, because each one is a place this could go wrong:++ - **A passing format check is not a verdict.** It writes no validation status. Being well-formed is not evidence that a business exists, and `verified` continues to mean a registry said so. A stock install therefore rejects mistyped numbers on save and still leaves every verdict blank.+ - **`Validator::Base.checks_registry?`** tells core whether a validator can answer a registry question at all; `EuVat` returns false. Without it, every saved VAT number would enqueue a check that nobody implements, and the job would record `unavailable` — which would be a lie, since no registry was asked. `TaxIdentifier#validatable?` reads this, so it keeps meaning "a registry can be asked here".+ - **Uncheckable member states still pass.** `valvat` has check-digit algorithms for 24 of the 27 member states and falls back to syntax for Czechia, Latvia and Slovakia. Rejecting what cannot be fully verified would turn away real business customers to catch a typo, which inverts the cost. `Valvat::Checksum.validate` already applies this fallback, so there is no country list to maintain.+ - **Greece is matched on its ISO code, not its VAT prefix.** It is the one member state where the two differ — it issues `EL…` numbers while its ISO code is `GR` — so a country check written against the prefix refuses every Greek business. Northern Ireland is the mirror image: `XI` is a VAT prefix with no ISO code of its own, so it is matched on the prefix.+ - **An order's frozen snapshot is never format-checked.** It is a copy of a number already accepted at the time, so re-checking it would let a rule tightened later — or a country leaving the VAT area, as Great Britain did — fail a checkout over history rather than over anything the buyer typed.++ An extension wanting the registry half re-registers `eu_vat` and takes over both halves:```ruby# Extensions register the kinds they cover; a tax provider gem may register@@ -310,13 +324,14 @@ CustomerGroup link; roles, approval workflows, purchase limits and invoicing. CoSpree.tax_identifier_validators['eu_vat'] = 'SpreeEuVat::TaxIdentifierValidator'# Each validator subclasses Spree::TaxIdentifiers::Validator::Base: a class-level- # valid_format? for the synchronous check, and call(tax_identifier:) →- # ValidationResult for the registry call. The row carries kind, value and its- # owner, so a credentialed validator reaches the store's Integration through- # the owner — no extra arguments.+ # valid_format? for the synchronous check, checks_registry? to say whether the+ # second half exists, and call(tax_identifier:) → ValidationResult for the+ # registry call. The row carries kind, value and its owner, so a credentialed+ # validator reaches the store's Integration through the owner — no extra+ # arguments.```- Lookup is deterministic from the row itself, two extensions covering different kinds coexist (a single swappable service would give the second one to load the slot and silently disable the first), and core can answer "can this installation validate this kind?" with `Spree.tax_identifier_validators.key?(kind)` — which is what the admin needs to distinguish *queued*, *no validator installed* and *checked and not registered*.+ Lookup is deterministic from the row itself, and two extensions covering different kinds coexist (a single swappable service would give the second one to load the slot and silently disable the first). Core answers "can this installation check this kind against a registry?" with `TaxIdentifier#validatable?` — the registered validator's `checks_registry?`, not the bare `key?(kind)`, since core now registers a validator that deliberately cannot. That is what the admin needs to distinguish *queued*, *no registry validator installed* and *checked and not registered*.**When it runs:** after the identifier is saved, in a background job — following the address-geocoding precedent (`Spree::Address#async_geocode` → `Spree::Addresses::GeocodeAddressJob`), which solves the same problem of enriching a row from an external lookup:@@ -1116,7 +1131,7 @@ Shipped with the core-rewrite waves, not as originally phased: no "Internal dele- API: `/admin/tax_rates` CRUD (without it the Internal provider cannot be configured or verified through the API — see the API surface section), tax identifier endpoints (with admin `validatable` + the re-validate action), tax lines exposed on the Store API, admin tax-line serializer gaining `taxability_reason`/jurisdiction/`data`, and the Ransack allowlist for tax reporting.- `estimate` signature: `tax_date:`/`tax_identifier:`/`exemptions:`/`context:`; `refund(order, return_items, tax_date:)` replaces `refund(owner, amount)`; `exempt?` removed.- `Spree::TaxExemption` + `ItemOverride` value objects; `tax_resolve_exemptions_service` dependency (default empty); `#resolved_tax_identifier` on `Spree::Purchase::Taxation`.-- `Spree::TaxIdentifiers::Validator::Base` + `Spree.tax_identifier_validators` registry (empty by default, class names) + `Spree::TaxIdentifiers::Validate` (sole writer of the validation columns) + `ValidateJob` + `Spree.queues.tax_identifiers` + the `after_commit` enqueue guarded on kind/value changes.+- `Spree::TaxIdentifiers::Validator::Base` (incl. `checks_registry?`) + `Spree.tax_identifier_validators` registry (class names; core registers the format-only `Spree::TaxIdentifiers::Validator::EuVat` for `eu_vat`, backed by `valvat`) + `Spree::TaxIdentifiers::Validate` (sole writer of the validation columns) + `ValidateJob` + `Spree.queues.tax_identifiers` + the `after_commit` enqueue guarded on kind/value changes.- Synchronous format validation on `TaxIdentifier`: whitespace/case normalization, presence, and the registered validator's class-level `valid_format?` (no format rules in core). Hard validation — a number a validator rejects never persists.- Capability declarations + Internal's unsupported list.- **Store binding** (the 2026-07-29 note above): `store_id` on `spree_tax_rates` and `spree_tax_categories` via `Spree::SingleStoreResource`, a backfill rake task, and store-scoped fetching in the endpoints above; `null: false` waits for 6.1 once the backfill has run everywhere. `TaxIdentifier`, `TaxLine` and the other typed rows deliberately get **no** `store_id` — they are owned rows whose owner already carries the store, matching `spree_tax_lines` as shipped; a denormalized copy would only be a second thing to keep in sync.diff --git a/packages/dashboard-ui/src/index.ts b/packages/dashboard-ui/src/index.tsindex 17d6bdc5e8..28d8e39a34 100644--- a/packages/dashboard-ui/src/index.ts+++ b/packages/dashboard-ui/src/index.ts@@ -63,6 +63,7 @@ export * from './spree/search-input'export * from './spree/secret-input'export * from './spree/storefront-visible-switch'export * from './spree/tag-list'+export * from './spree/tax-identifiers-card'export * from './spree/theme-provider'export * from './spree/theme-toggle'// ---------------------------------------------------------------------------diff --git a/packages/dashboard-ui/src/spree/tax-identifiers-card.tsx b/packages/dashboard-ui/src/spree/tax-identifiers-card.tsxnew file mode 100644index 0000000000..280926e623--- /dev/null+++ b/packages/dashboard-ui/src/spree/tax-identifiers-card.tsx@@ -0,0 +1,418 @@+import { BadgeCheckIcon, EllipsisVerticalIcon, PencilIcon, PlusIcon, TrashIcon } from 'lucide-react'+import { useEffect, useState } from 'react'+import { Controller, type UseFormSetError, useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'+import {+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardHeader,+ CardTitle,+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Field,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ Input,+ RelativeTime,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+ StatusBadge,+ useConfirm,+} from '../index'++/** One selectable registration kind. */+interface KindOption {+ value: string+ label: string+}++/**+ * A registration as the API returns it. Declared here rather than imported+ * from an SDK: this package is headless, and the admin and seller SDKs+ * describe the same row.+ */+export interface TaxIdentifier {+ id: string+ kind: string+ value: string+ validation_status?: string | null+ validated_at?: string | null+ validatable?: boolean+}++export interface TaxIdentifierParams {+ kind: string+ value: string+}++interface TaxIdentifierFormValues {+ kind: string+ value: string+}++const TAX_IDENTIFIER_DEFAULTS: TaxIdentifierFormValues = { kind: '', value: '' }++/**+ * The registration kinds Spree ships strings for. Any string is accepted by+ * the API — what a kind means is decided by whichever validator is registered+ * for it — so the merchant can type their own.+ */+export const TAX_IDENTIFIER_KINDS = ['eu_vat', 'gb_vat', 'ch_vat', 'au_abn', 'us_ein'] as const++/**+ * Mutations differ by owner (a company's registrations hang off the company,+ * a customer's off the customer) while the panel itself does not — so the+ * owner supplies them and this stays one component.+ */+export interface TaxIdentifierMutations {+ create: (params: TaxIdentifierParams) => Promise<unknown>+ update: (id: string, params: TaxIdentifierParams) => Promise<unknown>+ remove: (id: string) => Promise<unknown>+ validate: (id: string) => Promise<unknown>+ isValidating?: boolean+ /**+ * Routes a rejected save onto the form. Supplied by the host because it is+ * the host's SDK that defines what a validation error looks like; returning+ * false means "not mine", and the error is rethrown.+ */+ mapErrors: (error: unknown, setError: UseFormSetError<TaxIdentifierFormValues>) => boolean+}++/**+ * The buyer's VAT or business number. What makes EU B2B reverse charge+ * possible, so the verdict matters as much as the number: a row nothing can+ * check reads as such rather than as merely unverified.+ */+export function TaxIdentifiersCard({+ identifiers,+ isLoading,+ mutations,+ canEdit,+}: {+ identifiers: TaxIdentifier[]+ isLoading?: boolean+ mutations: TaxIdentifierMutations+ canEdit: boolean+}) {+ const { t } = useTranslation()+ const confirm = useConfirm()+ const [addOpen, setAddOpen] = useState(false)+ const [editing, setEditing] = useState<TaxIdentifier | null>(null)++ async function handleDelete(identifier: TaxIdentifier) {+ const ok = await confirm({+ title: t('admin.tax_identifiers.delete_confirm.title'),+ message: t('admin.tax_identifiers.delete_confirm.message', { value: identifier.value }),+ variant: 'destructive',+ confirmLabel: t('admin.actions.delete'),+ })+ if (!ok) return+ await mutations.remove(identifier.id).catch(() => undefined)+ }++ return (+ <Card>+ <CardHeader>+ <CardTitle>+ {t('admin.tax_identifiers.title')}+ {identifiers.length > 0 && <Badge variant="outline">{identifiers.length}</Badge>}+ </CardTitle>+ {canEdit && (+ <CardAction>+ <Button size="sm" variant="outline" onClick={() => setAddOpen(true)}>+ <PlusIcon className="size-4" />+ {t('admin.tax_identifiers.add_cta')}+ </Button>+ </CardAction>+ )}+ </CardHeader>++ {isLoading ? (+ <CardContent>+ <p className="text-muted-foreground text-sm">{t('admin.common.loading')}</p>+ </CardContent>+ ) : identifiers.length === 0 ? (+ <CardContent>+ <p className="text-muted-foreground text-sm">{t('admin.tax_identifiers.empty')}</p>+ </CardContent>+ ) : (+ <CardContent className="flex flex-col gap-3">+ {identifiers.map((identifier) => (+ <div+ key={identifier.id}+ className="flex items-start justify-between gap-3 rounded-md border p-3"+ >+ <div className="flex min-w-0 flex-col gap-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-medium text-sm">{identifier.value}</span>+ <Badge variant="outline">+ {t(`admin.tax_identifiers.kinds.${identifier.kind}`, {+ defaultValue: identifier.kind,+ })}+ </Badge>+ {identifier.validation_status ? (+ <StatusBadge+ status={identifier.validation_status}+ label={t(+ `admin.tax_identifiers.validation_status.${identifier.validation_status}`,+ { defaultValue: identifier.validation_status },+ )}+ />+ ) : (+ <Badge variant="secondary">+ {t('admin.tax_identifiers.validation_status.not_checked')}+ </Badge>+ )}+ </div>+ {identifier.validated_at && (+ <span className="text-muted-foreground text-xs">+ <RelativeTime+ iso={identifier.validated_at}+ prefix={t('admin.tax_identifiers.checked_prefix')}+ />+ </span>+ )}+ {!identifier.validatable && (+ <span className="text-muted-foreground text-xs">+ {t('admin.tax_identifiers.not_validatable')}+ </span>+ )}+ </div>++ {canEdit && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon-xs">+ <EllipsisVerticalIcon className="size-4" />+ <span className="sr-only">{t('admin.actions.actions_menu')}</span>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ disabled={!identifier.validatable || mutations.isValidating}+ onClick={() => mutations.validate(identifier.id).catch(() => undefined)}+ >+ <BadgeCheckIcon className="size-4" />+ {t('admin.tax_identifiers.validate_action')}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => setEditing(identifier)}>+ <PencilIcon className="size-4" />+ {t('admin.actions.edit')}+ </DropdownMenuItem>+ <DropdownMenuItem+ className="text-destructive focus:text-destructive"+ onClick={() => handleDelete(identifier)}+ >+ <TrashIcon className="size-4" />+ {t('admin.actions.delete')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>+ ))}+ </CardContent>+ )}++ {addOpen && (+ <TaxIdentifierSheet+ open+ onOpenChange={setAddOpen}+ mapErrors={mutations.mapErrors}+ onSubmit={(params) => mutations.create(params)}+ />+ )}+ {editing && (+ <TaxIdentifierSheet+ open+ identifier={editing}+ onOpenChange={(next) => {+ if (!next) setEditing(null)+ }}+ mapErrors={mutations.mapErrors}+ onSubmit={(params) => mutations.update(editing.id, params)}+ />+ )}+ </Card>+ )+}++function TaxIdentifierSheet({+ open,+ onOpenChange,+ identifier,+ onSubmit,+ mapErrors,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ identifier?: TaxIdentifier+ onSubmit: (params: TaxIdentifierParams) => Promise<unknown>+ mapErrors: (error: unknown, setError: UseFormSetError<TaxIdentifierFormValues>) => boolean+}) {+ const { t } = useTranslation()+ const form = useForm<TaxIdentifierFormValues>({ defaultValues: TAX_IDENTIFIER_DEFAULTS })++ useEffect(() => {+ if (open) {+ form.reset(+ identifier ? { kind: identifier.kind, value: identifier.value } : TAX_IDENTIFIER_DEFAULTS,+ )+ }+ }, [open, identifier, form])++ async function handleSubmit(values: TaxIdentifierFormValues) {+ try {+ await onSubmit({ kind: values.kind, value: values.value })+ onOpenChange(false)+ } catch (err) {+ // The host maps its own SDK's errors: this package knows nothing about+ // either SDK, and a thrown error it cannot read is the host's to report.+ if (!mapErrors(err, form.setError)) throw err+ }+ }++ const { errors } = form.formState+ // The mapper always seeds `root` with the server's summary, as a safety net+ // for errors whose field is not on screen. Here both fields are, so showing+ // it as well repeats the same sentence twice in one small form.+ const rootIsRepeated = Boolean(errors.kind || errors.value)++ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent>+ <SheetHeader>+ <SheetTitle>+ {identifier+ ? t('admin.tax_identifiers.edit_title')+ : t('admin.tax_identifiers.add_title')}+ </SheetTitle>+ <SheetDescription>{t('admin.tax_identifiers.dialog_description')}</SheetDescription>+ </SheetHeader>+ <form+ onSubmit={(event) => {+ // This sheet can be rendered inside another form; stopping the+ // bubbled submit keeps the outer form from also submitting.+ form.handleSubmit(handleSubmit)(event)+ event.stopPropagation()+ }}+ className="flex min-h-0 flex-1 flex-col"+ >+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">+ <FieldGroup>+ {errors.root?.message && !rootIsRepeated && (+ <p className="text-destructive text-sm" role="alert">+ {errors.root.message}+ </p>+ )}+ <Field>+ <FieldLabel htmlFor="tax-identifier-kind">+ {t('admin.fields.tax_identifier.kind.label')}+ </FieldLabel>+ {/* The list seeds the picker rather than closing it: any string+ is a valid kind, and only the validator registered for one+ decides what it means. */}+ <Controller+ name="kind"+ control={form.control}+ rules={{ required: t('admin.fields.tax_identifier.kind.required') }}+ render={({ field }) => {+ // Combobox rather than Select: this card renders inside a+ // page card, and Base UI's Select popup does not survive+ // that portal nesting (the country picker below is a+ // Combobox for the same reason).+ const kindOptions = TAX_IDENTIFIER_KINDS.map((kind) => ({+ value: kind,+ label: t(`admin.tax_identifiers.kinds.${kind}`, { defaultValue: kind }),+ }))+ const selected = kindOptions.find((o) => o.value === field.value) ?? null+ return (+ <Combobox+ items={kindOptions}+ value={selected}+ onValueChange={(option: KindOption | null) =>+ field.onChange(option?.value ?? '')+ }+ // The list seeds the picker rather than closing it, so+ // a kind matching no item has to be read from the input+ // itself. Only genuine typing: picking an option also+ // rewrites the input, to the label rather than the key.+ onInputValueChange={(input: string, details: { reason?: string }) => {+ if (details.reason === 'input-change') field.onChange(input)+ }}+ itemToStringLabel={(option: KindOption | null) => option?.label ?? ''}+ itemToStringValue={(option: KindOption | null) => option?.value ?? ''}+ >+ <ComboboxInput+ id="tax-identifier-kind"+ placeholder={t('admin.tax_identifiers.select_kind')}+ />+ <ComboboxContent>+ <ComboboxEmpty>{t('admin.common.no_results')}</ComboboxEmpty>+ <ComboboxList>+ {(option: KindOption) => (+ <ComboboxItem key={option.value} value={option}>+ {option.label}+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ )+ }}+ />+ <FieldDescription>{t('admin.fields.tax_identifier.kind.help')}</FieldDescription>+ <FieldError errors={[errors.kind]} />+ </Field>++ <Field>+ <FieldLabel htmlFor="tax-identifier-value">+ {t('admin.fields.tax_identifier.value.label')}+ </FieldLabel>+ <Input+ id="tax-identifier-value"+ placeholder={t('admin.fields.tax_identifier.value.placeholder')}+ aria-invalid={!!errors.value || undefined}+ {...form.register('value', {+ required: t('admin.fields.tax_identifier.value.required'),+ })}+ />+ <FieldError errors={[errors.value]} />+ </Field>+ </FieldGroup>+ </div>+ <SheetFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ disabled={form.formState.isSubmitting}+ >+ {t('admin.actions.cancel')}+ </Button>+ <Button type="submit" disabled={form.formState.isSubmitting}>+ {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}+ </Button>+ </SheetFooter>+ </form>+ </SheetContent>+ </Sheet>+ )+}diff --git a/packages/dashboard/src/components/spree/tax-identifiers-card.tsx b/packages/dashboard/src/components/spree/tax-identifiers-card.tsxindex cc3f672538..1a000cc8f7 100644--- a/packages/dashboard/src/components/spree/tax-identifiers-card.tsx+++ b/packages/dashboard/src/components/spree/tax-identifiers-card.tsx@@ -1,373 +1,31 @@-import { zodResolver } from '@hookform/resolvers/zod'-import type { TaxIdentifier, TaxIdentifierParams } from '@spree/admin-sdk'import { mapSpreeErrorsToForm } from '@spree/dashboard-core'import {- Badge,- Button,- Card,- CardAction,- CardContent,- CardHeader,- CardTitle,- Combobox,- ComboboxContent,- ComboboxEmpty,- ComboboxInput,- ComboboxItem,- ComboboxList,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,- Field,- FieldDescription,- FieldError,- FieldGroup,- FieldLabel,- Input,- RelativeTime,- Sheet,- SheetContent,- SheetDescription,- SheetFooter,- SheetHeader,- SheetTitle,- StatusBadge,- useConfirm,+ TaxIdentifiersCard as SharedTaxIdentifiersCard,+ type TaxIdentifier,+ type TaxIdentifierMutations,} from '@spree/dashboard-ui'-import { BadgeCheckIcon, EllipsisVerticalIcon, PencilIcon, PlusIcon, TrashIcon } from 'lucide-react'-import { useEffect, useState } from 'react'-import { Controller, useForm } from 'react-hook-form'-import { useTranslation } from 'react-i18next'-import {- TAX_IDENTIFIER_DEFAULTS,- TAX_IDENTIFIER_KINDS,- type TaxIdentifierFormValues,- taxIdentifierFormSchema,- taxIdentifierValuesToParams,-} from '../../schemas/company'--/** One selectable registration kind. */-interface KindOption {- value: string- label: string-}-/**- * Mutations differ by owner (a company's registrations hang off the company,- * a customer's off the customer) while the panel itself does not — so the- * owner supplies them and this stays one component.- */-export interface TaxIdentifierMutations {- create: (params: TaxIdentifierParams) => Promise<unknown>- update: (id: string, params: TaxIdentifierParams) => Promise<unknown>- remove: (id: string) => Promise<unknown>- validate: (id: string) => Promise<unknown>- isValidating?: boolean-}+export type { TaxIdentifier, TaxIdentifierMutations }/**- * The buyer's VAT or business number. What makes EU B2B reverse charge- * possible, so the verdict matters as much as the number: a row nothing can- * check reads as such rather than as merely unverified.+ * The buyer's VAT or business number, wired to this dashboard's SDK.+ *+ * The panel itself lives in `@spree/dashboard-ui` so the seller panel renders+ * the same one: a seller manages registrations exactly as a company does, and+ * the two surfaces drifting is how the hardcoded kind and the hidden toast+ * ended up in only one of them. All this adds is the error mapper, which is+ * the one piece that knows which SDK raised the failure.*/export function TaxIdentifiersCard({- identifiers,- isLoading,mutations,- canEdit,-}: {- identifiers: TaxIdentifier[]- isLoading?: boolean- mutations: TaxIdentifierMutations- canEdit: boolean+ ...props+}: Omit<Parameters<typeof SharedTaxIdentifiersCard>[0], 'mutations'> & {+ mutations: Omit<TaxIdentifierMutations, 'mapErrors'>}) {- const { t } = useTranslation()- const confirm = useConfirm()- const [addOpen, setAddOpen] = useState(false)- const [editing, setEditing] = useState<TaxIdentifier | null>(null)-- async function handleDelete(identifier: TaxIdentifier) {- const ok = await confirm({- title: t('admin.tax_identifiers.delete_confirm.title'),- message: t('admin.tax_identifiers.delete_confirm.message', { value: identifier.value }),- variant: 'destructive',- confirmLabel: t('admin.actions.delete'),- })- if (!ok) return- await mutations.remove(identifier.id).catch(() => undefined)- }-return (- <Card>- <CardHeader>- <CardTitle>- {t('admin.tax_identifiers.title')}- {identifiers.length > 0 && <Badge variant="outline">{identifiers.length}</Badge>}- </CardTitle>- {canEdit && (- <CardAction>- <Button size="sm" variant="outline" onClick={() => setAddOpen(true)}>- <PlusIcon className="size-4" />- {t('admin.tax_identifiers.add_cta')}- </Button>- </CardAction>- )}- </CardHeader>-- {isLoading ? (- <CardContent>- <p className="text-muted-foreground text-sm">{t('admin.common.loading')}</p>- </CardContent>- ) : identifiers.length === 0 ? (- <CardContent>- <p className="text-muted-foreground text-sm">{t('admin.tax_identifiers.empty')}</p>- </CardContent>- ) : (- <CardContent className="flex flex-col gap-3">- {identifiers.map((identifier) => (- <div- key={identifier.id}- className="flex items-start justify-between gap-3 rounded-md border p-3"- >- <div className="flex min-w-0 flex-col gap-1">- <div className="flex flex-wrap items-center gap-2">- <span className="font-medium text-sm">{identifier.value}</span>- <Badge variant="outline">- {t(`admin.tax_identifiers.kinds.${identifier.kind}`, {- defaultValue: identifier.kind,- })}- </Badge>- {identifier.validation_status ? (- <StatusBadge- status={identifier.validation_status}- label={t(- `admin.tax_identifiers.validation_status.${identifier.validation_status}`,- { defaultValue: identifier.validation_status },- )}- />- ) : (- <Badge variant="secondary">- {t('admin.tax_identifiers.validation_status.not_checked')}- </Badge>- )}- </div>- {identifier.validated_at && (- <span className="text-muted-foreground text-xs">- <RelativeTime- iso={identifier.validated_at}- prefix={t('admin.tax_identifiers.checked_prefix')}- />- </span>- )}- {!identifier.validatable && (- <span className="text-muted-foreground text-xs">- {t('admin.tax_identifiers.not_validatable')}- </span>- )}- </div>-- {canEdit && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="icon-xs">- <EllipsisVerticalIcon className="size-4" />- <span className="sr-only">{t('admin.actions.actions_menu')}</span>- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- disabled={!identifier.validatable || mutations.isValidating}- onClick={() => mutations.validate(identifier.id).catch(() => undefined)}- >- <BadgeCheckIcon className="size-4" />- {t('admin.tax_identifiers.validate_action')}- </DropdownMenuItem>- <DropdownMenuItem onClick={() => setEditing(identifier)}>- <PencilIcon className="size-4" />- {t('admin.actions.edit')}- </DropdownMenuItem>- <DropdownMenuItem- variant="destructive"- onClick={() => handleDelete(identifier)}- >- <TrashIcon className="size-4" />- {t('admin.actions.delete')}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}- </div>- ))}- </CardContent>- )}-- {addOpen && (- <TaxIdentifierSheet- open- onOpenChange={setAddOpen}- onSubmit={(params) => mutations.create(params)}- />- )}- {editing && (- <TaxIdentifierSheet- open- identifier={editing}- onOpenChange={(next) => {- if (!next) setEditing(null)- }}- onSubmit={(params) => mutations.update(editing.id, params)}- />- )}- </Card>- )-}--function TaxIdentifierSheet({- open,- onOpenChange,- identifier,- onSubmit,-}: {- open: boolean- onOpenChange: (open: boolean) => void- identifier?: TaxIdentifier- onSubmit: (params: TaxIdentifierParams) => Promise<unknown>-}) {- const { t } = useTranslation()- const form = useForm<TaxIdentifierFormValues>({- // eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(taxIdentifierFormSchema) as any,- defaultValues: TAX_IDENTIFIER_DEFAULTS,- })-- useEffect(() => {- if (open) {- form.reset(- identifier ? { kind: identifier.kind, value: identifier.value } : TAX_IDENTIFIER_DEFAULTS,- )- }- }, [open, identifier, form])-- async function handleSubmit(values: TaxIdentifierFormValues) {- try {- await onSubmit(taxIdentifierValuesToParams(values))- onOpenChange(false)- } catch (err) {- if (!mapSpreeErrorsToForm(err, form.setError)) throw err- }- }-- const { errors } = form.formState-- return (- <Sheet open={open} onOpenChange={onOpenChange}>- <SheetContent>- <SheetHeader>- <SheetTitle>- {identifier- ? t('admin.tax_identifiers.edit_title')- : t('admin.tax_identifiers.add_title')}- </SheetTitle>- <SheetDescription>{t('admin.tax_identifiers.dialog_description')}</SheetDescription>- </SheetHeader>- <form- onSubmit={(event) => {- // This sheet can be rendered inside another form; stopping the- // bubbled submit keeps the outer form from also submitting.- form.handleSubmit(handleSubmit)(event)- event.stopPropagation()- }}- className="flex min-h-0 flex-1 flex-col"- >- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">- <FieldGroup>- {errors.root?.message && (- <p className="text-destructive text-sm" role="alert">- {errors.root.message}- </p>- )}- <Field>- <FieldLabel htmlFor="tax-identifier-kind">- {t('admin.fields.tax_identifier.kind.label')}- </FieldLabel>- {/* A constrained list, not free text: the kind has to match the- key its validator is registered under, and a typo would be- stored and used as entered rather than rejected. */}- <Controller- name="kind"- control={form.control}- render={({ field }) => {- // Combobox rather than Select: this card renders inside a- // page card, and Base UI's Select popup does not survive- // that portal nesting (the country picker below is a- // Combobox for the same reason).- const kindOptions = TAX_IDENTIFIER_KINDS.map((kind) => ({- value: kind,- label: t(`admin.tax_identifiers.kinds.${kind}`, { defaultValue: kind }),- }))- const selected = kindOptions.find((o) => o.value === field.value) ?? null- return (- <Combobox- items={kindOptions}- value={selected}- onValueChange={(option: KindOption | null) =>- field.onChange(option?.value ?? '')- }- itemToStringLabel={(option: KindOption | null) => option?.label ?? ''}- itemToStringValue={(option: KindOption | null) => option?.value ?? ''}- >- <ComboboxInput- id="tax-identifier-kind"- placeholder={t('admin.tax_identifiers.select_kind')}- />- <ComboboxContent>- <ComboboxEmpty>{t('admin.common.no_results')}</ComboboxEmpty>- <ComboboxList>- {(option: KindOption) => (- <ComboboxItem key={option.value} value={option}>- {option.label}- </ComboboxItem>- )}- </ComboboxList>- </ComboboxContent>- </Combobox>- )- }}- />- <FieldDescription>{t('admin.fields.tax_identifier.kind.help')}</FieldDescription>- <FieldError errors={[errors.kind]} />- </Field>-- <Field>- <FieldLabel htmlFor="tax-identifier-value">- {t('admin.fields.tax_identifier.value.label')}- </FieldLabel>- <Input- id="tax-identifier-value"- placeholder={t('admin.fields.tax_identifier.value.placeholder')}- aria-invalid={!!errors.value || undefined}- {...form.register('value')}- />- <FieldError errors={[errors.value]} />- </Field>- </FieldGroup>- </div>- <SheetFooter>- <Button- type="button"- variant="outline"- onClick={() => onOpenChange(false)}- disabled={form.formState.isSubmitting}- >- {t('admin.actions.cancel')}- </Button>- <Button type="submit" disabled={form.formState.isSubmitting}>- {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}- </Button>- </SheetFooter>- </form>- </SheetContent>- </Sheet>+ <SharedTaxIdentifiersCard+ {...props}+ mutations={{ ...mutations, mapErrors: mapSpreeErrorsToForm }}+ />)}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 6a39abd028..320b2c3ea8 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -1990,11 +1990,13 @@"tax_identifier": {"kind": {"help": "نوع هذا الرقم. يجب أن يطابق التحقق المُعد له، لذا فالكتابة الصحيحة مهمة.",- "label": "النوع"+ "label": "النوع",+ "required": "اختر نوع التسجيل أو اكتبه"},"value": {"label": "الرقم",- "placeholder": "DE123456789"+ "placeholder": "DE123456789",+ "required": "أدخل رقم التسجيل"}},"tax_rate": {@@ -4726,7 +4728,7 @@"validation_failed": "تعذر التحقق من الرقم","validation_requested": "جارٍ التحقق من الرقم لدى السجل"},- "not_validatable": "لا يوجد تحقق مُعد لهذا النوع، لذا يُستخدم الرقم كما أُدخل.",+ "not_validatable": "لا يوجد سجل للتحقق من هذا النوع، لذا يُسجَّل الرقم كما أُدخل.","select_kind": "اختر النوع","title": "الرقم الضريبي","validate_action": "التحقق لدى السجل",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 45adad401e..c5f994290c 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -1976,11 +1976,13 @@"tax_identifier": {"kind": {"help": "Um welche Nummer es sich handelt. Sie muss zur eingerichteten Prüfung passen, die Schreibweise ist also wichtig.",- "label": "Art"+ "label": "Art",+ "required": "Registrierungsart wählen oder eingeben"},"value": {"label": "Nummer",- "placeholder": "DE123456789"+ "placeholder": "DE123456789",+ "required": "Registrierungsnummer eingeben"}},"tax_rate": {@@ -4708,7 +4710,7 @@"validation_failed": "Die Nummer konnte nicht geprüft werden","validation_requested": "Die Nummer wird beim Register geprüft"},- "not_validatable": "Für diese Art ist keine Prüfung eingerichtet, die Nummer wird wie eingegeben verwendet.",+ "not_validatable": "Für diese Art gibt es kein Register zum Abgleich, die Nummer wird wie eingegeben erfasst.","select_kind": "Art wählen","title": "Steuernummer","validate_action": "Beim Register prüfen",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex a527e8dee8..a74f1ed7ab 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -1976,11 +1976,13 @@"tax_identifier": {"kind": {"help": "Which registration this is. It has to match the validator registered for it, so spelling matters.",- "label": "Kind"+ "label": "Kind",+ "required": "Choose or type a registration type"},"value": {"label": "Number",- "placeholder": "DE123456789"+ "placeholder": "DE123456789",+ "required": "Enter the registration number"}},"tax_rate": {@@ -4708,7 +4710,7 @@"validation_failed": "Could not check the number","validation_requested": "Checking the number with the registry"},- "not_validatable": "No validator is set up for this kind, so the number is used as entered.",+ "not_validatable": "No registry to check this kind against, so the number is recorded as entered.","select_kind": "Select a kind","title": "Tax registration","validate_action": "Check with registry",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 6d2c20b915..350f62d706 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -1976,11 +1976,13 @@"tax_identifier": {"kind": {"help": "De quel numéro il s'agit. Il doit correspondre à la vérification configurée, l'orthographe compte donc.",- "label": "Type"+ "label": "Type",+ "required": "Choisissez ou saisissez un type d'enregistrement"},"value": {"label": "Numéro",- "placeholder": "FR12345678901"+ "placeholder": "FR12345678901",+ "required": "Saisissez le numéro d'enregistrement"}},"tax_rate": {@@ -4708,7 +4710,7 @@"validation_failed": "Impossible de vérifier le numéro","validation_requested": "Vérification du numéro auprès du registre"},- "not_validatable": "Aucune vérification n'est configurée pour ce type, le numéro est utilisé tel qu'il a été saisi.",+ "not_validatable": "Aucun registre ne permet de vérifier ce type, le numéro est enregistré tel qu'il a été saisi.","select_kind": "Choisir un type","title": "Numéro de TVA","validate_action": "Vérifier auprès du registre",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 95e833919f..2c759b990d 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -1988,11 +1988,13 @@"tax_identifier": {"kind": {"help": "Jaki to numer. Musi odpowiadać skonfigurowanej weryfikacji, więc pisownia ma znaczenie.",- "label": "Rodzaj"+ "label": "Rodzaj",+ "required": "Wybierz lub wpisz rodzaj rejestracji"},"value": {"label": "Numer",- "placeholder": "PL1234567890"+ "placeholder": "PL1234567890",+ "required": "Podaj numer rejestracyjny"}},"tax_rate": {@@ -4760,7 +4762,7 @@"validation_failed": "Nie udało się sprawdzić numeru","validation_requested": "Trwa sprawdzanie numeru w rejestrze"},- "not_validatable": "Dla tego rodzaju nie skonfigurowano weryfikacji, numer jest używany tak, jak go wpisano.",+ "not_validatable": "Dla tego rodzaju nie ma rejestru do sprawdzenia, numer jest zapisywany tak, jak go wpisano.","select_kind": "Wybierz rodzaj","title": "Numer podatkowy","validate_action": "Sprawdź w rejestrze",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 1de1a9d496..30f8ea9e98 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -1972,11 +1972,13 @@"tax_identifier": {"kind": {"help": "该号码的类型。必须与配置的校验方式一致,因此拼写很重要。",- "label": "类型"+ "label": "类型",+ "required": "请选择或输入登记类型"},"value": {"label": "号码",- "placeholder": "DE123456789"+ "placeholder": "DE123456789",+ "required": "请输入登记号码"}},"tax_rate": {@@ -4700,7 +4702,7 @@"validation_failed": "无法核验该号码","validation_requested": "正在向登记机构核验该号码"},- "not_validatable": "该类型未配置校验方式,将按填写的内容直接使用。",+ "not_validatable": "该类型没有可核对的登记机构,号码将按填写的内容记录。","select_kind": "选择类型","title": "税务登记号","validate_action": "向登记机构核验",diff --git a/packages/seller-dashboard/src/components/seller-business-card.tsx b/packages/seller-dashboard/src/components/seller-business-card.tsxindex a1a5414a47..7322b32d47 100644--- a/packages/seller-dashboard/src/components/seller-business-card.tsx+++ b/packages/seller-dashboard/src/components/seller-business-card.tsx@@ -23,17 +23,19 @@ import { useState } from 'react'import { useTranslation } from 'react-i18next'import { sellerClient } from '../api-client'-/** The registration kind this panel collects. */-const VAT_KIND = 'eu_vat'+function errorMessage(error: unknown, fallback: string) {+ return error instanceof Error && error.message ? error.message : fallback+}/**- * The business behind the seller, as the marketplace's commission invoice- * must address it: legal name, registration number, and the VAT number that- * decides whether that invoice carries VAT or is reverse-charged.+ * The business behind the seller, as the marketplace's commission invoice must+ * address it: the legal name and registration number.+ *+ * The tax registrations sit in their own card beside this one, on the same+ * panel a company's are managed from — a business trading in several regimes+ * holds a registration in each, so they are a collection rather than a field.*- * Separate from the billing address, which is only where post goes. Most of- * what an invoice needs is not an address, and putting a VAT number in an- * address form is what makes it get lost.+ * Separate from the billing address, which is only where post goes.*/export function SellerBusinessCard({ profile }: { profile: Profile }) {const { t } = useTranslation()@@ -41,19 +43,33 @@ export function SellerBusinessCard({ profile }: { profile: Profile }) {const queryClient = useQueryClient()const [editing, setEditing] = useState(false)- const vat = profile.tax_identifiers?.find((identifier) => identifier.kind === VAT_KIND)-const [legalName, setLegalName] = useState(profile.legal_name ?? '')const [registrationNumber, setRegistrationNumber] = useState(profile.registration_number ?? '')- const [vatNumber, setVatNumber] = useState(vat?.value ?? '')+ // Shown in the sheet rather than as a toast: the toast stack deliberately+ // sits below the sheet overlay, so a rejection raised here would be hidden+ // behind the very form that caused it.+ const [formError, setFormError] = useState<string | null>(null)++ // Opening the sheet is the seller starting over, so it shows what is on file+ // rather than whatever they last typed — the card never remounts, so an+ // abandoned edit would otherwise outlive the sheet that made it.+ function setSheetOpen(open: boolean) {+ if (open) {+ setLegalName(profile.legal_name ?? '')+ setRegistrationNumber(profile.registration_number ?? '')+ setFormError(null)+ }+ setEditing(open)+ }const save = useMutation({- mutationFn: () =>- sellerClient().profile.update({+ mutationFn: () => {+ setFormError(null)+ return sellerClient().profile.update({legal_name: legalName || null,registration_number: registrationNumber || null,- tax_identifier: { kind: VAT_KIND, value: vatNumber },- }),+ })+ },onSuccess: (updated) => {queryClient.setQueryData(['seller', sellerId, 'profile'], updated)// A checklist kind may read these, so it has to re-evaluate.@@ -61,17 +77,12 @@ export function SellerBusinessCard({ profile }: { profile: Profile }) {setEditing(false)toastManager.add({ type: 'success', title: t('profile.saved') })},- onError: (err) =>- toastManager.add({- type: 'error',- title: err instanceof Error ? err.message : t('common.error'),- }),+ onError: (err) => setFormError(errorMessage(err, t('common.error'))),})const rows = [{ label: t('profile.legal_name'), value: profile.legal_name },{ label: t('profile.registration_number'), value: profile.registration_number },- { label: t('profile.vat_number'), value: vat?.value },]return (@@ -80,7 +91,7 @@ export function SellerBusinessCard({ profile }: { profile: Profile }) {<CardHeader><CardTitle>{t('profile.business_details')}</CardTitle><CardAction>- <Button variant="outline" size="sm" onClick={() => setEditing(true)}>+ <Button variant="outline" size="sm" onClick={() => setSheetOpen(true)}><PencilIcon className="size-4" />{t('profile.edit')}</Button>@@ -93,24 +104,20 @@ export function SellerBusinessCard({ profile }: { profile: Profile }) {<span className="text-right">{row.value || '—'}</span></div>))}- {/* A number the seller believes is on file but which came back- unverified is worth them knowing about. */}- {vat?.validation_status && vat.validation_status !== 'verified' && (- <p className="text-muted-foreground text-xs">- {t(`profile.vat_status.${vat.validation_status}`, {- defaultValue: vat.validation_status,- })}- </p>- )}</CardContent></Card>- <Sheet open={editing} onOpenChange={setEditing}>+ <Sheet open={editing} onOpenChange={setSheetOpen}><SheetContent><SheetHeader><SheetTitle>{t('profile.business_details')}</SheetTitle></SheetHeader><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">+ {formError && (+ <p role="alert" className="text-destructive text-sm">+ {formError}+ </p>+ )}<Field><FieldLabel htmlFor="legal-name">{t('profile.legal_name')}</FieldLabel><Input@@ -129,17 +136,9 @@ export function SellerBusinessCard({ profile }: { profile: Profile }) {onChange={(event) => setRegistrationNumber(event.target.value)}/></Field>- <Field>- <FieldLabel htmlFor="vat-number">{t('profile.vat_number')}</FieldLabel>- <Input- id="vat-number"- value={vatNumber}- onChange={(event) => setVatNumber(event.target.value)}- />- </Field></div><SheetFooter>- <Button variant="outline" size="sm" onClick={() => setEditing(false)}>+ <Button variant="outline" size="sm" onClick={() => setSheetOpen(false)}>{t('common.cancel')}</Button><Button size="sm" disabled={save.isPending} onClick={() => save.mutate()}>diff --git a/packages/seller-dashboard/src/components/seller-tax-identifiers-card.tsx b/packages/seller-dashboard/src/components/seller-tax-identifiers-card.tsxnew file mode 100644index 0000000000..b6933debed--- /dev/null+++ b/packages/seller-dashboard/src/components/seller-tax-identifiers-card.tsx@@ -0,0 +1,63 @@+import { mapSpreeErrorsToForm } from '@spree/dashboard-core'+import { TaxIdentifiersCard } from '@spree/dashboard-ui'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useParams } from '@tanstack/react-router'+import { sellerClient } from '../api-client'++/**+ * The seller's own tax registrations, rendered by the same panel a company's+ * are managed from: a seller is a business like any other, and two surfaces+ * for one job is how they come to behave differently.+ */+export function SellerTaxIdentifiersCard() {+ const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })+ const queryClient = useQueryClient()+ const queryKey = ['seller', sellerId, 'tax_identifiers']++ const { data, isLoading } = useQuery({+ queryKey,+ queryFn: () => sellerClient().taxIdentifiers.list(),+ })++ // A registration can satisfy an onboarding requirement, so the checklist has+ // to re-evaluate whenever one changes.+ function refresh() {+ void queryClient.invalidateQueries({ queryKey })+ void queryClient.invalidateQueries({ queryKey: ['seller', sellerId, 'onboarding'] })+ }++ const create = useMutation({+ mutationFn: (params: { kind: string; value: string }) =>+ sellerClient().taxIdentifiers.create(params),+ onSuccess: refresh,+ })+ const update = useMutation({+ mutationFn: ({ id, params }: { id: string; params: { kind: string; value: string } }) =>+ sellerClient().taxIdentifiers.update(id, params),+ onSuccess: refresh,+ })+ const remove = useMutation({+ mutationFn: (id: string) => sellerClient().taxIdentifiers.remove(id),+ onSuccess: refresh,+ })+ const validate = useMutation({+ mutationFn: (id: string) => sellerClient().taxIdentifiers.validate(id),+ onSuccess: refresh,+ })++ return (+ <TaxIdentifiersCard+ identifiers={data?.data ?? []}+ isLoading={isLoading}+ canEdit+ mutations={{+ create: (params) => create.mutateAsync(params),+ update: (id, params) => update.mutateAsync({ id, params }),+ remove: (id) => remove.mutateAsync(id),+ validate: (id) => validate.mutateAsync(id),+ isValidating: validate.isPending,+ mapErrors: mapSpreeErrorsToForm,+ }}+ />+ )+}diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.jsonindex bbe815e838..3d667f55c6 100644--- a/packages/seller-dashboard/src/locales/en.json+++ b/packages/seller-dashboard/src/locales/en.json@@ -13,12 +13,76 @@"title": "Join the team"},"admin": {+ "actions": {+ "actions_menu": "Actions",+ "cancel": "Cancel",+ "delete": "Delete",+ "edit": "Edit",+ "save": "Save",+ "saving": "Saving…"+ },+ "common": {+ "loading": "Loading…",+ "no_results": "No results"+ },"components": {"export_button": {"all": {"description": "Ignore filters and export all of your records."}}+ },+ "fields": {+ "tax_identifier": {+ "kind": {+ "help": "Which registration this is. It has to match the validator registered for it, so spelling matters.",+ "label": "Kind",+ "required": "Choose or type a registration type"+ },+ "value": {+ "label": "Number",+ "placeholder": "DE123456789",+ "required": "Enter the registration number"+ }+ }+ },+ "tax_identifiers": {+ "add_cta": "Add registration",+ "add_title": "Add tax registration",+ "checked_prefix": "Checked",+ "delete_confirm": {+ "message": "{{value}} will be removed. Orders already placed keep the number they were invoiced with.",+ "title": "Delete this registration?"+ },+ "dialog_description": "The VAT or business number that appears on invoices. It is what makes EU B2B reverse charge possible.",+ "edit_title": "Edit tax registration",+ "empty": "No tax registration on file",+ "kinds": {+ "au_abn": "Australian Business Number",+ "ch_vat": "Swiss VAT",+ "eu_vat": "EU VAT",+ "gb_vat": "UK VAT",+ "us_ein": "US EIN"+ },+ "messages": {+ "created": "Registration added",+ "deleted": "Registration deleted",+ "updated": "Registration updated",+ "validation_failed": "Could not check the number",+ "validation_requested": "Checking the number with the registry"+ },+ "not_validatable": "No registry to check this kind against, so the number is recorded as entered.",+ "select_kind": "Select a kind",+ "title": "Tax registration",+ "validate_action": "Check with registry",+ "validation_status": {+ "not_checked": "Not checked",+ "pending": "Checking",+ "unavailable": "Registry unavailable",+ "unsupported": "Cannot be checked",+ "unverified": "Not valid",+ "verified": "Verified"+ }}},"app": {@@ -30,6 +94,7 @@"delete": "Delete","error": "Something went wrong.","loading": "Loading…",+ "no_results": "No results","remove": "Remove","retry": "Try again","save": "Save",@@ -88,6 +153,7 @@"confirm": "Confirm","document_help": "PDF or an image of the document.","document_label": "Document",+ "done": "This one is done.","go": "Go there","note_placeholder": "Anything the marketplace should know (optional)","optional": "Optional",@@ -210,33 +276,33 @@"details": "Details","empty": "No products yet. Add one to start selling.","fields": {+ "alt": "Alt text",+ "categories": "Categories",+ "categories_placeholder": "Search categories…",+ "collections": "Collections",+ "collections_placeholder": "Search collections…",+ "country_of_origin": "Country of origin",+ "country_of_origin_placeholder": "e.g. PL","description": "Description",+ "hs_code": "HS code",+ "hs_code_placeholder": "e.g. 9405.20",+ "meta_description": "Meta description",+ "meta_keywords": "Meta keywords",+ "meta_title": "Page title","name": "Name",+ "option": "Option",+ "option_name": "Option",+ "option_value": "Value","price": "Price",+ "price_in": "Price ({{currency}})","price_placeholder": "Leave blank to keep the current price",- "status": "Status",- "slug": "URL handle",- "meta_title": "Page title",- "meta_description": "Meta description",- "meta_keywords": "Meta keywords","product_type": "Product type","product_type_placeholder": "Choose a type",- "alt": "Alt text","sku": "SKU",+ "slug": "URL handle",+ "status": "Status","stock": "Stock",- "option": "Option",- "option_name": "Option",- "option_value": "Value",- "price_in": "Price ({{currency}})",- "weight": "Weight",- "hs_code": "HS code",- "hs_code_placeholder": "e.g. 9405.20",- "country_of_origin": "Country of origin",- "country_of_origin_placeholder": "e.g. PL",- "categories": "Categories",- "categories_placeholder": "Search categories…",- "collections": "Collections",- "collections_placeholder": "Search collections…"+ "weight": "Weight"},"media": "Media","media_remove_confirm_description": "It comes off the product when you save.",@@ -250,11 +316,11 @@"seo": "Search engine listing","shipping": "Shipping and customs","status_help": {+ "active": "On sale and visible to shoppers.",+ "archived": "Off sale and out of your active listings.","draft": "Only you can see this. Submit it when you are ready for the marketplace to review it.","proposed": "Waiting for the marketplace to review it. You can still make changes.",- "active": "On sale and visible to shoppers.",- "rejected": "The marketplace asked for changes. Edit it, then submit it again.",- "archived": "Off sale and out of your active listings."+ "rejected": "The marketplace asked for changes. Edit it, then submit it again."},"status_updated": "Status updated","statuses": {@@ -307,6 +373,7 @@"section_contact": "Contact","section_settlement": "Payouts and tax","section_standing": "Standing",+ "select_tax_identifier_kind": "Select or type a registration type","status_help": {"approved": "You are approved and can sell on this marketplace.","canceled": "This seller account is closed.",@@ -318,6 +385,14 @@"suspended": "Selling is paused. Contact the marketplace to find out more."},"subtitle": "How your storefront presents you, and how the marketplace reaches you.",+ "tax_identifier_kind": "Registration type",+ "tax_identifier_kinds": {+ "au_abn": "Australian Business Number",+ "ch_vat": "Swiss VAT",+ "eu_vat": "EU VAT",+ "gb_vat": "UK VAT",+ "us_ein": "US EIN"+ },"tax_remittance": "Tax remitted by","team_count": "Team members","vat_number": "VAT number",diff --git a/packages/seller-dashboard/src/pages/profile.tsx b/packages/seller-dashboard/src/pages/profile.tsxindex bac6251dcb..1fcd0f7f7b 100644--- a/packages/seller-dashboard/src/pages/profile.tsx+++ b/packages/seller-dashboard/src/pages/profile.tsx@@ -35,6 +35,7 @@ import { CenteredMessage } from '../components/centered-message'import { SellerAddressCard } from '../components/seller-address-card'import { SellerBusinessCard } from '../components/seller-business-card'import { SellerReturnsLocationCard } from '../components/seller-returns-location-card'+import { SellerTaxIdentifiersCard } from '../components/seller-tax-identifiers-card'interface ProfileValues {name: string@@ -90,6 +91,7 @@ export function ProfilePage() {<AtAGlanceCard profile={profile} teamCount={team?.data?.length} /><ContactCard profile={profile} onEdit={() => setEditing(true)} /><SellerBusinessCard profile={profile} />+ <SellerTaxIdentifiersCard /><SellerAddressCard profile={profile} /><SellerReturnsLocationCard /><SettlementCard profile={profile} />diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.tsindex 88ec9555e9..94a7b155f0 100644--- a/packages/seller-sdk/src/seller-client.ts+++ b/packages/seller-sdk/src/seller-client.ts@@ -15,6 +15,7 @@ import type {RequirementSubmission,SellerSummary,StockLocation,+ TaxIdentifier,TeamMember,} from './types'@@ -141,6 +142,39 @@ export class SellerClient {this.request<Profile>('PATCH', '/profile', { ...options, body: params }),}+ /**+ * The seller's own tax registrations — the numbers the marketplace's+ * commission invoice is made out to. A collection, like a company's: a+ * business trading in several regimes holds a registration in each.+ */+ readonly taxIdentifiers = {+ list: (options?: RequestOptions): Promise<{ data: TaxIdentifier[] }> =>+ this.request<{ data: TaxIdentifier[] }>('GET', '/tax_identifiers', options),++ create: (params: SellerTaxIdentifierParams, options?: RequestOptions): Promise<TaxIdentifier> =>+ this.request<TaxIdentifier>('POST', '/tax_identifiers', { ...options, body: params }),++ update: (+ id: string,+ params: SellerTaxIdentifierParams,+ options?: RequestOptions,+ ): Promise<TaxIdentifier> =>+ this.request<TaxIdentifier>('PATCH', `/tax_identifiers/${id}`, {+ ...options,+ body: params,+ }),++ remove: (id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>('DELETE', `/tax_identifiers/${id}`, options),++ /**+ * Asks the registry whether the number is still registered. A verdict+ * answers "valid now", so a number verified last year may have lapsed.+ */+ validate: (id: string, options?: RequestOptions): Promise<TaxIdentifier> =>+ this.request<TaxIdentifier>('POST', `/tax_identifiers/${id}/validate`, options),+ }+/** Who runs this seller. */readonly team = {list: (options?: RequestOptions): Promise<{ data: TeamMember[] }> =>@@ -634,6 +668,12 @@ export interface SellerExportCreateParams {results_url?: string}+/** What a seller sends when recording a registration. */+export interface SellerTaxIdentifierParams {+ kind: string+ value: string+}+/** A country as the address form needs it. */export interface SellerCountry {iso: string@@ -793,7 +833,6 @@ export interface ProfileUpdateParams {* the number, and an empty value removes it. A changed number drops its* validation verdict, since that answer was about the old one.*/- tax_identifier?: { kind: string; value: string }billing_address?: SellerAddressParamsreturns_address?: SellerAddressParams/**diff --git a/packages/seller-sdk/src/types/generated/Profile.ts b/packages/seller-sdk/src/types/generated/Profile.tsindex f3a231bd1b..6b3cc3cbe7 100644--- a/packages/seller-sdk/src/types/generated/Profile.ts+++ b/packages/seller-sdk/src/types/generated/Profile.ts@@ -1,7 +1,7 @@-// Typelizer digest aa10dfb2e93b7376941d10745f2c3df9+// Typelizer digest 02820f8dc724a065c976137144085bbd//// DO NOT MODIFY: This file was automatically generated by Typelizer.-import type {Policy, TaxIdentifier, Address} from '@/types'+import type {Policy, Address} from '@/types'type Profile = {id: string;@@ -29,7 +29,6 @@ type Profile = {default_currency: string;supported_currencies: Array<string>;products_count: number;- tax_identifiers: Array<TaxIdentifier>;billing_address?: Address;returns_address?: Address;}diff --git a/spree/api/app/controllers/concerns/spree/api/v3/tax_identifier_validation.rb b/spree/api/app/controllers/concerns/spree/api/v3/tax_identifier_validation.rbnew file mode 100644index 0000000000..2e460d61f1--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/tax_identifier_validation.rb@@ -0,0 +1,41 @@+module Spree+ module Api+ module V3+ # The re-check action, shared by every surface where a registration is+ # managed: nested under a customer, under a company, and the seller's+ # own panel.+ #+ # Separate from the number-changed path, which the model stamps and a+ # subscriber queues. This is staff asking "is it still valid now" — a+ # number verified last year may have been deregistered since — so it+ # queues a check without the number having changed.+ module TaxIdentifierValidation+ extend ActiveSupport::Concern++ def validate+ authorize_resource!(@resource, :update)++ # A kind can be format-checked here and still have no registry to+ # ask — core ships exactly that for EU VAT — so the message says+ # what is missing rather than claiming nothing is registered.+ unless @resource.validatable?+ render_error(+ code: 'tax_id_not_validatable',+ message: "No registry validator is installed for tax identifier kind '#{@resource.kind}'",+ status: :unprocessable_content+ )+ return+ end++ # Marked pending before the job is queued, not after: the job can+ # finish first, and writing 'pending' afterwards would bury the+ # verdict it just recorded.+ @resource.update_columns(validation_status: 'pending', validated_at: nil, updated_at: Time.current)+ Spree::TaxIdentifiers::ValidateJob.perform_later(@resource.id)++ render json: serialize_resource(@resource.reload), status: :accepted+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/companies/tax_identifiers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies/tax_identifiers_controller.rbindex e598f28a7f..3ba6ea0978 100644--- a/spree/api/app/controllers/spree/api/v3/admin/companies/tax_identifiers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/companies/tax_identifiers_controller.rb@@ -10,7 +10,7 @@ module Spree# re-validation: a registry answers only "valid now", so a number# verified last year may have been deregistered since.class TaxIdentifiersController < BaseController- include Spree::Api::V3::Admin::Concerns::TaxIdentifierValidation+ include Spree::Api::V3::TaxIdentifierValidationbefore_action :authorize_parent_access!# Re-declaring the filter replaces the inherited options, so thediff --git a/spree/api/app/controllers/spree/api/v3/admin/concerns/tax_identifier_validation.rb b/spree/api/app/controllers/spree/api/v3/admin/concerns/tax_identifier_validation.rbdeleted file mode 100644index 24b8bca5cf..0000000000--- a/spree/api/app/controllers/spree/api/v3/admin/concerns/tax_identifier_validation.rb+++ /dev/null@@ -1,41 +0,0 @@-module Spree- module Api- module V3- module Admin- module Concerns- # The re-check action, shared by the two places a registration is- # managed: nested under a customer, and nested under a company.- #- # Separate from the number-changed path, which the model stamps and a- # subscriber queues. This is staff asking "is it still valid now" — a- # number verified last year may have been deregistered since — so it- # queues a check without the number having changed.- module TaxIdentifierValidation- extend ActiveSupport::Concern-- def validate- authorize_resource!(@resource, :update)-- unless @resource.validatable?- render_error(- code: 'tax_id_not_validatable',- message: "No validator is registered for tax identifier kind '#{@resource.kind}'",- status: :unprocessable_content- )- return- end-- # Marked pending before the job is queued, not after: the job can- # finish first, and writing 'pending' afterwards would bury the- # verdict it just recorded.- @resource.update_columns(validation_status: 'pending', validated_at: nil, updated_at: Time.current)- Spree::TaxIdentifiers::ValidateJob.perform_later(@resource.id)-- render json: serialize_resource(@resource.reload), status: :accepted- end- end- end- end- end- end-enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/tax_identifiers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/tax_identifiers_controller.rbindex c558f96581..aae4989254 100644--- a/spree/api/app/controllers/spree/api/v3/admin/customers/tax_identifiers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/tax_identifiers_controller.rb@@ -6,7 +6,7 @@ module Spreeclass TaxIdentifiersController < BaseControllerscoped_resource :customers- include Spree::Api::V3::Admin::Concerns::TaxIdentifierValidation+ include Spree::Api::V3::TaxIdentifierValidation# Re-declaring the filter replaces the inherited options, so the# standard actions have to be listed alongside the custom one.diff --git a/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rbindex c603706241..a02c1f2493 100644--- a/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb@@ -36,14 +36,11 @@ module Spreerequested_custom_fields(attributes.delete(:custom_fields_attributes))end- tax_identifier = attributes.delete(:tax_identifier)+ current_seller.update!(attributes)- if current_seller.update(attributes)- upsert_tax_identifier(tax_identifier) if tax_identifier.present?- render json: serialize_seller- else- render_validation_error(current_seller.errors)- end+ render json: serialize_seller+ rescue ActiveRecord::RecordInvalid => error+ render_validation_error(error.record.errors)endprotected@@ -83,16 +80,6 @@ module Spree# A changed number drops its verdict — the validator's answer was# about the old one, and carrying it over would show a number as# verified that nobody has checked.- def upsert_tax_identifier(attributes)- kind = attributes[:kind].presence- return if kind.blank?-- value = attributes[:value]- return current_seller.tax_identifiers.find_by(kind: kind)&.destroy if value.blank?-- current_seller.tax_identifiers.find_or_initialize_by(kind: kind).update(value: value)- end-# Narrowed to the definitions this marketplace's onboarding actually# asks this seller for.#@@ -121,7 +108,6 @@ module Spreeparams.permit(:name, :contact_email, :billing_email, :about,:legal_name, :registration_number,:logo, :square_logo, :cover_photo,- tax_identifier: [:kind, :value],billing_address: Spree::Api::V3::AddressParams::ADDRESS_KEYS,custom_fields: [:id, :custom_field_definition_id, :value,{ value: [] }, { value: {} }])diff --git a/spree/api/app/controllers/spree/api/v3/seller/tax_identifiers_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/tax_identifiers_controller.rbnew file mode 100644index 0000000000..4c438f4b8e--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/seller/tax_identifiers_controller.rb@@ -0,0 +1,48 @@+module Spree+ module Api+ module V3+ module Seller+ # The seller's own tax registrations — the numbers the marketplace's+ # commission invoice is made out to, and what makes EU reverse charge+ # on that fee possible.+ #+ # A collection rather than a single field, for the same reason a+ # company's is: a business trading in more than one regime holds a+ # registration in each, and they are not alternatives. One per kind,+ # which the model enforces.+ #+ # Rooted in `current_seller.tax_identifiers`, so an id belonging to+ # another seller is a 404.+ class TaxIdentifiersController < Seller::ResourceController+ include Spree::Api::V3::TaxIdentifierValidation++ # Part of the seller's own identity, like the legal name and billing+ # address the profile carries — not a store-wide setting.+ scoped_resource :seller_profile++ # Re-declaring the filter replaces the inherited options, so the+ # standard actions have to be listed alongside the custom one.+ before_action :set_resource, only: [:show, :update, :destroy, :validate]++ protected++ def model_class+ Spree::TaxIdentifier+ end++ def serializer_class+ Spree.api.seller_tax_identifier_serializer+ end++ def seller_association+ :tax_identifiers+ end++ def permitted_params+ params.permit(:kind, :value)+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rbindex 193f77d7f2..810b456651 100644--- a/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb@@ -61,9 +61,6 @@ module Spreeseller.products.countend- many :tax_identifiers,- resource: proc { Spree.api.seller_tax_identifier_serializer }-one :billing_address,resource: proc { Spree.api.address_serializer },if: proc { |seller| seller.billing_address.present? }diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex bda1f459b6..b15aa9e1a7 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -753,6 +753,15 @@ Spree::Core::Engine.add_routes do# Singular: the seller in play is always `current_seller`.resource :profile, only: [:show, :update], controller: 'profile'+ # The seller's own registrations — a collection, like a company's: a+ # business trading in several regimes holds one in each.+ resources :tax_identifiers, only: [:index, :create, :update, :destroy],+ controller: 'tax_identifiers' do+ member do+ post :validate+ end+ end+resources :team, only: [:index, :create, :destroy], controller: 'team'# Creating an invitation is hiring, so it lives on `team`; chasing ordiff --git a/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_identifiers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_identifiers_controller_spec.rbindex 9a584db632..c068529cca 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_identifiers_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_identifiers_controller_spec.rb@@ -6,12 +6,13 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxIdentifiersController, type:include_context 'API v3 Admin authenticated'let!(:company) { create(:company, store: store) }+ let(:vat_number) { eu_vat_number(0) }before { request.headers.merge!(headers) }describe 'GET #index' doit 'lists the business registrations' do- create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE123456789')+ create(:tax_identifier, owner: company, kind: 'eu_vat', value: vat_number)get :index, params: { company_id: company.prefixed_id }, as: :json@@ -19,7 +20,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxIdentifiersController, type:row = json_response['data'].firstexpect(row['id']).to start_with('txi_')expect(row['kind']).to eq('eu_vat')- expect(row['value']).to eq('DE123456789')+ expect(row['value']).to eq(vat_number)endit '404s under another store company' do@@ -33,21 +34,22 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxIdentifiersController, type:# Phase 3 made a business registration outrank the buyer's; without this# endpoint that behaviour was only reachable from a console.it 'registers a number against the business' do- post :create, params: { company_id: company.prefixed_id, kind: 'eu_vat', value: 'DE123456789' }, as: :json+ post :create, params: { company_id: company.prefixed_id, kind: 'eu_vat', value: vat_number }, as: :jsonexpect(response).to have_http_status(:created)- expect(json_response['value']).to eq('DE123456789')+ expect(json_response['value']).to eq(vat_number)expect(company.tax_identifiers.sole.kind).to eq('eu_vat')endit 'takes effect on a sale for that business' do- create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE222222222')+ company_vat_number = eu_vat_number(1)+ create(:tax_identifier, owner: company, kind: 'eu_vat', value: company_vat_number)customer = create(:customer)create(:company_membership, company: company, customer: customer)- create(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE111111111')+ create(:tax_identifier, owner: customer, kind: 'eu_vat', value: eu_vat_number(2))cart = create(:cart, store: store, customer: customer, company: company)- expect(cart.resolved_tax_identifier.value).to eq('DE222222222')+ expect(cart.resolved_tax_identifier.value).to eq(company_vat_number)end# The division's purchases read their registration through the legal@@ -55,15 +57,16 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxIdentifiersController, type:it 'refuses a registration on a division node' dodivision = create(:company, store: store, kind: 'division', parent: company)- post :create, params: { company_id: division.prefixed_id, kind: 'eu_vat', value: 'DE123456789' }, as: :json+ post :create, params: { company_id: division.prefixed_id, kind: 'eu_vat', value: vat_number }, as: :jsonexpect(response).to have_http_status(:unprocessable_content)endit 'holds one registration per kind' do- create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE123456789')+ create(:tax_identifier, owner: company, kind: 'eu_vat')- post :create, params: { company_id: company.prefixed_id, kind: 'eu_vat', value: 'DE999999999' }, as: :json+ post :create, params: { company_id: company.prefixed_id, kind: 'eu_vat',+ value: eu_vat_number(1) }, as: :jsonexpect(response).to have_http_status(:unprocessable_content)end@@ -81,24 +84,25 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxIdentifiersController, type:def self.valid_format?(value) = value.to_s.start_with?('DE')endstub_const('SpecEuVatValidator', validator)- Spree.tax_identifier_validators['eu_vat'] = 'SpecEuVatValidator'- post :create, params: { company_id: company.prefixed_id, kind: 'eu_vat', value: '!!' }, as: :json+ with_tax_identifier_validator('eu_vat', 'SpecEuVatValidator') do+ post :create, params: { company_id: company.prefixed_id, kind: 'eu_vat', value: '!!' }, as: :json+ endexpect(response).to have_http_status(:unprocessable_content)- ensure- Spree.tax_identifier_validators.delete('eu_vat')endenddescribe 'PATCH #update' doit 'corrects the number' do- identifier = create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE123456789')+ corrected_vat_number = eu_vat_number(1)+ identifier = create(:tax_identifier, owner: company, kind: 'eu_vat', value: vat_number)- patch :update, params: { company_id: company.prefixed_id, id: identifier.prefixed_id, value: 'DE987654321' }, as: :json+ patch :update, params: { company_id: company.prefixed_id, id: identifier.prefixed_id,+ value: corrected_vat_number }, as: :jsonexpect(response).to have_http_status(:ok)- expect(identifier.reload.value).to eq('DE987654321')+ expect(identifier.reload.value).to eq(corrected_vat_number)endenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/customers/tax_identifiers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/customers/tax_identifiers_controller_spec.rbindex bbd5f35cb7..47beea8fd3 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/customers/tax_identifiers_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/customers/tax_identifiers_controller_spec.rb@@ -6,7 +6,8 @@ RSpec.describe Spree::Api::V3::Admin::Customers::TaxIdentifiersController, type:include_context 'API v3 Admin authenticated'let!(:customer) { create(:user) }- let!(:tax_identifier) { create(:tax_identifier, :verified, owner: customer, kind: 'eu_vat', value: 'DE123456789') }+ let(:vat_number) { eu_vat_number(0) }+ let!(:tax_identifier) { create(:tax_identifier, :verified, owner: customer, kind: 'eu_vat', value: vat_number) }before { request.headers.merge!(headers) }@@ -17,7 +18,7 @@ RSpec.describe Spree::Api::V3::Admin::Customers::TaxIdentifiersController, type:expect(response).to have_http_status(:ok)row = json_response['data'].firstexpect(row['kind']).to eq('eu_vat')- expect(row['value']).to eq('DE123456789')+ expect(row['value']).to eq(vat_number)expect(row['validation_status']).to eq('verified')expect(row['validation_evidence']['registry']).to eq('vies')expect(row['customer_id']).to eq(customer.prefixed_id)@@ -49,12 +50,15 @@ RSpec.describe Spree::Api::V3::Admin::Customers::TaxIdentifiersController, type:enddescribe 'PATCH #update' do+ let(:corrected_vat_number) { eu_vat_number(1) }+it 'updates the number' do- patch :update, params: { customer_id: customer.prefixed_id, id: tax_identifier.prefixed_id, value: 'DE987654321' },+ patch :update, params: { customer_id: customer.prefixed_id, id: tax_identifier.prefixed_id,+ value: corrected_vat_number },as: :jsonexpect(response).to have_http_status(:ok)- expect(tax_identifier.reload.value).to eq('DE987654321')+ expect(tax_identifier.reload.value).to eq(corrected_vat_number)endend@@ -70,10 +74,7 @@ RSpec.describe Spree::Api::V3::Admin::Customers::TaxIdentifiersController, type:describe 'POST #validate' docontext 'when a validator is registered for the kind' doaround do |example|- Spree.tax_identifier_validators['eu_vat'] = 'Spree::TaxIdentifiers::Validator::Base'- example.run- ensure- Spree.tax_identifier_validators.delete('eu_vat')+ with_tax_identifier_validator('eu_vat', 'Spree::TaxIdentifiers::Validator::Base') { example.run }endit 'queues a fresh registry check' dodiff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_identifiers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_identifiers_controller_spec.rbindex 577ae91a07..49b406b234 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_identifiers_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_identifiers_controller_spec.rb@@ -6,18 +6,19 @@ RSpec.describe Spree::Api::V3::Admin::Orders::TaxIdentifiersController, type: :cinclude_context 'API v3 Admin authenticated'let!(:order) { create(:completed_order_with_totals, store: store) }+ let(:vat_number) { eu_vat_number(0) }before { request.headers.merge!(headers) }describe 'GET #show' doit 'returns the snapshot with the verdict and the evidence behind it' do- create(:tax_identifier, :on_order, :verified, owner: order, kind: 'eu_vat', value: 'DE123456789')+ create(:tax_identifier, :on_order, :verified, owner: order, kind: 'eu_vat', value: vat_number)get :show, params: { order_id: order.prefixed_id }, as: :jsonexpect(response).to have_http_status(:ok)expect(json_response['kind']).to eq('eu_vat')- expect(json_response['value']).to eq('DE123456789')+ expect(json_response['value']).to eq(vat_number)# The fields the store serializer withholds — why staff come here.expect(json_response['validation_status']).to eq('verified')expect(json_response['validation_evidence']['registry']).to eq('vies')@@ -43,7 +44,8 @@ RSpec.describe Spree::Api::V3::Admin::Orders::TaxIdentifiersController, type: :cit 'does not route a write — the snapshot is what the invoice says' doexpect {- patch :update, params: { order_id: order.prefixed_id, value: 'DE999999999' }, as: :json+ patch :update, params: { order_id: order.prefixed_id, value: eu_vat_number(1) },+ as: :json}.to raise_error(ActionController::UrlGenerationError)endenddiff --git a/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rbindex e3a2b4cb86..aff3a1eb5b 100644--- a/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb@@ -228,42 +228,6 @@ RSpec.describe Spree::Api::V3::Seller::ProfileController, type: :controller doexpect(seller.registration_number).to eq('01234567')end- it 'records a tax registration' do- patch :update, params: { tax_identifier: { kind: 'eu_vat', value: 'GB123456789' } }, as: :json-- expect(response).to have_http_status(:ok)- identifier = seller.reload.tax_identifiers.find_by(kind: 'eu_vat')- expect(identifier.value).to eq('GB123456789')- end-- # One per kind, so correcting the number replaces it rather than stacking- # a second row the model would refuse.- it 'corrects a registration rather than adding a second' do- patch :update, params: { tax_identifier: { kind: 'eu_vat', value: 'GB111' } }, as: :json- patch :update, params: { tax_identifier: { kind: 'eu_vat', value: 'GB222' } }, as: :json-- expect(response).to have_http_status(:ok)- identifiers = seller.reload.tax_identifiers.where(kind: 'eu_vat')- expect(identifiers.count).to eq(1)- expect(identifiers.first.value).to eq('GB222')- end-- it 'removes it when the seller clears the number' do- patch :update, params: { tax_identifier: { kind: 'eu_vat', value: 'GB111' } }, as: :json- patch :update, params: { tax_identifier: { kind: 'eu_vat', value: '' } }, as: :json-- expect(seller.reload.tax_identifiers.where(kind: 'eu_vat')).to be_empty- end-- it 'serializes them back' do- seller.tax_identifiers.create!(kind: 'eu_vat', value: 'GB123456789')-- get :show, as: :json-- expect(json_response['tax_identifiers'].first).to include(- 'kind' => 'eu_vat', 'value' => 'GB123456789'- )- endend# The profile inherits its policies association from the store serializer,diff --git a/spree/api/spec/controllers/spree/api/v3/seller/tax_identifiers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/tax_identifiers_controller_spec.rbnew file mode 100644index 0000000000..23230b358c--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/seller/tax_identifiers_controller_spec.rb@@ -0,0 +1,115 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Seller::TaxIdentifiersController, type: :controller do+ render_views++ include_context 'API v3 Seller'++ let(:seller_user) do+ create(:admin_user, :without_admin_role).tap { |user| seller.add_user(user) }+ end+ let(:token) do+ Spree::Api::V3::TestingSupport.generate_jwt(+ seller_user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_SELLER+ )+ end++ let(:vat_number) { eu_vat_number(0) }+ let(:corrected_vat_number) { eu_vat_number(1) }++ before do+ request.headers['Authorization'] = "Bearer #{token}"+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id+ end++ describe 'GET #index' do+ it "lists only this seller's registrations" do+ seller.tax_identifiers.create!(kind: 'eu_vat', value: vat_number)+ other_seller = create(:seller, :approved, store: store)+ other_seller.tax_identifiers.create!(kind: 'eu_vat', value: corrected_vat_number)++ get :index, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].pluck('value')).to contain_exactly(vat_number)+ end+ end++ describe 'POST #create' do+ it 'records a registration' do+ post :create, params: { kind: 'eu_vat', value: vat_number }, as: :json++ expect(response).to have_http_status(:created)+ expect(seller.reload.tax_identifiers.find_by(kind: 'eu_vat').value).to eq(vat_number)+ end++ # A business trading in two regimes holds a registration in each, exactly+ # as a company does — they are not alternatives.+ it 'holds one registration per regime' do+ post :create, params: { kind: 'eu_vat', value: vat_number }, as: :json+ post :create, params: { kind: 'gb_vat', value: 'GB123456789' }, as: :json++ expect(response).to have_http_status(:created)+ expect(seller.reload.tax_identifiers.pluck(:kind)).to contain_exactly('eu_vat', 'gb_vat')+ end++ it 'refuses a second registration of the same kind' do+ seller.tax_identifiers.create!(kind: 'eu_vat', value: vat_number)++ post :create, params: { kind: 'eu_vat', value: corrected_vat_number }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end++ # Silently dropping it would answer 2xx to a number that was never stored.+ it 'refuses a malformed number' do+ post :create, params: { kind: 'eu_vat', value: 'DE123' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(seller.reload.tax_identifiers).to be_empty+ end+ end++ describe 'PATCH #update' do+ it 'corrects the number' do+ identifier = seller.tax_identifiers.create!(kind: 'eu_vat', value: vat_number)++ patch :update, params: { id: identifier.prefixed_id, value: corrected_vat_number }, as: :json++ expect(response).to have_http_status(:ok)+ expect(identifier.reload.value).to eq(corrected_vat_number)+ end++ it "refuses another seller's registration" do+ other_seller = create(:seller, :approved, store: store)+ theirs = other_seller.tax_identifiers.create!(kind: 'eu_vat', value: vat_number)++ patch :update, params: { id: theirs.prefixed_id, value: corrected_vat_number }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'DELETE #destroy' do+ it 'removes the registration' do+ identifier = seller.tax_identifiers.create!(kind: 'eu_vat', value: vat_number)++ delete :destroy, params: { id: identifier.prefixed_id }, as: :json++ expect(seller.reload.tax_identifiers).to be_empty+ end+ end++ describe 'POST #validate' do+ # Core format-checks eu_vat but asks no registry, so there is nothing to+ # queue and the seller is told why rather than left waiting.+ it 'reports that no registry validator is installed' do+ identifier = seller.tax_identifiers.create!(kind: 'eu_vat', value: vat_number)++ post :validate, params: { id: identifier.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('tax_id_not_validatable')+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/store/customer/tax_identifiers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/customer/tax_identifiers_controller_spec.rbindex 733739ef23..72b8461b18 100644--- a/spree/api/spec/controllers/spree/api/v3/store/customer/tax_identifiers_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/customer/tax_identifiers_controller_spec.rb@@ -5,7 +5,8 @@ RSpec.describe Spree::Api::V3::Store::Customer::TaxIdentifiersController, type:include_context 'API v3 Store'- let!(:eu) { create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789') }+ let(:vat_number) { eu_vat_number(0) }+ let!(:eu) { create(:tax_identifier, owner: user, kind: 'eu_vat', value: vat_number) }let!(:gb) { create(:tax_identifier, owner: user, kind: 'gb_vat', value: 'GB123456789') }before do@@ -21,15 +22,16 @@ RSpec.describe Spree::Api::V3::Store::Customer::TaxIdentifiersController, type:expect(response).to have_http_status(:ok)expect(json_response['data'].map { |row| row['kind'] }).to contain_exactly('eu_vat', 'gb_vat')- expect(json_response['data'].map { |row| row['value'] }).to contain_exactly('DE123456789', 'GB123456789')+ expect(json_response['data'].map { |row| row['value'] }).to contain_exactly(vat_number, 'GB123456789')endit 'lists nobody else\'s' do- create(:tax_identifier, owner: create(:user), kind: 'eu_vat', value: 'FR999999999')+ other_vat_number = eu_vat_number(1)+ create(:tax_identifier, owner: create(:user), kind: 'eu_vat', value: other_vat_number)get :index- expect(json_response['data'].map { |row| row['value'] }).not_to include('FR999999999')+ expect(json_response['data'].map { |row| row['value'] }).not_to include(other_vat_number)endit 'returns an empty list for a buyer with none' dodiff --git a/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rbindex e9ddc6f0fa..5fbd4a578f 100644--- a/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rb@@ -7,8 +7,9 @@ RSpec.describe 'Admin Company Tax Identifiers API', type: :request, swagger_doc:let(:Authorization) { "Bearer #{admin_jwt_token}" }let!(:company) { create(:company, store: store) }+ let(:vat_number) { eu_vat_number(0) }let!(:tax_identifier) do- create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE123456789')+ create(:tax_identifier, owner: company, kind: 'eu_vat', value: vat_number)endpath '/api/v3/admin/companies/{company_id}/tax_identifiers' do@@ -35,7 +36,7 @@ RSpec.describe 'Admin Company Tax Identifiers API', type: :request, swagger_doc:response '200', 'registrations found' dorun_test! do |response|data = JSON.parse(response.body)- expect(data['data'].pluck('value')).to include('DE123456789')+ expect(data['data'].pluck('value')).to include(vat_number)endendend@@ -73,7 +74,7 @@ RSpec.describe 'Admin Company Tax Identifiers API', type: :request, swagger_doc:response '422', 'invalid request' do# One registration per kind.- let(:body) { { kind: 'eu_vat', value: 'DE999999999' } }+ let(:body) { { kind: 'eu_vat', value: eu_vat_number(1) } }run_test!enddiff --git a/spree/api/spec/integration/spree/api/v3/seller/profile_spec.rb b/spree/api/spec/integration/spree/api/v3/seller/profile_spec.rbindex a267bd25c7..adaff18241 100644--- a/spree/api/spec/integration/spree/api/v3/seller/profile_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/seller/profile_spec.rb@@ -60,10 +60,6 @@ RSpec.describe 'Seller Profile API', type: :request, swagger_doc: 'api-reference`slug`, since a seller renaming their own storefront address would breakevery link pointing at it.- `tax_identifier` holds one registration per kind: re-sending a kind- corrects the number, and an empty value removes it. A changed number- drops its validation verdict, because that answer was about the old one.-`accept_terms: true` stamps the moment the seller accepted themarketplace's terms, which is what the matching onboarding requirementreads. One-way — sending `false` does not unmake the stamp.@@ -87,13 +83,6 @@ RSpec.describe 'Seller Profile API', type: :request, swagger_doc: 'api-referencesquare_logo: { type: :string, nullable: true },cover_photo: { type: :string, nullable: true },accept_terms: { type: :boolean, description: 'Stamps acceptance of the marketplace terms' },- tax_identifier: {- type: :object,- properties: {- kind: { type: :string, example: 'eu_vat' },- value: { type: :string, example: 'PL1234567890' }- }- },billing_address: { type: :object, additionalProperties: true },custom_fields: {type: :array,diff --git a/spree/api/spec/integration/spree/api/v3/seller/tax_identifiers_spec.rb b/spree/api/spec/integration/spree/api/v3/seller/tax_identifiers_spec.rbnew file mode 100644index 0000000000..4b52cfafef--- /dev/null+++ b/spree/api/spec/integration/spree/api/v3/seller/tax_identifiers_spec.rb@@ -0,0 +1,159 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'Seller Tax Identifiers API', type: :request, swagger_doc: 'api-reference/seller.yaml' do+ include_context 'API v3 Seller'++ let(:seller_user) do+ create(:admin_user, :without_admin_role).tap { |user| seller.add_user(user) }+ end+ let(:vat_number) { eu_vat_number(0) }++ path '/api/v3/seller/tax_identifiers' do+ get 'List tax registrations' do+ tags 'Tax Identifiers'+ produces 'application/json'+ security [bearer_auth: []]+ description <<~DESC+ The seller's own registrations — the numbers the marketplace's+ commission invoice is made out to, and what makes EU reverse charge on+ that fee possible.++ A collection rather than a single field: a business trading in more+ than one regime holds a registration in each, and they are not+ alternatives. One per kind.+ DESC++ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true++ response '200', 'registrations returned' do+ let(:Authorization) { "Bearer #{seller_jwt_token}" }+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }++ before { seller.tax_identifiers.create!(kind: 'eu_vat', value: vat_number) }++ run_test! do |response|+ expect(JSON.parse(response.body)['data'].first['value']).to eq(vat_number)+ end+ end+ end++ post 'Add a tax registration' do+ tags 'Tax Identifiers'+ consumes 'application/json'+ produces 'application/json'+ security [bearer_auth: []]+ description <<~DESC+ `kind` names the regime — `eu_vat`, `gb_vat`, and whatever else a+ validator is registered for. Any string is accepted; what a kind means+ is decided by its validator, and a kind nothing is registered for is+ stored and used as entered.++ A number a registered validator refuses is rejected outright rather+ than stored, so a typo cannot reach an invoice.+ DESC++ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true+ parameter name: :body, in: :body, schema: {+ type: :object,+ properties: {+ kind: { type: :string, example: 'eu_vat' },+ value: { type: :string, example: 'DE100000008' }+ },+ required: %w[kind value]+ }++ response '201', 'registration recorded' do+ let(:Authorization) { "Bearer #{seller_jwt_token}" }+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }+ let(:body) { { kind: 'eu_vat', value: vat_number } }++ run_test!+ end++ response '422', 'the number is not valid for its regime' do+ let(:Authorization) { "Bearer #{seller_jwt_token}" }+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }+ let(:body) { { kind: 'eu_vat', value: 'DE123' } }++ run_test!+ end+ end+ end++ path '/api/v3/seller/tax_identifiers/{id}' do+ parameter name: :id, in: :path, type: :string++ patch 'Correct a tax registration' do+ tags 'Tax Identifiers'+ consumes 'application/json'+ produces 'application/json'+ security [bearer_auth: []]+ description <<~DESC+ A changed number drops its validation verdict, because that answer was+ about the old one.+ DESC++ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true+ parameter name: :body, in: :body, schema: {+ type: :object,+ properties: {+ kind: { type: :string, example: 'eu_vat' },+ value: { type: :string, example: 'DE100000016' }+ }+ }++ response '200', 'registration corrected' do+ let(:Authorization) { "Bearer #{seller_jwt_token}" }+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }+ let(:id) { seller.tax_identifiers.create!(kind: 'eu_vat', value: vat_number).prefixed_id }+ let(:body) { { value: eu_vat_number(1) } }++ run_test!+ end+ end++ delete 'Remove a tax registration' do+ tags 'Tax Identifiers'+ security [bearer_auth: []]++ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true++ response '204', 'registration removed' do+ let(:Authorization) { "Bearer #{seller_jwt_token}" }+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }+ let(:id) { seller.tax_identifiers.create!(kind: 'eu_vat', value: vat_number).prefixed_id }++ run_test!+ end+ end+ end++ path '/api/v3/seller/tax_identifiers/{id}/validate' do+ parameter name: :id, in: :path, type: :string++ post 'Re-check a registration against its registry' do+ tags 'Tax Identifiers'+ produces 'application/json'+ security [bearer_auth: []]+ description <<~DESC+ A registry answers "valid now", so a number verified last year may have+ been deregistered since. Refused when no registry validator is+ installed for the kind — core format-checks EU VAT numbers but asks no+ registry, so a stock install answers 422 here rather than queueing a+ check nobody can answer.+ DESC++ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true++ response '422', 'no registry validator is installed for this kind' do+ let(:Authorization) { "Bearer #{seller_jwt_token}" }+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }+ let(:id) { seller.tax_identifiers.create!(kind: 'eu_vat', value: vat_number).prefixed_id }++ run_test!+ end+ end+ end+enddiff --git a/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb b/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rbindex fbe3d25498..1f4742c4e7 100644--- a/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb+++ b/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb@@ -4,24 +4,30 @@ RSpec.describe 'Store tax identifiers', type: :request doinclude_context 'API v3 Store authenticated'describe 'the customer own registration' do+ let(:vat_number) { eu_vat_number(0) }+ let(:corrected_vat_number) { eu_vat_number(1) }+it 'is upserted, read back and removed' do+ # Typed as a human would: grouped with spaces and in lower case.+ typed = vat_number.downcase.scan(/.{1,3}/).join(' ')+put '/api/v3/store/customers/me/tax_identifier',- params: { kind: 'eu_vat', value: ' de 123 456 789 ' }, headers: headers, as: :json+ params: { kind: 'eu_vat', value: " #{typed} " }, headers: headers, as: :jsonexpect(response).to have_http_status(:created)body = JSON.parse(response.body)- expect(body['value']).to eq('DE123456789')+ expect(body['value']).to eq(vat_number)# The verdict is the platform's bookkeeping, not the buyer's business.expect(body).not_to have_key('validation_status')put '/api/v3/store/customers/me/tax_identifier',- params: { kind: 'eu_vat', value: 'DE987654321' }, headers: headers, as: :json+ params: { kind: 'eu_vat', value: corrected_vat_number }, headers: headers, as: :jsonexpect(response).to have_http_status(:ok)expect(user.tax_identifiers.count).to eq(1)get '/api/v3/store/customers/me/tax_identifier',params: { kind: 'eu_vat' }, headers: headers, as: :json- expect(JSON.parse(response.body)['value']).to eq('DE987654321')+ expect(JSON.parse(response.body)['value']).to eq(corrected_vat_number)delete '/api/v3/store/customers/me/tax_identifier',params: { kind: 'eu_vat' }, headers: headers, as: :json@@ -36,7 +42,7 @@ RSpec.describe 'Store tax identifiers', type: :request do# be told which one. Guessing meant a DELETE removed whichever row came back# first — not the buyer's choice, and not predictable.it 'refuses to guess which registration was meant' do- create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789')+ create(:tax_identifier, owner: user, kind: 'eu_vat')create(:tax_identifier, owner: user, kind: 'gb_vat', value: 'GB123456789')delete '/api/v3/store/customers/me/tax_identifier', headers: headers, as: :json@@ -49,31 +55,34 @@ RSpec.describe 'Store tax identifiers', type: :request dodescribe 'a checkout override on the cart' dolet(:cart) { create(:cart_with_line_items, line_items_count: 1, store: store, customer: user) }+ let(:profile_vat_number) { eu_vat_number(2) }+ let(:override_vat_number) { eu_vat_number(3) }+ let(:entered_vat_number) { eu_vat_number(4) }it 'reads the customer registration when the cart has no override' do- create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789')+ create(:tax_identifier, owner: user, kind: 'eu_vat', value: profile_vat_number)get "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",headers: headers.merge('x-spree-token' => cart.token), as: :json# What the provider will be handed, which is the question a checkout asks.expect(response).to have_http_status(:ok)- expect(JSON.parse(response.body)['value']).to eq('DE123456789')+ expect(JSON.parse(response.body)['value']).to eq(profile_vat_number)endit 'prefers the cart override over the customer registration' do- create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789')- create(:tax_identifier, owner: cart, kind: 'eu_vat', value: 'DE999999999')+ create(:tax_identifier, owner: user, kind: 'eu_vat', value: profile_vat_number)+ create(:tax_identifier, owner: cart, kind: 'eu_vat', value: override_vat_number)get "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",headers: headers.merge('x-spree-token' => cart.token), as: :json- expect(JSON.parse(response.body)['value']).to eq('DE999999999')+ expect(JSON.parse(response.body)['value']).to eq(override_vat_number)endit 'clears only the override, leaving the customer registration alone' do- profile = create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789')- create(:tax_identifier, owner: cart, kind: 'eu_vat', value: 'DE999999999')+ profile = create(:tax_identifier, owner: user, kind: 'eu_vat', value: profile_vat_number)+ create(:tax_identifier, owner: cart, kind: 'eu_vat', value: override_vat_number)delete "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",headers: headers.merge('x-spree-token' => cart.token), as: :json@@ -84,7 +93,7 @@ RSpec.describe 'Store tax identifiers', type: :request doendit 'has nothing of its own to delete when the registration is inherited' do- create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789')+ create(:tax_identifier, owner: user, kind: 'eu_vat')delete "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",headers: headers.merge('x-spree-token' => cart.token), as: :json@@ -97,7 +106,7 @@ RSpec.describe 'Store tax identifiers', type: :request do# used to relabel the number already there under a regime it was not issued# for.it 'refuses to relabel the existing number under a new kind' do- create(:tax_identifier, owner: cart, kind: 'eu_vat', value: 'DE999999999')+ create(:tax_identifier, owner: cart, kind: 'eu_vat', value: override_vat_number)put "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",params: { kind: 'gb_vat' },@@ -108,16 +117,16 @@ RSpec.describe 'Store tax identifiers', type: :request dooverride = cart.reload.tax_identifierexpect(override.kind).to eq('eu_vat')- expect(override.value).to eq('DE999999999')+ expect(override.value).to eq(override_vat_number)endit 'is stored against the cart and read back' doput "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",- params: { kind: 'eu_vat', value: 'DE555555555' },+ params: { kind: 'eu_vat', value: entered_vat_number },headers: headers.merge('x-spree-token' => cart.token), as: :jsonexpect(response).to have_http_status(:created)- expect(cart.reload.tax_identifier.value).to eq('DE555555555')+ expect(cart.reload.tax_identifier.value).to eq(entered_vat_number)get "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",headers: headers.merge('x-spree-token' => cart.token), as: :json@@ -139,7 +148,7 @@ RSpec.describe 'Store tax identifiers', type: :request doexpect(cart.tax_lines).to be_emptyput "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",- params: { kind: 'eu_vat', value: 'DE555555555' },+ params: { kind: 'eu_vat', value: entered_vat_number },headers: headers.merge('x-spree-token' => cart.token), as: :jsonexpect(response).to have_http_status(:created)@@ -149,7 +158,7 @@ RSpec.describe 'Store tax identifiers', type: :request doendit 'happens when the override is cleared' do- create(:tax_identifier, owner: cart, kind: 'eu_vat', value: 'DE999999999')+ create(:tax_identifier, owner: cart, kind: 'eu_vat', value: override_vat_number)delete "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",headers: headers.merge('x-spree-token' => cart.token), as: :json@@ -166,33 +175,34 @@ RSpec.describe 'Store tax identifiers', type: :request dovalue.start_with?('DE')endend)- Spree.tax_identifier_validators['eu_vat'] = 'SpecStoreValidator'- put "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",- params: { kind: 'eu_vat', value: '123' },- headers: headers.merge('x-spree-token' => cart.token), as: :json+ with_tax_identifier_validator('eu_vat', 'SpecStoreValidator') do+ put "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",+ params: { kind: 'eu_vat', value: '123' },+ headers: headers.merge('x-spree-token' => cart.token), as: :json+ endexpect(response).to have_http_status(:unprocessable_content)- ensure- Spree.tax_identifier_validators.delete('eu_vat')endenddescribe 'the snapshot on a placed order' dolet(:order) { create(:completed_order_with_totals, store: store, customer: user) }+ let(:snapshot_vat_number) { eu_vat_number(5) }it 'is readable and cannot be written' do- create(:tax_identifier, :on_order, owner: order, value: 'DE111111111')+ create(:tax_identifier, :on_order, owner: order, value: snapshot_vat_number)get "/api/v3/store/orders/#{order.prefixed_id}/tax_identifier", headers: headers, as: :jsonexpect(response).to have_http_status(:ok)- expect(JSON.parse(response.body)['value']).to eq('DE111111111')+ expect(JSON.parse(response.body)['value']).to eq(snapshot_vat_number)put "/api/v3/store/orders/#{order.prefixed_id}/tax_identifier",- params: { kind: 'eu_vat', value: 'DE222222222' }, headers: headers, as: :json+ params: { kind: 'eu_vat', value: eu_vat_number(6) },+ headers: headers, as: :jsonexpect(response).to have_http_status(:not_found)- expect(order.reload.tax_identifier.value).to eq('DE111111111')+ expect(order.reload.tax_identifier.value).to eq(snapshot_vat_number)endendenddiff --git a/spree/api/spec/spec_helper.rb b/spree/api/spec/spec_helper.rbindex cbe6cf3971..777b402769 100644--- a/spree/api/spec/spec_helper.rb+++ b/spree/api/spec/spec_helper.rb@@ -50,6 +50,7 @@ require 'spree/testing_support/factories'require 'spree/testing_support/jobs'require 'spree/testing_support/store'require 'spree/testing_support/preferences'+require 'spree/testing_support/tax_identifier_validators'require 'spree/testing_support/image_helpers'require 'spree/api/testing_support/v3/base'diff --git a/spree/core/app/models/spree/tax_identifier.rb b/spree/core/app/models/spree/tax_identifier.rbindex 60872e5ff5..6e1aa7f94b 100644--- a/spree/core/app/models/spree/tax_identifier.rb+++ b/spree/core/app/models/spree/tax_identifier.rb@@ -20,13 +20,15 @@ module Spree# Which registration this is — an EU VAT number, a UK one, an Australian# business number. Any string is accepted, and nothing here narrows it: the# kinds that exist are the ones somebody has a validator or a provider for,- # and core ships neither.+ # and core ships one, the format check for +eu_vat+.## It does have to match the key that validator is registered under in# {Spree.tax_identifier_validators}, because that lookup is by exact string. A kind# nothing is registered for is stored and used as entered — never# format-checked, never sent to a registry — and {#validatable?} reports as- # much. So a misspelled kind fails silently rather than loudly.+ # much. So a misspelled kind fails silently rather than loudly, and a VAT+ # number filed under +vat+ rather than +eu_vat+ skips the check core does+ # ship.## The kinds in circulation read as a region or country prefix plus the tax's# name: +eu_vat+, +gb_vat+, +ch_vat+, +au_abn+. Matching that spares a@@ -72,7 +74,10 @@ module Spreevalidates :value, length: { maximum: 64 }validates :validation_status, inclusion: { in: VALIDATION_STATUSES }, allow_nil: truevalidates :source, inclusion: { in: SOURCES }, allow_nil: true- validate :value_format+ # An order's snapshot is a copy of a number already accepted, so a rule+ # tightened since — or a country leaving the VAT area — must not fail the+ # order it was placed on.+ validate :value_format, unless: :order_owned?# Registrations exist only on legal-entity nodes — a division's purchases# read theirs through the legal entity. A validation rather than a schema# difference, so a per-division foreign registration can be allowed later@@ -92,13 +97,27 @@ module Spreevalidation_status == 'verified'end- # Whether this installation can check a number of this kind at all. What+ # Whether a registry can be asked about a number of this kind here. What# tells the admin apart the two reasons a row has no verdict: not attempted# yet, or nothing here knows how to ask.#+ # A format-only validator does not count. Core registers one for +eu_vat+,+ # so a stock install rejects a mistyped VAT number on save and still leaves+ # the verdict blank — the shape being right is not evidence that the+ # business is registered, and only a registry can supply that.+ ## @return [Boolean]def validatable?- !order_owned? && Spree.tax_identifier_validators.key?(kind)+ return false if order_owned?++ validator = validator_class+ return false if validator.nil?+ # A validator predating the predicate, or one not built on Base at all —+ # the registry takes any class name. Assume it can ask, which is what+ # every validator did before the predicate existed.+ return true unless validator.respond_to?(:checks_registry?)++ validator.checks_registry?endprivate@@ -109,17 +128,45 @@ module Spreeowner_type == 'Spree::Order'end- # Format knowledge lives entirely in the registered validator. Core asserts- # nothing about the shape of a number whose rules live in someone else's- # statute book: a rule spanning every tax regime on earth would be a guess,- # and its failure mode is turning away a real business customer. Kinds with- # no validator are accepted as entered.+ # Format knowledge lives entirely in the registered validator, so a kind+ # with none is accepted as entered: a single rule spanning every tax regime+ # on earth would be a guess, and its failure mode is turning away a real+ # business customer.def value_format- validator = Spree.tax_identifier_validators[kind]- return if validator.blank?- return if validator.to_s.constantize.valid_format?(value)+ # Blank is the presence validation's business; saying it twice for one+ # mistake helps nobody.+ return if value.blank?++ validator = validator_class+ return if validator.nil?+ return if validator.valid_format?(value)++ # Named after the regime the buyer picked rather than left generic: "is+ # invalid" on a field labelled Number tells them nothing they can act on,+ # and the same validation speaks for every kind an extension registers.+ errors.add(:value, :invalid, kind: kind_label)+ end- errors.add(:value, :invalid)+ # The kind as the dashboard shows it, falling back to the raw key so an+ # extension's kind reads as itself rather than blank.+ def kind_label+ Spree.t("tax_identifier_kinds.#{kind}", default: kind.to_s.humanize)+ end++ # The class registered for this kind, or nil when nothing is registered and+ # when what is registered cannot be loaded.+ #+ # A registry entry naming a class that is gone — an initializer left behind+ # after its gem was dropped, or a typo — used to be inert, since the lookup+ # only asked whether the key existed. It is read on every save and on every+ # admin serialization, so letting it raise would take out the whole tax+ # identifier listing over one stale line of configuration.+ # Deliberately not memoized: the registry is mutable configuration, and a+ # cached class would go on answering for a validator that has since been+ # swapped. The lookup costs microseconds against a request that also hits+ # the database.+ def validator_class+ Spree.tax_identifier_validators[kind].presence&.to_s&.safe_constantizeenddef number_changing?diff --git a/spree/core/app/models/spree/tax_identifiers/validator/base.rb b/spree/core/app/models/spree/tax_identifiers/validator/base.rbindex f7792391c5..e5e1df0c39 100644--- a/spree/core/app/models/spree/tax_identifiers/validator/base.rb+++ b/spree/core/app/models/spree/tax_identifiers/validator/base.rb@@ -22,6 +22,17 @@ module Spreetrueend+ # Whether this validator can ask a registry at all. False for a+ # format-only validator such as {EuVat}, and what stops core enqueueing+ # a check nobody is going to answer — an unasked question is not an+ # unavailable registry, and recording it as one would fill the admin+ # with failures that mean nothing.+ #+ # @return [Boolean]+ def self.checks_registry?+ true+ end+# Asks the registry whether the number is registered. Runs in# {Spree::TaxIdentifiers::ValidateJob}.#diff --git a/spree/core/app/models/spree/tax_identifiers/validator/eu_vat.rb b/spree/core/app/models/spree/tax_identifiers/validator/eu_vat.rbnew file mode 100644index 0000000000..3e89cabb93--- /dev/null+++ b/spree/core/app/models/spree/tax_identifiers/validator/eu_vat.rb@@ -0,0 +1,76 @@+# Loaded here rather than with core's other gems: valvat's entry point pulls in+# its VIES lookup client, and with it REXML and net/http — around 90ms and a+# hundred files for a SOAP service this validator never calls. Loading it with+# the class keeps that off anything that never resolves this constant, which in+# development and test is most rake tasks and consoles. An eager-loading+# production boot resolves it like every other model and pays it once.+require 'valvat'++module Spree+ module TaxIdentifiers+ module Validator+ # The offline half of checking an EU VAT number, and only that half.+ #+ # Registered for +eu_vat+ out of the box, because a number's shape is+ # arithmetic rather than a service: the rules are published in the+ # directive, they do not change between installations, and checking them+ # costs nothing. This follows the same reasoning that puts postal codes on+ # +validates_zipcode+ and phone numbers on +phonelib+ — a merchant should+ # not have to install anything to be told that +DE123+ is not a VAT+ # number.+ #+ # What it deliberately does not do is ask VIES whether the number is+ # *registered*. That is a network call to a service which is regularly+ # slow or down, so it stays with the extension that wants it. Declaring+ # {checks_registry?} false is what keeps core from queueing a check+ # nobody here can answer; an extension covering the registry re-registers+ # +eu_vat+ and takes over both halves.+ #+ # A passing check is not a claim that the business exists — only that the+ # number is not a typo. Registration is what +verified+ means, and only a+ # registry can say it.+ class EuVat < Base+ # No registry client here, so core never enqueues a check for a number+ # of this kind. Verdicts stay blank rather than reading +unavailable+,+ # which is the honest answer: nobody was asked.+ #+ # @return [Boolean]+ def self.checks_registry?+ false+ end++ # True when the number is well-formed for the member state that issued+ # it.+ #+ # Checksums are applied for the 24 member states valvat has an algorithm+ # for and syntax alone decides Czechia, Latvia and Slovakia. That+ # fallback is the point: refusing every number we cannot fully verify+ # would turn away real customers in those three to catch a typo, and+ # turning away a paying business is the more expensive mistake.+ #+ # valvat recognises the 27 member states and Great Britain, and nothing+ # else — so excluding Great Britain is the whole of the area check.+ # Northern Ireland kept EU VAT treatment for goods under the Windsor+ # Framework and is the reason that exclusion reads on the prefix: its+ # +XI+ numbers report +GB+ as their country.+ #+ # @param value [String] already normalized (whitespace stripped, upcased)+ # @return [Boolean]+ def self.valid_format?(value)+ entered = value.to_s+ # valvat strips punctuation before checking, while Spree keeps what+ # the buyer typed — punctuation is part of the canonical number in+ # other regimes. An EU VAT number has none, so anything valvat had to+ # remove would be stored in a spelling no registry will match, and is+ # a typo rather than a house style.+ return false unless entered == Valvat::Utils.normalize(entered)++ vat = Valvat.new(entered)+ return false if vat.iso_country_code == 'GB' && vat.vat_country_code != 'XI'++ Valvat::Checksum.validate(vat)+ end+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/tax_identifiers/validate.rb b/spree/core/app/services/spree/tax_identifiers/validate.rbindex 5bd7486440..86a810567c 100644--- a/spree/core/app/services/spree/tax_identifiers/validate.rb+++ b/spree/core/app/services/spree/tax_identifiers/validate.rb@@ -15,12 +15,22 @@ module Spree# written over the new one — see #persist.@checked = tax_identifier.slice(:kind, :value)- validator = Spree.tax_identifier_validators[tax_identifier.kind]+ # Absent, or named by an entry that no longer loads — a gem dropped+ # while a check was already queued. Both mean the same thing here as a+ # deregistration does, and neither is a registry that failed to answer,+ # so they must not be recorded as an outage.+ validator_class = Spree.tax_identifier_validators[tax_identifier.kind].presence&.to_s&.safe_constantize+ return persist(tax_identifier, unsupported_result) if validator_class.nil?- # Narrow race: the validator was deregistered between enqueue and run.- return persist(tax_identifier, unsupported_result) if validator.blank?+ # Nothing should enqueue a check for a format-only validator, since+ # TaxIdentifier#validatable? reports false for one. Belt and braces all+ # the same: it must not surface as a job that crashes. A validator+ # predating the predicate is assumed to ask, as it always did.+ if validator_class.respond_to?(:checks_registry?) && !validator_class.checks_registry?+ return persist(tax_identifier, unsupported_result)+ end- result = validator.to_s.constantize.new.call(tax_identifier: tax_identifier)+ result = validator_class.new.call(tax_identifier: tax_identifier)persist(tax_identifier, result)rescue StandardError => error# A number nobody could check is not a number known to be wrong, so itdiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 7a9c4a9950..9bc69301f7 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -195,6 +195,9 @@ en:spree/tax_category:description: Descriptionname: Name+ spree/tax_identifier:+ kind: Registration type+ value: Numberspree/tax_rate:amount: Rateincluded_in_price: Included in Price@@ -379,6 +382,8 @@ en:attributes:company:must_be_legal_entity: must be a legal entity, not a division+ value:+ invalid: does not look like a valid %{kind} registrationspree/taxon_image:attributes:attachment:@@ -1762,6 +1767,12 @@ en:label: US local taxtax_category: Tax Categorytax_code: Tax Code+ tax_identifier_kinds:+ au_abn: Australian Business Number+ ch_vat: Swiss VAT+ eu_vat: EU VAT+ gb_vat: UK VAT+ us_ein: US EINtax_inclusive: Tax inclusivetax_rates: Tax Ratestaxes: Taxesdiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 489dc74c86..4c0f20fc1e 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -160,12 +160,20 @@ module Spree@@search_provider = value.to_send- # Tax ID validators, keyed by registration kind. Empty by default: core ships- # no registry client, because VAT number rules live in 27 different statute- # books and a guess would reject real business customers.+ # Tax ID validators, keyed by registration kind.#+ # Core ships one, for +eu_vat+, and it checks format only — the shape of an EU+ # VAT number is arithmetic, so it costs nothing and needs no credentials.+ # Core ships **no registry client** for any jurisdiction: asking whether a+ # number is actually registered means a network call to somebody's government,+ # and that belongs to the extension that wants it.+ #+ # # Take over both halves of eu_vat, format and registry alike.# Spree.tax_identifier_validators['eu_vat'] = 'SpreeEuVat::TaxIdentifierValidator'#+ # # Or cover a kind nothing here knows about.+ # Spree.tax_identifier_validators['au_abn'] = 'SpreeAuAbn::TaxIdentifierValidator'+ ## Class names are stored as strings and constantized at call time, so an# initializer can register a validator before its class is autoloaded.# Whether a kind has a validator is also what tells the admin apart the two@@ -173,7 +181,7 @@ module Spree## @return [Hash{String => String}]def self.tax_identifier_validators- @@tax_identifier_validators ||= {}+ @@tax_identifier_validators ||= { 'eu_vat' => 'Spree::TaxIdentifiers::Validator::EuVat' }end# Returns the events adapter class used for publishing and subscribing to events.diff --git a/spree/core/lib/spree/testing_support/factories/tax_identifier_factory.rb b/spree/core/lib/spree/testing_support/factories/tax_identifier_factory.rbindex 9b8c5fb800..dd8f00abdd 100644--- a/spree/core/lib/spree/testing_support/factories/tax_identifier_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/tax_identifier_factory.rb@@ -2,7 +2,8 @@ FactoryBot.define dofactory :tax_identifier, class: Spree::TaxIdentifier doowner factory: :customerkind { 'eu_vat' }- sequence(:value) { |n| "DE#{123_456_780 + n}" }+ # Real enough to survive the format check core applies to eu_vat.+ sequence(:value) { |n| TaxIdentifierValidatorHelpers.eu_vat_number(n) }trait :verified dovalidation_status { 'verified' }diff --git a/spree/core/lib/spree/testing_support/tax_identifier_validators.rb b/spree/core/lib/spree/testing_support/tax_identifier_validators.rbnew file mode 100644index 0000000000..a259a902de--- /dev/null+++ b/spree/core/lib/spree/testing_support/tax_identifier_validators.rb@@ -0,0 +1,68 @@+# The validator registry is process-global and core registers a default for+# +eu_vat+, so a spec that swaps one in has to put back whatever was there+# rather than deleting its own entry — deleting strips core's default (or an+# installed provider gem's) for every example that follows, which shows up as+# an unrelated spec failing under some seeds and not others.+#+# Lives in testing_support rather than core's spec/support because the API+# suite registers validators too, and the default it would delete is shared.+module TaxIdentifierValidatorHelpers+ # @param kind [String] the registration kind, e.g. 'eu_vat'+ # @param class_name [String] validator to register for the block+ def with_tax_identifier_validator(kind, class_name)+ previous = Spree.tax_identifier_validators[kind]+ had_previous = Spree.tax_identifier_validators.key?(kind)+ Spree.tax_identifier_validators[kind] = class_name++ yield+ ensure+ if had_previous+ Spree.tax_identifier_validators[kind] = previous+ else+ Spree.tax_identifier_validators.delete(kind)+ end+ end++ # A structurally valid EU VAT number, by position in the fixture.+ #+ # Core format-checks +eu_vat+, so specs cannot invent numbers — the check+ # digit puts valid ones at irregular intervals. Distinct indexes give+ # distinct numbers, which is what lets an example prove WHICH registration+ # won. Wraps, so an owner needing more than the fixture holds would repeat a+ # number and hit the uniqueness validation instead.+ #+ # @param index [Integer] any counter; wraps around the fixture+ # @return [String]+ def eu_vat_number(index)+ numbers = eu_vat_numbers+ numbers[index.to_i % numbers.size]+ end++ # The whole fixture, for a spec that needs a number DIFFERENT from one it+ # already holds — the factory sequence is global and never resets, so a fixed+ # index eventually collides with whatever the factory just produced.+ #+ # @return [Array<String>]+ def eu_vat_numbers+ TaxIdentifierValidatorHelpers.eu_vat_numbers+ end+ # Callable on the module too, for the factory — FactoryBot blocks run outside+ # RSpec example scope, so they cannot reach an included helper.+ module_function :eu_vat_number+ public :eu_vat_number++ # Read lazily rather than at load: the fixture ships in the gem, but a+ # consumer that vendors only lib/ would otherwise take down the whole+ # spec_helper on require instead of just the specs that need a number.+ def self.eu_vat_numbers+ @eu_vat_numbers ||= Spree::Core::Engine.root+ .join('spec', 'fixtures', 'files', 'eu_vat_numbers.txt')+ .readlines(chomp: true)+ .grep_v(/\A\s*(#|\z)/)+ .freeze+ end+end++RSpec.configure do |config|+ config.include TaxIdentifierValidatorHelpers+enddiff --git a/spree/core/spec/fixtures/files/eu_vat_numbers.txt b/spree/core/spec/fixtures/files/eu_vat_numbers.txtnew file mode 100644index 0000000000..81f4a31cfc--- /dev/null+++ b/spree/core/spec/fixtures/files/eu_vat_numbers.txt@@ -0,0 +1,56 @@+# Structurally valid EU VAT numbers for the :tax_identifier factory.+#+# Core format-checks eu_vat, so a factory cannot invent numbers by counting+# upward: the check digit puts valid ones at irregular intervals. These pass+# the German checksum and nothing more — they identify no business, and no+# registry has been asked about them.+DE100000008+DE100000016+DE100000024+DE100000032+DE100000049+DE100000057+DE100000065+DE100000073+DE100000081+DE100000090+DE100000104+DE100000112+DE100000129+DE100000137+DE100000145+DE100000153+DE100000161+DE100000170+DE100000188+DE100000196+DE100000207+DE100000215+DE100000223+DE100000231+DE100000240+DE100000258+DE100000266+DE100000274+DE100000282+DE100000299+DE100000303+DE100000311+DE100000320+DE100000338+DE100000346+DE100000354+DE100000362+DE100000379+DE100000387+DE100000395+DE100000400+DE100000418+DE100000426+DE100000434+DE100000442+DE100000459+DE100000467+DE100000475+DE100000483+DE100000491diff --git a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rbindex 774b8d2650..5c61580708 100644--- a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb+++ b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb@@ -61,9 +61,8 @@ RSpec.shared_examples 'a taxation host' do# The invoice is addressed to the entity, so its registration wins.it 'prefers the company registration over the buyer own' do- create(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE111111111')- company_identifier = create(:tax_identifier, owner: company,- kind: 'eu_vat', value: 'DE222222222')+ create(:tax_identifier, owner: customer, kind: 'eu_vat')+ company_identifier = create(:tax_identifier, owner: company, kind: 'eu_vat')expect(record.resolved_tax_identifier).to eq(company_identifier)end@@ -84,7 +83,7 @@ RSpec.shared_examples 'a taxation host' doit 'prefers the record own override over the customer registration' docreate(:tax_identifier, owner: customer)- override = create(:tax_identifier, kind: 'eu_vat', value: 'DE555555555', owner: record)+ override = create(:tax_identifier, kind: 'eu_vat', owner: record)expect(record.resolved_tax_identifier).to eq(override)enddiff --git a/spree/core/spec/models/spree/tax_identifier_spec.rb b/spree/core/spec/models/spree/tax_identifier_spec.rbindex bd05a5843d..41aa217bb1 100644--- a/spree/core/spec/models/spree/tax_identifier_spec.rb+++ b/spree/core/spec/models/spree/tax_identifier_spec.rb@@ -28,7 +28,11 @@ describe Spree::TaxIdentifier, type: :model dosnapshot = create(:tax_identifier, :on_order, owner: order)expect(snapshot).to be_readonly- expect { snapshot.update!(value: 'DE999999999') }.to raise_error(ActiveRecord::ReadOnlyRecord)+ # A valid number, so it is the readonly guard that refuses the write and+ # not the format check standing in front of it.+ expect { snapshot.update!(value: eu_vat_number(9)) }.to(+ raise_error(ActiveRecord::ReadOnlyRecord)+ )endit 'is writable while unsaved' do@@ -84,6 +88,97 @@ describe Spree::TaxIdentifier, type: :model doendend+ # No stubbed validator here on purpose: this is what a stock install does.+ describe 'the EU VAT format check core ships' do+ it 'rejects a mistyped VAT number' do+ identifier = build(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE123')++ expect(identifier).not_to be_valid+ expect(identifier.errors[:value]).to be_present+ end++ it 'accepts a well-formed one' do+ expect(+ build(:tax_identifier, owner: customer, kind: 'eu_vat',+ value: eu_vat_number(0))+ ).to be_valid+ end++ # "is invalid" on a field labelled Number tells a merchant nothing they can+ # act on, and the attribute name is not what the form calls it.+ it 'says which regime the number failed as' do+ identifier = build(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE123')+ identifier.valid?++ expect(identifier.errors[:value]).to eq(['does not look like a valid EU VAT registration'])+ expect(identifier.errors.full_messages).to eq(+ ['Number does not look like a valid EU VAT registration']+ )+ end++ it 'reports one problem, not two, for a blank number' do+ identifier = build(:tax_identifier, owner: customer, kind: 'eu_vat', value: '')++ expect(identifier).not_to be_valid+ expect(identifier.errors[:value]).to eq(identifier.errors[:value].uniq)+ expect(identifier.errors[:value].size).to eq(1)+ end++ # A registration accepted before a rule tightened — or one whose country+ # has since left the VAT area — must not fail the order it was placed on.+ it 'does not re-check a number frozen onto an order' do+ snapshot = build(:tax_identifier, owner: create(:order), kind: 'eu_vat',+ value: 'GB123456789', source: 'customer')++ expect(snapshot).to be_valid+ end++ # An initializer left behind after its gem was dropped names a class that+ # no longer loads. That used to be inert, and it is read on every save and+ # every admin serialization.+ it 'treats an unloadable registered validator as absent' do+ with_tax_identifier_validator('eu_vat', 'NoSuchValidatorConstant') do+ identifier = build(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'anything')++ expect { identifier.valid? }.not_to raise_error+ expect(identifier).to be_valid+ expect { identifier.validatable? }.not_to raise_error+ expect(identifier).not_to be_validatable+ end+ end++ # The registry takes any class name, so a validator written before+ # checks_registry? existed has no such method. Raising here would break the+ # save outright, since this is read from a validation.+ it 'treats a validator predating the predicate as able to ask' do+ legacy = Class.new do+ def self.valid_format?(_value) = true+ end+ stub_const('LegacyRegistryValidator', legacy)++ with_tax_identifier_validator('eu_vat', 'LegacyRegistryValidator') do+ identifier = build(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'anything')++ expect { identifier.valid? }.not_to raise_error+ expect(identifier).to be_validatable+ end+ end++ # Being well-formed is not evidence that the business is registered, and+ # only a registry can supply that — so a stock install leaves the verdict+ # blank rather than queueing a check nobody here can answer.+ it 'records no verdict and queues nothing', events: true do+ identifier = nil++ expect { identifier = create(:tax_identifier, owner: customer, kind: 'eu_vat') }.not_to(+ have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)+ )++ expect(identifier.validation_status).to be_nil+ expect(identifier).not_to be_validatable+ end+ end+# The check now runs from Spree::TaxIdentifierValidationSubscriber, so these# need the event bus the suite disables by default.describe 'the registry check', events: true do@@ -108,8 +203,14 @@ describe Spree::TaxIdentifier, type: :model doit 'is queued again when the number changes' doidentifier = create(:tax_identifier, owner: customer, kind: 'eu_vat')+ # Derived from the row rather than a fixed index: the factory sequence is+ # global and never resets, so a fixed one eventually IS the number already+ # on the row, and a write that changes nothing enqueues nothing.+ replacement = eu_vat_numbers.find { |number| number != identifier.value }- expect { identifier.update!(value: 'DE987654321') }.to have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)+ expect { identifier.update!(value: replacement) }.to(+ have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)+ )end# The stamp is part of the write, not the subscriber's doing: the response to@@ -140,7 +241,7 @@ describe Spree::TaxIdentifier, type: :model doidentifier = create(:tax_identifier, owner: customer, kind: 'eu_vat')identifier.update_columns(validation_status: 'verified', validated_at: Time.current)- identifier.update!(value: 'DE987654321')+ identifier.update!(value: eu_vat_numbers.find { |number| number != identifier.value })expect(identifier.validation_status).to eq('pending')expect(identifier.validated_at).to be_nil@@ -197,15 +298,18 @@ describe Spree::TaxIdentifier, type: :model dolet(:seller) { create(:seller) }it 'is a valid owner' do- identifier = described_class.new(owner: seller, kind: 'eu_vat', value: 'GB123456789')+ identifier = described_class.new(owner: seller, kind: 'eu_vat',+ value: eu_vat_number(0))expect(identifier).to be_validexpect(identifier.owner).to eq(seller)endit 'holds one registration per kind' do- described_class.create!(owner: seller, kind: 'eu_vat', value: 'GB123456789')- duplicate = described_class.new(owner: seller, kind: 'eu_vat', value: 'GB987654321')+ described_class.create!(owner: seller, kind: 'eu_vat',+ value: eu_vat_number(0))+ duplicate = described_class.new(owner: seller, kind: 'eu_vat',+ value: eu_vat_number(1))expect(duplicate).not_to be_validenddiff --git a/spree/core/spec/models/spree/tax_identifiers/validator/eu_vat_spec.rb b/spree/core/spec/models/spree/tax_identifiers/validator/eu_vat_spec.rbnew file mode 100644index 0000000000..21cc188438--- /dev/null+++ b/spree/core/spec/models/spree/tax_identifiers/validator/eu_vat_spec.rb@@ -0,0 +1,85 @@+require 'spec_helper'++RSpec.describe Spree::TaxIdentifiers::Validator::EuVat do+ describe '.valid_format?' do+ it 'accepts a well-formed number from every member state it can check' do+ # One per checksum algorithm family, so a regression names the country.+ %w[+ DE100000008+ ATU13585627+ IE6388047V+ FR32123456789+ NL123456782B12+ IT00743110157+ ES54362315K+ BE0776091951+ PL5260001246+ SE556188840401+ ].each do |number|+ expect(described_class.valid_format?(number)).to be(true), "expected #{number} to be accepted"+ end+ end++ it 'rejects a number whose check digit is wrong' do+ # DE100000008 with its last digit changed — right length, right country,+ # right shape, and still not a number anyone was issued.+ expect(described_class.valid_format?('DE100000009')).to be(false)+ expect(described_class.valid_format?('ATU13585628')).to be(false)+ end++ it 'rejects a number that is the wrong length for its country' do+ expect(described_class.valid_format?('DE10000000')).to be(false)+ end++ it 'accepts a member state whose check digit no algorithm covers' do+ # Czech and Latvian numbers get syntax alone. Turning away a real business+ # to catch a typo is the more expensive mistake, so these must pass.+ expect(described_class.valid_format?('CZ25123891')).to be(true)+ expect(described_class.valid_format?('LV40003009497')).to be(true)+ end++ # Greece is the one member state whose VAT prefix is not its ISO code: it+ # issues EL numbers while its ISO code is GR. Matching the prefix against a+ # list of ISO codes refuses every Greek business.+ it 'accepts a Greek number, which is prefixed EL rather than GR' do+ expect(described_class.valid_format?('EL094014201')).to be(true)+ end++ it 'rejects a Greek number spelled with its ISO code' do+ # No such registration exists — GR is not a VAT prefix.+ expect(described_class.valid_format?('GR094014201')).to be(false)+ end++ it 'accepts a Northern Ireland number' do+ # XI keeps EU VAT treatment for goods under the Windsor Framework.+ expect(described_class.valid_format?('XI123456782')).to be(true)+ end++ it 'rejects a number from outside the EU VAT area' do+ # Great Britain left it; Switzerland was never in it. Both are real+ # registrations, and both belong under a different kind.+ expect(described_class.valid_format?('GB123456782')).to be(false)+ expect(described_class.valid_format?('CHE116281710')).to be(false)+ end++ # Spree stores what the buyer typed, so a number accepted with punctuation+ # would be kept in a spelling no registry can match. EU VAT numbers carry+ # none, so punctuation here is a typo rather than a house style.+ it 'rejects a number written with punctuation' do+ expect(described_class.valid_format?('D-E100000008')).to be(false)+ expect(described_class.valid_format?('DE-100.000.008')).to be(false)+ end++ it 'rejects a value that is not a VAT number at all' do+ ['', '123456789', 'NOTAVAT', nil].each do |value|+ expect(described_class.valid_format?(value)).to be(false), "expected #{value.inspect} to be rejected"+ end+ end+ end++ describe '.checks_registry?' do+ it 'is false, because core asks no registry' do+ expect(described_class.checks_registry?).to be(false)+ end+ end+enddiff --git a/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb b/spree/core/spec/services/spree/tax_identifiers/validate_spec.rbindex 442d444ad8..5fb47363c2 100644--- a/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb+++ b/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb@@ -2,7 +2,9 @@ require 'spec_helper'describe Spree::TaxIdentifiers::Validate dolet(:customer) { create(:user) }- let(:tax_identifier) { create(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE123456789') }+ # Built before a stub validator is registered in some examples, so it has to+ # survive the format check core ships for eu_vat.+ let(:tax_identifier) { create(:tax_identifier, owner: customer, kind: 'eu_vat') }def register(validator_class)stub_const('SpecRegistryValidator', validator_class)@@ -40,7 +42,9 @@ describe Spree::TaxIdentifiers::Validate doit 'leaves the number as the buyer entered it' dodescribed_class.call(tax_identifier: tax_identifier)- expect(tax_identifier.reload.value).to eq('DE123456789')+ entered = tax_identifier.value++ expect(tax_identifier.reload.value).to eq(entered)endit 'does not queue itself again' do@@ -74,6 +78,36 @@ describe Spree::TaxIdentifiers::Validate docontext 'when the validator disappeared between enqueue and run' doit 'records unsupported' do+ # The row has to exist while the validator still does, since creating it+ # is what the format check runs on.+ tax_identifier+ # Deregistered outright, which the surrounding `around` puts back.+ Spree.tax_identifier_validators.delete('eu_vat')++ described_class.call(tax_identifier: tax_identifier)++ expect(tax_identifier.reload.validation_status).to eq('unsupported')+ end+ end++ # A gem dropped while a check was already queued. Nobody asked a registry, so+ # this is not an outage and must not be recorded as one.+ context 'when the registered validator no longer loads' do+ it 'records unsupported rather than unavailable' do+ tax_identifier++ with_tax_identifier_validator('eu_vat', 'NoSuchValidatorConstant') do+ described_class.call(tax_identifier: tax_identifier)+ end++ expect(tax_identifier.reload.validation_status).to eq('unsupported')+ end+ end++ # Core registers one of these for eu_vat, so this is the ordinary case rather+ # than an edge one: the row must come out marked, not crash the job.+ context 'when the registered validator only checks format' do+ it 'records unsupported without asking anything' dodescribed_class.call(tax_identifier: tax_identifier)expect(tax_identifier.reload.validation_status).to eq('unsupported')diff --git a/spree/core/spec/spec_helper.rb b/spree/core/spec/spec_helper.rbindex ce9f96c5ab..5fb96193c0 100644--- a/spree/core/spec/spec_helper.rb+++ b/spree/core/spec/spec_helper.rb@@ -61,6 +61,7 @@ require 'spree/testing_support/store'require 'spree/testing_support/metadata'require 'spree/testing_support/lifecycle_events'require 'spree/testing_support/preferences'+require 'spree/testing_support/tax_identifier_validators'require 'spree/testing_support/url_helpers'require 'spree/testing_support/kernel'require 'spree/testing_support/imports'diff --git a/spree/core/spec/subscribers/spree/tax_identifier_validation_subscriber_spec.rb b/spree/core/spec/subscribers/spree/tax_identifier_validation_subscriber_spec.rbindex 1ec4a32b11..ec13d0ee0d 100644--- a/spree/core/spec/subscribers/spree/tax_identifier_validation_subscriber_spec.rb+++ b/spree/core/spec/subscribers/spree/tax_identifier_validation_subscriber_spec.rb@@ -8,11 +8,11 @@ RSpec.describe Spree::TaxIdentifierValidationSubscriber dolet(:store) { @default_store }let(:customer) { create(:customer) }+ # Base checks a registry as far as the subscriber is concerned, which is what+ # makes the enqueue happen; core's own eu_vat validator deliberately does not.+ # Restored through the helper rather than deleted, or the default goes with it.around do |example|- Spree.tax_identifier_validators['eu_vat'] = 'Spree::TaxIdentifiers::Validator::Base'- example.run- ensure- Spree.tax_identifier_validators.delete('eu_vat')+ with_tax_identifier_validator('eu_vat', 'Spree::TaxIdentifiers::Validator::Base') { example.run }enddescribe '.subscription_patterns' dodiff --git a/spree/core/spec/support/tax_identifier_validators.rb b/spree/core/spec/support/tax_identifier_validators.rbdeleted file mode 100644index 2aa646ad29..0000000000--- a/spree/core/spec/support/tax_identifier_validators.rb+++ /dev/null@@ -1,23 +0,0 @@-# The validator registry is process-global. Specs that register one have to put-# back whatever was there before rather than deleting their own entry, or they-# strip a registration another spec (or an installed provider gem) relies on and-# make the suite order-dependent.-module TaxIdentifierValidatorHelpers- def with_tax_identifier_validator(kind, class_name)- previous = Spree.tax_identifier_validators[kind]- had_previous = Spree.tax_identifier_validators.key?(kind)- Spree.tax_identifier_validators[kind] = class_name-- yield- ensure- if had_previous- Spree.tax_identifier_validators[kind] = previous- else- Spree.tax_identifier_validators.delete(kind)- end- end-end--RSpec.configure do |config|- config.include TaxIdentifierValidatorHelpers-enddiff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rbindex 56b79ca19b..a749cdda3e 100644--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb@@ -221,27 +221,44 @@ module Spreedescribe 'tax identifier snapshot' dolet(:customer) { create(:user) }+ # Distinct numbers so the assertion proves which registration won, and+ # real ones because eu_vat is format-checked.+ let(:customer_vat) { eu_vat_number(0) }+ let(:override_vat) { eu_vat_number(1) }+ let(:company_vat) { eu_vat_number(2) }before { ready_cart.update!(customer: customer) }it 'freezes the customer registration onto the order' do- create(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE123456789')+ create(:tax_identifier, owner: customer, kind: 'eu_vat', value: customer_vat)order = described_class.call(cart: ready_cart).valuesnapshot = order.tax_identifier- expect(snapshot.value).to eq('DE123456789')+ expect(snapshot.value).to eq(customer_vat)expect(snapshot.source).to eq('customer')expect(snapshot).to be_readonlyend+ # A number stored before the format rule tightened, or one whose country+ # has since left the VAT area, must not turn into a failed checkout.+ it 'completes even when the stored number would no longer be accepted' do+ identifier = create(:tax_identifier, owner: customer, kind: 'eu_vat')+ identifier.update_columns(value: 'GB123456789')++ result = described_class.call(cart: ready_cart)++ expect(result).to be_success+ expect(result.value.tax_identifier.value).to eq('GB123456789')+ end+it 'records a checkout override as such' do- create(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE123456789')- create(:tax_identifier, owner: ready_cart, kind: 'eu_vat', value: 'DE999999999')+ create(:tax_identifier, owner: customer, kind: 'eu_vat', value: customer_vat)+ create(:tax_identifier, owner: ready_cart, kind: 'eu_vat', value: override_vat)order = described_class.call(cart: ready_cart).value- expect(order.tax_identifier.value).to eq('DE999999999')+ expect(order.tax_identifier.value).to eq(override_vat)expect(order.tax_identifier.source).to eq('override')end@@ -249,11 +266,11 @@ module Spreecompany = create(:company, store: store)create(:company_membership, company: company, customer: customer)ready_cart.update!(company: company)- create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE777777777')+ create(:tax_identifier, owner: company, kind: 'eu_vat', value: company_vat)order = described_class.call(cart: ready_cart).value- expect(order.tax_identifier.value).to eq('DE777777777')+ expect(order.tax_identifier.value).to eq(company_vat)expect(order.tax_identifier.source).to eq('company')# The copy belongs to the order, not the company it was resolved from.expect(order.tax_identifier.owner).to eq(order)diff --git a/spree/core/spree_core.gemspec b/spree/core/spree_core.gemspecindex 61f727c7d8..baa3a3c50c 100644--- a/spree/core/spree_core.gemspec+++ b/spree/core/spree_core.gemspec@@ -58,6 +58,7 @@ Gem::Specification.new do |s|s.add_dependency 'stringex's.add_dependency 'tracking_number's.add_dependency 'validates_zipcode'+ s.add_dependency 'valvat', '~> 2.0's.add_dependency 'image_processing', '~> 1.2's.add_dependency 'active_storage_validations', '>= 1.3', '< 4's.add_dependency 'mobility', '~> 1.3', '>= 1.3.2'