Skip to content

armgit / spree

Public Imported from GitHub
0

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

12.7 KB
Raw Blame

VIES VAT Registry Validation

Status: Design Finalized (open questions resolved 2026-09-05) Target: Spree 6.1 Depends on: 6.0-tax-provider.md (shipped Spree::TaxIdentifier + Spree.tax_id_validators registry, TaxIdentifiers::Validate service, ValidateJob, validation subscriber, POST …/tax_identifiers/:id/validate); 6.0-b2b-companies-and-catalogs.md (company-owned identifiers, legal_entity resolution) Author: Damian + Claude Last updated: 2026-09-05 Tracking: Linear V-3619 · GitHub spree/spree#14614

Summary

Ship the registry half of EU VAT number validation as a free open-source gem: a validator that asks VIES (the EU's VAT Information Exchange System) whether a number is actually registered, records audit-grade evidence — the consultation number a qualified check returns — and keeps verdicts fresh over time. Core 6.0 deliberately shipped only the offline half (Spree::TaxIdentifiers::Validator::EuVat: format + checksum via valvat, checks_registry? false) with a documented contract that an extension re-registers eu_vat and takes over both halves; this plan is that extension. The pipeline — statuses (pending / verified / unverified / unavailable / unsupported), async job, subscriber, admin validate endpoint — already exists and starts doing real work the moment the gem registers.

Free because compliance plumbing cannot be a paid feature (the same reasoning that put exemption certificates in OSS): the underlying API is free and credential-less, the strongest precedent ships it free in open source, and closed SaaS platforms validate at checkout as a built-in — "real VIES validation with audit-grade evidence, free" extends the 6.0 B2B headline. The Enterprise tier keeps its distance: governance and commercial terms, never compliance.

Key Decisions (do not deviate without discussion)

  • A gem, never core. Reaffirming 6.0-tax-provider.md: no registry client in core. The gem re-registers the eu_vat kind with a validator whose checks_registry? is true and which keeps the offline half as its first step (format-invalid fails fast as unverified, no network call).
  • valvat's lookup client is the transport. Core already depends on valvat for checksums and deliberately avoids loading its lookup half; the gem uses it. valvat supports the qualified request (requester: option) and surfaces the consultation number and trader details — hand-rolling a VIES client would duplicate a battle-tested one we already ship.
  • Qualified checks whenever possible — the consultation number is the point. A plain check answers valid/invalid; a qualified check (supplying the merchant's own VAT number) returns a consultation number, the official proof that this number was verified on that date — what defends zero-rating a reverse-charge sale in an audit. When the store has no requester VAT number configured, the gem downgrades to plain checks and says so in the evidence.
  • The merchant's own registrations become first-class: store is the fifth TaxIdentifier owner (2026-09-05). A small core 6.1 change adds store_id to spree_tax_identifiers (exactly-one-owner validation extended, (store_id, kind) unique) with admin CRUD and a "Your tax registrations" card in dashboard tax settings. The gem reads its requester as store.tax_identifiers of kind eu_vat — no preference field — and the merchant's own number flows through the same validation pipeline as everyone else's. This is also the durable home future merchant-side registrations (OSS/IOSS, GB) were always going to need.
  • Evidence is persisted, not just a status. Every registry answer writes the identifier's validation_status/validated_at (as today) and an evidence record in the identifier's metadata under a vies key: verdict, checked-at, consultation number, requester VAT used, and the trader name/address VIES returned — plus a capped history (last 10 checks), because the audit question is "was it valid when you zero-rated it", which the current-status columns alone cannot answer.
  • invalid and couldn't ask never blur. VIES proxies 27 national registries and individual member states go down routinely (MS_UNAVAILABLE), rate limits included. A registry that cannot answer yields unavailable (the base contract already demands this) and the check is re-queued with backoff; only an actual "not registered" answer yields unverified. The gem never turns an outage into a rejection.
  • Verdicts are data; tax policy stays with tax providers. The gem delivers statuses and evidence. Whether an unverified-but-format-valid number still earns reverse charge during a VIES outage is a decision for the consuming tax provider — this gem takes no checkout-blocking stance (deliberately unlike the SaaS precedent, which blocks with no override).
  • Name/address matching is a soft signal, never a gate. Returned trader details are stored and surfaced (a "registered name differs" hint in the dashboard) but never fail a validation — several member states (Germany foremost) return no trader details at all.
  • EU first; GB is a fast-follow kind in the same gem (2026-09-05). SpreeVies::HmrcValidator registers for gb_vat right after the VIES core ships — HMRC's free check-VAT API follows the same evidence pattern (it returns a consultation number too). Switzerland and Norway arrive later as further kinds — nothing in this gem's design may assume VIES is the only registry.

Design Details

The validator

module SpreeVies
  class Validator < Spree::TaxIdentifiers::Validator::EuVat
    def self.checks_registry? = true

    # Called by Spree::TaxIdentifiers::Validate (unchanged core service).
    # 1. Offline half first — inherited valid_format?; a malformed number is
    #    'unverified' with no network call.
    # 2. Qualified VIES lookup via Valvat::Lookup (requester: store VAT when
    #    configured), mapped to a ValidationResult:
    #      registered      -> 'verified'   (+ evidence)
    #      not registered  -> 'unverified' (+ evidence)
    #      MS_UNAVAILABLE, timeout, rate-limit -> 'unavailable' (retryable)
    def self.check_registry(tax_identifier)
      # ...
    end
  end
end

# engine initializer
Spree.tax_id_validators['eu_vat'] = 'SpreeVies::Validator'

The core Validate service already maps raised transport errors to an unavailable result; the validator only raises typed errors for genuinely unexpected failures.

Evidence shape (tax_identifier.metadata['vies'])

{
  "last": {
    "status": "verified",
    "checked_at": "2026-09-05T10:12:00Z",
    "consultation_number": "WAPIAAAAY8kFxxxx",
    "requester_vat": "PL5252242171",
    "name": "ACME GMBH",
    "address": "HAUPTSTR. 1, 10115 BERLIN"
  },
  "history": [ { "...": "last 10 entries, newest first" } ]
}

Not columns: the shape is registry-specific, and the HMRC/CH/NO validators will write their own keys. The columns stay what they are today — the cross-registry summary (validation_status, validated_at).

Requester VAT number — store-owned TaxIdentifier (core 6.1 change)

Core gains store as the fifth identifier owner: store_id on spree_tax_identifiers, the exactly-one-owner validation extended, (store_id, kind) unique index, Spree::Store has_many :tax_identifiers, admin CRUD (/api/v3/admin/tax_identifiers, store-owned rows only, under the settings scope) and a "Your tax registrations" card in dashboard tax settings. The merchant's own numbers run through the same validation pipeline as buyers' numbers — a merchant with an invalid registration finds out from their own dashboard.

The gem resolves its requester as the store's eu_vat identifier. Present → every check is qualified and earns a consultation number; absent → plain checks, and the evidence records "qualified": false so the admin UI can nudge ("add your VAT registration to get audit evidence").

Resilience & freshness

  • Retries: unavailable results re-queue the existing ValidateJob with exponential backoff (minutes → hours, capped attempts per day); VIES's own rate-limit responses are honored with a global cool-off.
  • Throttling: one identifier is never checked twice concurrently (the job already runs per-identifier; the gem adds an in-flight guard).
  • Re-validation: numbers get deregistered, so verified decays — a recurring task (spree_vies:revalidate, wired as a Solid Queue recurring job in the starter, plain rake elsewhere) re-enqueues identifiers whose validated_at is older than the freshness window (default 90 days, gem-configurable). On-demand re-checks stay on the existing admin endpoint.

Dashboard

Small additions to the existing tax registration card (company page and customer page): the status badge gains evidence detail — "Verified via VIES on ⟨date⟩ · consultation #⟨n⟩", registered name/address when returned, a soft "differs from company name" hint, a re-validate button (existing endpoint), and the requester-VAT nudge when checks are unqualified. Plus the requester VAT field in tax settings. All behind data the serializer already carries (metadata).

Testing

Client stubbed with WebMock fixtures for the full verdict matrix (valid, invalid, MS_UNAVAILABLE, timeout, rate-limited, qualified vs plain) — never live VIES in CI. valvat's own test helpers cover lookup stubbing.

Migration Path

One additive core migration (store_id on spree_tax_identifiers); no data tasks, no upgrade-manifest step. Phases:

  1. Core: store-owned identifiers — fifth owner (store_id, exactly-one validation, (store_id, kind) unique), Store has_many, admin CRUD + serializer, dashboard "Your tax registrations" card in tax settings.
  2. Gem skeleton — spree/providers/vies (spree_vies) engine with the validator, registry re-registration, verdict mapping, evidence persistence.
  3. Resilience — backoff/re-queue on unavailable, rate-limit cool-off, in-flight guard.
  4. Qualified checks — requester resolution from the store's eu_vat identifier, evidence qualified flag.
  5. Freshness — spree_vies:revalidate recurring task (default 90 days, SpreeVies.freshness configurable), wired as a Solid Queue recurring job in the starter.
  6. Dashboard — evidence on the registration card, re-validate affordance, requester nudge.
  7. Docs — how verification interacts with reverse charge and exemptions; the "verdicts are data" guidance for tax-provider authors.
  8. GB fast-follow — SpreeVies::HmrcValidator for the gb_vat kind (HMRC check-VAT REST, its consultation number in evidence under an hmrc key).

Constraints on Current Work

  • Core's Validator::EuVat stays the offline half and keeps working standalone — no VIES calls, no valvat lookup loading in core, ever.
  • Nothing may treat validation_status as a checkout gate. Consumers (tax providers, exemption resolution) read it as evidence quality: unavailable/pending mean not yet known, never invalid. Blocking behavior, if a merchant wants it, belongs to the tax provider's configuration — not to core, not to this gem.
  • Registry evidence lives under a registry-specific metadata key, and new registry validators follow the same pattern — no evidence columns on spree_tax_identifiers.
  • A new registry (GB, CH, NO) is a new validator kind in Spree.tax_id_validators — never a special case inside the VIES validator.

Open Questions

All four design questions (gem location, requester VAT source, freshness window, GB scope) were resolved 2026-09-05 and folded into Key Decisions: monorepo spree/providers/vies; store-owned TaxIdentifier as the fifth owner; 90-day freshness default; GB as a fast-follow kind in the same gem. Nothing is currently open.

References

  • Core contract this fills: spree/core/app/models/spree/tax_identifiers/validator/eu_vat.rb (checks_registry? and its documentation), validator/base.rb, spree/core/app/services/spree/tax_identifiers/validate.rb, spree/core/app/jobs/spree/tax_identifiers/validate_job.rb
  • 6.0-tax-provider.md — the validator-registry decision ("NOT a provider method, no registry client in core"); 6.0-b2b-companies-and-catalogs.md — identifiers on legal-entity nodes, legal_entity resolution
  • VIES REST/SOAP services (credential-less); valvat lookup (requester: → consultation number); HMRC check-VAT API (GB follow-on)
  • Precedent: the leading open-source suite ships built-in VIES validation free with automatic group assignment; the leading SaaS validates at checkout with no override on outage — the resilience stance above is the deliberate contrast.