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 store-owned tax exemption reasons, a Taxes settings page and clearer tax engine failures
Damian Legawiec214c5aa64bb7
diff --git a/.changeset/tax-exemption-reasons.md b/.changeset/tax-exemption-reasons.mdnew file mode 100644index 0000000000..b753d0fb4a--- /dev/null+++ b/.changeset/tax-exemption-reasons.md@@ -0,0 +1,6 @@+---+"@spree/admin-sdk": minor+"@spree/dashboard": minor+---++Added `taxExemptionReasons`, the store's own list of reasons a business can give for buying without tax, with list, get, create, update and delete. Each reason has a `code` the tax engine receives. Tax exemption certificates now point at a reason with `tax_exemption_reason_id` instead of recording `reason_code`, and can expand `tax_exemption_reason`. `taxProviders.list()` is now typed (`TaxProviderOption`) and says which exemption reason codes each engine reads. The dashboard gains one Settings → Taxes page with tabs for tax categories, tax rates and exemption reasons, which also shows the tax service each market uses; the certificate form offers the store's reasons.diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex f53c2a1a22..d994afa772 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -27673,6 +27673,399 @@ paths:responses:'204':description: return reason deleted+ "/api/v3/admin/tax_exemption_reasons":+ get:+ summary: List tax exemption reasons+ tags:+ - Reasons+ security:+ - api_key: []+ bearer_auth: []+ description: |-+ Why a business buys without tax — the reasons a merchant can record on a+ tax exemption certificate. Each has the merchant's own `name` and a `code`,+ which certificates record and the tax provider receives.++ The vocabulary is the merchant's own — seeded with a starting set and+ edited from the dashboard. A provider whose engine reads the code lists+ the codes it understands on `GET /tax_providers`. Inactive rows stay on the+ certificates that already record them, but are not offered on new ones.+++ **Required scope:** `read_settings` (for API-key authentication).+ x-codeSamples:+ - lang: javascript+ label: Spree Admin SDK+ source: |-+ import { createAdminClient } from '@spree/admin-sdk'++ const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+ })++ const { data: reasons } = await client.taxExemptionReasons.list()+ - lang: bash+ label: Spree CLI+ source: spree api get /tax_exemption_reasons+ parameters:+ - name: x-spree-api-key+ in: header+ required: true+ schema:+ type: string+ - name: Authorization+ in: header+ required: true+ description: Bearer token for admin authentication+ schema:+ type: string+ - name: page+ in: query+ required: false+ description: Page number+ schema:+ type: integer+ - name: limit+ in: query+ required: false+ description: Number of records per page+ schema:+ type: integer+ - name: q+ in: query+ required: false+ style: deepObject+ explode: true+ schema:+ type: object+ additionalProperties: true+ description: Attribute filters, as `q[<attribute>_<predicate>]=value`. See+ Filters above for the list.+ - name: sort+ in: query+ required: false+ description: Sort by field. Prefix with `-` for descending (e.g., `-created_at`).+ schema:+ type: string+ x-mint:+ content: |-+ ## Filters++ Filter with `q[<attribute>_<predicate>]=value`, for example `q[name_cont]=…`. Send a list as `q[<attribute>_in][]=a&q[<attribute>_in][]=b`. [How filters work](/api-reference/admin-api/querying#which-filters-an-endpoint-accepts).++ | Attribute | Kind | Predicates |+ |---|---|---|+ | `active` | True or false | `eq` `not_eq` `in` `not_in` `true` `false` `null` |+ | `code` | Text | `eq` `not_eq` `in` `not_in` `cont` `i_cont` `not_cont` `start` `end` `null` `not_null` `present` `blank` |+ | `created_at` | Date and time | `eq` `not_eq` `in` `not_in` `lt` `lteq` `gt` `gteq` `null` `not_null` |+ | `id` | Prefixed ID | `eq` `not_eq` `in` `not_in` `null` `not_null` |+ | `name` | Text | `eq` `not_eq` `in` `not_in` `cont` `i_cont` `not_cont` `start` `end` `null` `not_null` `present` `blank` |+ | `updated_at` | Date and time | `eq` `not_eq` `in` `not_in` `lt` `lteq` `gt` `gteq` `null` `not_null` |++ **Sort by:** `active`, `code`, `created_at`, `id`, `name`, `updated_at`. Prefix a field with `-` to sort descending.+ x-spree-filters:+ table: TaxExemptionReason+ sortable:+ - active+ - code+ - created_at+ - id+ - name+ - updated_at+ responses:+ '200':+ description: tax exemption reasons found+ content:+ application/json:+ example:+ data:+ - id: txr_UkLWZg9DAJ+ name: Reseller (wholesale)+ code: G+ active: true+ metadata: {}+ created_at: '2026-01-15T12:00:00.000Z'+ updated_at: '2026-01-15T12:00:00.000Z'+ can_be_deleted: true+ meta:+ page: 1+ limit: 25+ count: 1+ pages: 1+ from: 1+ to: 1+ in: 1+ previous:+ next:+ '401':+ description: unauthorized+ content:+ application/json:+ example:+ error:+ code: authentication_required+ message: Authentication required+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ post:+ summary: Create a tax exemption reason+ tags:+ - Reasons+ security:+ - api_key: []+ bearer_auth: []+ description: |-+ Adds a tax exemption reason to this store. Names and codes are unique per store.++ **Required scope:** `write_settings` (for API-key authentication).+ x-codeSamples:+ - lang: javascript+ label: Spree Admin SDK+ source: |-+ import { createAdminClient } from '@spree/admin-sdk'++ const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+ })++ // `code` is what certificates record and the tax engine receives — on+ // Avalara, an entity use code such as `G` (resale).+ const reason = await client.taxExemptionReasons.create({+ name: 'Reseller (wholesale)',+ code: 'G',+ })+ - lang: bash+ label: Spree CLI+ source: spree api post /tax_exemption_reasons -d '{"name":"Reseller (wholesale)","code":"G"}'+ parameters:+ - name: x-spree-api-key+ in: header+ required: true+ schema:+ type: string+ - name: Authorization+ in: header+ required: true+ description: Bearer token for admin authentication+ schema:+ type: string+ responses:+ '201':+ description: tax exemption reason created+ content:+ application/json:+ example:+ id: txr_gbHJdmfrXB+ name: Federal government+ code: A+ active: true+ metadata: {}+ created_at: '2026-01-15T12:00:00.000Z'+ updated_at: '2026-01-15T12:00:00.000Z'+ can_be_deleted: true+ '422':+ description: validation error+ content:+ application/json:+ example:+ error:+ code: validation_error+ message: Name can't be blank and Code can't be blank+ details:+ name:+ - code: blank+ message: can't be blank+ specific: false+ code:+ - code: blank+ message: can't be blank+ specific: false+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ requestBody:+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/TaxExemptionReasonCreateParams"+ required: true+ "/api/v3/admin/tax_exemption_reasons/{id}":+ parameters:+ - name: id+ in: path+ required: true+ description: Tax exemption reason ID+ schema:+ type: string+ get:+ summary: Get a tax exemption reason+ tags:+ - Reasons+ security:+ - api_key: []+ bearer_auth: []+ description: |-+ Returns a single tax exemption reason by prefixed ID.++ **Required scope:** `read_settings` (for API-key authentication).+ x-codeSamples:+ - lang: javascript+ label: Spree Admin SDK+ source: |-+ import { createAdminClient } from '@spree/admin-sdk'++ const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+ })++ const reason = await client.taxExemptionReasons.get('txr_UkLWZg9DAJ')+ - lang: bash+ label: Spree CLI+ source: spree api get /tax_exemption_reasons/{id}+ parameters:+ - name: x-spree-api-key+ in: header+ required: true+ schema:+ type: string+ - name: Authorization+ in: header+ required: true+ description: Bearer token for admin authentication+ schema:+ type: string+ responses:+ '200':+ description: tax exemption reason found+ content:+ application/json:+ example:+ id: txr_UkLWZg9DAJ+ name: Reseller (wholesale)+ code: G+ active: true+ metadata: {}+ created_at: '2026-01-15T12:00:00.000Z'+ updated_at: '2026-01-15T12:00:00.000Z'+ can_be_deleted: true+ '404':+ description: tax exemption reason not found+ content:+ application/json:+ example:+ error:+ code: record_not_found+ message: Tax exemption reason not found+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ patch:+ summary: Update a tax exemption reason+ tags:+ - Reasons+ security:+ - api_key: []+ bearer_auth: []+ description: |-+ Renames a tax exemption reason or retires it. Deactivating keeps it on the+ certificates that already record it while removing it from the pickers. The+ code is fixed once a certificate records it.+++ **Required scope:** `write_settings` (for API-key authentication).+ x-codeSamples:+ - lang: javascript+ label: Spree Admin SDK+ source: |-+ import { createAdminClient } from '@spree/admin-sdk'++ const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+ })++ const reason = await client.taxExemptionReasons.update('txr_UkLWZg9DAJ', {+ active: false,+ })+ - lang: bash+ label: Spree CLI+ source: spree api patch /tax_exemption_reasons/{id} -d '{"active":false}'+ parameters:+ - name: x-spree-api-key+ in: header+ required: true+ schema:+ type: string+ - name: Authorization+ in: header+ required: true+ description: Bearer token for admin authentication+ schema:+ type: string+ responses:+ '200':+ description: tax exemption reason updated+ content:+ application/json:+ example:+ id: txr_UkLWZg9DAJ+ name: Reseller (wholesale)+ code: G+ active: false+ metadata: {}+ created_at: '2026-01-15T12:00:00.000Z'+ updated_at: '2026-01-15T12:00:00.000Z'+ can_be_deleted: true+ requestBody:+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/TaxExemptionReasonUpdateParams"+ required: true+ delete:+ summary: Delete a tax exemption reason+ tags:+ - Reasons+ security:+ - api_key: []+ bearer_auth: []+ description: |-+ Removes a tax exemption reason the store no longer uses. A reason a+ certificate records is refused — deactivate it instead.+++ **Required scope:** `write_settings` (for API-key authentication).+ x-codeSamples:+ - lang: javascript+ label: Spree Admin SDK+ source: |-+ import { createAdminClient } from '@spree/admin-sdk'++ const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+ })++ await client.taxExemptionReasons.delete('txr_UkLWZg9DAJ')+ - lang: bash+ label: Spree CLI+ source: spree api delete /tax_exemption_reasons/{id}+ parameters:+ - name: x-spree-api-key+ in: header+ required: true+ schema:+ type: string+ - name: Authorization+ in: header+ required: true+ description: Bearer token for admin authentication+ schema:+ type: string+ responses:+ '204':+ description: tax exemption reason deleted"/api/v3/admin/promotions/{promotion_id}/coupon_codes":parameters:- name: promotion_id@@ -41217,11 +41610,11 @@ paths:| `created_at` | Date and time | `eq` `not_eq` `in` `not_in` `lt` `lteq` `gt` `gteq` `null` `not_null` || `expires_at` | Date and time | `eq` `not_eq` `in` `not_in` `lt` `lteq` `gt` `gteq` `null` `not_null` || `id` | Prefixed ID | `eq` `not_eq` `in` `not_in` `null` `not_null` |- | `reason_code` | Text | `eq` `not_eq` `in` `not_in` `cont` `i_cont` `not_cont` `start` `end` `null` `not_null` `present` `blank` || `status` | One of `pending`, `verified`, `expired`, `revoked` | `eq` `not_eq` `in` `not_in` `null` `not_null` |+ | `tax_exemption_reason_id` | Prefixed ID | `eq` `not_eq` `in` `not_in` `null` `not_null` || `updated_at` | Date and time | `eq` `not_eq` `in` `not_in` `lt` `lteq` `gt` `gteq` `null` `not_null` |- **Sort by:** `certificate_number`, `created_at`, `expires_at`, `id`, `reason_code`, `status`, `updated_at`. Prefix a field with `-` to sort descending.+ **Sort by:** `certificate_number`, `created_at`, `expires_at`, `id`, `status`, `tax_exemption_reason_id`, `updated_at`. Prefix a field with `-` to sort descending.x-spree-filters:table: TaxExemptionCertificatesortable:@@ -41229,8 +41622,8 @@ paths:- created_at- expires_at- id- - reason_code- status+ - tax_exemption_reason_id- updated_atresponses:'200':@@ -41241,7 +41634,6 @@ paths:data:- id: cert_UkLWZg9DAJcertificate_number: DE-RESALE-1- reason_code: resalestatus: pendingissuing_authority:metadata: {}@@ -41251,6 +41643,7 @@ paths:created_at: '2026-01-15T12:00:00.000Z'updated_at: '2026-01-15T12:00:00.000Z'company_id: comp_UkLWZg9DAJ+ tax_exemption_reason_id: txr_UkLWZg9DAJcountry_code:state_code:active: false@@ -41300,7 +41693,7 @@ paths:// `signed_id` comes from `client.files.upload(file, { visibility: 'private' })`.const certificate = await client.companies.taxExemptionCertificates.create('comp_UkLWZg9DAJ', {certificate_number: 'DE-RESALE-7',- reason_code: 'resale',+ tax_exemption_reason_id: 'txr_UkLWZg9DAJ',country_code: 'DE',document_signed_id: signed_id,})@@ -41317,7 +41710,6 @@ paths:example:id: cert_gbHJdmfrXBcertificate_number: DE-RESALE-7- reason_code: resalestatus: pendingissuing_authority:metadata: {}@@ -41327,6 +41719,7 @@ paths:created_at: '2026-01-15T12:00:00.000Z'updated_at: '2026-01-15T12:00:00.000Z'company_id: comp_UkLWZg9DAJ+ tax_exemption_reason_id: txr_UkLWZg9DAJcountry_code: DEstate_code:active: false@@ -41416,7 +41809,6 @@ paths:example:id: cert_UkLWZg9DAJcertificate_number: DE-RESALE-1- reason_code: resalestatus: pendingissuing_authority: Finanzamt Berlinmetadata: {}@@ -41426,6 +41818,7 @@ paths:created_at: '2026-01-15T12:00:00.000Z'updated_at: '2026-01-15T12:00:00.000Z'company_id: comp_UkLWZg9DAJ+ tax_exemption_reason_id: txr_UkLWZg9DAJcountry_code:state_code:active: false@@ -41508,7 +41901,6 @@ paths:example:id: cert_UkLWZg9DAJcertificate_number: DE-RESALE-1- reason_code: resalestatus: verifiedissuing_authority:metadata: {}@@ -41518,6 +41910,7 @@ paths:created_at: '2026-01-15T12:00:00.000Z'updated_at: '2026-01-15T12:00:00.000Z'company_id: comp_UkLWZg9DAJ+ tax_exemption_reason_id: txr_UkLWZg9DAJcountry_code:state_code:active: true@@ -41588,7 +41981,6 @@ paths:example:id: cert_gbHJdmfrXBcertificate_number: CERT-1- reason_code: resalestatus: revokedissuing_authority:metadata: {}@@ -41598,6 +41990,7 @@ paths:created_at: '2026-01-15T12:00:00.000Z'updated_at: '2026-01-15T12:00:00.000Z'company_id: comp_UkLWZg9DAJ+ tax_exemption_reason_id: txr_UkLWZg9DAJcountry_code:state_code:active: false@@ -55480,8 +55873,8 @@ tags:- name: Policiesdescription: The store's legal documents — terms of service, privacy, returns, shipping- name: Reasons- description: Merchant-owned vocabularies for why a return, claim, refund or cancellation- happened+ description: Merchant-owned vocabularies for why a return, claim, refund, cancellation+ or tax exemption happened- name: Promotionsdescription: Promotions, promotion rules, promotion actions, and coupon codes- name: Refunds@@ -71758,8 +72151,6 @@ components:type: stringcertificate_number:type: string- reason_code:- type: stringstatus:anyOf:- type: string@@ -71792,6 +72183,10 @@ components:type: stringcompany_id:type: string+ tax_exemption_reason_id:+ type: string+ tax_exemption_reason:+ "$ref": "#/components/schemas/TaxExemptionReason"country_code:type: stringnullable: true@@ -72057,7 +72452,6 @@ components:required:- id- certificate_number- - reason_code- status- issuing_authority- metadata@@ -72067,6 +72461,7 @@ components:- created_at- updated_at- company_id+ - tax_exemption_reason_id- country_code- state_code- active@@ -72076,6 +72471,36 @@ components:- document_byte_size- document_urlx-typelizer: true+ TaxExemptionReason:+ type: object+ properties:+ id:+ type: string+ name:+ type: string+ code:+ type: string+ active:+ type: boolean+ metadata:+ type: object+ nullable: true+ created_at:+ type: string+ updated_at:+ type: string+ can_be_deleted:+ type: boolean+ required:+ - id+ - name+ - code+ - active+ - metadata+ - created_at+ - updated_at+ - can_be_deleted+ x-typelizer: trueTaxIdentifier:type: objectproperties:@@ -81837,10 +82262,10 @@ components:certificate_number:type: stringexample: DE-RESALE-7- reason_code:+ tax_exemption_reason_id:type: string- description: Becomes the tax provider's entity use code.- example: resale+ description: One of the store's active tax exemption reasons. The tax provider+ receives its `code`.issuing_authority:type: stringexample: Finanzamt Berlin@@ -81870,17 +82295,17 @@ components:additionalProperties: truerequired:- certificate_number- - reason_code+ - tax_exemption_reason_idTaxExemptionCertificateUpdateParams:type: objectproperties:certificate_number:type: stringexample: DE-RESALE-7- reason_code:+ tax_exemption_reason_id:type: string- description: Becomes the tax provider's entity use code.- example: resale+ description: One of the store's active tax exemption reasons. The tax provider+ receives its `code`.issuing_authority:type: stringexample: Finanzamt Berlin@@ -81908,6 +82333,43 @@ components:metadata:type: objectadditionalProperties: true+ TaxExemptionReasonCreateParams:+ type: object+ properties:+ name:+ type: string+ active:+ type: boolean+ description: Whether the reason is offered on new records.+ code:+ type: string+ description: What the tax provider receives for every certificate holding+ this reason — for Avalara, an entity use code such as `G`. Saved in capitals.+ Changing it changes what those certificates send from then on.+ example: RESALE+ metadata:+ type: object+ additionalProperties: true+ required:+ - name+ - code+ TaxExemptionReasonUpdateParams:+ type: object+ properties:+ name:+ type: string+ active:+ type: boolean+ description: Whether the reason is offered on new records.+ code:+ type: string+ description: What the tax provider receives for every certificate holding+ this reason — for Avalara, an entity use code such as `G`. Saved in capitals.+ Changing it changes what those certificates send from then on.+ example: RESALE+ metadata:+ type: object+ additionalProperties: trueTaxIdentifierCreateParams:type: objectproperties:@@ -83820,13 +84282,23 @@ components:created_at: datetimeexpires_at: datetimeid: id- reason_code: textstatus:enum:- pending- verified- expired- revoked+ tax_exemption_reason_id: id+ updated_at: datetime+ associations: {}+ scopes: {}+ TaxExemptionReason:+ attributes:+ active: boolean+ code: text+ created_at: datetime+ id: id+ name: textupdated_at: datetimeassociations: {}scopes: {}diff --git a/docs/developer/core-concepts/taxes.mdx b/docs/developer/core-concepts/taxes.mdxindex c5c8bc5283..86b70894c1 100644--- a/docs/developer/core-concepts/taxes.mdx+++ b/docs/developer/core-concepts/taxes.mdx@@ -246,6 +246,8 @@ Business customers are often exempt, and the paperwork is real. Spree records aExemption is decided when tax is worked out, not stored as a flag on the customer, so an expired certificate stops applying by itself. See [Companies](/developer/core-concepts/companies).+Each certificate points at one of the store's **tax exemption reasons** — a list the merchant manages, like return and refund reasons. The tax service receives the reason's `code`. A tax service that decides exemptions by code declares the codes it understands, and the dashboard offers them when a merchant adds a reason. See [Exemption reasons](/developer/how-to/build-a-b2b-store#exemption-reasons).+## Related- [Order totals](/developer/core-concepts/order-totals) — how tax rolls into what a customer paysdiff --git a/docs/developer/how-to/build-a-b2b-store.mdx b/docs/developer/how-to/build-a-b2b-store.mdxindex a5cfea4787..745cb57cca 100644--- a/docs/developer/how-to/build-a-b2b-store.mdx+++ b/docs/developer/how-to/build-a-b2b-store.mdx@@ -805,6 +805,30 @@ curl -X POST 'https://api.mystore.com/api/v3/admin/companies/comp_xxx/tax_identiWhen a sale is for a company, the company's registration takes precedence over the buyer's own, because the invoice is addressed to the business.+### Exemption reasons++Every certificate points at one of the store's active tax exemption reasons, the way a product points at a tax category. A reason has a `name` in your own wording and a `code` your tax service reads. A new store has six neutral ones (`RESALE`, `GOVERNMENT`, `CHARITABLE`, `EDUCATIONAL`, `MANUFACTURING`, `AGRICULTURAL`). Avalara decides an exemption by its entity use code, so on Avalara change each reason's code to Avalara's, such as `G` for resale. `taxProviders.list()` returns the codes each tax service understands as `exemption_reason_codes`. Codes are stored in upper case.++<CodeGroup>++```typescript Admin SDK+const reason = await adminClient.taxExemptionReasons.create({+ name: 'Reseller (wholesale)',+ code: 'G',+})+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/admin/tax_exemption_reasons' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{ "name": "Reseller (wholesale)", "code": "G" }'+```++</CodeGroup>++Changing a reason's code changes what every certificate holding it sends from then on; orders already placed keep the code they were taxed with. Turn off `active` to stop offering a reason; certificates that already hold it keep it. A reason that certificates hold cannot be deleted.+### Exemption certificatesA certificate starts `pending` and exempts nothing until staff verify it. Scope it to the country or state that issued it, or leave both empty for one that holds everywhere.@@ -814,7 +838,7 @@ A certificate starts `pending` and exempts nothing until staff verify it. Scope```typescript Admin SDKconst certificate = await adminClient.companies.taxExemptionCertificates.create('comp_xxx', {certificate_number: 'RS-44-1901',- reason_code: 'resale',+ tax_exemption_reason_id: 'txr_xxx',country_code: 'US',state_code: 'CA',expires_at: '2027-12-31',diff --git a/docs/docs.json b/docs/docs.jsonindex 9d09b3dfa9..a4adf0b51f 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -594,7 +594,7 @@},{"source": "/user/settings/tax",- "destination": "/user/settings/tax-rates"+ "destination": "/user/settings/taxes"},{"source": "/user/settings/returns-configuration",@@ -1376,6 +1376,7 @@"pages": ["user/settings/markets","user/settings/payments",+ "user/settings/taxes","user/settings/tax-categories","user/settings/tax-rates"]diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.mdindex bc047ee227..c0ab1c7734 100644--- a/docs/plans/6.0-tax-provider.md+++ b/docs/plans/6.0-tax-provider.md@@ -451,10 +451,32 @@ endMultiple certificates = multiple entries. Certificate *lifecycle* (verified/expired) is a resolution-time filter — only active certificates produce entries; presence of an entry is the claim. Providers translate: Avalara `reason_code` → `entityUseCode`, `certificate_number` → `exemptionNo`, item overrides → line-level codes (the generalization of what `spree_avatax_official` sends today from its user-level fields); Stripe → `taxability_override`.-**Assembly** — the `tax_resolve_exemptions_service` dependency (`Spree::Tax::ResolveExemptions`, plain Tier 1 service, `call(order:)` → array, **default returns `[]`**). Callers never build exemptions; providers never fetch them. In stock 6.0 the input is empty and the working exemption paths are provider-native certificates (Avalara merchants get durable per-customer exemption through Avalara's certificate store, needing nothing from our schema) and extensions swapping the service — the `spree_tax_avalara` gem keeping the legacy user-level `exemption_number`/`entity_use_code` as gem-owned storage is the seam's first real implementation. Company-backed `TaxExemptionCertificate` records become the default implementation's source in Phase 7, resolving into the same entries — which is what the empty default was standing in for, and why the seam shipped first.+**Assembly** — the `tax_resolve_exemptions_service` dependency (`Spree::Tax::ResolveExemptions`, plain Tier 1 service, `call(order:)` → array, **default returns `[]`**). Callers never build exemptions; providers never fetch them. In stock 6.0 the input is empty and the working exemption paths are provider-native certificates (Avalara merchants get durable per-customer exemption through Avalara's certificate store, needing nothing from our schema) and extensions swapping the service. (An earlier sketch had the Avalara gem keeping the legacy user-level `exemption_number`/`entity_use_code` as gem-owned storage swapped into this seam; `6.0-avalara-provider-gem.md` dropped that on 2026-08-19 — the gem consumes the seam without swapping it, and customer-level exemptions are its open question, preferring a core extension.) Company-backed `TaxExemptionCertificate` records became the default implementation's source in Phase 7, resolving into the same entries — which is what the empty default was standing in for, and why the seam shipped first.**Output** — zero-amount TaxLines with `customer_exempt`/`product_exempt` reasons, per the write contract. No flags anywhere: the claim is ephemeral input, the outcome is rows.+**A placed order keeps the claims it was priced with (2026-09-04).** "Never persisted" is narrowed, not reversed: resolution stays live for a cart, there is still no `spree_tax_exemptions` table and still no FK from a tax row to a certificate — but `spree_orders.applied_tax_exemptions` holds the resolved entries as plain data, frozen at completion beside the tax identifier and read back by `usable_exemptions` for a completed order. Re-resolving later is not the same evidence: a certificate lapses on its own `expires_at` with nothing written to it (`scope :active` is `verified AND not past its date`), can be revoked, and is destroyed with its company. An external provider commits and credits *after* placement, so a credit for an exempt sale was being filed with no `entityUseCode` at all — declaring tax the sale never collected. Which claims a sale was granted is a fact about that sale, like its registration. Orders placed before the column existed hold nothing and still resolve live.++Two corrections the review caught, both in the first cut of this (2026-09-04): **an empty snapshot is+a snapshot.** A consumer sale freezes `[]`, which records that the sale resolved and found nothing —+only `nil` is the legacy no-snapshot state, and the reader tests for that rather than `present?`.+Skipping the write for an empty result sent those orders back to live resolution, so a certificate+added to the company afterwards would start explaining a sale it was never part of: the same fault as+a lapsed certificate vanishing from one, in the other direction. And **a per-item override is+re-owned on the way in.** `ItemOverride#item_id` names its line by prefixed id, and completion gives+every line a new one, so the cart's ids match nothing on the order — and an override that matches+nothing does not narrow its claim, it widens it, which would exempt every line and file away tax the+sale collected. `Carts::Complete` translates line-item, fulfillment and fee ids through the maps it+already builds; one naming something the sale never had narrowed nothing while the cart was priced+either, so it is kept as-is and reported.++Two more paths the review found (2026-09-04): a **draft order** never went through the cart copier at+all — `Carts::Complete` hands it to `Orders::Complete`, which now pins its own claims, and that is the+path company certificates actually take. And a **split** hands the cart's snapshot to each sibling+through `CARRIED_TO_SIBLING`: every child is placed through `Orders::Complete` and so would pin+something regardless, but a child left to resolve again takes the resolver's cart-side override ids,+which match nothing it owns — widening the claim over every line it holds.+**Product-based exemption stays out of this input entirely** — groceries/clothing taxability is a property of the product, riding the existing TaxCategory → provider tax-code mapping (TaxCategory "Clothing" → Avalara `PC040100`), decided per line by the provider's own jurisdiction rules.**Hook boundary:** the `set_tax_line_context` hook is NOT the exemption channel. Typed inputs — exemptions from `tax_resolve_exemptions_service`, the identifier from `#resolved_tax_identifier`, the tax date from the caller — arrive as named `estimate` parameters: declared shapes, one implementation each, no deep-merge collisions. The hook remains for untyped provider-specific extras only (riding into `TaxLine.data` / provider requests as the `context:` parameter); its doc comment — which currently names "exemption certificates, customer tax IDs" as its payload — must be corrected before the 6.0 hook-contract freeze.@@ -1302,8 +1324,9 @@ class CreateSpreeTaxExemptionCertificates < ActiveRecord::Migration[8.1]t.string :country_code # nil = every countryt.string :state_code # nil = the entire countryt.string :certificate_number, null: false- t.string :reason_code, null: false # resale, government, … — becomes the- # provider's entity use code+ t.references :tax_exemption_reason, null: false # the store's reason (2026-10-17);+ # its code becomes the provider's+ # entity use codet.string :status, null: false # no DB default: set by the creating servicet.datetime :issued_att.datetime :expires_at@@ -1335,7 +1358,9 @@ class Spree::TaxExemptionCertificate < Spree.base_classhas_one_attached :document # the uploaded certificate PDF or image- validates :certificate_number, :reason_code, presence: true+ belongs_to :tax_exemption_reason++ validates :certificate_number, presence: truescope :active, -> { verified.where('expires_at IS NULL OR expires_at > ?', Time.current) }scope :for_address, ->(address) {@@ -1354,7 +1379,8 @@ def call(order:)success(company.tax_exemption_certificates.active.for_address(order.tax_address).map do |certificate|Spree::TaxExemption.new(- reason_code: certificate.reason_code,+ reason_code: certificate.tax_exemption_reason.code,+ reason_name: certificate.tax_exemption_reason.name,certificate_number: certificate.certificate_number,country_code: certificate.country&.iso,state_code: certificate.state&.abbrdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 3c20b8f21c..4d7b7d1257 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,23 @@+## 2026-10-17: Certificates point at their exemption reason++**Context:** Certificates stored a copy of their reason's code, so a code had to be locked once any certificate used it. A new store's seeded reasons could then never be switched to Avalara's codes, and finding a reason's certificates meant joining through companies on a copied string.++**Decision:** `Spree::TaxExemptionCertificate` `belongs_to :tax_exemption_reason`, like products and tax categories; the API takes `tax_exemption_reason_id`. A reason's code can change at any time and is stored in upper case. A tax line's exemption snapshot keeps the reason's name beside its code.++**Consequences:** Merchants on Avalara change each seeded code to Avalara's. Placed orders keep the code and name they were taxed with. A `spree:upgrade:tax_exemption_reasons` step seeds existing stores, saves existing codes in capitals, and links certificates recorded before reasons existed to the reason matching their old `reason_code`, which the migration keeps (nullable) for that purpose; until it runs, tax still reads an unlinked certificate's old code. The dashboard offers an engine's own codes only once a market uses that engine.++**Plan:** `6.0-tax-provider.md`.++## 2026-10-16: Tax exemption reasons are a store-owned model++**Context:** The reasons a merchant records on a tax exemption certificate came from a code registry: six values hard-coded in core, replaced by the vocabulary of whichever tax provider gem registered one. Spree's own tax engine never reads the reason, so for most stores it was a label the merchant could not rename, translate or extend, unlike every other reason list.++**Decision:** `Spree::TaxExemptionReason` is a store-owned model (`name`, `code`, `active`), managed beside return, claim, refund and order-cancellation reasons through `/api/v3/admin/tax_exemption_reasons`. A certificate keeps its `reason_code` string, which must name an active reason of its store when set. A tax provider declares the codes its engine understands (`exemption_reason_codes`, published on `/tax_providers`) so the dashboard can offer them, but it does not own the list. The registry, the default list in core and the `…/tax_exemption_certificates/reason_codes` endpoint are removed.++**Consequences:** Seeds give each store six neutral reasons; the Avalara upgrade task adds one per Avalara entity use code. A provider whose engine reads reason codes adds `exemption_reason_codes` rather than registering a list.++**Plan:** `6.0-tax-provider.md`.+## 2026-10-10: One upload endpoint, store-owned blobs, and `<slot>_signed_id` everywhere**Context:** Files reached Spree through `/direct_uploads`, which copied Active Storage's nested request and minted references that never expired, and nothing recorded which store a blob belonged to. Endpoints that took those references named them seven different ways.diff --git a/docs/user/customers/companies.mdx b/docs/user/customers/companies.mdxindex fdc1281e89..e6a900d117 100644--- a/docs/user/customers/companies.mdx+++ b/docs/user/customers/companies.mdx@@ -49,7 +49,7 @@ Tax registrations and exemption certificates belong to legal entities only, so aThat lookup stops at the first company, whether or not it holds a registration. A subsidiary with no VAT number of its own therefore has none: it never quietly borrows its parent's, because in most places that would be a false declaration.-Exemption certificates are scoped to the country or state that issued them, and stop applying when they expire.+Exemption certificates are scoped to the country or state that issued them, and stop applying when they expire. The reason a certificate gives comes from your own list of tax exemption reasons, which you manage in [<u>Taxes</u>](/user/settings/taxes#tax-exemption-reasons).## Purchase order numbersdiff --git a/docs/user/settings/returns-and-reasons.mdx b/docs/user/settings/returns-and-reasons.mdxindex ffe9e8aab0..ec3b0d6e06 100644--- a/docs/user/settings/returns-and-reasons.mdx+++ b/docs/user/settings/returns-and-reasons.mdx@@ -81,7 +81,7 @@ These reasons separate cancellations you can do something about from the ones yoFind the card for the kind of reason you are adding, then click **Add reason** on that card.-<Warning>All four cards carry a button labelled **Add reason**. The card you click on decides which list the reason joins, and a reason cannot be moved afterwards.</Warning>+<Warning>Every card carries a button labelled **Add reason**. The card you click on decides which list the reason joins, and a reason cannot be moved afterwards.</Warning>- **Name** - A description of the reason that staff will pick from a dropdown. Keep it short and unambiguous.- **Available on new records** - On by default. Controls whether the reason is offered when staff open a new return, claim, refund or cancellation.@@ -104,3 +104,4 @@ Unused reasons can be deleted outright from the row menu.- [<u>Claims</u>](/user/orders/claims) - Handling a delivery that went wrong- [<u>Processing Orders</u>](/user/orders/processing-orders) - Refunding and canceling an order- [<u>Policies</u>](/user/settings/policies) - Publishing your returns policy+- [<u>Taxes</u>](/user/settings/taxes) - Where tax exemption reasons are manageddiff --git a/docs/user/settings/tax-categories.mdx b/docs/user/settings/tax-categories.mdxindex f4bf680ff6..f76a7dd136 100644--- a/docs/user/settings/tax-categories.mdx+++ b/docs/user/settings/tax-categories.mdx@@ -7,7 +7,7 @@ A tax category groups products by how they should be taxed. Most stores need atA category holds no percentage of its own. It is a label you attach to products, and a [<u>tax rate</u>](/user/settings/tax-rates) then names the category and supplies the figure. Splitting it this way means one category can carry a different rate in every country you sell to.-To manage tax categories, navigate to **Settings → Tax categories**, under the **Selling** group.+To manage tax categories, navigate to **Settings → Taxes**, under the **Selling** group, and open the **Categories** tab. See [<u>Taxes</u>](/user/settings/taxes) for the whole screen.diff --git a/docs/user/settings/tax-rates.mdx b/docs/user/settings/tax-rates.mdxindex 3fbfebac04..2964c73550 100644--- a/docs/user/settings/tax-rates.mdx+++ b/docs/user/settings/tax-rates.mdx@@ -9,9 +9,9 @@ The figures themselves come from the tax authority in each place you sell. WhatMost stores end up with several: one per category per country, and more where a country taxes by state. For example, a store selling standard and reduced-rate goods into three countries needs six rates.-To manage tax rates, navigate to **Settings → Tax rates**, under the **Selling** group.+To manage tax rates, navigate to **Settings → Taxes**, under the **Selling** group, and open the **Rates** tab. See [<u>Taxes</u>](/user/settings/taxes) for the whole screen.-<Note>Tax rates configure Spree's built-in tax engine. They do not decide which engine a market uses. If you have connected an external tax provider, select it in **Tax engine** on each [<u>market</u>](/user/settings/markets) rather than configuring rates here.</Note>+<Note>Tax rates configure Spree's built-in tax engine. They do not decide which engine a market uses. If you have connected an external tax provider, select it in **Tax engine** on each [<u>market</u>](/user/settings/markets) rather than configuring rates here. The **Rates** tab names any market that uses a connected service, since these rates do not apply there.</Note>## Reviewing Your Tax Ratesdiff --git a/docs/user/settings/taxes.mdx b/docs/user/settings/taxes.mdxnew file mode 100644index 0000000000..b9419c127a--- /dev/null+++ b/docs/user/settings/taxes.mdx@@ -0,0 +1,51 @@+---+title: "Taxes"+description: "Learn where tax is set up in Spree Commerce: tax categories, tax rates and the reasons businesses give for buying without tax."+---++Everything that decides the tax on an order sits on one screen. Navigate to **Settings → Taxes**, under the **Selling** group.++The screen has three tabs:++- **Categories** - How your products are grouped for tax, such as Standard or Reduced rate. See [<u>Tax Categories</u>](/user/settings/tax-categories).+- **Rates** - The percentages Spree's built-in tax calculation charges, per category and place. See [<u>Tax Rates</u>](/user/settings/tax-rates).+- **Exemption reasons** - Why a business may buy without tax. See [Tax Exemption Reasons](#tax-exemption-reasons) below.++You only see the tabs your role lets you open.++## Which Service Works Out Your Tax++Each [<u>market</u>](/user/settings/markets) chooses who works out its tax: Spree's built-in calculation, or a connected service such as Avalara. The **Tax calculation** box under the page title lists your markets by the service each one uses, for example **Avalara AvaTax in United States**. Click **Manage markets** to change it.++This matters for the **Rates** tab. Your tax rates only apply to markets on Spree's built-in calculation. A connected service works the tax out itself and never reads them. The **Rates** tab says so, and when some of your markets use a connected service it names them, so you know the rates you edit there do not apply in those markets.++## Tax Exemption Reasons++Why a business buys without tax, such as resale or a government purchase. Staff pick one when recording a company's [<u>tax exemption certificate</u>](/user/customers/companies).++Each reason has a **Name**, which is your own wording, and a **Code**, which your tax service receives. Spree's built-in calculation only keeps the code for reference, so any short code works. If a market calculates tax through Avalara, the code decides the exemption: once a market uses Avalara, the form offers Avalara's codes, such as `G` for resale or `A` for federal government, and you name each reason however you like. Change the code of each reason you use to Avalara's.++A new store arrives with six:++- Agricultural+- Charitable organization+- Educational institution+- Government+- Manufacturing+- Resale++To add one, click **Add reason** and fill in:++- **Name** - What staff pick from the list on a certificate.+- **Code** - What your tax service receives. Saved in capital letters.+- **Available on new records** - On by default. Turn it off to stop offering the reason on new certificates.++<Note>You can change a reason's name or code at any time. Every certificate with that reason follows, while orders already placed keep the reason they were taxed with. A reason that certificates use cannot be deleted, but you can retire it by turning off **Available on new records**.</Note>++## Further Reading++- [<u>Tax Categories</u>](/user/settings/tax-categories) - Grouping products by how they are taxed+- [<u>Tax Rates</u>](/user/settings/tax-rates) - The percentages charged in each place+- [<u>Markets</u>](/user/settings/markets) - Where each market's tax service is chosen+- [<u>Companies</u>](/user/customers/companies) - Recording a business's tax exemption certificates+- [<u>Integrations</u>](/user/settings/integrations) - Connecting a tax service such as Avalaradiff --git a/docs/user/user-quickstart-guide.mdx b/docs/user/user-quickstart-guide.mdxindex cc89653a09..f31de35711 100644--- a/docs/user/user-quickstart-guide.mdx+++ b/docs/user/user-quickstart-guide.mdx@@ -83,7 +83,7 @@ This address will appear on your storefront and works as a contact for your cust-To charge the correct taxes at checkout, click **Setup Tax Rates** to be taken to **Settings → Tax**.+To charge the correct taxes at checkout, click **Setup Tax Rates** to be taken to **Settings → Taxes**.From here, you can configure:diff --git a/packages/admin-sdk/examples/tax-exemption-certificates/create.ts b/packages/admin-sdk/examples/tax-exemption-certificates/create.tsindex d811b68dad..31e7e93d2c 100644--- a/packages/admin-sdk/examples/tax-exemption-certificates/create.ts+++ b/packages/admin-sdk/examples/tax-exemption-certificates/create.ts@@ -13,7 +13,7 @@ const { signed_id } = await client.files.upload(certificatePdf, { visibility: 'p// `signed_id` comes from `client.files.upload(file, { visibility: 'private' })`.const certificate = await client.companies.taxExemptionCertificates.create('comp_UkLWZg9DAJ', {certificate_number: 'DE-RESALE-7',- reason_code: 'resale',+ tax_exemption_reason_id: 'txr_UkLWZg9DAJ',country_code: 'DE',document_signed_id: signed_id,})diff --git a/packages/admin-sdk/examples/tax-exemption-reasons/create.ts b/packages/admin-sdk/examples/tax-exemption-reasons/create.tsnew file mode 100644index 0000000000..3790b8e0dc--- /dev/null+++ b/packages/admin-sdk/examples/tax-exemption-reasons/create.ts@@ -0,0 +1,18 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+// `code` is what certificates record and the tax engine receives — on+// Avalara, an entity use code such as `G` (resale).+const reason = await client.taxExemptionReasons.create({+ name: 'Reseller (wholesale)',+ code: 'G',+})++// endregion:example++export { reason }diff --git a/packages/admin-sdk/examples/tax-exemption-reasons/delete.ts b/packages/admin-sdk/examples/tax-exemption-reasons/delete.tsnew file mode 100644index 0000000000..4d00489083--- /dev/null+++ b/packages/admin-sdk/examples/tax-exemption-reasons/delete.ts@@ -0,0 +1,10 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+await client.taxExemptionReasons.delete('txr_UkLWZg9DAJ')+// endregion:examplediff --git a/packages/admin-sdk/examples/tax-exemption-reasons/get.ts b/packages/admin-sdk/examples/tax-exemption-reasons/get.tsnew file mode 100644index 0000000000..e462e819f0--- /dev/null+++ b/packages/admin-sdk/examples/tax-exemption-reasons/get.ts@@ -0,0 +1,13 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+const reason = await client.taxExemptionReasons.get('txr_UkLWZg9DAJ')++// endregion:example++export { reason }diff --git a/packages/admin-sdk/examples/tax-exemption-reasons/list.ts b/packages/admin-sdk/examples/tax-exemption-reasons/list.tsnew file mode 100644index 0000000000..9841d4732c--- /dev/null+++ b/packages/admin-sdk/examples/tax-exemption-reasons/list.ts@@ -0,0 +1,13 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+const { data: reasons } = await client.taxExemptionReasons.list()++// endregion:example++export { reasons }diff --git a/packages/admin-sdk/examples/tax-exemption-reasons/update.ts b/packages/admin-sdk/examples/tax-exemption-reasons/update.tsnew file mode 100644index 0000000000..c2c7290092--- /dev/null+++ b/packages/admin-sdk/examples/tax-exemption-reasons/update.ts@@ -0,0 +1,15 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+const reason = await client.taxExemptionReasons.update('txr_UkLWZg9DAJ', {+ active: false,+})++// endregion:example++export { reason }diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 1b4e17f72a..adc4678a21 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -178,6 +178,8 @@ import type {TaxCategorySort,TaxExemptionCertificateFilters,TaxExemptionCertificateSort,+ TaxExemptionReasonFilters,+ TaxExemptionReasonSort,TaxIdentifierFilters,TaxIdentifierSort,TaxLineFilters,@@ -584,8 +586,11 @@ import type {TaxCategoryUpdateParams,TaxExemptionCertificateCreateParams,TaxExemptionCertificateUpdateParams,+ TaxExemptionReasonCreateParams,+ TaxExemptionReasonUpdateParams,TaxIdentifierCreateParams,TaxIdentifierUpdateParams,+ TaxProviderOption,TaxRateCreateParams,TaxRateUpdateParams,TrackingCarrierOption,@@ -706,6 +711,7 @@ import type {Supplier,TaxCategory,TaxExemptionCertificate,+ TaxExemptionReason,TaxIdentifier,TaxLine,TaxRate,@@ -3908,8 +3914,8 @@ export class AdminClient {* letting a merchant discover it at checkout.*/readonly taxProviders = {- list: (options?: RequestOptions): Promise<PaginatedResponse<Record<string, unknown>>> =>- this.request<PaginatedResponse<Record<string, unknown>>>('GET', '/tax_providers', options),+ list: (options?: RequestOptions): Promise<PaginatedResponse<TaxProviderOption>> =>+ this.request<PaginatedResponse<TaxProviderOption>>('GET', '/tax_providers', options),}/**@@ -5193,6 +5199,47 @@ export class AdminClient {this.request<void>('DELETE', `/order_cancellation_reasons/${id}`, options),}+ /**+ * Why a business buys without tax — the reasons a merchant records on a tax+ * exemption certificate. `code` is what the certificate stores and the tax+ * engine receives; `taxProviders.list()` says which codes an engine reads.+ */+ readonly taxExemptionReasons = {+ list: (+ params?: ListParams<TaxExemptionReasonFilters, TaxExemptionReasonSort>,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<TaxExemptionReason>> =>+ this.request<PaginatedResponse<TaxExemptionReason>>('GET', '/tax_exemption_reasons', {+ ...options,+ params: params ? transformListParams(params) : undefined,+ }),++ get: (id: string, options?: RequestOptions): Promise<TaxExemptionReason> =>+ this.request<TaxExemptionReason>('GET', `/tax_exemption_reasons/${id}`, options),++ create: (+ params: TaxExemptionReasonCreateParams,+ options?: RequestOptions,+ ): Promise<TaxExemptionReason> =>+ this.request<TaxExemptionReason>('POST', '/tax_exemption_reasons', {+ ...options,+ body: params,+ }),++ update: (+ id: string,+ params: TaxExemptionReasonUpdateParams,+ options?: RequestOptions,+ ): Promise<TaxExemptionReason> =>+ this.request<TaxExemptionReason>('PATCH', `/tax_exemption_reasons/${id}`, {+ ...options,+ body: params,+ }),++ delete: (id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>('DELETE', `/tax_exemption_reasons/${id}`, options),+ }+/*** Why money went back. Some rows are seeded and immutable: core looks* them up by name, so `can_be_deleted` is false and renaming is refused.diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex 5c2c17d81f..d4df60f0e3 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -58,6 +58,24 @@ export interface StorePayoutProvider {default: boolean}+/** One tax engine a market can calculate through, from `taxProviders.list()`. */+export interface TaxProviderOption {+ /** The engine's shorthand (`internal`, `avalara`) — what a market's `tax_provider` takes. */+ id: string+ name: string+ /** False when the store has not connected what this engine needs. */+ available: boolean+ /** True for the engine used when a market names none. */+ default: boolean+ /** Tax domains this engine cannot handle, with what each costs the merchant. */+ unsupported_capabilities: Array<{ key: string; label: string; description?: string }>+ /**+ * The exemption reason codes this engine reads, to offer when a merchant adds+ * a tax exemption reason; null when any code will do.+ */+ exemption_reason_codes: Array<{ value: string; label: string }> | null+}+export interface StoreDataSources {pricing_providers: StoreDataSourceProvider[]inventory_providers: StoreDataSourceProvider[]diff --git a/packages/admin-sdk/src/types/filters.generated.ts b/packages/admin-sdk/src/types/filters.generated.tsindex d3539d1995..d4da21af53 100644--- a/packages/admin-sdk/src/types/filters.generated.ts+++ b/packages/admin-sdk/src/types/filters.generated.ts@@ -440,11 +440,16 @@ export type TaxCategoryFields = Filter.RangeFilters<'created_at' | 'updated_at'>& Filter.BooleanFilters<'is_default'>& Filter.TextFilters<'name' | 'tax_code'>-export type TaxExemptionCertificateFields = Filter.TextFilters<'certificate_number' | 'reason_code'>+export type TaxExemptionCertificateFields = Filter.TextFilters<'certificate_number'>& Filter.RangeFilters<'created_at' | 'expires_at' | 'updated_at'>- & Filter.IdFilters<'id'>+ & Filter.IdFilters<'id' | 'tax_exemption_reason_id'>& Filter.EnumFilters<'status', 'pending' | 'verified' | 'expired' | 'revoked'>+export type TaxExemptionReasonFields = Filter.BooleanFilters<'active'>+ & Filter.TextFilters<'code' | 'name'>+ & Filter.RangeFilters<'created_at' | 'updated_at'>+ & Filter.IdFilters<'id'>+export type TaxIdentifierFields = Filter.RangeFilters<'created_at' | 'updated_at'>& Filter.IdFilters<'id'>@@ -2502,7 +2507,27 @@ export type TaxExemptionCertificateFilters = TaxExemptionCertificateFields& Filter.OrFilters& TaxExemptionCertificateFilterExtensions-export type TaxExemptionCertificateSort = Filter.SortKey<'certificate_number' | 'created_at' | 'expires_at' | 'id' | 'reason_code' | 'status' | 'updated_at' | (keyof TaxExemptionCertificateSortExtensions & string)>+export type TaxExemptionCertificateSort = Filter.SortKey<'certificate_number' | 'created_at' | 'expires_at' | 'id' | 'status' | 'tax_exemption_reason_id' | 'updated_at' | (keyof TaxExemptionCertificateSortExtensions & string)>++/**+ * Filters your app adds to TaxExemptionReason lists. Generate them with `spree filters types`,+ * or declare them by hand in a file that has an `export`:+ *+ * export {}+ * declare module '@spree/admin-sdk' {+ * interface TaxExemptionReasonFilterExtensions { erp_id_eq?: string }+ * }+ */+export interface TaxExemptionReasonFilterExtensions {}++/** Sort fields your app adds to TaxExemptionReason lists, as keys: `{ erp_id: true }`. */+export interface TaxExemptionReasonSortExtensions {}++export type TaxExemptionReasonFilters = TaxExemptionReasonFields+ & Filter.OrFilters+ & TaxExemptionReasonFilterExtensions++export type TaxExemptionReasonSort = Filter.SortKey<'active' | 'code' | 'created_at' | 'id' | 'name' | 'updated_at' | (keyof TaxExemptionReasonSortExtensions & string)>/*** Filters your app adds to TaxIdentifier lists. Generate them with `spree filters types`,diff --git a/packages/admin-sdk/src/types/generated/TaxExemptionCertificate.ts b/packages/admin-sdk/src/types/generated/TaxExemptionCertificate.tsindex 4094044c3b..dd322457af 100644--- a/packages/admin-sdk/src/types/generated/TaxExemptionCertificate.ts+++ b/packages/admin-sdk/src/types/generated/TaxExemptionCertificate.ts@@ -1,12 +1,11 @@-// Typelizer digest a65c0d2fcaff64624f1edb12337d7e8c+// Typelizer digest 294ca3bacaa4074112b2feeeb49e8f3b//// DO NOT MODIFY: This file was automatically generated by Typelizer.-import type {TaxExemptionCertificateStatus, CountryCode} from '@/types'+import type {TaxExemptionReason, TaxExemptionCertificateStatus, CountryCode} from '@/types'interface TaxExemptionCertificate {id: string;certificate_number: string;- reason_code: string;status: TaxExemptionCertificateStatus;issuing_authority: string | null;metadata: Record<string, unknown> | null;@@ -16,6 +15,8 @@ interface TaxExemptionCertificate {created_at: string;updated_at: string;company_id: string;+ tax_exemption_reason_id: string;+ tax_exemption_reason?: TaxExemptionReason;country_code: CountryCode | null;state_code: string | null;active: boolean;diff --git a/packages/admin-sdk/src/types/generated/TaxExemptionReason.ts b/packages/admin-sdk/src/types/generated/TaxExemptionReason.tsnew file mode 100644index 0000000000..c5259c16d8--- /dev/null+++ b/packages/admin-sdk/src/types/generated/TaxExemptionReason.ts@@ -0,0 +1,16 @@+// Typelizer digest 942e6318225737067d303e0eaefae001+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++interface TaxExemptionReason {+ id: string;+ name: string;+ code: string;+ active: boolean;+ metadata: Record<string, unknown> | null;+ created_at: string;+ updated_at: string;+ can_be_deleted: boolean;+}++export default TaxExemptionReason;diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.tsindex ee86354099..ad17bb0142 100644--- a/packages/admin-sdk/src/types/generated/index.ts+++ b/packages/admin-sdk/src/types/generated/index.ts@@ -1,4 +1,4 @@-// Typelizer digest bdb7ea3ea25ffd19b87cc9b216fa3f49+// Typelizer digest 7d9152446131bb96c25de2ab10467fd8//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { ActorKind, ClaimStatus, CountryCode, CurrencyCode, DataRequestStatus, ExchangeStatus, FeeKind, FulfillmentItemStatus, FulfillmentStatus, GiftCardStatus, ImportRowStatus, ImportStatus, InvitationStatus, LocaleCode, PaymentStatus, PriceListStatus, ProductStatus, ProductSubmissionStatus, ReturnStatus, SellerPayoutStatus, SellerRequirementSubmissionStatus, SellerStatus, SellerTransferStatus, ShippingLabelStatus, StockLocationKind, TaxExemptionCertificateStatus } from './Enums'@@ -81,6 +81,11 @@ export type { default as Market } from './Market'export type { default as Media } from './Media'export type { default as MembershipProduct } from './MembershipProduct'export type { default as NewsletterSubscriber } from './NewsletterSubscriber'+export type { default as OauthAccessToken } from './OauthAccessToken'+export type { default as OauthApplication } from './OauthApplication'+export type { default as OauthConsentRequest } from './OauthConsentRequest'+export type { default as OauthProtectedResource } from './OauthProtectedResource'+export type { default as OauthRedirect } from './OauthRedirect'export type { default as OptionType } from './OptionType'export type { default as OptionValue } from './OptionValue'export type { default as OrderCancellationReason } from './OrderCancellationReason'@@ -143,6 +148,7 @@ export type { default as Store } from './Store'export type { default as Supplier } from './Supplier'export type { default as TaxCategory } from './TaxCategory'export type { default as TaxExemptionCertificate } from './TaxExemptionCertificate'+export type { default as TaxExemptionReason } from './TaxExemptionReason'export type { default as TaxIdentifier } from './TaxIdentifier'export type { default as TaxLine } from './TaxLine'export type { default as TaxRate } from './TaxRate'diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.tsindex ab71ce8b86..abbc2f52f7 100644--- a/packages/admin-sdk/src/types/index.ts+++ b/packages/admin-sdk/src/types/index.ts@@ -193,6 +193,7 @@ export type { default as StoreCreditEvent } from './generated/StoreCreditEvent'export type { default as Supplier } from './generated/Supplier'export type { default as TaxCategory } from './generated/TaxCategory'export type { default as TaxExemptionCertificate } from './generated/TaxExemptionCertificate'+export type { default as TaxExemptionReason } from './generated/TaxExemptionReason'export type { default as TaxIdentifier } from './generated/TaxIdentifier'export type { default as TaxLine } from './generated/TaxLine'export type { default as TaxRate } from './generated/TaxRate'diff --git a/packages/admin-sdk/src/types/params/TaxExemptionCertificateCreateParams.ts b/packages/admin-sdk/src/types/params/TaxExemptionCertificateCreateParams.tsindex 3890893c10..36204c14a2 100644--- a/packages/admin-sdk/src/types/params/TaxExemptionCertificateCreateParams.ts+++ b/packages/admin-sdk/src/types/params/TaxExemptionCertificateCreateParams.ts@@ -4,8 +4,8 @@ import type { CountryCode } from '../generated'export type TaxExemptionCertificateCreateParams = {certificate_number: string- /** Becomes the tax provider's entity use code. */- reason_code: string+ /** One of the store's active tax exemption reasons. The tax provider receives its `code`. */+ tax_exemption_reason_id: stringissuing_authority?: string | nullissued_at?: string | nullexpires_at?: string | nulldiff --git a/packages/admin-sdk/src/types/params/TaxExemptionCertificateUpdateParams.ts b/packages/admin-sdk/src/types/params/TaxExemptionCertificateUpdateParams.tsindex 4f2c2b8ecf..08a916cc07 100644--- a/packages/admin-sdk/src/types/params/TaxExemptionCertificateUpdateParams.ts+++ b/packages/admin-sdk/src/types/params/TaxExemptionCertificateUpdateParams.ts@@ -4,8 +4,8 @@ import type { CountryCode } from '../generated'export type TaxExemptionCertificateUpdateParams = {certificate_number?: string- /** Becomes the tax provider's entity use code. */- reason_code?: string+ /** One of the store's active tax exemption reasons. The tax provider receives its `code`. */+ tax_exemption_reason_id?: stringissuing_authority?: string | nullissued_at?: string | nullexpires_at?: string | nulldiff --git a/packages/admin-sdk/src/types/params/TaxExemptionReasonCreateParams.ts b/packages/admin-sdk/src/types/params/TaxExemptionReasonCreateParams.tsnew file mode 100644index 0000000000..8ee8af3e2e--- /dev/null+++ b/packages/admin-sdk/src/types/params/TaxExemptionReasonCreateParams.ts@@ -0,0 +1,14 @@+// This file is auto-generated from the request schemas in docs/api-reference by `pnpm generate:params`. Do not edit directly.++export type TaxExemptionReasonCreateParams = {+ name: string+ /** Whether the reason is offered on new records. */+ active?: boolean+ /**+ * What the tax provider receives for every certificate holding this reason — for Avalara, an+ * entity use code such as `G`. Saved in capitals. Changing it changes what those certificates+ * send from then on.+ */+ code: string+ metadata?: Record<string, unknown>+}diff --git a/packages/admin-sdk/src/types/params/TaxExemptionReasonUpdateParams.ts b/packages/admin-sdk/src/types/params/TaxExemptionReasonUpdateParams.tsnew file mode 100644index 0000000000..13e4d73eba--- /dev/null+++ b/packages/admin-sdk/src/types/params/TaxExemptionReasonUpdateParams.ts@@ -0,0 +1,14 @@+// This file is auto-generated from the request schemas in docs/api-reference by `pnpm generate:params`. Do not edit directly.++export type TaxExemptionReasonUpdateParams = {+ name?: string+ /** Whether the reason is offered on new records. */+ active?: boolean+ /**+ * What the tax provider receives for every certificate holding this reason — for Avalara, an+ * entity use code such as `G`. Saved in capitals. Changing it changes what those certificates+ * send from then on.+ */+ code?: string+ metadata?: Record<string, unknown>+}diff --git a/packages/admin-sdk/src/types/params/index.ts b/packages/admin-sdk/src/types/params/index.tsindex 3c9d5e3d60..6c84d25785 100644--- a/packages/admin-sdk/src/types/params/index.ts+++ b/packages/admin-sdk/src/types/params/index.ts@@ -221,6 +221,8 @@ export type { TaxCategoryCreateParams } from './TaxCategoryCreateParams'export type { TaxCategoryUpdateParams } from './TaxCategoryUpdateParams'export type { TaxExemptionCertificateCreateParams } from './TaxExemptionCertificateCreateParams'export type { TaxExemptionCertificateUpdateParams } from './TaxExemptionCertificateUpdateParams'+export type { TaxExemptionReasonCreateParams } from './TaxExemptionReasonCreateParams'+export type { TaxExemptionReasonUpdateParams } from './TaxExemptionReasonUpdateParams'export type { TaxIdentifierCreateParams } from './TaxIdentifierCreateParams'export type { TaxIdentifierUpdateParams } from './TaxIdentifierUpdateParams'export type { TaxRateCreateParams } from './TaxRateCreateParams'diff --git a/packages/admin-sdk/src/zod/generated/TaxExemptionCertificate.ts b/packages/admin-sdk/src/zod/generated/TaxExemptionCertificate.tsindex 828827afd9..cbeea8de14 100644--- a/packages/admin-sdk/src/zod/generated/TaxExemptionCertificate.ts+++ b/packages/admin-sdk/src/zod/generated/TaxExemptionCertificate.ts@@ -1,10 +1,10 @@// This file is auto-generated. Do not edit directly.import { z } from 'zod';+import { TaxExemptionReasonSchema } from './TaxExemptionReason';export const TaxExemptionCertificateSchema = z.object({id: z.string(),certificate_number: z.string(),- reason_code: z.string(),status: z.string(),issuing_authority: z.string().nullable(),metadata: z.record(z.string(), z.unknown()).nullable(),@@ -14,6 +14,8 @@ export const TaxExemptionCertificateSchema = z.object({created_at: z.string(),updated_at: z.string(),company_id: z.string(),+ tax_exemption_reason_id: z.string(),+ tax_exemption_reason: TaxExemptionReasonSchema.optional(),country_code: z.string().nullable(),state_code: z.string().nullable(),active: z.boolean(),diff --git a/packages/admin-sdk/src/zod/generated/TaxExemptionReason.ts b/packages/admin-sdk/src/zod/generated/TaxExemptionReason.tsnew file mode 100644index 0000000000..6c28e04eee--- /dev/null+++ b/packages/admin-sdk/src/zod/generated/TaxExemptionReason.ts@@ -0,0 +1,15 @@+// This file is auto-generated. Do not edit directly.+import { z } from 'zod';++export const TaxExemptionReasonSchema = z.object({+ id: z.string(),+ name: z.string(),+ code: z.string(),+ active: z.boolean(),+ metadata: z.record(z.string(), z.unknown()).nullable(),+ created_at: z.string(),+ updated_at: z.string(),+ can_be_deleted: z.boolean(),+});++export type TaxExemptionReason = z.infer<typeof TaxExemptionReasonSchema>;diff --git a/packages/admin-sdk/src/zod/generated/index.ts b/packages/admin-sdk/src/zod/generated/index.tsindex 388da1a282..fc0000cf57 100644--- a/packages/admin-sdk/src/zod/generated/index.ts+++ b/packages/admin-sdk/src/zod/generated/index.ts@@ -145,6 +145,7 @@ export { StoreCreditEventSchema, type StoreCreditEvent } from './StoreCreditEvenexport { SupplierSchema, type Supplier } from './Supplier';export { TaxCategorySchema, type TaxCategory } from './TaxCategory';export { TaxExemptionCertificateSchema, type TaxExemptionCertificate } from './TaxExemptionCertificate';+export { TaxExemptionReasonSchema, type TaxExemptionReason } from './TaxExemptionReason';export { TaxIdentifierSchema, type TaxIdentifier } from './TaxIdentifier';export { TaxLineSchema, type TaxLine } from './TaxLine';export { TaxRateSchema, type TaxRate } from './TaxRate';diff --git a/packages/admin-sdk/tests/companies.test.ts b/packages/admin-sdk/tests/companies.test.tsindex c19e10d012..49335dd86f 100644--- a/packages/admin-sdk/tests/companies.test.ts+++ b/packages/admin-sdk/tests/companies.test.ts@@ -32,7 +32,7 @@ const sampleCertificate = {id: 'cert_abc123',company_id: 'comp_abc123',certificate_number: 'DE-RESALE-1',- reason_code: 'resale',+ tax_exemption_reason_id: 'txr_abc123',status: 'pending',country_code: 'DE',state_code: null,@@ -273,13 +273,13 @@ describe('companies', () => {await createTestClient().companies.taxExemptionCertificates.create('comp_abc123', {certificate_number: 'DE-RESALE-7',- reason_code: 'resale',+ tax_exemption_reason_id: 'txr_abc123',document: 'signed-blob-id',})expect(body).toEqual({certificate_number: 'DE-RESALE-7',- reason_code: 'resale',+ tax_exemption_reason_id: 'txr_abc123',document: 'signed-blob-id',})})diff --git a/packages/dashboard-core/src/components/preferences-form.tsx b/packages/dashboard-core/src/components/preferences-form.tsxindex 511ca44e7e..296f92acd0 100644--- a/packages/dashboard-core/src/components/preferences-form.tsx+++ b/packages/dashboard-core/src/components/preferences-form.tsx@@ -46,6 +46,8 @@ export interface PreferenceFieldDef {format?: stringdefault: unknownchoices?: string[]+ /** Labels the declaration gave its choices, for values that cannot name themselves (an endpoint URL). */+ choiceLabels?: Record<string, string>/** Whether the setting may be left empty (it reads back as null). */nullable: boolean/** The property's own JSON Schema, for widgets that need more (list items, object properties). */@@ -101,6 +103,7 @@ export function preferenceFields(format: property.format ?? property.items?.format,default: property.default ?? null,choices: property.enum?.filter((choice): choice is string => typeof choice === 'string'),+ choiceLabels: property['x-spree-choice-labels'],nullable: Array.isArray(property.type) && property.type.includes('null'),schema: property,}))@@ -432,12 +435,23 @@ export function PreferenceField({// the set is what the server validates against, so typing anything// else can only fail on save.if (field.choices?.length) {- const options = field.choices.map((choice) => ({+ // A translation wins where one exists, so the locale files stay in+ // charge of the values that read as words; then the label the+ // declaration supplied, for the ones that do not — a URL cannot serve+ // as its own i18n key, let alone as a label.+ const declared = field.choices.map((choice) => ({value: choice,label: i18n.exists(`${preferenceKey}_options.${choice}`)? t(`${preferenceKey}_options.${choice}`)- : humanizeKey(choice),+ : (field.choiceLabels?.[choice] ?? humanizeKey(choice)),}))+ // A stored value outside the set is offered as its own option rather+ // than dropped, so one written past the picker by an API client is not+ // silently rewritten to the first choice.+ const options =+ typeof value === 'string' && value !== '' && !declared.some((o) => o.value === value)+ ? [...declared, { value, label: value }]+ : declaredreturn (<Field>diff --git a/packages/dashboard-core/src/lib/permissions.ts b/packages/dashboard-core/src/lib/permissions.tsindex 351285ca47..a37fbcc8d0 100644--- a/packages/dashboard-core/src/lib/permissions.ts+++ b/packages/dashboard-core/src/lib/permissions.ts@@ -46,6 +46,7 @@ export const Subject = {ClaimReason: 'claim_reason',RefundReason: 'refund_reason',OrderCancellationReason: 'order_cancellation_reason',+ TaxExemptionReason: 'tax_exemption_reason',CustomFieldDefinition: 'custom_field_definition',Integration: 'integration',PaymentMethod: 'payment_method',diff --git a/packages/dashboard-core/src/lib/settings-nav-registry.test.ts b/packages/dashboard-core/src/lib/settings-nav-registry.test.tsnew file mode 100644index 0000000000..cfea5c61da--- /dev/null+++ b/packages/dashboard-core/src/lib/settings-nav-registry.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest'+import { canSeeSettingsEntry, type SettingsNavEntry } from './settings-nav-registry'++const entry = (overrides: Partial<SettingsNavEntry>): SettingsNavEntry => ({+ key: 'settings.example',+ label: 'Example',+ path: '/example',+ group: 'store',+ ...overrides,+})++const allowing =+ (...subjects: string[]) =>+ (_action: string, subject: string) =>+ subjects.includes(subject)++describe('canSeeSettingsEntry', () => {+ it('shows an entry without a subject to everyone', () => {+ expect(canSeeSettingsEntry(entry({}), allowing())).toBe(true)+ })++ it('checks a single subject', () => {+ expect(canSeeSettingsEntry(entry({ subject: 'tax_rate' }), allowing('tax_rate'))).toBe(true)+ expect(canSeeSettingsEntry(entry({ subject: 'tax_rate' }), allowing())).toBe(false)+ })++ // A page of tabs is reachable through any one of them.+ it('shows an entry with several subjects when any one is allowed', () => {+ const taxes = entry({ subjects: ['tax_category', 'tax_rate', 'tax_exemption_reason'] })++ expect(canSeeSettingsEntry(taxes, allowing('tax_exemption_reason'))).toBe(true)+ expect(canSeeSettingsEntry(taxes, allowing('product'))).toBe(false)+ })+})diff --git a/packages/dashboard-core/src/lib/settings-nav-registry.ts b/packages/dashboard-core/src/lib/settings-nav-registry.tsindex ecc455fb3e..82b71d7c4d 100644--- a/packages/dashboard-core/src/lib/settings-nav-registry.ts+++ b/packages/dashboard-core/src/lib/settings-nav-registry.ts@@ -60,6 +60,12 @@ export interface SettingsNavEntry {position?: number/** CanCanCan subject required to see this item. Omit for always-visible. */subject?: SubjectName+ /**+ * For a page holding several resources, as tabs: the entry is shown when+ * `action` is allowed on any of these, so a role reaching one tab still+ * finds the page. Takes precedence over `subject`.+ */+ subjects?: SubjectName[]/*** Action checked against `subject`. Defaults to `'read'`. Settings pages* that only exist to *change* something (store settings, emails) should@@ -220,6 +226,19 @@ export function settingsEntryMatches(return haystack.some((value) => value?.toLowerCase().includes(needle))}+/**+ * Whether a staff member may reach this settings entry. The sidebar, the+ * settings landing page and the command palette all ask this, so they agree.+ */+export function canSeeSettingsEntry(+ entry: SettingsNavEntry,+ can: (action: string, subject: string) => boolean,+): boolean {+ const action = entry.action ?? 'read'+ if (entry.subjects?.length) return entry.subjects.some((subject) => can(action, subject))+ return !entry.subject || can(action, entry.subject)+}+/*** Drop entries the current staff member cannot reach. Exported because the* sidebar and the settings landing page must agree on what a role can see —@@ -231,7 +250,7 @@ export function filterSettingsByPermissions(permissions: { can: (action: string, subject: string) => boolean },): SettingsNavSnapshot {return regroup(snapshot, (entry) =>- !entry.subject ? true : permissions.can(entry.action ?? 'read', entry.subject),+ canSeeSettingsEntry(entry, (action, subject) => permissions.can(action, subject)),)}@@ -265,9 +284,7 @@ export function hasVisibleSettingsEntries(permissions: unknown): boolean {?.canif (typeof can !== 'function') return false- return getSnapshot().all.some(- (entry) => !entry.subject || can(entry.action ?? 'read', entry.subject),- )+ return getSnapshot().all.some((entry) => canSeeSettingsEntry(entry, can))}/** Test-only: clear the registry. */diff --git a/packages/dashboard-starter/src/routeTree.gen.ts b/packages/dashboard-starter/src/routeTree.gen.tsindex cb9052e034..f226d49b88 100644--- a/packages/dashboard-starter/src/routeTree.gen.ts+++ b/packages/dashboard-starter/src/routeTree.gen.ts@@ -80,8 +80,7 @@ import { Route as SettingsSellerRequirementsRouteImport } from './../../dashboarimport { Route as SettingsStaffRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/staff'import { Route as SettingsStockLocationsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/stock-locations'import { Route as SettingsStoreRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/store'-import { Route as SettingsTaxCategoriesRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/tax-categories'-import { Route as SettingsTaxRatesRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/tax-rates'+import { Route as SettingsTaxesRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/taxes'import { Route as TransfersIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/transfers/index'import { Route as TransfersNewRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/transfers/new'import { Route as OrdersOrderIdIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/orders/$orderId/index'@@ -103,6 +102,10 @@ import { Route as SellersPayoutsPayoutIdRouteImport } from './../../dashboard/srimport { Route as SettingsDeliveryProfilesIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/delivery-profiles/index'import { Route as SettingsEmailsIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/emails/index'import { Route as SettingsImportsIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/imports/index'+import { Route as SettingsTaxesIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/taxes/index'+import { Route as SettingsTaxesCategoriesRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/taxes/categories'+import { Route as SettingsTaxesExemptionReasonsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/taxes/exemption-reasons'+import { Route as SettingsTaxesRatesRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/taxes/rates'import { Route as SettingsWebhooksIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/webhooks/index'import { Route as SettingsWebhooksWebhookEndpointIdRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/webhooks/$webhookEndpointId'import { Route as TransfersTransferIdIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/transfers/$transferId/index'@@ -471,14 +474,9 @@ const SettingsStoreRoute = SettingsStoreRouteImport.update({path: '/store',getParentRoute: () => SettingsRoute,} as any)-const SettingsTaxCategoriesRoute = SettingsTaxCategoriesRouteImport.update({- id: '/tax-categories',- path: '/tax-categories',- getParentRoute: () => SettingsRoute,-} as any)-const SettingsTaxRatesRoute = SettingsTaxRatesRouteImport.update({- id: '/tax-rates',- path: '/tax-rates',+const SettingsTaxesRoute = SettingsTaxesRouteImport.update({+ id: '/taxes',+ path: '/taxes',getParentRoute: () => SettingsRoute,} as any)const TransfersIndexRoute = TransfersIndexRouteImport.update({@@ -593,6 +591,27 @@ const SettingsImportsIndexRoute = SettingsImportsIndexRouteImport.update({path: '/imports/',getParentRoute: () => SettingsRoute,} as any)+const SettingsTaxesIndexRoute = SettingsTaxesIndexRouteImport.update({+ id: '/',+ path: '/',+ getParentRoute: () => SettingsTaxesRoute,+} as any)+const SettingsTaxesCategoriesRoute = SettingsTaxesCategoriesRouteImport.update({+ id: '/categories',+ path: '/categories',+ getParentRoute: () => SettingsTaxesRoute,+} as any)+const SettingsTaxesExemptionReasonsRoute =+ SettingsTaxesExemptionReasonsRouteImport.update({+ id: '/exemption-reasons',+ path: '/exemption-reasons',+ getParentRoute: () => SettingsTaxesRoute,+ } as any)+const SettingsTaxesRatesRoute = SettingsTaxesRatesRouteImport.update({+ id: '/rates',+ path: '/rates',+ getParentRoute: () => SettingsTaxesRoute,+} as any)const SettingsWebhooksIndexRoute = SettingsWebhooksIndexRouteImport.update({id: '/webhooks/',path: '/webhooks/',@@ -712,8 +731,7 @@ export interface FileRoutesByFullPath {'/$storeId/settings/staff': typeof SettingsStaffRoute'/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute'/$storeId/settings/store': typeof SettingsStoreRoute- '/$storeId/settings/tax-categories': typeof SettingsTaxCategoriesRoute- '/$storeId/settings/tax-rates': typeof SettingsTaxRatesRoute+ '/$storeId/settings/taxes': typeof SettingsTaxesRouteWithChildren'/$storeId/transfers/new': typeof TransfersNewRoute'/$storeId/brands/': typeof BrandsDotindexRoute'/$storeId/companies/': typeof CompaniesIndexRoute@@ -736,6 +754,9 @@ export interface FileRoutesByFullPath {'/$storeId/products/price-lists/new': typeof ProductsPriceListsNewRoute'/$storeId/purchase-orders/$purchaseOrderId/edit': typeof PurchaseOrdersPurchaseOrderIdEditRoute'/$storeId/sellers/payouts/$payoutId': typeof SellersPayoutsPayoutIdRoute+ '/$storeId/settings/taxes/categories': typeof SettingsTaxesCategoriesRoute+ '/$storeId/settings/taxes/exemption-reasons': typeof SettingsTaxesExemptionReasonsRoute+ '/$storeId/settings/taxes/rates': typeof SettingsTaxesRatesRoute'/$storeId/settings/webhooks/$webhookEndpointId': typeof SettingsWebhooksWebhookEndpointIdRoute'/$storeId/transfers/$transferId/edit': typeof TransfersTransferIdEditRoute'/$storeId/orders/$orderId/': typeof OrdersOrderIdIndexRoute@@ -748,6 +769,7 @@ export interface FileRoutesByFullPath {'/$storeId/settings/delivery-profiles/': typeof SettingsDeliveryProfilesIndexRoute'/$storeId/settings/emails/': typeof SettingsEmailsIndexRoute'/$storeId/settings/imports/': typeof SettingsImportsIndexRoute+ '/$storeId/settings/taxes/': typeof SettingsTaxesIndexRoute'/$storeId/settings/webhooks/': typeof SettingsWebhooksIndexRoute'/$storeId/transfers/$transferId/': typeof TransfersTransferIdIndexRoute'/$storeId/settings/emails/templates/$templateId': typeof SettingsEmailsTemplatesTemplateIdRoute@@ -815,8 +837,6 @@ export interface FileRoutesByTo {'/$storeId/settings/staff': typeof SettingsStaffRoute'/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute'/$storeId/settings/store': typeof SettingsStoreRoute- '/$storeId/settings/tax-categories': typeof SettingsTaxCategoriesRoute- '/$storeId/settings/tax-rates': typeof SettingsTaxRatesRoute'/$storeId/transfers/new': typeof TransfersNewRoute'/$storeId/brands': typeof BrandsDotindexRoute'/$storeId/companies': typeof CompaniesIndexRoute@@ -839,6 +859,9 @@ export interface FileRoutesByTo {'/$storeId/products/price-lists/new': typeof ProductsPriceListsNewRoute'/$storeId/purchase-orders/$purchaseOrderId/edit': typeof PurchaseOrdersPurchaseOrderIdEditRoute'/$storeId/sellers/payouts/$payoutId': typeof SellersPayoutsPayoutIdRoute+ '/$storeId/settings/taxes/categories': typeof SettingsTaxesCategoriesRoute+ '/$storeId/settings/taxes/exemption-reasons': typeof SettingsTaxesExemptionReasonsRoute+ '/$storeId/settings/taxes/rates': typeof SettingsTaxesRatesRoute'/$storeId/settings/webhooks/$webhookEndpointId': typeof SettingsWebhooksWebhookEndpointIdRoute'/$storeId/transfers/$transferId/edit': typeof TransfersTransferIdEditRoute'/$storeId/orders/$orderId': typeof OrdersOrderIdIndexRoute@@ -851,6 +874,7 @@ export interface FileRoutesByTo {'/$storeId/settings/delivery-profiles': typeof SettingsDeliveryProfilesIndexRoute'/$storeId/settings/emails': typeof SettingsEmailsIndexRoute'/$storeId/settings/imports': typeof SettingsImportsIndexRoute+ '/$storeId/settings/taxes': typeof SettingsTaxesIndexRoute'/$storeId/settings/webhooks': typeof SettingsWebhooksIndexRoute'/$storeId/transfers/$transferId': typeof TransfersTransferIdIndexRoute'/$storeId/settings/emails/templates/$templateId': typeof SettingsEmailsTemplatesTemplateIdRoute@@ -922,8 +946,7 @@ export interface FileRoutesById {'/_authenticated/$storeId/settings/staff': typeof SettingsStaffRoute'/_authenticated/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute'/_authenticated/$storeId/settings/store': typeof SettingsStoreRoute- '/_authenticated/$storeId/settings/tax-categories': typeof SettingsTaxCategoriesRoute- '/_authenticated/$storeId/settings/tax-rates': typeof SettingsTaxRatesRoute+ '/_authenticated/$storeId/settings/taxes': typeof SettingsTaxesRouteWithChildren'/_authenticated/$storeId/transfers/new': typeof TransfersNewRoute'/_authenticated/$storeId/brands/': typeof BrandsDotindexRoute'/_authenticated/$storeId/companies/': typeof CompaniesIndexRoute@@ -946,6 +969,9 @@ export interface FileRoutesById {'/_authenticated/$storeId/products/price-lists/new': typeof ProductsPriceListsNewRoute'/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit': typeof PurchaseOrdersPurchaseOrderIdEditRoute'/_authenticated/$storeId/sellers/payouts/$payoutId': typeof SellersPayoutsPayoutIdRoute+ '/_authenticated/$storeId/settings/taxes/categories': typeof SettingsTaxesCategoriesRoute+ '/_authenticated/$storeId/settings/taxes/exemption-reasons': typeof SettingsTaxesExemptionReasonsRoute+ '/_authenticated/$storeId/settings/taxes/rates': typeof SettingsTaxesRatesRoute'/_authenticated/$storeId/settings/webhooks/$webhookEndpointId': typeof SettingsWebhooksWebhookEndpointIdRoute'/_authenticated/$storeId/transfers/$transferId/edit': typeof TransfersTransferIdEditRoute'/_authenticated/$storeId/orders/$orderId/': typeof OrdersOrderIdIndexRoute@@ -958,6 +984,7 @@ export interface FileRoutesById {'/_authenticated/$storeId/settings/delivery-profiles/': typeof SettingsDeliveryProfilesIndexRoute'/_authenticated/$storeId/settings/emails/': typeof SettingsEmailsIndexRoute'/_authenticated/$storeId/settings/imports/': typeof SettingsImportsIndexRoute+ '/_authenticated/$storeId/settings/taxes/': typeof SettingsTaxesIndexRoute'/_authenticated/$storeId/settings/webhooks/': typeof SettingsWebhooksIndexRoute'/_authenticated/$storeId/transfers/$transferId/': typeof TransfersTransferIdIndexRoute'/_authenticated/$storeId/settings/emails/templates/$templateId': typeof SettingsEmailsTemplatesTemplateIdRoute@@ -1029,8 +1056,7 @@ export interface FileRouteTypes {| '/$storeId/settings/staff'| '/$storeId/settings/stock-locations'| '/$storeId/settings/store'- | '/$storeId/settings/tax-categories'- | '/$storeId/settings/tax-rates'+ | '/$storeId/settings/taxes'| '/$storeId/transfers/new'| '/$storeId/brands/'| '/$storeId/companies/'@@ -1053,6 +1079,9 @@ export interface FileRouteTypes {| '/$storeId/products/price-lists/new'| '/$storeId/purchase-orders/$purchaseOrderId/edit'| '/$storeId/sellers/payouts/$payoutId'+ | '/$storeId/settings/taxes/categories'+ | '/$storeId/settings/taxes/exemption-reasons'+ | '/$storeId/settings/taxes/rates'| '/$storeId/settings/webhooks/$webhookEndpointId'| '/$storeId/transfers/$transferId/edit'| '/$storeId/orders/$orderId/'@@ -1065,6 +1094,7 @@ export interface FileRouteTypes {| '/$storeId/settings/delivery-profiles/'| '/$storeId/settings/emails/'| '/$storeId/settings/imports/'+ | '/$storeId/settings/taxes/'| '/$storeId/settings/webhooks/'| '/$storeId/transfers/$transferId/'| '/$storeId/settings/emails/templates/$templateId'@@ -1132,8 +1162,6 @@ export interface FileRouteTypes {| '/$storeId/settings/staff'| '/$storeId/settings/stock-locations'| '/$storeId/settings/store'- | '/$storeId/settings/tax-categories'- | '/$storeId/settings/tax-rates'| '/$storeId/transfers/new'| '/$storeId/brands'| '/$storeId/companies'@@ -1156,6 +1184,9 @@ export interface FileRouteTypes {| '/$storeId/products/price-lists/new'| '/$storeId/purchase-orders/$purchaseOrderId/edit'| '/$storeId/sellers/payouts/$payoutId'+ | '/$storeId/settings/taxes/categories'+ | '/$storeId/settings/taxes/exemption-reasons'+ | '/$storeId/settings/taxes/rates'| '/$storeId/settings/webhooks/$webhookEndpointId'| '/$storeId/transfers/$transferId/edit'| '/$storeId/orders/$orderId'@@ -1168,6 +1199,7 @@ export interface FileRouteTypes {| '/$storeId/settings/delivery-profiles'| '/$storeId/settings/emails'| '/$storeId/settings/imports'+ | '/$storeId/settings/taxes'| '/$storeId/settings/webhooks'| '/$storeId/transfers/$transferId'| '/$storeId/settings/emails/templates/$templateId'@@ -1238,8 +1270,7 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/settings/staff'| '/_authenticated/$storeId/settings/stock-locations'| '/_authenticated/$storeId/settings/store'- | '/_authenticated/$storeId/settings/tax-categories'- | '/_authenticated/$storeId/settings/tax-rates'+ | '/_authenticated/$storeId/settings/taxes'| '/_authenticated/$storeId/transfers/new'| '/_authenticated/$storeId/brands/'| '/_authenticated/$storeId/companies/'@@ -1262,6 +1293,9 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/products/price-lists/new'| '/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit'| '/_authenticated/$storeId/sellers/payouts/$payoutId'+ | '/_authenticated/$storeId/settings/taxes/categories'+ | '/_authenticated/$storeId/settings/taxes/exemption-reasons'+ | '/_authenticated/$storeId/settings/taxes/rates'| '/_authenticated/$storeId/settings/webhooks/$webhookEndpointId'| '/_authenticated/$storeId/transfers/$transferId/edit'| '/_authenticated/$storeId/orders/$orderId/'@@ -1274,6 +1308,7 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/settings/delivery-profiles/'| '/_authenticated/$storeId/settings/emails/'| '/_authenticated/$storeId/settings/imports/'+ | '/_authenticated/$storeId/settings/taxes/'| '/_authenticated/$storeId/settings/webhooks/'| '/_authenticated/$storeId/transfers/$transferId/'| '/_authenticated/$storeId/settings/emails/templates/$templateId'@@ -1792,18 +1827,11 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsStoreRouteImportparentRoute: typeof SettingsRoute}- '/_authenticated/$storeId/settings/tax-categories': {- id: '/_authenticated/$storeId/settings/tax-categories'- path: '/tax-categories'- fullPath: '/$storeId/settings/tax-categories'- preLoaderRoute: typeof SettingsTaxCategoriesRouteImport- parentRoute: typeof SettingsRoute- }- '/_authenticated/$storeId/settings/tax-rates': {- id: '/_authenticated/$storeId/settings/tax-rates'- path: '/tax-rates'- fullPath: '/$storeId/settings/tax-rates'- preLoaderRoute: typeof SettingsTaxRatesRouteImport+ '/_authenticated/$storeId/settings/taxes': {+ id: '/_authenticated/$storeId/settings/taxes'+ path: '/taxes'+ fullPath: '/$storeId/settings/taxes'+ preLoaderRoute: typeof SettingsTaxesRouteImportparentRoute: typeof SettingsRoute}'/_authenticated/$storeId/transfers/': {@@ -1953,6 +1981,34 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsImportsIndexRouteImportparentRoute: typeof SettingsRoute}+ '/_authenticated/$storeId/settings/taxes/': {+ id: '/_authenticated/$storeId/settings/taxes/'+ path: '/'+ fullPath: '/$storeId/settings/taxes/'+ preLoaderRoute: typeof SettingsTaxesIndexRouteImport+ parentRoute: typeof SettingsTaxesRoute+ }+ '/_authenticated/$storeId/settings/taxes/categories': {+ id: '/_authenticated/$storeId/settings/taxes/categories'+ path: '/categories'+ fullPath: '/$storeId/settings/taxes/categories'+ preLoaderRoute: typeof SettingsTaxesCategoriesRouteImport+ parentRoute: typeof SettingsTaxesRoute+ }+ '/_authenticated/$storeId/settings/taxes/exemption-reasons': {+ id: '/_authenticated/$storeId/settings/taxes/exemption-reasons'+ path: '/exemption-reasons'+ fullPath: '/$storeId/settings/taxes/exemption-reasons'+ preLoaderRoute: typeof SettingsTaxesExemptionReasonsRouteImport+ parentRoute: typeof SettingsTaxesRoute+ }+ '/_authenticated/$storeId/settings/taxes/rates': {+ id: '/_authenticated/$storeId/settings/taxes/rates'+ path: '/rates'+ fullPath: '/$storeId/settings/taxes/rates'+ preLoaderRoute: typeof SettingsTaxesRatesRouteImport+ parentRoute: typeof SettingsTaxesRoute+ }'/_authenticated/$storeId/settings/webhooks/': {id: '/_authenticated/$storeId/settings/webhooks/'path: '/webhooks'@@ -2026,6 +2082,24 @@ declare module '@tanstack/react-router' {}}+interface SettingsTaxesRouteChildren {+ SettingsTaxesCategoriesRoute: typeof SettingsTaxesCategoriesRoute+ SettingsTaxesExemptionReasonsRoute: typeof SettingsTaxesExemptionReasonsRoute+ SettingsTaxesRatesRoute: typeof SettingsTaxesRatesRoute+ SettingsTaxesIndexRoute: typeof SettingsTaxesIndexRoute+}++const SettingsTaxesRouteChildren: SettingsTaxesRouteChildren = {+ SettingsTaxesCategoriesRoute: SettingsTaxesCategoriesRoute,+ SettingsTaxesExemptionReasonsRoute: SettingsTaxesExemptionReasonsRoute,+ SettingsTaxesRatesRoute: SettingsTaxesRatesRoute,+ SettingsTaxesIndexRoute: SettingsTaxesIndexRoute,+}++const SettingsTaxesRouteWithChildren = SettingsTaxesRoute._addFileChildren(+ SettingsTaxesRouteChildren,+)+interface SettingsRouteChildren {SettingsAiAgentsRoute: typeof SettingsAiAgentsRouteSettingsAllowedOriginsRoute: typeof SettingsAllowedOriginsRoute@@ -2048,8 +2122,7 @@ interface SettingsRouteChildren {SettingsStaffRoute: typeof SettingsStaffRouteSettingsStockLocationsRoute: typeof SettingsStockLocationsRouteSettingsStoreRoute: typeof SettingsStoreRoute- SettingsTaxCategoriesRoute: typeof SettingsTaxCategoriesRoute- SettingsTaxRatesRoute: typeof SettingsTaxRatesRoute+ SettingsTaxesRoute: typeof SettingsTaxesRouteWithChildrenSettingsIndexRoute: typeof SettingsIndexRouteSettingsWebhooksWebhookEndpointIdRoute: typeof SettingsWebhooksWebhookEndpointIdRouteSettingsDeliveryProfilesIndexRoute: typeof SettingsDeliveryProfilesIndexRoute@@ -2085,8 +2158,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {SettingsStaffRoute: SettingsStaffRoute,SettingsStockLocationsRoute: SettingsStockLocationsRoute,SettingsStoreRoute: SettingsStoreRoute,- SettingsTaxCategoriesRoute: SettingsTaxCategoriesRoute,- SettingsTaxRatesRoute: SettingsTaxRatesRoute,+ SettingsTaxesRoute: SettingsTaxesRouteWithChildren,SettingsIndexRoute: SettingsIndexRoute,SettingsWebhooksWebhookEndpointIdRoute:SettingsWebhooksWebhookEndpointIdRoute,diff --git a/packages/dashboard-ui/src/index.ts b/packages/dashboard-ui/src/index.tsindex c4408dada7..cc7d92b627 100644--- a/packages/dashboard-ui/src/index.ts+++ b/packages/dashboard-ui/src/index.ts@@ -117,6 +117,7 @@ export * from './ui/empty'export * from './ui/field'export * from './ui/input'export * from './ui/input-group'+export * from './ui/item'export * from './ui/label'export * from './ui/media-preview'export * from './ui/pagination'diff --git a/packages/dashboard-ui/src/spree/icons.ts b/packages/dashboard-ui/src/spree/icons.tsindex 6515658335..e99c58bf8c 100644--- a/packages/dashboard-ui/src/spree/icons.ts+++ b/packages/dashboard-ui/src/spree/icons.ts@@ -25,6 +25,7 @@ export {BoxesIcon,BracesIcon,Building2Icon,+ CalculatorIcon,CalendarIcon,CalendarOffIcon,ChartColumnIcon,diff --git a/packages/dashboard-ui/src/spree/secret-input.tsx b/packages/dashboard-ui/src/spree/secret-input.tsxindex 457d44ba0c..0ed9a3f020 100644--- a/packages/dashboard-ui/src/spree/secret-input.tsx+++ b/packages/dashboard-ui/src/spree/secret-input.tsx@@ -2,7 +2,8 @@ import { useState } from 'react'import { useTranslation } from 'react-i18next'import { Button } from '../ui/button'import { Field, FieldLabel } from '../ui/field'-import { Input } from '../ui/input'+import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '../ui/input-group'+import { EyeIcon, EyeOffIcon } from './icons'// Server masks stored secrets as `••••…` on read so admins can see "yes,// something is stored" without exposing the actual value. Detecting that@@ -35,7 +36,9 @@ interface SecretInputProps {* mask (`••••3K9z`) and renders as a read-only badge with a "Replace"* button — never as an input, and never with a reveal toggle, because the* server does not send the secret and there is nothing to unhide. Replace- * switches to an empty password input so the admin opts in to rotation;+ * switches to an empty password input so the admin opts in to rotation; that+ * input does carry a reveal toggle, since what it hides is what the admin is+ * typing right now;* Cancel reverts to the badge so the next save preserves the existing* secret via the backend's masked round-trip guard.*@@ -57,6 +60,7 @@ export function SecretInput({// after `onChange('')` has cleared the parent value.const [pendingMask, setPendingMask] = useState<string | null>(null)const replacing = pendingMask !== null+ const [revealed, setRevealed] = useState(false)// A stored secret always renders as the badge: the server sent a mask,// not the value, so there is nothing a reveal toggle could show.@@ -93,17 +97,29 @@ export function SecretInput({<Field><FieldLabel htmlFor={id}>{label}</FieldLabel><div className="flex items-center gap-2">- <Input- id={id}- type="password"- autoComplete="new-password"- placeholder={- replacing ? t('admin.components.secret_input.new_value_placeholder') : placeholder- }- value={(value as string) ?? ''}- onChange={(e) => onChange(e.target.value)}- className="flex-1"- />+ <InputGroup className="flex-1">+ <InputGroupInput+ id={id}+ type={revealed ? 'text' : 'password'}+ autoComplete="new-password"+ spellCheck={false}+ placeholder={+ replacing ? t('admin.components.secret_input.new_value_placeholder') : placeholder+ }+ value={(value as string) ?? ''}+ onChange={(e) => onChange(e.target.value)}+ />+ <InputGroupAddon align="inline-end">+ <InputGroupButton+ size="icon-xs"+ aria-label={revealed ? t('admin.actions.hide') : t('admin.actions.show')}+ aria-pressed={revealed}+ onClick={() => setRevealed((visible) => !visible)}+ >+ {revealed ? <EyeOffIcon /> : <EyeIcon />}+ </InputGroupButton>+ </InputGroupAddon>+ </InputGroup>{replacing && (<Buttontype="button"diff --git a/packages/dashboard-ui/src/ui/item.tsx b/packages/dashboard-ui/src/ui/item.tsxnew file mode 100644index 0000000000..a046bf8ad7--- /dev/null+++ b/packages/dashboard-ui/src/ui/item.tsx@@ -0,0 +1,188 @@+import { mergeProps } from '@base-ui/react/merge-props'+import { useRender } from '@base-ui/react/use-render'+import { cva, type VariantProps } from 'class-variance-authority'+import * as React from 'react'+import { cn } from '../lib/utils'++import { Separator } from './separator'++function ItemGroup({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ role="list"+ data-slot="item-group"+ className={cn(+ 'group/item-group flex w-full flex-col gap-4 has-data-[size=sm]:gap-2.5 has-data-[size=xs]:gap-2',+ className,+ )}+ {...props}+ />+ )+}++function ItemSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {+ return (+ <Separator+ data-slot="item-separator"+ orientation="horizontal"+ className={cn('my-2', className)}+ {...props}+ />+ )+}++const itemVariants = cva(+ 'group/item flex w-full flex-wrap items-center rounded-lg border text-sm transition-colors duration-100 outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 [a]:transition-colors [a]:hover:bg-muted',+ {+ variants: {+ variant: {+ default: 'border-transparent',+ outline: 'border-border',+ muted: 'border-transparent bg-muted/50',+ },+ size: {+ default: 'gap-2.5 px-3 py-2.5',+ sm: 'gap-2.5 px-3 py-2.5',+ xs: 'gap-2 px-2.5 py-2 in-data-[slot=dropdown-menu-content]:p-0',+ },+ },+ defaultVariants: {+ variant: 'default',+ size: 'default',+ },+ },+)++function Item({+ className,+ variant = 'default',+ size = 'default',+ render,+ ...props+}: useRender.ComponentProps<'div'> & VariantProps<typeof itemVariants>) {+ return useRender({+ defaultTagName: 'div',+ props: mergeProps<'div'>(+ {+ className: cn(itemVariants({ variant, size, className })),+ },+ props,+ ),+ render,+ state: {+ slot: 'item',+ variant,+ size,+ },+ })+}++const itemMediaVariants = cva(+ 'flex shrink-0 items-center justify-center gap-2 group-has-data-[slot=item-description]/item:translate-y-0.5 group-has-data-[slot=item-description]/item:self-start [&_svg]:pointer-events-none',+ {+ variants: {+ variant: {+ default: 'bg-transparent',+ icon: "[&_svg:not([class*='size-'])]:size-4",+ image:+ 'size-10 overflow-hidden rounded-sm group-data-[size=sm]/item:size-8 group-data-[size=xs]/item:size-6 [&_img]:size-full [&_img]:object-cover',+ },+ },+ defaultVariants: {+ variant: 'default',+ },+ },+)++function ItemMedia({+ className,+ variant = 'default',+ ...props+}: React.ComponentProps<'div'> & VariantProps<typeof itemMediaVariants>) {+ return (+ <div+ data-slot="item-media"+ data-variant={variant}+ className={cn(itemMediaVariants({ variant, className }))}+ {...props}+ />+ )+}++function ItemContent({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="item-content"+ className={cn(+ 'flex flex-1 flex-col gap-1 group-data-[size=xs]/item:gap-0 [&+[data-slot=item-content]]:flex-none',+ className,+ )}+ {...props}+ />+ )+}++function ItemTitle({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="item-title"+ className={cn(+ 'line-clamp-1 flex w-fit items-center gap-2 text-sm leading-snug font-medium underline-offset-4',+ className,+ )}+ {...props}+ />+ )+}++function ItemDescription({ className, ...props }: React.ComponentProps<'p'>) {+ return (+ <p+ data-slot="item-description"+ className={cn(+ 'line-clamp-2 text-left text-sm leading-normal font-normal text-muted-foreground group-data-[size=xs]/item:text-xs [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary',+ className,+ )}+ {...props}+ />+ )+}++function ItemActions({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div data-slot="item-actions" className={cn('flex items-center gap-2', className)} {...props} />+ )+}++function ItemHeader({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="item-header"+ className={cn('flex basis-full items-center justify-between gap-2', className)}+ {...props}+ />+ )+}++function ItemFooter({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="item-footer"+ className={cn('flex basis-full items-center justify-between gap-2', className)}+ {...props}+ />+ )+}++export {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemFooter,+ ItemGroup,+ ItemHeader,+ ItemMedia,+ ItemSeparator,+ ItemTitle,+}diff --git a/packages/dashboard/e2e/companies.spec.ts b/packages/dashboard/e2e/companies.spec.tsindex aa5601328a..c0a337105c 100644--- a/packages/dashboard/e2e/companies.spec.ts+++ b/packages/dashboard/e2e/companies.spec.ts@@ -178,7 +178,7 @@ test.describe('companies', () => {const certificateNumber = `RESALE-${Date.now()}`await sheet.locator('#certificate_number').fill(certificateNumber)- await sheet.locator('#reason_code').click()+ await sheet.locator('#tax_exemption_reason_id').click()await page.getByRole('option', { name: /^resale$/i }).click()await sheet.locator('input[type="file"]').setInputFiles({name: 'certificate.pdf',@@ -194,6 +194,77 @@ test.describe('companies', () => {await expect(certificates.getByRole('button', { name: /certificate\.pdf/i })).toBeVisible()})+ // Certificates point at the store's own reasons: the picker offers the+ // active ones only, and renaming a reason renames it on every certificate.+ test('picks a tax exemption reason the store added', async ({ page }) => {+ const creds = await login(page)+ const suffix = Date.now()+ const offered = `E2E Diplomatic ${suffix}`+ const retired = `E2E Retired ${suffix}`+ const renamed = `E2E Embassy ${suffix}`+ const reasons = card(page, /^tax exemption reasons$/i)++ await page.goto(`/${creds.store_id}/settings/taxes/exemption-reasons`)+ for (const [name, code] of [+ [offered, `DIPLOMATIC_${suffix}`],+ [retired, `RETIRED_${suffix}`],+ ]) {+ await reasons.getByRole('button', { name: /add reason/i }).click()+ await page.locator('#reason-name').fill(name)+ await page.locator('#reason-code').fill(code)+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^create$/i })+ .click()+ await expect(reasons.getByText(name)).toBeVisible({ timeout: 15_000 })+ }+ await openRowMenu(page, retired)+ await page.getByRole('menuitem', { name: /^edit$/i }).click()+ await page.getByRole('switch', { name: /available on new records/i }).click()+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^save$/i })+ .click()+ await expect(+ reasons+ .getByRole('row')+ .filter({ hasText: retired })+ .getByText(/^inactive$/i),+ ).toBeVisible({ timeout: 15_000 })++ await createCompany(page, creds.store_id, `E2E Consulate ${suffix}`)+ const certificates = card(page, /exemption certificates/i)+ await certificates.getByRole('button', { name: /add certificate/i }).click()+ const sheet = page.getByRole('dialog')+ const certificateNumber = `DIP-${suffix}`+ await sheet.locator('#certificate_number').fill(certificateNumber)+ await sheet.locator('#tax_exemption_reason_id').click()+ await expect(page.getByRole('option', { name: retired })).toHaveCount(0)+ await page.getByRole('option', { name: offered }).click()+ await sheet.getByRole('button', { name: /^create$/i }).click()++ await expect(certificates.getByText(certificateNumber)).toBeVisible({ timeout: 15_000 })+ await expect(certificates.getByText(offered)).toBeVisible()++ const companyUrl = page.url()+ await page.goto(`/${creds.store_id}/settings/taxes/exemption-reasons`)+ await openRowMenu(page, offered)+ await page.getByRole('menuitem', { name: /^edit$/i }).click()+ await page.locator('#reason-name').fill(renamed)+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^save$/i })+ .click()+ await expect(reasons.getByText(renamed)).toBeVisible({ timeout: 15_000 })++ await page.goto(companyUrl)+ await expect(+ card(page, /exemption certificates/i)+ .getByText(renamed)+ .first(),+ ).toBeVisible({ timeout: 15_000 })+ })+test('deletes a company from the list', async ({ page }) => {const creds = await login(page)const name = `E2E Dissolved ${Date.now()}`diff --git a/packages/dashboard/e2e/getting-started.spec.ts b/packages/dashboard/e2e/getting-started.spec.tsindex 7de16f4c93..bd529fe81f 100644--- a/packages/dashboard/e2e/getting-started.spec.ts+++ b/packages/dashboard/e2e/getting-started.spec.ts@@ -19,7 +19,7 @@ test.describe('getting started', () => {if ((await step.getAttribute('aria-expanded')) !== 'true') await step.click()await page.getByRole('link', { name: /^tax settings$/i }).click()- await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/settings/tax-rates`))+ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/settings/taxes/rates`))await expect(page.getByRole('button', { name: /add tax rate/i })).toBeVisible({timeout: 15_000,})diff --git a/packages/dashboard/e2e/integrations.spec.ts b/packages/dashboard/e2e/integrations.spec.tsindex 3448101d50..80d4368975 100644--- a/packages/dashboard/e2e/integrations.spec.ts+++ b/packages/dashboard/e2e/integrations.spec.ts@@ -70,6 +70,12 @@ test.describe('integrations', () => {await accountId.fill('acct-e2e')await secret.fill('relay-secret-4321')+ // The eye shows what was typed, and hides it again.+ await expect(secret).toHaveAttribute('type', 'password')+ await sheet.getByRole('button', { name: /^show$/i }).click()+ await expect(secret).toHaveAttribute('type', 'text')+ await sheet.getByRole('button', { name: /^hide$/i }).click()+ await expect(secret).toHaveAttribute('type', 'password')await interval.fill('30')await sandbox.click()await sheet.getByRole('button', { name: /^connect$/i }).click()diff --git a/packages/dashboard/e2e/markets.spec.ts b/packages/dashboard/e2e/markets.spec.tsindex 3aba622eb9..9efff2b47f 100644--- a/packages/dashboard/e2e/markets.spec.ts+++ b/packages/dashboard/e2e/markets.spec.ts@@ -124,14 +124,14 @@ test.describe('markets', () => {// Name the built-in engine explicitly rather than inheriting the default,// so reopening proves the saved provider matches the catalog's entry.await page.locator('#market-tax-provider').click()- await page.getByRole('option', { name: /^internal$/i }).click()+ await page.getByRole('option', { name: /^spree tax rates$/i }).click()await page.getByRole('button', { name: /^save$/i }).click()await expect(rowButton(page, updated)).toBeVisible({ timeout: 15_000 })await rowButton(page, updated).click()await expect(page.getByRole('heading', { name: updated })).toBeVisible({ timeout: 15_000 })- await expect(page.locator('#market-tax-provider')).toHaveText(/^internal$/i)+ await expect(page.locator('#market-tax-provider')).toHaveText(/^spree tax rates$/i)})test('deletes a market', async ({ page }) => {diff --git a/packages/dashboard/e2e/products-tax-category.spec.ts b/packages/dashboard/e2e/products-tax-category.spec.tsindex 20360877a5..8eecb7c25b 100644--- a/packages/dashboard/e2e/products-tax-category.spec.ts+++ b/packages/dashboard/e2e/products-tax-category.spec.ts@@ -7,7 +7,7 @@ import {variantsCard as variantsCardLocator,} from './products-helpers'-const TAX_CATEGORIES_PATH = (storeId: string) => `/${storeId}/settings/tax-categories`+const TAX_CATEGORIES_PATH = (storeId: string) => `/${storeId}/settings/taxes/categories`async function createTaxCategory(page: Page, name: string) {await page.getByRole('button', { name: /add tax category/i }).click()diff --git a/packages/dashboard/e2e/reasons.spec.ts b/packages/dashboard/e2e/reasons.spec.tsindex 00f5616500..f9f235fbc0 100644--- a/packages/dashboard/e2e/reasons.spec.ts+++ b/packages/dashboard/e2e/reasons.spec.ts@@ -3,7 +3,7 @@ import { login, openRowMenu } from './helpers'const REASONS_PATH = (storeId: string) => `/${storeId}/settings/reasons`-/** One of the four reason lists on the page, found by its card title. */+/** One of the reason lists on the page, found by its card title. */function reasonCard(page: Page, title: RegExp) {return page.locator('[data-slot="card"]')diff --git a/packages/dashboard/e2e/settings-index.spec.ts b/packages/dashboard/e2e/settings-index.spec.tsindex 01a66d1709..eb268f328b 100644--- a/packages/dashboard/e2e/settings-index.spec.ts+++ b/packages/dashboard/e2e/settings-index.spec.ts@@ -13,10 +13,10 @@ test.describe('settings index', () => {timeout: 15_000,})// The card, not the sidebar entry: the card's name carries its description.- await main.getByRole('link', { name: /^tax rates rates applied/i }).click()+ await main.getByRole('link', { name: /^taxes tax categories/i }).click()- await expect(page).toHaveURL(new RegExp(`${SETTINGS_PATH(creds.store_id)}/tax-rates`))- await expect(page.getByRole('button', { name: /add tax rate/i })).toBeVisible({+ await expect(page).toHaveURL(new RegExp(`${SETTINGS_PATH(creds.store_id)}/taxes/categories`))+ await expect(page.getByRole('button', { name: /add tax category/i })).toBeVisible({timeout: 15_000,})})@@ -34,7 +34,7 @@ test.describe('settings index', () => {await search.fill('webhook')await expect(main.getByRole('link', { name: /^webhooks/i })).toBeVisible()- await expect(main.getByRole('link', { name: /^tax rates/i })).toHaveCount(0)+ await expect(main.getByRole('link', { name: /^taxes/i })).toHaveCount(0)await search.fill('zzz-nothing-matches')await expect(main.getByText(/no settings match/i)).toBeVisible()diff --git a/packages/dashboard/e2e/tax-categories.spec.ts b/packages/dashboard/e2e/tax-categories.spec.tsindex d9714f41cf..9762c0c8e5 100644--- a/packages/dashboard/e2e/tax-categories.spec.ts+++ b/packages/dashboard/e2e/tax-categories.spec.ts@@ -1,7 +1,7 @@import { expect, type Page, test } from '@playwright/test'import { gotoIndex, login, openRowMenu, rowButton } from './helpers'-const TAX_CATEGORIES_PATH = (storeId: string) => `/${storeId}/settings/tax-categories`+const TAX_CATEGORIES_PATH = (storeId: string) => `/${storeId}/settings/taxes/categories`const CTA = /add tax category/iasync function createTaxCategory(diff --git a/packages/dashboard/e2e/tax-rates.spec.ts b/packages/dashboard/e2e/tax-rates.spec.tsindex c24709152e..0058d2ab9d 100644--- a/packages/dashboard/e2e/tax-rates.spec.ts+++ b/packages/dashboard/e2e/tax-rates.spec.ts@@ -1,7 +1,7 @@import { expect, type Page, test } from '@playwright/test'import { gotoIndex, login, openRowMenu, rowButton } from './helpers'-const TAX_RATES_PATH = (storeId: string) => `/${storeId}/settings/tax-rates`+const TAX_RATES_PATH = (storeId: string) => `/${storeId}/settings/taxes/rates`const CTA = /add tax rate/iasync function createTaxRate(diff --git a/packages/dashboard/e2e/taxes.spec.ts b/packages/dashboard/e2e/taxes.spec.tsnew file mode 100644index 0000000000..e116dbb66c--- /dev/null+++ b/packages/dashboard/e2e/taxes.spec.ts@@ -0,0 +1,66 @@+import { expect, type Page, test } from '@playwright/test'+import { login } from './helpers'++const TAXES_PATH = (storeId: string) => `/${storeId}/settings/taxes`++function exemptionReasons(page: Page) {+ return page.locator('[data-slot="card"]').filter({+ has: page.locator('[data-slot="card-title"]', { hasText: /^tax exemption reasons$/i }),+ })+}++test.describe('taxes', () => {+ test('opens on categories and switches between the tabs', async ({ page }) => {+ const creds = await login(page)+ await page.goto(TAXES_PATH(creds.store_id))++ await expect(page).toHaveURL(new RegExp(`${TAXES_PATH(creds.store_id)}/categories`))+ await expect(page.getByRole('heading', { name: /^taxes$/i })).toBeVisible({ timeout: 15_000 })+ await expect(page.getByRole('tab', { name: /^categories$/i })).toHaveAttribute(+ 'aria-selected',+ 'true',+ )+ await expect(page.getByText(/^tax calculation$/i)).toBeVisible()+ await expect(page.getByRole('link', { name: /manage markets/i })).toBeVisible()+ await expect(page.getByRole('button', { name: /add tax category/i })).toBeVisible()++ await page.getByRole('tab', { name: /^rates$/i }).click()+ await expect(page).toHaveURL(new RegExp(`${TAXES_PATH(creds.store_id)}/rates`))+ await expect(page.getByRole('tab', { name: /^rates$/i })).toHaveAttribute(+ 'aria-selected',+ 'true',+ )+ await expect(page.getByRole('button', { name: /add tax rate/i })).toBeVisible({+ timeout: 15_000,+ })++ await page.getByRole('tab', { name: /^exemption reasons$/i }).click()+ await expect(page).toHaveURL(new RegExp(`${TAXES_PATH(creds.store_id)}/exemption-reasons`))+ await expect(+ exemptionReasons(page).getByRole('cell', { name: 'RESALE', exact: true }),+ ).toBeVisible({ timeout: 15_000 })+ })++ // The tax engine reads the code, not the name, so the list shows both.+ test('adds a tax exemption reason with its code', async ({ page }) => {+ const creds = await login(page)+ await page.goto(`${TAXES_PATH(creds.store_id)}/exemption-reasons`)++ const name = `E2E Diplomatic ${Date.now()}`+ const code = `diplomatic_${Date.now()}`+ await exemptionReasons(page)+ .getByRole('button', { name: /add reason/i })+ .click()+ await page.locator('#reason-name').fill(name)+ await page.locator('#reason-code').fill(code)+ // Codes are stored upper case, the way tax engines compare them.+ await expect(page.locator('#reason-code')).toHaveValue(code.toUpperCase())+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^create$/i })+ .click()++ const row = exemptionReasons(page).getByRole('row').filter({ hasText: name })+ await expect(row.getByText(code.toUpperCase())).toBeVisible({ timeout: 15_000 })+ })+})diff --git a/packages/dashboard/src/components/spree/command-palette/command-palette.tsx b/packages/dashboard/src/components/spree/command-palette/command-palette.tsxindex c4415d6eca..299bec23f2 100644--- a/packages/dashboard/src/components/spree/command-palette/command-palette.tsx+++ b/packages/dashboard/src/components/spree/command-palette/command-palette.tsx@@ -1,4 +1,5 @@import {+ canSeeSettingsEntry,type NavEntry,type Permissions,permittedCreateActions,@@ -338,7 +339,7 @@ function buildGotoCommands({// `comingSoon` pages are disabled in the sidebar — keep them unreachable// from the palette too.if (entry.comingSoon) continue- if (!canRead(entry.subject, permissions)) continue+ if (!canSeeSettingsEntry(entry, (action, subject) => permissions.can(action, subject))) continuecommands.push({key: `settings:${entry.key}`,label: resolveNavLabel(entry, t),diff --git a/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsx b/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsxindex e48ce510d3..f8515bd373 100644--- a/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsx+++ b/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsx@@ -119,12 +119,8 @@ function taxExemptionDetail(group: TaxLineGroup): string | null {const number = group.exemption?.certificate_numberif (group.taxabilityReason !== 'customer_exempt' || !number) return null- const reasonCode = group.exemption?.reason_code- const reason = reasonCode- ? i18n.t(`admin.tax_exemption_certificates.reason_codes.${reasonCode}`, {- defaultValue: reasonCode,- })- : null+ // The name the reason had when the sale was taxed; older lines carry only the code.+ const reason = group.exemption?.reason_name ?? group.exemption?.reason_codereturn reason? i18n.t('admin.orders.detail.adjustment_lines.tax_exempt_certificate', {diff --git a/packages/dashboard/src/components/spree/reasons/reason-section.tsx b/packages/dashboard/src/components/spree/reasons/reason-section.tsxnew file mode 100644index 0000000000..1d1cb5c550--- /dev/null+++ b/packages/dashboard/src/components/spree/reasons/reason-section.tsx@@ -0,0 +1,475 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { Can, mapSpreeErrorsToForm, Subject, usePermissions } from '@spree/dashboard-core'+import {+ ActiveBadge,+ Badge,+ Button,+ Field,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ Input,+ RowActions,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+ Switch,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ useConfirm,+} from '@spree/dashboard-ui'+import { PlusIcon, RotateCcwIcon } from '@spree/dashboard-ui/icons'+import { useState } from 'react'+import { Controller, type UseFormReturn, useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'+import {+ type Reason,+ type ReasonKind,+ type ReasonParams,+ useCreateReason,+ useDeleteReason,+ useReasons,+ useUpdateReason,+} from '../../../hooks/use-reasons'+import { useTaxProviders } from '../../../hooks/use-tax-rates'+import {+ REASON_DEFAULTS,+ type ReasonFormValues,+ reasonFormSchema,+ taxExemptionReasonFormSchema,+} from '../../../schemas/reason'+import { SettingsListCard } from '../settings-list-card'+import { useMarketTaxProviders } from '../taxes/market-tax-providers'++/** One reason list: which kind, who may manage it, and how its card reads. */+export interface SectionConfig {+ kind: ReasonKind+ subject: string+ titleKey: string+ helpKey: string+ /** Tax exemption reasons carry the code a tax engine reads beside their name. */+ withCode?: boolean+}++/** A reason's code only when its list carries one, so the others send what they accept. */+function reasonParams(values: ReasonFormValues, withCode: boolean): ReasonParams {+ const { code, ...rest } = values+ return withCode ? { ...rest, code: code?.trim() } : rest+}++/** The code a reason in the table shows, for the one list that has them. */+function reasonCode(reason: Reason): string | undefined {+ return 'code' in reason ? reason.code : undefined+}++/** One reason list as a card: its rows, and the sheets that add and edit them. */+export function ReasonSection({+ kind,+ subject,+ titleKey,+ helpKey,+ withCode = false,+}: SectionConfig) {+ const { t } = useTranslation()+ const { data, isLoading, isError } = useReasons(kind)++ const [creating, setCreating] = useState(false)+ const [editing, setEditing] = useState<Reason | null>(null)++ const reasons = data?.data ?? []++ return (+ <>+ <SettingsListCard+ title={t(titleKey)}+ description={t(helpKey)}+ action={+ <Can I="create" a={subject}>+ <Button size="sm" onClick={() => setCreating(true)}>+ <PlusIcon className="size-4" />+ {t('admin.reasons.add_cta')}+ </Button>+ </Can>+ }+ isLoading={isLoading}+ isError={isError}+ isEmpty={reasons.length === 0}+ emptyIcon={<RotateCcwIcon />}+ emptyTitle={t('admin.reasons.empty')}+ >+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>{t('admin.fields.name.label')}</TableHead>+ {withCode && <TableHead>{t('admin.fields.code.label')}</TableHead>}+ <TableHead>{t('admin.fields.status.label')}</TableHead>+ <TableHead className="w-12" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {reasons.map((reason) => (+ <ReasonRow+ key={reason.id}+ kind={kind}+ subject={subject}+ reason={reason}+ withCode={withCode}+ onEdit={setEditing}+ />+ ))}+ </TableBody>+ </Table>+ </SettingsListCard>++ {creating && (+ <CreateReasonSheet kind={kind} withCode={withCode} onClose={() => setCreating(false)} />+ )}+ {editing && (+ <EditReasonSheet+ kind={kind}+ reason={editing}+ withCode={withCode}+ onClose={() => setEditing(null)}+ />+ )}+ </>+ )+}++function ReasonRow({+ kind,+ subject,+ reason,+ withCode,+ onEdit,+}: {+ kind: ReasonKind+ subject: string+ reason: Reason+ withCode: boolean+ onEdit: (reason: Reason) => void+}) {+ const { t } = useTranslation()+ const confirm = useConfirm()+ const { permissions } = usePermissions()+ const deleteMutation = useDeleteReason(kind)++ async function handleDelete() {+ const ok = await confirm({+ title: t('admin.reasons.delete_confirm.title'),+ message: t('admin.reasons.delete_confirm.message', { name: reason.name }),+ variant: 'destructive',+ confirmLabel: t('admin.actions.delete'),+ })+ if (!ok) return+ await deleteMutation.mutateAsync(reason.id).catch(() => undefined)+ }++ return (+ <TableRow>+ <TableCell>+ <span className="flex items-center gap-2 font-medium">+ {reason.name}+ {!reason.can_be_deleted && (+ <Badge variant="outline" title={t('admin.reasons.in_use_help')}>+ {t('admin.reasons.in_use')}+ </Badge>+ )}+ </span>+ </TableCell>+ {withCode && (+ <TableCell>+ <code className="text-sm">{reasonCode(reason)}</code>+ </TableCell>+ )}+ <TableCell>+ <ActiveBadge+ active={reason.active}+ activeLabel={t('admin.fields.active.label')}+ inactiveLabel={t('admin.reasons.inactive')}+ />+ </TableCell>+ <TableCell>+ <RowActions+ actions={[+ {+ key: 'edit',+ visible: permissions.can('update', subject),+ onSelect: () => onEdit(reason),+ },+ {+ key: 'delete',+ destructive: true,+ visible: permissions.can('destroy', subject) && reason.can_be_deleted,+ disabled: deleteMutation.isPending,+ onSelect: handleDelete,+ },+ ]}+ />+ </TableCell>+ </TableRow>+ )+}++function CreateReasonSheet({+ kind,+ withCode,+ onClose,+}: {+ kind: ReasonKind+ withCode: boolean+ onClose: () => void+}) {+ const { t } = useTranslation()+ const createMutation = useCreateReason(kind)+ const form = useForm<ReasonFormValues>({+ resolver: zodResolver(withCode ? taxExemptionReasonFormSchema : reasonFormSchema),+ defaultValues: REASON_DEFAULTS,+ })++ async function onSubmit(values: ReasonFormValues) {+ try {+ await createMutation.mutateAsync(reasonParams(values, withCode))+ onClose()+ } catch (err) {+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err+ }+ }++ return (+ <Sheet open onOpenChange={(next) => !next && onClose()}>+ <SheetContent>+ <SheetHeader>+ <SheetTitle>{t('admin.reasons.add_sheet_title')}</SheetTitle>+ <SheetDescription>+ {t(+ withCode+ ? 'admin.reasons.tax_exemption.create_description'+ : 'admin.reasons.create_description',+ )}+ </SheetDescription>+ </SheetHeader>+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">+ <ReasonFormFields form={form} withCode={withCode} />+ </div>+ <SheetFooter>+ <Button type="button" variant="outline" onClick={onClose}>+ {t('admin.actions.cancel')}+ </Button>+ <Button type="submit" disabled={createMutation.isPending}>+ {t('admin.actions.create')}+ </Button>+ </SheetFooter>+ </form>+ </SheetContent>+ </Sheet>+ )+}++function EditReasonSheet({+ kind,+ reason,+ withCode,+ onClose,+}: {+ kind: ReasonKind+ reason: Reason+ withCode: boolean+ onClose: () => void+}) {+ const { t } = useTranslation()+ const updateMutation = useUpdateReason(kind, reason.id)+ const form = useForm<ReasonFormValues>({+ resolver: zodResolver(withCode ? taxExemptionReasonFormSchema : reasonFormSchema),+ defaultValues: { name: reason.name, active: reason.active, code: reasonCode(reason) ?? '' },+ })++ async function onSubmit(values: ReasonFormValues) {+ try {+ await updateMutation.mutateAsync(reasonParams(values, withCode))+ onClose()+ } catch (err) {+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err+ }+ }++ return (+ <Sheet open onOpenChange={(next) => !next && onClose()}>+ <SheetContent>+ <SheetHeader>+ <SheetTitle>{t('admin.reasons.edit_sheet_title')}</SheetTitle>+ </SheetHeader>+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">+ <ReasonFormFields form={form} withCode={withCode} />+ </div>+ <SheetFooter>+ <Button type="button" variant="outline" onClick={onClose}>+ {t('admin.actions.cancel')}+ </Button>+ <Button type="submit" disabled={updateMutation.isPending}>+ {t('admin.actions.save')}+ </Button>+ </SheetFooter>+ </form>+ </SheetContent>+ </Sheet>+ )+}++function ReasonFormFields({+ form,+ withCode,+}: {+ form: UseFormReturn<ReasonFormValues>+ withCode: boolean+}) {+ const { t } = useTranslation()+ const { errors } = form.formState++ return (+ <FieldGroup>+ {errors.root?.message && (+ <p className="text-sm text-destructive" role="alert">+ {errors.root.message}+ </p>+ )}++ <Field>+ <FieldLabel htmlFor="reason-name">{t('admin.fields.name.label')}</FieldLabel>+ <Input+ id="reason-name"+ aria-invalid={!!errors.name}+ placeholder={t(+ withCode+ ? 'admin.reasons.tax_exemption.name_placeholder'+ : 'admin.reasons.name_placeholder',+ )}+ {...form.register('name')}+ />+ {errors.name && <FieldError>{errors.name.message}</FieldError>}+ </Field>++ {withCode && <ReasonCodeField form={form} />}++ <Field orientation="horizontal">+ <FieldLabel htmlFor="reason-active">{t('admin.reasons.active_label')}</FieldLabel>+ <Controller+ control={form.control}+ name="active"+ render={({ field }) => (+ <Switch id="reason-active" checked={field.value} onCheckedChange={field.onChange} />+ )}+ />+ </Field>+ </FieldGroup>+ )+}++/**+ * The code a tax exemption reason records. Where a connected tax engine reads+ * codes (Avalara's entity use codes), the merchant picks one of those, since+ * any other is sent as a catch-all; otherwise the code is the merchant's own.+ */+function ReasonCodeField({ form }: { form: UseFormReturn<ReasonFormValues> }) {+ const { t } = useTranslation()+ const { errors } = form.formState+ const { data } = useTaxProviders()+ const { permissions } = usePermissions()+ const marketProviders = useMarketTaxProviders()+ // Only engines a market actually taxes with: a store that has Avalara set+ // up but still taxes every market itself keeps free-text codes. Staff who+ // cannot see markets fall back to every engine the store has set up.+ const usedProviderIds = permissions.can('read', Subject.Market)+ ? new Set(marketProviders.map((group) => group.providerId))+ : null++ // Engines may share a code; each is offered once.+ const engineCodes = [+ ...new Map(+ (data?.data ?? [])+ .filter((provider) => provider.available)+ .filter((provider) => !usedProviderIds || usedProviderIds.has(provider.id))+ .flatMap((provider) => provider.exemption_reason_codes ?? [])+ .map((code) => [code.value, code]),+ ).values(),+ ]+ const codeInput = form.register('code')+ const help = engineCodes.length+ ? t('admin.reasons.code_engine_help')+ : t('admin.reasons.code_help')++ return (+ <Field>+ <FieldLabel htmlFor="reason-code">{t('admin.fields.code.label')}</FieldLabel>+ {engineCodes.length ? (+ <Controller+ control={form.control}+ name="code"+ render={({ field }) => {+ // A code recorded before the engine was connected stays selectable+ // rather than being silently replaced by the first option.+ const items = engineCodes.some((code) => code.value === field.value)+ ? engineCodes+ : field.value+ ? [{ value: field.value, label: field.value }, ...engineCodes]+ : engineCodes+ const options = items.map((code) => ({+ value: code.value,+ label: code.value === code.label ? code.value : `${code.value} — ${code.label}`,+ }))+ return (+ <Select+ items={options}+ value={field.value ?? ''}+ onValueChange={(next) => field.onChange(next ?? '')}+ >+ <SelectTrigger id="reason-code" aria-invalid={!!errors.code}>+ <SelectValue placeholder={t('admin.reasons.code_placeholder')} />+ </SelectTrigger>+ <SelectContent>+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+ }}+ />+ ) : (+ <Input+ id="reason-code"+ aria-invalid={!!errors.code}+ placeholder={t('admin.reasons.code_placeholder')}+ {...codeInput}+ onChange={(event) => {+ // Codes are saved in capitals, so show them that way while typing.+ const input = event.target+ const { selectionStart, selectionEnd } = input+ input.value = input.value.toUpperCase()+ input.setSelectionRange(selectionStart, selectionEnd)+ codeInput.onChange(event)+ }}+ />+ )}+ <FieldDescription>{help}</FieldDescription>+ {errors.code && <FieldError>{errors.code.message}</FieldError>}+ </Field>+ )+}diff --git a/packages/dashboard/src/components/spree/settings-list-card.tsx b/packages/dashboard/src/components/spree/settings-list-card.tsxnew file mode 100644index 0000000000..c46b74895c--- /dev/null+++ b/packages/dashboard/src/components/spree/settings-list-card.tsx@@ -0,0 +1,90 @@+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ Empty,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ Skeleton,+} from '@spree/dashboard-ui'+import { TriangleAlertIcon } from '@spree/dashboard-ui/icons'+import type { ReactNode } from 'react'+import { useTranslation } from 'react-i18next'++/**+ * A short settings list in a card: title, one line of help, an add button,+ * then the rows. For vocabularies a merchant reads in one go (reasons, tax+ * categories, tax rates), where a full resource table's search, filters and+ * column picker would be more chrome than content.+ */+export function SettingsListCard({+ title,+ description,+ action,+ isLoading,+ isError,+ isEmpty,+ emptyIcon,+ emptyTitle,+ children,+ footer,+}: {+ title: string+ description?: string+ action?: ReactNode+ isLoading: boolean+ isError: boolean+ isEmpty: boolean+ emptyIcon: ReactNode+ emptyTitle: string+ /** The table, rendered once the rows have loaded and there is at least one. */+ children: ReactNode+ /** Rendered under the table, such as its pagination. */+ footer?: ReactNode+}) {+ const { t } = useTranslation()++ return (+ <Card>+ <CardHeader className="flex flex-row items-start justify-between gap-3 space-y-0">+ <div>+ <CardTitle>{title}</CardTitle>+ {description && <p className="mt-1 text-sm text-muted-foreground">{description}</p>}+ </div>+ {action}+ </CardHeader>+ <CardContent className="p-0">+ {isLoading ? (+ <div className="p-4">+ <Skeleton className="h-10 w-full" />+ </div>+ ) : isError ? (+ // Distinct from the empty state: "nothing here yet" would tell an+ // admin the list is empty when the request actually failed.+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <TriangleAlertIcon />+ </EmptyMedia>+ <EmptyTitle>{t('admin.errors.failed_to_load')}</EmptyTitle>+ </EmptyHeader>+ </Empty>+ ) : isEmpty ? (+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">{emptyIcon}</EmptyMedia>+ <EmptyTitle>{emptyTitle}</EmptyTitle>+ </EmptyHeader>+ </Empty>+ ) : (+ <>+ {children}+ {footer}+ </>+ )}+ </CardContent>+ </Card>+ )+}diff --git a/packages/dashboard/src/components/spree/tax-exemption-certificates-card.tsx b/packages/dashboard/src/components/spree/tax-exemption-certificates-card.tsxindex bbcaec5eb9..3f82c12c38 100644--- a/packages/dashboard/src/components/spree/tax-exemption-certificates-card.tsx+++ b/packages/dashboard/src/components/spree/tax-exemption-certificates-card.tsx@@ -56,7 +56,7 @@ import {} from '@spree/dashboard-ui/icons'import { parseISO } from 'date-fns'import { formatInTimeZone } from 'date-fns-tz'-import { useEffect, useState } from 'react'+import { useEffect, useMemo, useState } from 'react'import { Controller, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import {@@ -66,9 +66,9 @@ import {useTaxExemptionCertificates,useVerifyTaxExemptionCertificate,} from '../../hooks/use-companies'+import { useTaxExemptionReasons } from '../../hooks/use-reasons'import {TAX_EXEMPTION_CERTIFICATE_DEFAULTS,- TAX_EXEMPTION_REASON_CODES,type TaxExemptionCertificateFormValues,taxExemptionCertificateFormSchema,taxExemptionCertificateValuesToParams,@@ -201,9 +201,7 @@ export function TaxExemptionCertificatesCard({)}</div><span className="text-muted-foreground text-xs">- {t(`admin.tax_exemption_certificates.reason_codes.${certificate.reason_code}`, {- defaultValue: certificate.reason_code,- })}+ {certificate.tax_exemption_reason?.name ?? '—'}{' · '}<JurisdictionLabelcountryCode={certificate.country_code}@@ -338,6 +336,15 @@ function CertificateSheet({}) {const { t } = useTranslation()const createMutation = useCreateTaxExemptionCertificate(companyId)+ const reasons = useTaxExemptionReasons()+ // Only the reasons the store still offers; the server refuses any other.+ const reasonOptions: ReasonOption[] = useMemo(+ () =>+ reasons+ .filter((reason) => reason.active)+ .map((reason) => ({ value: reason.id, label: reason.name })),+ [reasons],+ )const form = useForm<TaxExemptionCertificateFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(taxExemptionCertificateFormSchema) as any,@@ -400,17 +407,13 @@ function CertificateSheet({</Field><Field>- <FieldLabel htmlFor="reason_code">{t('admin.fields.reason_code.label')}</FieldLabel>+ <FieldLabel htmlFor="tax_exemption_reason_id">+ {t('admin.fields.tax_exemption_reason_id.label')}+ </FieldLabel><Controller- name="reason_code"+ name="tax_exemption_reason_id"control={form.control}render={({ field }) => {- const reasonOptions = TAX_EXEMPTION_REASON_CODES.map((code) => ({- value: code,- label: t(`admin.tax_exemption_certificates.reason_codes.${code}`, {- defaultValue: code,- }),- }))const selected = reasonOptions.find((o) => o.value === field.value) ?? nullreturn (<Combobox@@ -423,11 +426,15 @@ function CertificateSheet({itemToStringValue={(option: ReasonOption | null) => option?.value ?? ''}><ComboboxInput- id="reason_code"+ id="tax_exemption_reason_id"placeholder={t('admin.tax_exemption_certificates.select_reason')}/><ComboboxContent>- <ComboboxEmpty>{t('admin.common.no_results')}</ComboboxEmpty>+ <ComboboxEmpty>+ {reasonOptions.length+ ? t('admin.common.no_results')+ : t('admin.tax_exemption_certificates.no_reasons')}+ </ComboboxEmpty><ComboboxList>{(option: ReasonOption) => (<ComboboxItem key={option.value} value={option}>@@ -440,8 +447,10 @@ function CertificateSheet({)}}/>- <FieldDescription>{t('admin.fields.reason_code.help')}</FieldDescription>- <FieldError errors={[errors.reason_code]} />+ <FieldDescription>+ {t('admin.fields.tax_exemption_reason_id.help')}+ </FieldDescription>+ <FieldError errors={[errors.tax_exemption_reason_id]} /></Field><Field>diff --git a/packages/dashboard/src/components/spree/tax-provider-field.tsx b/packages/dashboard/src/components/spree/tax-provider-field.tsxindex a9c291cc43..55a4ac03c1 100644--- a/packages/dashboard/src/components/spree/tax-provider-field.tsx+++ b/packages/dashboard/src/components/spree/tax-provider-field.tsx@@ -16,15 +16,6 @@ import { Controller, type UseFormReturn } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { useTaxProviders } from '../../hooks/use-tax-rates'-/** One entry from `GET /tax_providers` — classes registered in code, not rows. */-interface TaxProviderOption {- id: string- name: string- available: boolean- default: boolean- unsupported_capabilities?: Array<{ key: string; label: string; description?: string }>-}-/** Any form whose values carry a `tax_provider` string. */interface TaxProviderFormShape {tax_provider?: string@@ -43,7 +34,7 @@ export function TaxProviderField<T extends TaxProviderFormShape>({}) {const { t } = useTranslation()const { data } = useTaxProviders()- const providers = (data?.data ?? []) as unknown as TaxProviderOption[]+ const providers = data?.data ?? []const defaultProvider = providers.find((provider) => provider.default)const defaultLabel = defaultProviderdiff --git a/packages/dashboard/src/components/spree/taxes/market-tax-providers.tsx b/packages/dashboard/src/components/spree/taxes/market-tax-providers.tsxnew file mode 100644index 0000000000..22d7b563cb--- /dev/null+++ b/packages/dashboard/src/components/spree/taxes/market-tax-providers.tsx@@ -0,0 +1,125 @@+import type { Market } from '@spree/admin-sdk'+import { Subject, usePermissions } from '@spree/dashboard-core'+import {+ Alert,+ AlertDescription,+ Button,+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from '@spree/dashboard-ui'+import { CalculatorIcon, InfoIcon } from '@spree/dashboard-ui/icons'+import { Link, useParams } from '@tanstack/react-router'+import { useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import { useAllMarkets } from '../../../hooks/use-markets'+import { useTaxProviders } from '../../../hooks/use-tax-rates'++/** Spree's own engine, the only one that reads the store's tax rates. */+const INTERNAL_PROVIDER = 'internal'++interface ProviderMarkets {+ providerId: string+ providerName: string+ markets: Market[]+}++/**+ * The store's markets grouped by the tax engine each one uses. A market that+ * names no engine runs on the installation default. Empty for staff who+ * cannot read markets.+ */+export function useMarketTaxProviders(): ProviderMarkets[] {+ const { permissions } = usePermissions()+ const canReadMarkets = permissions.can('read', Subject.Market)+ const { markets } = useAllMarkets({ enabled: canReadMarkets })+ const { data } = useTaxProviders()++ return useMemo(() => {+ if (!canReadMarkets) return []++ const providers = data?.data ?? []+ const defaultId = providers.find((provider) => provider.default)?.id ?? INTERNAL_PROVIDER+ const groups = new Map<string, ProviderMarkets>()++ for (const market of markets) {+ const providerId = market.tax_provider || defaultId+ const group = groups.get(providerId) ?? {+ providerId,+ providerName: providers.find((provider) => provider.id === providerId)?.name ?? providerId,+ markets: [],+ }+ group.markets.push(market)+ groups.set(providerId, group)+ }++ return [...groups.values()]+ }, [canReadMarkets, markets, data])+}++/** Which tax engine each market uses, with a link to change it. */+export function TaxProviderSummary() {+ const { t } = useTranslation()+ const { storeId } = useParams({ strict: false }) as { storeId: string }+ const groups = useMarketTaxProviders()++ if (groups.length === 0) return null++ return (+ <Item variant="outline">+ <ItemMedia variant="icon">+ <CalculatorIcon />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{t('admin.taxes.providers_title')}</ItemTitle>+ {groups.map((group) => (+ <ItemDescription key={group.providerId}>+ {t('admin.taxes.provider_markets', {+ provider: group.providerName,+ markets: group.markets.map((market) => market.name).join(', '),+ })}+ </ItemDescription>+ ))}+ </ItemContent>+ <ItemActions>+ <Button variant="outline" size="sm" asChild>+ <Link to="/$storeId/settings/markets" params={{ storeId }}>+ {t('admin.taxes.manage_markets')}+ </Link>+ </Button>+ </ItemActions>+ </Item>+ )+}++/**+ * Says which markets ignore the tax rates, because their engine works tax out+ * itself. Shown rather than hiding the rates, since a store can mix markets on+ * Spree's rates with markets on an external service.+ */+export function TaxRatesUsageNote() {+ const { t } = useTranslation()+ const groups = useMarketTaxProviders()++ const external = groups.filter((group) => group.providerId !== INTERNAL_PROVIDER)+ if (external.length === 0) return null++ const markets = external+ .flatMap((group) => group.markets.map((market) => `${market.name} (${group.providerName})`))+ .join(', ')+ const noneUseRates = external.length === groups.length++ return (+ <Alert>+ <InfoIcon />+ <AlertDescription>+ {noneUseRates+ ? t('admin.taxes.rates_unused_everywhere', { markets })+ : t('admin.taxes.rates_unused_in', { markets })}+ </AlertDescription>+ </Alert>+ )+}diff --git a/packages/dashboard/src/components/spree/taxes/taxes-tabs.tsx b/packages/dashboard/src/components/spree/taxes/taxes-tabs.tsxnew file mode 100644index 0000000000..aee419d62f--- /dev/null+++ b/packages/dashboard/src/components/spree/taxes/taxes-tabs.tsx@@ -0,0 +1,51 @@+import { Subject, type SubjectName, usePermissions } from '@spree/dashboard-core'+import { Tabs, TabsList, TabsTrigger } from '@spree/dashboard-ui'+import { useNavigate, useParams, useRouterState } from '@tanstack/react-router'+import { useTranslation } from 'react-i18next'++type TaxesTab = 'categories' | 'rates' | 'exemption-reasons'++/** Each tab is its own route, so a link or the back button lands on it. */+export const TAXES_TABS: { value: TaxesTab; subject: SubjectName; labelKey: string }[] = [+ { value: 'categories', subject: Subject.TaxCategory, labelKey: 'admin.taxes.tabs.categories' },+ { value: 'rates', subject: Subject.TaxRate, labelKey: 'admin.taxes.tabs.rates' },+ {+ value: 'exemption-reasons',+ subject: Subject.TaxExemptionReason,+ labelKey: 'admin.taxes.tabs.exemption_reasons',+ },+]++/** The tabs a staff member may read; none at all when only one is left. */+export function TaxesTabs() {+ const { t } = useTranslation()+ const navigate = useNavigate()+ const { storeId } = useParams({ strict: false }) as { storeId: string }+ const { permissions } = usePermissions()+ const pathname = useRouterState({ select: (state) => state.location.pathname })++ const tabs = TAXES_TABS.filter((tab) => permissions.can('read', tab.subject))+ if (tabs.length < 2) return null++ const current = tabs.find((tab) => pathname.endsWith(`/taxes/${tab.value}`))?.value++ return (+ <Tabs+ // Never undefined: on `/taxes`, before the redirect to a tab, no tab+ // matches, and an undefined value would leave Base UI uncontrolled and+ // deaf to the tab the redirect lands on.+ value={current ?? null}+ onValueChange={(value) =>+ navigate({ to: `/$storeId/settings/taxes/${value as TaxesTab}`, params: { storeId } })+ }+ >+ <TabsList>+ {tabs.map((tab) => (+ <TabsTrigger key={tab.value} value={tab.value}>+ {t(tab.labelKey)}+ </TabsTrigger>+ ))}+ </TabsList>+ </Tabs>+ )+}diff --git a/packages/dashboard/src/hooks/use-companies.ts b/packages/dashboard/src/hooks/use-companies.tsindex deda621af7..794b8c75af 100644--- a/packages/dashboard/src/hooks/use-companies.ts+++ b/packages/dashboard/src/hooks/use-companies.ts@@ -274,7 +274,10 @@ export function useValidateCompanyTaxIdentifier(companyId: string) {export function useTaxExemptionCertificates(companyId: string | undefined) {return useQuery({queryKey: useResourceKey('companies', companyId ?? 'noop', 'tax-exemption-certificates'),- queryFn: () => adminClient.companies.taxExemptionCertificates.list(companyId as string),+ queryFn: () =>+ adminClient.companies.taxExemptionCertificates.list(companyId as string, {+ expand: ['tax_exemption_reason'],+ }),enabled: !!companyId,})}diff --git a/packages/dashboard/src/hooks/use-markets.ts b/packages/dashboard/src/hooks/use-markets.tsindex 6ab616db81..60fa9e6f10 100644--- a/packages/dashboard/src/hooks/use-markets.ts+++ b/packages/dashboard/src/hooks/use-markets.ts@@ -29,11 +29,12 @@ export function useMarkets({ page = 1, limit = 100, expand }: UseMarketsParams =* (e.g. the Market price rule) that need to filter client-side without* round-tripping the API on each keystroke.*/-export function useAllMarkets() {+export function useAllMarkets({ enabled = true }: { enabled?: boolean } = {}) {const { data, isLoading } = useQuery({queryKey: useResourceKey('markets', 'all'),queryFn: () => adminClient.markets.list({ limit: 100, sort: 'position' }),staleTime: 1000 * 60 * 30,+ enabled,})return { markets: data?.data ?? [], isLoading }diff --git a/packages/dashboard/src/hooks/use-reasons.ts b/packages/dashboard/src/hooks/use-reasons.tsindex 3dc81d9ef1..26ad11be06 100644--- a/packages/dashboard/src/hooks/use-reasons.ts+++ b/packages/dashboard/src/hooks/use-reasons.ts@@ -5,13 +5,23 @@ import type {ReasonUpdateParams,RefundReason,ReturnReason,+ TaxExemptionReason,} from '@spree/admin-sdk'import { adminClient, useResourceKey, useResourceMutation } from '@spree/dashboard-core'import { useQuery } from '@tanstack/react-query'import i18n from 'i18next'+import { useMemo } from 'react'-/** Any of the reason lists — they share one shape. */-export type Reason = ReturnReason | ClaimReason | RefundReason | OrderCancellationReason+/** Any of the reason lists. Tax exemption reasons also carry the `code` a tax engine reads. */+export type Reason =+ | ReturnReason+ | ClaimReason+ | RefundReason+ | OrderCancellationReason+ | TaxExemptionReason++/** What a reason form sends; `code` applies to tax exemption reasons only. */+export type ReasonParams = ReasonCreateParams & ReasonUpdateParams & { code?: string }/** Which list a screen is working with. Doubles as the query key. */export type ReasonKind =@@ -19,12 +29,17 @@ export type ReasonKind =| 'claim-reasons'| 'refund-reasons'| 'order-cancellation-reasons'+ | 'tax-exemption-reasons'const CLIENTS = {'return-reasons': () => adminClient.returnReasons,'claim-reasons': () => adminClient.claimReasons,'refund-reasons': () => adminClient.refundReasons,'order-cancellation-reasons': () => adminClient.orderCancellationReasons,+ // Typed as the other lists: its create body is theirs plus `code`, which+ // `ReasonParams` carries.+ 'tax-exemption-reasons': () =>+ adminClient.taxExemptionReasons as unknown as typeof adminClient.returnReasons,} as const/**@@ -43,7 +58,7 @@ export function useReasons(kind: ReasonKind) {}export function useCreateReason(kind: ReasonKind) {- return useResourceMutation<Reason, Error, ReasonCreateParams>({+ return useResourceMutation<Reason, Error, ReasonParams>({mutationFn: (params) => CLIENTS[kind]().create(params),invalidate: [[kind]],successMessage: i18n.t('admin.reasons.messages.created'),@@ -52,7 +67,7 @@ export function useCreateReason(kind: ReasonKind) {}export function useUpdateReason(kind: ReasonKind, id: string) {- return useResourceMutation<Reason, Error, ReasonUpdateParams>({+ return useResourceMutation<Reason, Error, ReasonParams>({mutationFn: (params) => CLIENTS[kind]().update(id, params),invalidate: [[kind]],successMessage: i18n.t('admin.reasons.messages.updated'),@@ -68,3 +83,10 @@ export function useDeleteReason(kind: ReasonKind) {errorMessage: i18n.t('admin.errors.failed_to_delete'),})}++/** The store's tax exemption reasons, typed with the `code` the other lists lack. */+export function useTaxExemptionReasons() {+ const { data } = useReasons('tax-exemption-reasons')+ // The list endpoint is the tax exemption one, whatever the shared client type says.+ return useMemo(() => (data?.data ?? []) as TaxExemptionReason[], [data])+}diff --git a/packages/dashboard/src/hooks/use-tax-categories.ts b/packages/dashboard/src/hooks/use-tax-categories.tsindex 1ee849423e..cd1351fac2 100644--- a/packages/dashboard/src/hooks/use-tax-categories.ts+++ b/packages/dashboard/src/hooks/use-tax-categories.ts@@ -20,7 +20,7 @@ interface UseTaxCategoriesParams {export function useTaxCategories({ page = 1, limit = 100 }: UseTaxCategoriesParams = {}) {return useQuery({queryKey: useResourceKey('tax-categories', { page, limit }),- queryFn: () => adminClient.taxCategories.list({ page, limit }),+ queryFn: () => adminClient.taxCategories.list({ page, limit, sort: 'name' }),staleTime: 1000 * 60 * 5,})}diff --git a/packages/dashboard/src/hooks/use-tax-rates.ts b/packages/dashboard/src/hooks/use-tax-rates.tsindex fb221cd0ce..070aa2fe0d 100644--- a/packages/dashboard/src/hooks/use-tax-rates.ts+++ b/packages/dashboard/src/hooks/use-tax-rates.ts@@ -8,6 +8,14 @@ import {import { useQuery, useQueryClient } from '@tanstack/react-query'import i18n from 'i18next'+export function useTaxRates({ page = 1, limit = 100 }: { page?: number; limit?: number } = {}) {+ return useQuery({+ queryKey: useResourceKey('tax-rates', { page, limit }),+ queryFn: () => adminClient.taxRates.list({ page, limit, sort: 'name' }),+ staleTime: 1000 * 60 * 5,+ })+}+export function useTaxRate(id: string | undefined) {return useQuery({queryKey: useResourceKey('tax-rates', id ?? 'noop'),diff --git a/packages/dashboard/src/lib/tax-line-groups.ts b/packages/dashboard/src/lib/tax-line-groups.tsindex e30b1eaded..47c5af3109 100644--- a/packages/dashboard/src/lib/tax-line-groups.ts+++ b/packages/dashboard/src/lib/tax-line-groups.ts@@ -20,6 +20,7 @@ export interface GroupableTaxLine {/** The exemption snapshot a tax provider stamps onto a line. */export interface TaxLineExemption {reason_code?: string+ reason_name?: stringcertificate_number?: string}@@ -46,11 +47,16 @@ export function taxLineExemption(row: GroupableTaxLine): TaxLineExemption | nullconst record = raw as Record<string, unknown>const reasonCode = typeof record.reason_code === 'string' ? record.reason_code : undefined+ const reasonName = typeof record.reason_name === 'string' ? record.reason_name : undefinedconst certificateNumber =typeof record.certificate_number === 'string' ? record.certificate_number : undefinedif (!reasonCode && !certificateNumber) return null- return { reason_code: reasonCode, certificate_number: certificateNumber }+ return {+ reason_code: reasonCode,+ ...(reasonName ? { reason_name: reasonName } : {}),+ certificate_number: certificateNumber,+ }}/**diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 9671f656ff..ffbdebcafb 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -1811,10 +1811,6 @@"placeholder": "غير محدود"}},- "reason_code": {- "help": "يُمرَّر إلى محرك حساب الضريبة كرمز للاستخدام.",- "label": "السبب"- },"role": {"description": {"label": "الوصف",@@ -2417,6 +2413,10 @@"help": "العلبة التي تُحسب على أساسها أسعار شحن طرودك. علبة افتراضية واحدة في كل مرة."}},+ "tax_exemption_reason_id": {+ "help": "أدر الأسباب المعروضة هنا من الإعدادات ← الضرائب ← أسباب الإعفاء.",+ "label": "السبب"+ },"oauth_application": {"name": {"label": "الاسم",@@ -4876,12 +4876,15 @@"help": "ما حدث من خطأ في التسليم — تالف أو مفقود أو منتج خاطئ.","title": "أسباب المطالبة"},+ "code_engine_help": "يقرر محرك الضرائب الإعفاء وفق هذا الرمز، لذا اختر الرمز الذي يحدده لهذا السبب.",+ "code_help": "معرّف قصير تسجله الشهادات. فريد في متجرك.",+ "code_placeholder": "مثل RESALE","create_description": "تظهر الأسباب في قائمة منسدلة عند إنشاء مرتجع أو مطالبة أو مبلغ مسترد.","delete_confirm": {"message": "لن يعود {{name}} متاحًا. تحتفظ به السجلات التي تستخدمه بالفعل.","title": "حذف السبب؟"},- "description": "قوائم الأسباب التي يختار منها فريقك عند التعامل مع المرتجعات والمطالبات والمبالغ المستردة والإلغاءات.",+ "description": "القوائم التي يختار منها فريقك عند معالجة المرتجعات والمطالبات والمبالغ المستردة والإلغاءات.","edit_sheet_title": "تعديل السبب","empty": "لا توجد أسباب بعد","in_use": "قيد الاستخدام",@@ -4905,6 +4908,12 @@"help": "سبب إعادة العميل للمنتج. مشترك بين المرتجعات والاستبدال.","title": "أسباب الإرجاع"},+ "tax_exemption": {+ "create_description": "يختار فريقك سببًا عند تسجيل شهادة الإعفاء الضريبي لشركة.",+ "help": "سبب شراء الشركة دون ضريبة. يُسجَّل في شهادات الإعفاء الخاصة بها، ويُرسَل الرمز إلى محرك الضرائب لديك.",+ "name_placeholder": "مثل إعادة البيع",+ "title": "أسباب الإعفاء الضريبي"+ },"title": "المرتجعات والأسباب"},"roles": {@@ -5230,12 +5239,11 @@"staff": "الأشخاص الذين يمكنهم الوصول إلى لوحة التحكم","stock_locations": "المستودعات ونقاط الاستلام التي تحتفظ بالمخزون","store": "اسم المتجر والمنطقة الزمنية والوحدات والإعدادات الإقليمية",- "tax_categories": "فئات الضريبة المخصصة للمنتجات",- "tax_rates": "النسب المطبقة حسب السوق والمنطقة","webhooks": "نقاط النهاية التي تُخطر عند وقوع الأحداث","package_types": "صناديق وكراتين ومنصات وحاويات","suppliers": "من تشتري منه المخزون، وكيفية التواصل معه","marketplace": "مدفوعات البائعين، والموافقة على البائعين، ورسائل البائعين، والضريبة على العمولة",+ "taxes": "فئات الضرائب والمعدلات وأسباب الإعفاء","ai_agents": "وكلاء الذكاء الاصطناعي الذين لديهم حق الوصول إلى هذا المتجر","oauth_clients": "تسجيل عملاء OAuth وتهيئتهم"},@@ -5276,6 +5284,7 @@"package_types": "أنواع التغليف","suppliers": "الموردون","marketplace": "الإعدادات",+ "taxes": "الضرائب","ai_agents": "وكلاء الذكاء الاصطناعي","oauth_clients": "عملاء OAuth"},@@ -5626,7 +5635,6 @@"sellers": "البائعون الخارجيون الذين يتاجرون في سوقك، وحالة كل منهم.","store_credits": "أرصدة يمكن للعملاء إنفاقها عند الدفع، وكيف تم إصدار كل منها.","tax_categories": "تجميعات تحدد معدل الضريبة الذي ينطبق على المنتج.",- "tax_rates": "الضريبة المفروضة حسب الفئة والمنطقة.","webhook_deliveries": "كل حدث أُرسل إلى نقطة النهاية هذه، وما إذا تم استلامه.","webhook_endpoints": "أين يتم إخطار أنظمتك الأخرى عندما يحدث شيء في المتجر.","returns": "البضائع العائدة، من الطلب حتى استرداد المبلغ.",@@ -5647,8 +5655,7 @@"created": "تم إنشاء فئة الضريبة","deleted": "تم حذف فئة الضريبة","updated": "تم تحديث فئة الضريبة"- },- "search_placeholder": "البحث بالاسم…"+ }},"tax_exemption_certificates": {"add_cta": "إضافة شهادة",@@ -5671,14 +5678,7 @@},"never_expires": "بلا تاريخ انتهاء","no_document": "لا يوجد مستند مرفق",- "reason_codes": {- "agricultural": "الزراعة",- "charitable": "جهة خيرية",- "educational": "جهة تعليمية",- "government": "جهة حكومية",- "manufacturing": "التصنيع",- "resale": "إعادة البيع"- },+ "no_reasons": "لا توجد أسباب إعفاء بعد. أضفها من الإعدادات ← الأسباب.","revoke_action": "إلغاء","revoke_confirm": {"message": "لن تعود الشهادة {{number}} تسري على الطلبات الجديدة، لكنها تبقى محفوظة كسجل.",@@ -5757,7 +5757,6 @@"deleted": "تم حذف النسبة","updated": "تم تحديث النسبة"},- "search_placeholder": "البحث في نسب الضريبة","select_category": "اختر فئة"},"translations": {@@ -6413,6 +6412,21 @@"view_on_github": "عرض على GitHub","release_notes_unavailable": "تعذر تحميل ملاحظات الإصدار. اقرأها على GitHub بدلاً من ذلك."},+ "taxes": {+ "title": "الضرائب",+ "description": "كيف تُفرض الضريبة على منتجاتك، والمعدلات التي يطبقها Spree، ولماذا يمكن للشركات الشراء دون ضريبة.",+ "providers_title": "حساب الضريبة",+ "provider_markets": "{{provider}} في {{markets}}",+ "manage_markets": "إدارة الأسواق",+ "tabs": {+ "categories": "الفئات",+ "rates": "المعدلات",+ "exemption_reasons": "أسباب الإعفاء"+ },+ "rates_unused_in": "لا تُستخدم هذه المعدلات في {{markets}}، حيث تحسب خدمة خارجية الضريبة.",+ "rates_unused_everywhere": "لا يستخدم أي من أسواقك هذه المعدلات: في {{markets}} تحسب خدمة خارجية الضريبة.",+ "rates_help": "الضريبة المفروضة حسب الفئة والمنطقة. تُستخدم فقط في الأسواق التي تعتمد معدلات Spree الضريبية: خدمة متصلة مثل Avalara تحسب الضريبة بنفسها وتتجاهل هذه المعدلات."+ },"mcp_connect": {"open_cta": "ربط وكيل","title": "ربط وكيل",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex b932f0879c..0d58aa37da 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -1793,10 +1793,6 @@"placeholder": "Unbegrenzt"}},- "reason_code": {- "help": "Wird als Verwendungszweck an die Steuerberechnung übergeben.",- "label": "Grund"- },"role": {"description": {"label": "Beschreibung",@@ -2399,6 +2395,10 @@"help": "Die Verpackung, auf der Ihre Paketangebote basieren. Nur eine Standardverpackung gleichzeitig."}},+ "tax_exemption_reason_id": {+ "help": "Die hier angebotenen Gründe verwalten Sie unter Einstellungen → Steuern → Befreiungsgründe.",+ "label": "Grund"+ },"oauth_application": {"name": {"label": "Name",@@ -4843,6 +4843,9 @@"help": "Was bei der Lieferung schiefging – beschädigt, fehlend oder falscher Artikel.","title": "Reklamationsgründe"},+ "code_engine_help": "Ihre Steuerberechnung entscheidet anhand dieses Codes über die Befreiung. Wählen Sie den Code, den sie für diesen Grund vorsieht.",+ "code_help": "Eine kurze Kennung, die Nachweise speichern. In Ihrem Shop eindeutig.",+ "code_placeholder": "z. B. RESALE","create_description": "Gründe erscheinen als Auswahl, wenn Mitarbeitende eine Rücksendung, Reklamation oder Rückerstattung anlegen.","delete_confirm": {"message": "{{name}} wird nicht mehr angeboten. Bestehende Vorgänge behalten ihn.",@@ -4872,6 +4875,12 @@"help": "Warum ein Kunde etwas zurückschickt. Gilt für Rücksendungen und Umtausch.","title": "Rücksendegründe"},+ "tax_exemption": {+ "create_description": "Ihr Team wählt einen Grund, wenn es den Befreiungsnachweis eines Unternehmens erfasst.",+ "help": "Warum ein Unternehmen steuerfrei einkauft. Wird auf seinen Befreiungsnachweisen festgehalten; der Code geht an Ihre Steuerberechnung.",+ "name_placeholder": "z. B. Wiederverkauf",+ "title": "Gründe für Steuerbefreiungen"+ },"title": "Rücksendungen & Gründe"},"roles": {@@ -5197,12 +5206,11 @@"staff": "Personen mit Zugriff auf dieses Dashboard","stock_locations": "Lager und Abholpunkte mit Beständen","store": "Shopname, Zeitzone, Einheiten und regionale Standards",- "tax_categories": "Steuerklassen für Produkte",- "tax_rates": "Sätze pro Markt und Region","webhooks": "Endpunkte, die bei Ereignissen benachrichtigt werden","package_types": "Kartons, Paletten und Container","suppliers": "Von wem Sie Ware einkaufen und wie Sie sie erreichen","marketplace": "Auszahlungen, Verkäuferfreigabe, Verkäufer-E-Mails und Steuer auf Provision",+ "taxes": "Steuerkategorien, Steuersätze und Befreiungsgründe","ai_agents": "KI-Agenten mit Zugriff auf diesen Shop","oauth_clients": "OAuth-Clients registrieren und konfigurieren"},@@ -5243,6 +5251,7 @@"package_types": "Verpackungsarten","suppliers": "Lieferanten","marketplace": "Einstellungen",+ "taxes": "Steuern","ai_agents": "KI-Agenten","oauth_clients": "OAuth-Clients"},@@ -5589,7 +5598,6 @@"sellers": "Die Drittanbieter auf Ihrem Marktplatz und der Stand jedes einzelnen.","store_credits": "Guthaben, das Kunden an der Kasse ausgeben können, und wie es ausgestellt wurde.","tax_categories": "Gruppen, die entscheiden, welcher Steuersatz für ein Produkt gilt.",- "tax_rates": "Die je Kategorie und Region berechnete Steuer.","webhook_deliveries": "Jedes an diesen Endpunkt gesendete Ereignis und ob es empfangen wurde.","webhook_endpoints": "Wohin Ihre anderen Systeme benachrichtigt werden, wenn im Shop etwas passiert.","returns": "Zurückkommende Ware, von der Anfrage bis zur Erstattung.",@@ -5610,8 +5618,7 @@"created": "Steuerkategorie erstellt","deleted": "Steuerkategorie gelöscht","updated": "Steuerkategorie aktualisiert"- },- "search_placeholder": "Nach Name suchen…"+ }},"tax_exemption_certificates": {"add_cta": "Bescheinigung hinzufügen",@@ -5634,14 +5641,7 @@},"never_expires": "Läuft nicht ab","no_document": "Kein Dokument hinterlegt",- "reason_codes": {- "agricultural": "Landwirtschaft",- "charitable": "Gemeinnützig",- "educational": "Bildung",- "government": "Behörde",- "manufacturing": "Produktion",- "resale": "Wiederverkauf"- },+ "no_reasons": "Noch keine Befreiungsgründe. Fügen Sie sie unter Einstellungen → Gründe hinzu.","revoke_action": "Widerrufen","revoke_confirm": {"message": "Bescheinigung {{number}} gilt dann nicht mehr für neue Bestellungen. Sie bleibt als Nachweis erhalten.",@@ -5720,7 +5720,6 @@"deleted": "Steuersatz gelöscht","updated": "Steuersatz aktualisiert"},- "search_placeholder": "Steuersätze suchen","select_category": "Kategorie wählen"},"translations": {@@ -6373,6 +6372,21 @@"view_on_github": "Auf GitHub ansehen","release_notes_unavailable": "Die Versionshinweise konnten nicht geladen werden. Lesen Sie sie stattdessen auf GitHub."},+ "taxes": {+ "title": "Steuern",+ "description": "Wie Ihre Produkte besteuert werden, welche Sätze Spree berechnet und warum Unternehmen steuerfrei einkaufen dürfen.",+ "providers_title": "Steuerberechnung",+ "provider_markets": "{{provider}} in {{markets}}",+ "manage_markets": "Märkte verwalten",+ "tabs": {+ "categories": "Kategorien",+ "rates": "Steuersätze",+ "exemption_reasons": "Befreiungsgründe"+ },+ "rates_unused_in": "Diese Steuersätze gelten nicht in {{markets}}, wo ein externer Dienst die Steuer berechnet.",+ "rates_unused_everywhere": "Keiner Ihrer Märkte verwendet diese Steuersätze: In {{markets}} berechnet ein externer Dienst die Steuer.",+ "rates_help": "Die je Kategorie und Region berechnete Steuer. Gilt nur für Märkte mit Spree-Steuersätzen: Ein angebundener Dienst wie Avalara berechnet die Steuer selbst und ignoriert diese Sätze."+ },"mcp_connect": {"open_cta": "Agent verbinden","title": "Agent verbinden",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex e4b04b8d32..bba0c6f18b 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -1793,10 +1793,6 @@"placeholder": "Unlimited"}},- "reason_code": {- "help": "Becomes the tax engine's entity use code.",- "label": "Reason"- },"role": {"description": {"label": "Description",@@ -2399,6 +2395,10 @@"help": "The packaging your parcel quotes are built on. One default at a time."}},+ "tax_exemption_reason_id": {+ "help": "Manage the reasons offered here in Settings → Taxes → Exemption reasons.",+ "label": "Reason"+ },"oauth_application": {"name": {"label": "Name",@@ -4843,6 +4843,9 @@"help": "What went wrong with a delivery — damaged, missing or wrong item.","title": "Claim reasons"},+ "code_engine_help": "Your tax engine decides the exemption by this code, so pick the one it defines for this reason.",+ "code_help": "A short identifier certificates record. Unique in your store.",+ "code_placeholder": "e.g. RESALE","create_description": "Reasons appear in a dropdown when staff open a return, claim or refund.","delete_confirm": {"message": "{{name}} will no longer be offered. Records already using it keep it.",@@ -4872,6 +4875,12 @@"help": "Why a customer is sending something back. Shared by returns and exchanges.","title": "Return reasons"},+ "tax_exemption": {+ "create_description": "Staff pick a reason when recording a company's tax exemption certificate.",+ "help": "Why a business buys without tax. Recorded on its exemption certificates; the code is what your tax engine receives.",+ "name_placeholder": "e.g. Resale",+ "title": "Tax exemption reasons"+ },"title": "Returns & reasons"},"roles": {@@ -5197,12 +5206,11 @@"staff": "People with access to this dashboard","stock_locations": "Warehouses and pickup points that hold stock","store": "Store name, timezone, units and regional defaults",- "tax_categories": "Tax classes assigned to products",- "tax_rates": "Rates applied per market and region","webhooks": "Endpoints notified when events happen","package_types": "Boxes, cartons, pallets and containers","suppliers": "Who you buy stock from, and how to reach them","marketplace": "Seller payouts, seller approval, seller emails and commission tax",+ "taxes": "Tax categories, rates and exemption reasons","ai_agents": "AI agents with access to this store","oauth_clients": "Register and configure OAuth clients"},@@ -5243,6 +5251,7 @@"package_types": "Package types","suppliers": "Suppliers","marketplace": "Settings",+ "taxes": "Taxes","ai_agents": "AI Agents","oauth_clients": "OAuth clients"},@@ -5589,7 +5598,6 @@"sellers": "The third-party sellers trading on your marketplace, and where each one stands.","store_credits": "Balances customers can spend at checkout, and how each was issued.","tax_categories": "Groupings that decide which tax rate a product gets.",- "tax_rates": "The tax charged per category and region.","webhook_deliveries": "Each event sent to this endpoint, and whether it was received.","webhook_endpoints": "Where your other systems are notified when something happens in the store.","returns": "Goods coming back, from request to refund.",@@ -5610,8 +5618,7 @@"created": "Tax category created","deleted": "Tax category deleted","updated": "Tax category updated"- },- "search_placeholder": "Search by name…"+ }},"tax_exemption_certificates": {"add_cta": "Add certificate",@@ -5634,14 +5641,7 @@},"never_expires": "Does not expire","no_document": "No document attached",- "reason_codes": {- "agricultural": "Agricultural",- "charitable": "Charitable",- "educational": "Educational",- "government": "Government",- "manufacturing": "Manufacturing",- "resale": "Resale"- },+ "no_reasons": "No exemption reasons yet. Add them in Settings → Reasons.","revoke_action": "Revoke","revoke_confirm": {"message": "Certificate {{number}} stops applying to new orders. It stays on file as a record.",@@ -5720,7 +5720,6 @@"deleted": "Tax rate deleted","updated": "Tax rate updated"},- "search_placeholder": "Search tax rates","select_category": "Select a category"},"translations": {@@ -6373,6 +6372,21 @@"view_on_github": "View on GitHub","release_notes_unavailable": "The release notes could not be loaded. Read them on GitHub instead."},+ "taxes": {+ "title": "Taxes",+ "description": "How your products are taxed, the rates Spree charges, and why businesses may buy without tax.",+ "providers_title": "Tax calculation",+ "provider_markets": "{{provider}} in {{markets}}",+ "manage_markets": "Manage markets",+ "tabs": {+ "categories": "Categories",+ "rates": "Rates",+ "exemption_reasons": "Exemption reasons"+ },+ "rates_unused_in": "These rates are not used in {{markets}}, which work out tax with an external service.",+ "rates_unused_everywhere": "None of your markets use these rates: {{markets}} work out tax with an external service.",+ "rates_help": "The tax charged per category and region. Used only by markets on Spree tax rates: a connected service such as Avalara works out tax itself and ignores these rates."+ },"mcp_connect": {"open_cta": "Connect an agent","title": "Connect an agent",diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex c87ab58a8c..a4c6be4f42 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -1889,10 +1889,6 @@"placeholder": "Ilimitado"}},- "reason_code": {- "help": "Se vuelve el código de uso de entidad del motor de impuestos.",- "label": "Motivo"- },"role": {"description": {"label": "Descripción",@@ -2495,6 +2491,10 @@"help": "El empaque sobre el que se calculan tus cotizaciones de paquetería. Solo una predeterminada a la vez."}},+ "tax_exemption_reason_id": {+ "help": "Gestiona los motivos que se ofrecen aquí en Configuración → Impuestos → Motivos de exención.",+ "label": "Motivo"+ },"oauth_application": {"name": {"label": "Nombre",@@ -4268,12 +4268,11 @@"staff": "Personas con acceso a este dashboard","stock_locations": "Depósitos y puntos de retiro que guardan stock","store": "Nombre de la tienda, zona horaria, unidades y predeterminados regionales",- "tax_categories": "Clases de impuestos asignadas a los productos",- "tax_rates": "Tasas aplicadas por mercado y región","webhooks": "Endpoints notificados cuando ocurren eventos","package_types": "Cajas, cajones, palets y contenedores","suppliers": "A quién le comprás stock y cómo contactarlos","marketplace": "Pagos a vendedores, aprobación de vendedores, correos a vendedores e impuesto sobre la comisión",+ "taxes": "Categorías fiscales, tipos impositivos y motivos de exención","ai_agents": "Agentes de IA con acceso a esta tienda","oauth_clients": "Registrar y configurar clientes OAuth"},@@ -4314,6 +4313,7 @@"package_types": "Tipos de empaque","suppliers": "Proveedores","marketplace": "Configuración",+ "taxes": "Impuestos","ai_agents": "Agentes de IA","oauth_clients": "Clientes OAuth"},@@ -5050,14 +5050,7 @@},"never_expires": "No vence","no_document": "Sin documento adjunto",- "reason_codes": {- "agricultural": "Agrícola",- "charitable": "Benéfico",- "educational": "Educativo",- "government": "Gubernamental",- "manufacturing": "Manufactura",- "resale": "Reventa"- },+ "no_reasons": "Aún no hay motivos de exención. Añádelos en Configuración → Motivos.","revoke_action": "Revocar","revoke_confirm": {"message": "El certificado {{number}} deja de aplicar a pedidos nuevos. Queda archivado como registro.",@@ -5389,12 +5382,15 @@"help": "Qué salió mal con una entrega: artículo dañado, faltante o equivocado.","title": "Motivos de reclamo"},+ "code_engine_help": "Tu motor de impuestos decide la exención por este código, así que elige el que define para este motivo.",+ "code_help": "Un identificador corto que registran los certificados. Único en tu tienda.",+ "code_placeholder": "p. ej. RESALE","create_description": "Los motivos aparecen en un desplegable cuando el staff abre una devolución, un reclamo o un reembolso.","delete_confirm": {"message": "{{name}} ya no se ofrecerá. Los registros que ya lo usan lo conservan.","title": "¿Eliminar motivo?"},- "description": "Los vocabularios de los que elige tu equipo al manejar devoluciones, reclamos, reembolsos y cancelaciones.",+ "description": "Las listas que usa tu equipo al gestionar devoluciones, reclamaciones, reembolsos y cancelaciones.","edit_sheet_title": "Editar motivo","empty": "Todavía no hay motivos","in_use": "En uso",@@ -5418,6 +5414,12 @@"help": "Por qué un cliente devuelve algo. Lo comparten devoluciones y cambios.","title": "Motivos de devolución"},+ "tax_exemption": {+ "create_description": "Tu equipo elige un motivo al registrar el certificado de exención de una empresa.",+ "help": "Por qué una empresa compra sin impuestos. Se registra en sus certificados de exención; el código es lo que recibe tu motor de impuestos.",+ "name_placeholder": "p. ej. Reventa",+ "title": "Motivos de exención de impuestos"+ },"title": "Devoluciones y motivos"},"roles": {@@ -5628,7 +5630,6 @@"sellers": "Los vendedores terceros que operan en tu marketplace y en qué punto está cada uno.","store_credits": "Saldos que los clientes pueden gastar al finalizar la compra y cómo se emitió cada uno.","tax_categories": "Agrupaciones que deciden qué tasa impositiva recibe un producto.",- "tax_rates": "El impuesto cobrado por categoría y región.","webhook_deliveries": "Cada evento enviado a este endpoint y si se recibió.","webhook_endpoints": "Dónde se notifica a tus otros sistemas cuando pasa algo en la tienda.","returns": "Mercadería que vuelve, desde la solicitud hasta el reembolso.",@@ -5904,7 +5905,6 @@"deleted": "Tasa de impuesto eliminada","updated": "Tasa de impuesto actualizada"},- "search_placeholder": "Buscar tasas de impuesto","select_category": "Seleccionar una categoría"},"translations": {@@ -6092,8 +6092,7 @@"created": "Categoría de impuestos creada","deleted": "Categoría de impuestos eliminada","updated": "Categoría de impuestos actualizada"- },- "search_placeholder": "Buscar por nombre…"+ }},"inventory_lines": {"add_label": "Agregar un producto",@@ -6373,6 +6372,21 @@"view_on_github": "Ver en GitHub","release_notes_unavailable": "No se pudieron cargar las notas de la versión. Léelas en GitHub."},+ "taxes": {+ "title": "Impuestos",+ "description": "Cómo se gravan tus productos, qué tipos aplica Spree y por qué las empresas pueden comprar sin impuestos.",+ "providers_title": "Cálculo de impuestos",+ "provider_markets": "{{provider}} en {{markets}}",+ "manage_markets": "Gestionar mercados",+ "tabs": {+ "categories": "Categorías",+ "rates": "Tipos",+ "exemption_reasons": "Motivos de exención"+ },+ "rates_unused_in": "Estos tipos no se usan en {{markets}}, donde un servicio externo calcula el impuesto.",+ "rates_unused_everywhere": "Ninguno de tus mercados usa estos tipos: en {{markets}} un servicio externo calcula el impuesto.",+ "rates_help": "El impuesto cobrado por categoría y región. Solo lo usan los mercados con los tipos de Spree: un servicio conectado como Avalara calcula el impuesto por su cuenta e ignora estos tipos."+ },"mcp_connect": {"open_cta": "Conectar un agente","title": "Conectar un agente",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex cabe4bbfa6..c9f1a290e2 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -1793,10 +1793,6 @@"placeholder": "Illimité"}},- "reason_code": {- "help": "Transmis au moteur de calcul comme code d'usage.",- "label": "Motif"- },"role": {"description": {"label": "Description",@@ -2399,6 +2395,10 @@"help": "L'emballage sur lequel vos tarifs de colis sont calculés. Un seul par défaut à la fois."}},+ "tax_exemption_reason_id": {+ "help": "Gérez les motifs proposés ici dans Paramètres → Taxes → Motifs d’exonération.",+ "label": "Motif"+ },"oauth_application": {"name": {"label": "Nom",@@ -4843,12 +4843,15 @@"help": "Ce qui s'est mal passé à la livraison — endommagé, manquant ou article incorrect.","title": "Motifs de réclamation"},+ "code_engine_help": "Votre moteur fiscal décide de l'exonération selon ce code : choisissez celui qu'il définit pour ce motif.",+ "code_help": "Un identifiant court enregistré sur les certificats. Unique dans votre boutique.",+ "code_placeholder": "ex. RESALE","create_description": "Les motifs apparaissent dans une liste déroulante lors de la création d'un retour, d'une réclamation ou d'un remboursement.","delete_confirm": {"message": "{{name}} ne sera plus proposé. Les enregistrements existants le conservent.","title": "Supprimer le motif ?"},- "description": "Les listes de motifs utilisées par votre équipe pour les retours, réclamations, remboursements et annulations.",+ "description": "Les listes dans lesquelles votre équipe choisit pour les retours, réclamations, remboursements et annulations.","edit_sheet_title": "Modifier le motif","empty": "Aucun motif pour l'instant","in_use": "Utilisé",@@ -4872,6 +4875,12 @@"help": "Pourquoi un client renvoie un article. Partagé par les retours et les échanges.","title": "Motifs de retour"},+ "tax_exemption": {+ "create_description": "Votre équipe choisit un motif lorsqu'elle enregistre le certificat d'exonération d'une entreprise.",+ "help": "Pourquoi une entreprise achète hors taxe. Enregistré sur ses certificats d'exonération ; le code est transmis à votre moteur fiscal.",+ "name_placeholder": "ex. Revente",+ "title": "Motifs d'exonération de taxe"+ },"title": "Retours et motifs"},"roles": {@@ -5197,12 +5206,11 @@"staff": "Personnes ayant accès à ce tableau de bord","stock_locations": "Entrepôts et points de retrait qui détiennent du stock","store": "Nom de la boutique, fuseau horaire, unités et valeurs régionales",- "tax_categories": "Classes de taxe attribuées aux produits",- "tax_rates": "Taux appliqués par marché et région","webhooks": "Points de terminaison notifiés lors d'événements","package_types": "Cartons, palettes et conteneurs","suppliers": "À qui vous achetez votre stock, et comment les joindre","marketplace": "Paiements, validation des vendeurs, e-mails vendeurs et taxe sur la commission",+ "taxes": "Catégories de taxe, taux et motifs d’exonération","ai_agents": "Agents IA ayant accès à cette boutique","oauth_clients": "Enregistrer et configurer des clients OAuth"},@@ -5243,6 +5251,7 @@"package_types": "Types d'emballage","suppliers": "Fournisseurs","marketplace": "Paramètres",+ "taxes": "Taxes","ai_agents": "Agents IA","oauth_clients": "Clients OAuth"},@@ -5589,7 +5598,6 @@"sellers": "Les vendeurs tiers actifs sur votre place de marché, et où en est chacun.","store_credits": "Avoirs que les clients peuvent dépenser au paiement, et comment chacun a été émis.","tax_categories": "Regroupements qui décident du taux de taxe appliqué à un produit.",- "tax_rates": "La taxe facturée par catégorie et par région.","webhook_deliveries": "Chaque événement envoyé à ce point de terminaison, et s'il a été reçu.","webhook_endpoints": "Où vos autres systèmes sont notifiés quand quelque chose se produit dans la boutique.","returns": "Marchandises qui reviennent, de la demande au remboursement.",@@ -5610,8 +5618,7 @@"created": "Catégorie de taxe créée","deleted": "Catégorie de taxe supprimée","updated": "Catégorie de taxe mise à jour"- },- "search_placeholder": "Rechercher par nom…"+ }},"tax_exemption_certificates": {"add_cta": "Ajouter une attestation",@@ -5634,14 +5641,7 @@},"never_expires": "Sans expiration","no_document": "Aucun document joint",- "reason_codes": {- "agricultural": "Agriculture",- "charitable": "Organisme caritatif",- "educational": "Enseignement",- "government": "Administration",- "manufacturing": "Production",- "resale": "Revente"- },+ "no_reasons": "Aucun motif d'exonération. Ajoutez-en dans Paramètres → Motifs.","revoke_action": "Révoquer","revoke_confirm": {"message": "L'attestation {{number}} ne s'appliquera plus aux nouvelles commandes. Elle reste conservée comme justificatif.",@@ -5720,7 +5720,6 @@"deleted": "Taux supprimé","updated": "Taux mis à jour"},- "search_placeholder": "Rechercher des taux","select_category": "Choisir une catégorie"},"translations": {@@ -6373,6 +6372,21 @@"view_on_github": "Voir sur GitHub","release_notes_unavailable": "Impossible de charger les notes de version. Consultez-les sur GitHub."},+ "taxes": {+ "title": "Taxes",+ "description": "Comment vos produits sont taxés, les taux appliqués par Spree et pourquoi des entreprises peuvent acheter hors taxes.",+ "providers_title": "Calcul des taxes",+ "provider_markets": "{{provider}} pour {{markets}}",+ "manage_markets": "Gérer les marchés",+ "tabs": {+ "categories": "Catégories",+ "rates": "Taux",+ "exemption_reasons": "Motifs d’exonération"+ },+ "rates_unused_in": "Ces taux ne sont pas utilisés dans {{markets}}, où un service externe calcule la taxe.",+ "rates_unused_everywhere": "Aucun de vos marchés n’utilise ces taux : dans {{markets}}, un service externe calcule la taxe.",+ "rates_help": "La taxe facturée par catégorie et par région. Utilisés uniquement par les marchés sur les taux Spree : un service connecté comme Avalara calcule la taxe lui-même et ignore ces taux."+ },"mcp_connect": {"open_cta": "Connecter un agent","title": "Connecter un agent",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex b1c825b20d..b37772dcaf 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -1811,10 +1811,6 @@"placeholder": "Bez ograniczeń"}},- "reason_code": {- "help": "Przekazywany do naliczania podatku jako kod przeznaczenia.",- "label": "Powód"- },"role": {"description": {"label": "Opis",@@ -2417,6 +2413,10 @@"help": "Opakowanie, na którym opierają się wyceny Twoich przesyłek. Tylko jedno domyślne naraz."}},+ "tax_exemption_reason_id": {+ "help": "Powody dostępne tutaj ustawisz w Ustawienia → Podatki → Powody zwolnień.",+ "label": "Powód"+ },"oauth_application": {"name": {"label": "Nazwa",@@ -4907,6 +4907,9 @@"help": "Co poszło nie tak z dostawą — uszkodzony, brakujący lub zły towar.","title": "Powody reklamacji"},+ "code_engine_help": "Silnik podatkowy rozstrzyga o zwolnieniu na podstawie tego kodu, więc wybierz kod, który definiuje dla tego powodu.",+ "code_help": "Krótki identyfikator zapisywany na zaświadczeniach. Unikalny w sklepie.",+ "code_placeholder": "np. RESALE","create_description": "Powody pojawiają się na liście przy tworzeniu zwrotu, reklamacji lub zwrotu pieniędzy.","delete_confirm": {"message": "{{name}} nie będzie już proponowany. Istniejące zgłoszenia go zachowują.",@@ -4936,6 +4939,12 @@"help": "Dlaczego klient odsyła towar. Wspólne dla zwrotów i wymian.","title": "Powody zwrotu"},+ "tax_exemption": {+ "create_description": "Zespół wybiera powód przy zapisywaniu zaświadczenia o zwolnieniu firmy.",+ "help": "Dlaczego firma kupuje bez podatku. Zapisywany na jej zaświadczeniach o zwolnieniu; kod trafia do silnika podatkowego.",+ "name_placeholder": "np. Odsprzedaż",+ "title": "Powody zwolnienia z podatku"+ },"title": "Zwroty i powody"},"roles": {@@ -5261,12 +5270,11 @@"staff": "Osoby z dostępem do tego panelu","stock_locations": "Magazyny i punkty odbioru przechowujące towar","store": "Nazwa sklepu, strefa czasowa, jednostki i ustawienia regionalne",- "tax_categories": "Klasy podatkowe przypisane do produktów",- "tax_rates": "Stawki stosowane według rynku i regionu","webhooks": "Adresy powiadamiane o zdarzeniach","package_types": "Kartony, palety i kontenery","suppliers": "Od kogo kupujesz towar i jak się z nimi skontaktować","marketplace": "Wypłaty, zatwierdzanie sprzedawców, e-maile do sprzedawców i podatek od prowizji",+ "taxes": "Kategorie podatkowe, stawki i powody zwolnień","ai_agents": "Agenty AI z dostępem do tego sklepu","oauth_clients": "Rejestrowanie i konfiguracja klientów OAuth"},@@ -5307,6 +5315,7 @@"package_types": "Rodzaje opakowań","suppliers": "Dostawcy","marketplace": "Ustawienia",+ "taxes": "Podatki","ai_agents": "Agenci AI","oauth_clients": "Klienci OAuth"},@@ -5655,7 +5664,6 @@"sellers": "Sprzedawcy zewnętrzni działający na Twoim marketplace i status każdego z nich.","store_credits": "Środki, które klienci mogą wydać przy kasie, oraz sposób ich wystawienia.","tax_categories": "Grupy decydujące o tym, która stawka podatku dotyczy produktu.",- "tax_rates": "Podatek naliczany według kategorii i regionu.","webhook_deliveries": "Każde zdarzenie wysłane do tego punktu końcowego i informacja, czy zostało odebrane.","webhook_endpoints": "Gdzie Twoje inne systemy są powiadamiane, gdy coś dzieje się w sklepie.","returns": "Towary wracające do sklepu, od zgłoszenia do zwrotu pieniędzy.",@@ -5676,8 +5684,7 @@"created": "Kategoria podatkowa utworzona","deleted": "Kategoria podatkowa usunięta","updated": "Kategoria podatkowa zaktualizowana"- },- "search_placeholder": "Szukaj według nazwy…"+ }},"tax_exemption_certificates": {"add_cta": "Dodaj certyfikat",@@ -5700,14 +5707,7 @@},"never_expires": "Bez daty wygaśnięcia","no_document": "Brak załączonego dokumentu",- "reason_codes": {- "agricultural": "Rolnictwo",- "charitable": "Organizacja charytatywna",- "educational": "Edukacja",- "government": "Instytucja publiczna",- "manufacturing": "Produkcja",- "resale": "Odsprzedaż"- },+ "no_reasons": "Brak powodów zwolnienia. Dodaj je w Ustawienia → Powody.","revoke_action": "Unieważnij","revoke_confirm": {"message": "Certyfikat {{number}} przestanie obowiązywać dla nowych zamówień. Pozostanie zapisany jako dokumentacja.",@@ -5786,7 +5786,6 @@"deleted": "Stawka usunięta","updated": "Stawka zaktualizowana"},- "search_placeholder": "Szukaj stawek","select_category": "Wybierz kategorię"},"translations": {@@ -6441,6 +6440,21 @@"view_on_github": "Zobacz na GitHubie","release_notes_unavailable": "Nie udało się wczytać informacji o wydaniu. Przeczytaj je na GitHubie."},+ "taxes": {+ "title": "Podatki",+ "description": "Jak opodatkowane są Twoje produkty, jakie stawki nalicza Spree i dlaczego firmy mogą kupować bez podatku.",+ "providers_title": "Obliczanie podatku",+ "provider_markets": "{{provider}}: {{markets}}",+ "manage_markets": "Zarządzaj rynkami",+ "tabs": {+ "categories": "Kategorie",+ "rates": "Stawki",+ "exemption_reasons": "Powody zwolnień"+ },+ "rates_unused_in": "Te stawki nie są używane na rynkach: {{markets}}, gdzie podatek oblicza zewnętrzna usługa.",+ "rates_unused_everywhere": "Żaden z Twoich rynków nie używa tych stawek: na rynkach {{markets}} podatek oblicza zewnętrzna usługa.",+ "rates_help": "Podatek naliczany według kategorii i regionu. Używane tylko na rynkach korzystających ze stawek Spree: podłączona usługa, np. Avalara, sama oblicza podatek i pomija te stawki."+ },"mcp_connect": {"open_cta": "Połącz agenta","title": "Połącz agenta",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex fe89b4cce7..88ee47e1d7 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -1788,10 +1788,6 @@"placeholder": "不限"}},- "reason_code": {- "help": "作为用途代码传递给税费计算引擎。",- "label": "事由"- },"role": {"description": {"label": "描述",@@ -2394,6 +2390,10 @@"help": "您的包裹报价所依据的包装。同一时间只能有一个默认包装。"}},+ "tax_exemption_reason_id": {+ "help": "在 设置 → 税费 → 免税原因 中管理此处提供的原因。",+ "label": "事由"+ },"oauth_application": {"name": {"label": "名称",@@ -4832,12 +4832,15 @@"help": "配送出现的问题——商品损坏、缺失或发错。","title": "理赔原因"},+ "code_engine_help": "您的税务引擎根据此代码判断是否免税,请选择它为此原因定义的代码。",+ "code_help": "证书记录的简短标识符,在店铺内唯一。",+ "code_placeholder": "例如 RESALE","create_description": "员工创建退货、理赔或退款时,可从下拉列表中选择原因。","delete_confirm": {"message": "将不再提供 {{name}}。已使用它的记录保持不变。","title": "删除原因?"},- "description": "团队在处理退货、理赔、退款和取消时可选用的原因列表。",+ "description": "您的团队在处理退货、索赔、退款和取消时可选择的原因列表。","edit_sheet_title": "编辑原因","empty": "暂无原因","in_use": "使用中",@@ -4861,6 +4864,12 @@"help": "客户退回商品的原因。退货和换货共用。","title": "退货原因"},+ "tax_exemption": {+ "create_description": "员工在记录企业的免税证书时选择一个原因。",+ "help": "企业免税采购的原因。记录在其免税证书上;代码会发送给您的税务引擎。",+ "name_placeholder": "例如 转售",+ "title": "免税原因"+ },"title": "退货与原因"},"roles": {@@ -5186,12 +5195,11 @@"staff": "可访问此后台的人员","stock_locations": "存放库存的仓库与自提点","store": "店铺名称、时区、单位与区域默认值",- "tax_categories": "分配给商品的税务类别",- "tax_rates": "按市场和地区适用的税率","webhooks": "事件发生时接收通知的端点","package_types": "纸箱、外箱、托盘与集装箱","suppliers": "你从谁那里采购库存,以及如何联系他们","marketplace": "卖家付款、卖家审核、卖家邮件与佣金税",+ "taxes": "税务类别、税率和免税原因","ai_agents": "有权访问此店铺的 AI 代理","oauth_clients": "注册并配置 OAuth 客户端"},@@ -5232,6 +5240,7 @@"package_types": "包装类型","suppliers": "供应商","marketplace": "设置",+ "taxes": "税费","ai_agents": "AI 代理","oauth_clients": "OAuth 客户端"},@@ -5577,7 +5586,6 @@"sellers": "在您平台上经营的第三方卖家及各自的状态。","store_credits": "客户可在结账时使用的余额,以及每笔余额的发放方式。","tax_categories": "决定商品适用哪种税率的分组。",- "tax_rates": "按类别和地区收取的税费。","webhook_deliveries": "发送到此端点的每个事件,以及是否已被接收。","webhook_endpoints": "店铺发生事件时通知您其他系统的地址。","returns": "退回的商品,从申请到退款。",@@ -5598,8 +5606,7 @@"created": "税务类别已创建","deleted": "税务类别已删除","updated": "税务类别已更新"- },- "search_placeholder": "按名称搜索…"+ }},"tax_exemption_certificates": {"add_cta": "添加证明",@@ -5622,14 +5629,7 @@},"never_expires": "长期有效","no_document": "未附文件",- "reason_codes": {- "agricultural": "农业",- "charitable": "慈善机构",- "educational": "教育机构",- "government": "政府机构",- "manufacturing": "生产制造",- "resale": "转售"- },+ "no_reasons": "尚无免税原因。请在 设置 → 原因 中添加。","revoke_action": "撤销","revoke_confirm": {"message": "证明 {{number}} 将不再适用于新订单,但会作为记录保留。",@@ -5708,7 +5708,6 @@"deleted": "税率已删除","updated": "税率已更新"},- "search_placeholder": "搜索税率","select_category": "选择类别"},"translations": {@@ -6360,6 +6359,21 @@"view_on_github": "在 GitHub 上查看","release_notes_unavailable": "无法加载版本说明,请前往 GitHub 查看。"},+ "taxes": {+ "title": "税费",+ "description": "您的商品如何计税、Spree 收取哪些税率,以及企业为何可以免税购买。",+ "providers_title": "税费计算",+ "provider_markets": "{{markets}}:{{provider}}",+ "manage_markets": "管理市场",+ "tabs": {+ "categories": "类别",+ "rates": "税率",+ "exemption_reasons": "免税原因"+ },+ "rates_unused_in": "这些税率不适用于 {{markets}},这些市场由外部服务计算税费。",+ "rates_unused_everywhere": "您的市场均未使用这些税率:{{markets}} 由外部服务计算税费。",+ "rates_help": "按类别和地区收取的税费。仅适用于使用 Spree 税率的市场:Avalara 等已连接的服务会自行计算税费,忽略这些税率。"+ },"mcp_connect": {"open_cta": "连接代理","title": "连接代理",diff --git a/packages/dashboard/src/nav/settings.ts b/packages/dashboard/src/nav/settings.tsindex 54db79d6c4..ba87c1d7f1 100644--- a/packages/dashboard/src/nav/settings.ts+++ b/packages/dashboard/src/nav/settings.ts@@ -12,7 +12,6 @@ import {PercentIcon,PlugIcon,RadioTowerIcon,- ReceiptTextIcon,ReturnRequestIcon,ScrollTextIcon,ShapesIcon,@@ -171,28 +170,31 @@ settingsNav.add({subject: Subject.PaymentMethod,})+// Categories, rates and exemption reasons share one page, so a merchant+// setting up tax finds all of it in one place.settingsNav.add({- key: 'settings.tax-categories',- labelKey: 'admin.settings_nav.items.tax_categories',- descriptionKey: 'admin.settings_nav.descriptions.tax_categories',- keywords: ['vat', 'gst', 'sales tax', 'tax class'],- path: '/tax-categories',+ key: 'settings.taxes',+ labelKey: 'admin.settings_nav.items.taxes',+ descriptionKey: 'admin.settings_nav.descriptions.taxes',+ keywords: [+ 'vat',+ 'gst',+ 'sales tax',+ 'tax class',+ 'tax categories',+ 'tax rates',+ 'rate',+ 'percentage',+ 'exemption',+ 'exempt',+ 'certificate',+ 'avalara',+ ],+ path: '/taxes',icon: PercentIcon,group: 'selling',position: 300,- subject: Subject.TaxCategory,-})--settingsNav.add({- key: 'settings.tax-rates',- labelKey: 'admin.settings_nav.items.tax_rates',- descriptionKey: 'admin.settings_nav.descriptions.tax_rates',- keywords: ['vat', 'gst', 'sales tax', 'rate', 'percentage'],- path: '/tax-rates',- icon: ReceiptTextIcon,- group: 'selling',- position: 400,- subject: Subject.TaxRate,+ subjects: [Subject.TaxCategory, Subject.TaxRate, Subject.TaxExemptionReason],})settingsNav.add({diff --git a/packages/dashboard/src/routeTree.gen.ts b/packages/dashboard/src/routeTree.gen.tsindex 8ae9cad411..4ce601e5d0 100644--- a/packages/dashboard/src/routeTree.gen.ts+++ b/packages/dashboard/src/routeTree.gen.ts@@ -78,8 +78,7 @@ import { Route as SettingsSellerRequirementsRouteImport } from './routes/_authenimport { Route as SettingsStaffRouteImport } from './routes/_authenticated/$storeId/settings/staff'import { Route as SettingsStockLocationsRouteImport } from './routes/_authenticated/$storeId/settings/stock-locations'import { Route as SettingsStoreRouteImport } from './routes/_authenticated/$storeId/settings/store'-import { Route as SettingsTaxCategoriesRouteImport } from './routes/_authenticated/$storeId/settings/tax-categories'-import { Route as SettingsTaxRatesRouteImport } from './routes/_authenticated/$storeId/settings/tax-rates'+import { Route as SettingsTaxesRouteImport } from './routes/_authenticated/$storeId/settings/taxes'import { Route as TransfersIndexRouteImport } from './routes/_authenticated/$storeId/transfers/index'import { Route as TransfersNewRouteImport } from './routes/_authenticated/$storeId/transfers/new'import { Route as OrdersOrderIdIndexRouteImport } from './routes/_authenticated/$storeId/orders/$orderId/index'@@ -101,6 +100,10 @@ import { Route as SellersPayoutsPayoutIdRouteImport } from './routes/_authenticaimport { Route as SettingsDeliveryProfilesIndexRouteImport } from './routes/_authenticated/$storeId/settings/delivery-profiles/index'import { Route as SettingsEmailsIndexRouteImport } from './routes/_authenticated/$storeId/settings/emails/index'import { Route as SettingsImportsIndexRouteImport } from './routes/_authenticated/$storeId/settings/imports/index'+import { Route as SettingsTaxesIndexRouteImport } from './routes/_authenticated/$storeId/settings/taxes/index'+import { Route as SettingsTaxesCategoriesRouteImport } from './routes/_authenticated/$storeId/settings/taxes/categories'+import { Route as SettingsTaxesExemptionReasonsRouteImport } from './routes/_authenticated/$storeId/settings/taxes/exemption-reasons'+import { Route as SettingsTaxesRatesRouteImport } from './routes/_authenticated/$storeId/settings/taxes/rates'import { Route as SettingsWebhooksIndexRouteImport } from './routes/_authenticated/$storeId/settings/webhooks/index'import { Route as SettingsWebhooksWebhookEndpointIdRouteImport } from './routes/_authenticated/$storeId/settings/webhooks/$webhookEndpointId'import { Route as TransfersTransferIdIndexRouteImport } from './routes/_authenticated/$storeId/transfers/$transferId/index'@@ -459,14 +462,9 @@ const SettingsStoreRoute = SettingsStoreRouteImport.update({path: '/store',getParentRoute: () => SettingsRoute,} as any)-const SettingsTaxCategoriesRoute = SettingsTaxCategoriesRouteImport.update({- id: '/tax-categories',- path: '/tax-categories',- getParentRoute: () => SettingsRoute,-} as any)-const SettingsTaxRatesRoute = SettingsTaxRatesRouteImport.update({- id: '/tax-rates',- path: '/tax-rates',+const SettingsTaxesRoute = SettingsTaxesRouteImport.update({+ id: '/taxes',+ path: '/taxes',getParentRoute: () => SettingsRoute,} as any)const TransfersIndexRoute = TransfersIndexRouteImport.update({@@ -581,6 +579,27 @@ const SettingsImportsIndexRoute = SettingsImportsIndexRouteImport.update({path: '/imports/',getParentRoute: () => SettingsRoute,} as any)+const SettingsTaxesIndexRoute = SettingsTaxesIndexRouteImport.update({+ id: '/',+ path: '/',+ getParentRoute: () => SettingsTaxesRoute,+} as any)+const SettingsTaxesCategoriesRoute = SettingsTaxesCategoriesRouteImport.update({+ id: '/categories',+ path: '/categories',+ getParentRoute: () => SettingsTaxesRoute,+} as any)+const SettingsTaxesExemptionReasonsRoute =+ SettingsTaxesExemptionReasonsRouteImport.update({+ id: '/exemption-reasons',+ path: '/exemption-reasons',+ getParentRoute: () => SettingsTaxesRoute,+ } as any)+const SettingsTaxesRatesRoute = SettingsTaxesRatesRouteImport.update({+ id: '/rates',+ path: '/rates',+ getParentRoute: () => SettingsTaxesRoute,+} as any)const SettingsWebhooksIndexRoute = SettingsWebhooksIndexRouteImport.update({id: '/webhooks/',path: '/webhooks/',@@ -699,8 +718,7 @@ export interface FileRoutesByFullPath {'/$storeId/settings/staff': typeof SettingsStaffRoute'/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute'/$storeId/settings/store': typeof SettingsStoreRoute- '/$storeId/settings/tax-categories': typeof SettingsTaxCategoriesRoute- '/$storeId/settings/tax-rates': typeof SettingsTaxRatesRoute+ '/$storeId/settings/taxes': typeof SettingsTaxesRouteWithChildren'/$storeId/transfers/new': typeof TransfersNewRoute'/$storeId/companies/': typeof CompaniesIndexRoute'/$storeId/customers/': typeof CustomersIndexRoute@@ -722,6 +740,9 @@ export interface FileRoutesByFullPath {'/$storeId/products/price-lists/new': typeof ProductsPriceListsNewRoute'/$storeId/purchase-orders/$purchaseOrderId/edit': typeof PurchaseOrdersPurchaseOrderIdEditRoute'/$storeId/sellers/payouts/$payoutId': typeof SellersPayoutsPayoutIdRoute+ '/$storeId/settings/taxes/categories': typeof SettingsTaxesCategoriesRoute+ '/$storeId/settings/taxes/exemption-reasons': typeof SettingsTaxesExemptionReasonsRoute+ '/$storeId/settings/taxes/rates': typeof SettingsTaxesRatesRoute'/$storeId/settings/webhooks/$webhookEndpointId': typeof SettingsWebhooksWebhookEndpointIdRoute'/$storeId/transfers/$transferId/edit': typeof TransfersTransferIdEditRoute'/$storeId/orders/$orderId/': typeof OrdersOrderIdIndexRoute@@ -734,6 +755,7 @@ export interface FileRoutesByFullPath {'/$storeId/settings/delivery-profiles/': typeof SettingsDeliveryProfilesIndexRoute'/$storeId/settings/emails/': typeof SettingsEmailsIndexRoute'/$storeId/settings/imports/': typeof SettingsImportsIndexRoute+ '/$storeId/settings/taxes/': typeof SettingsTaxesIndexRoute'/$storeId/settings/webhooks/': typeof SettingsWebhooksIndexRoute'/$storeId/transfers/$transferId/': typeof TransfersTransferIdIndexRoute'/$storeId/settings/emails/templates/$templateId': typeof SettingsEmailsTemplatesTemplateIdRoute@@ -800,8 +822,6 @@ export interface FileRoutesByTo {'/$storeId/settings/staff': typeof SettingsStaffRoute'/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute'/$storeId/settings/store': typeof SettingsStoreRoute- '/$storeId/settings/tax-categories': typeof SettingsTaxCategoriesRoute- '/$storeId/settings/tax-rates': typeof SettingsTaxRatesRoute'/$storeId/transfers/new': typeof TransfersNewRoute'/$storeId/companies': typeof CompaniesIndexRoute'/$storeId/customers': typeof CustomersIndexRoute@@ -823,6 +843,9 @@ export interface FileRoutesByTo {'/$storeId/products/price-lists/new': typeof ProductsPriceListsNewRoute'/$storeId/purchase-orders/$purchaseOrderId/edit': typeof PurchaseOrdersPurchaseOrderIdEditRoute'/$storeId/sellers/payouts/$payoutId': typeof SellersPayoutsPayoutIdRoute+ '/$storeId/settings/taxes/categories': typeof SettingsTaxesCategoriesRoute+ '/$storeId/settings/taxes/exemption-reasons': typeof SettingsTaxesExemptionReasonsRoute+ '/$storeId/settings/taxes/rates': typeof SettingsTaxesRatesRoute'/$storeId/settings/webhooks/$webhookEndpointId': typeof SettingsWebhooksWebhookEndpointIdRoute'/$storeId/transfers/$transferId/edit': typeof TransfersTransferIdEditRoute'/$storeId/orders/$orderId': typeof OrdersOrderIdIndexRoute@@ -835,6 +858,7 @@ export interface FileRoutesByTo {'/$storeId/settings/delivery-profiles': typeof SettingsDeliveryProfilesIndexRoute'/$storeId/settings/emails': typeof SettingsEmailsIndexRoute'/$storeId/settings/imports': typeof SettingsImportsIndexRoute+ '/$storeId/settings/taxes': typeof SettingsTaxesIndexRoute'/$storeId/settings/webhooks': typeof SettingsWebhooksIndexRoute'/$storeId/transfers/$transferId': typeof TransfersTransferIdIndexRoute'/$storeId/settings/emails/templates/$templateId': typeof SettingsEmailsTemplatesTemplateIdRoute@@ -905,8 +929,7 @@ export interface FileRoutesById {'/_authenticated/$storeId/settings/staff': typeof SettingsStaffRoute'/_authenticated/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute'/_authenticated/$storeId/settings/store': typeof SettingsStoreRoute- '/_authenticated/$storeId/settings/tax-categories': typeof SettingsTaxCategoriesRoute- '/_authenticated/$storeId/settings/tax-rates': typeof SettingsTaxRatesRoute+ '/_authenticated/$storeId/settings/taxes': typeof SettingsTaxesRouteWithChildren'/_authenticated/$storeId/transfers/new': typeof TransfersNewRoute'/_authenticated/$storeId/companies/': typeof CompaniesIndexRoute'/_authenticated/$storeId/customers/': typeof CustomersIndexRoute@@ -928,6 +951,9 @@ export interface FileRoutesById {'/_authenticated/$storeId/products/price-lists/new': typeof ProductsPriceListsNewRoute'/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit': typeof PurchaseOrdersPurchaseOrderIdEditRoute'/_authenticated/$storeId/sellers/payouts/$payoutId': typeof SellersPayoutsPayoutIdRoute+ '/_authenticated/$storeId/settings/taxes/categories': typeof SettingsTaxesCategoriesRoute+ '/_authenticated/$storeId/settings/taxes/exemption-reasons': typeof SettingsTaxesExemptionReasonsRoute+ '/_authenticated/$storeId/settings/taxes/rates': typeof SettingsTaxesRatesRoute'/_authenticated/$storeId/settings/webhooks/$webhookEndpointId': typeof SettingsWebhooksWebhookEndpointIdRoute'/_authenticated/$storeId/transfers/$transferId/edit': typeof TransfersTransferIdEditRoute'/_authenticated/$storeId/orders/$orderId/': typeof OrdersOrderIdIndexRoute@@ -940,6 +966,7 @@ export interface FileRoutesById {'/_authenticated/$storeId/settings/delivery-profiles/': typeof SettingsDeliveryProfilesIndexRoute'/_authenticated/$storeId/settings/emails/': typeof SettingsEmailsIndexRoute'/_authenticated/$storeId/settings/imports/': typeof SettingsImportsIndexRoute+ '/_authenticated/$storeId/settings/taxes/': typeof SettingsTaxesIndexRoute'/_authenticated/$storeId/settings/webhooks/': typeof SettingsWebhooksIndexRoute'/_authenticated/$storeId/transfers/$transferId/': typeof TransfersTransferIdIndexRoute'/_authenticated/$storeId/settings/emails/templates/$templateId': typeof SettingsEmailsTemplatesTemplateIdRoute@@ -1010,8 +1037,7 @@ export interface FileRouteTypes {| '/$storeId/settings/staff'| '/$storeId/settings/stock-locations'| '/$storeId/settings/store'- | '/$storeId/settings/tax-categories'- | '/$storeId/settings/tax-rates'+ | '/$storeId/settings/taxes'| '/$storeId/transfers/new'| '/$storeId/companies/'| '/$storeId/customers/'@@ -1033,6 +1059,9 @@ export interface FileRouteTypes {| '/$storeId/products/price-lists/new'| '/$storeId/purchase-orders/$purchaseOrderId/edit'| '/$storeId/sellers/payouts/$payoutId'+ | '/$storeId/settings/taxes/categories'+ | '/$storeId/settings/taxes/exemption-reasons'+ | '/$storeId/settings/taxes/rates'| '/$storeId/settings/webhooks/$webhookEndpointId'| '/$storeId/transfers/$transferId/edit'| '/$storeId/orders/$orderId/'@@ -1045,6 +1074,7 @@ export interface FileRouteTypes {| '/$storeId/settings/delivery-profiles/'| '/$storeId/settings/emails/'| '/$storeId/settings/imports/'+ | '/$storeId/settings/taxes/'| '/$storeId/settings/webhooks/'| '/$storeId/transfers/$transferId/'| '/$storeId/settings/emails/templates/$templateId'@@ -1111,8 +1141,6 @@ export interface FileRouteTypes {| '/$storeId/settings/staff'| '/$storeId/settings/stock-locations'| '/$storeId/settings/store'- | '/$storeId/settings/tax-categories'- | '/$storeId/settings/tax-rates'| '/$storeId/transfers/new'| '/$storeId/companies'| '/$storeId/customers'@@ -1134,6 +1162,9 @@ export interface FileRouteTypes {| '/$storeId/products/price-lists/new'| '/$storeId/purchase-orders/$purchaseOrderId/edit'| '/$storeId/sellers/payouts/$payoutId'+ | '/$storeId/settings/taxes/categories'+ | '/$storeId/settings/taxes/exemption-reasons'+ | '/$storeId/settings/taxes/rates'| '/$storeId/settings/webhooks/$webhookEndpointId'| '/$storeId/transfers/$transferId/edit'| '/$storeId/orders/$orderId'@@ -1146,6 +1177,7 @@ export interface FileRouteTypes {| '/$storeId/settings/delivery-profiles'| '/$storeId/settings/emails'| '/$storeId/settings/imports'+ | '/$storeId/settings/taxes'| '/$storeId/settings/webhooks'| '/$storeId/transfers/$transferId'| '/$storeId/settings/emails/templates/$templateId'@@ -1215,8 +1247,7 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/settings/staff'| '/_authenticated/$storeId/settings/stock-locations'| '/_authenticated/$storeId/settings/store'- | '/_authenticated/$storeId/settings/tax-categories'- | '/_authenticated/$storeId/settings/tax-rates'+ | '/_authenticated/$storeId/settings/taxes'| '/_authenticated/$storeId/transfers/new'| '/_authenticated/$storeId/companies/'| '/_authenticated/$storeId/customers/'@@ -1238,6 +1269,9 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/products/price-lists/new'| '/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit'| '/_authenticated/$storeId/sellers/payouts/$payoutId'+ | '/_authenticated/$storeId/settings/taxes/categories'+ | '/_authenticated/$storeId/settings/taxes/exemption-reasons'+ | '/_authenticated/$storeId/settings/taxes/rates'| '/_authenticated/$storeId/settings/webhooks/$webhookEndpointId'| '/_authenticated/$storeId/transfers/$transferId/edit'| '/_authenticated/$storeId/orders/$orderId/'@@ -1250,6 +1284,7 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/settings/delivery-profiles/'| '/_authenticated/$storeId/settings/emails/'| '/_authenticated/$storeId/settings/imports/'+ | '/_authenticated/$storeId/settings/taxes/'| '/_authenticated/$storeId/settings/webhooks/'| '/_authenticated/$storeId/transfers/$transferId/'| '/_authenticated/$storeId/settings/emails/templates/$templateId'@@ -1754,18 +1789,11 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsStoreRouteImportparentRoute: typeof SettingsRoute}- '/_authenticated/$storeId/settings/tax-categories': {- id: '/_authenticated/$storeId/settings/tax-categories'- path: '/tax-categories'- fullPath: '/$storeId/settings/tax-categories'- preLoaderRoute: typeof SettingsTaxCategoriesRouteImport- parentRoute: typeof SettingsRoute- }- '/_authenticated/$storeId/settings/tax-rates': {- id: '/_authenticated/$storeId/settings/tax-rates'- path: '/tax-rates'- fullPath: '/$storeId/settings/tax-rates'- preLoaderRoute: typeof SettingsTaxRatesRouteImport+ '/_authenticated/$storeId/settings/taxes': {+ id: '/_authenticated/$storeId/settings/taxes'+ path: '/taxes'+ fullPath: '/$storeId/settings/taxes'+ preLoaderRoute: typeof SettingsTaxesRouteImportparentRoute: typeof SettingsRoute}'/_authenticated/$storeId/transfers/': {@@ -1915,6 +1943,34 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsImportsIndexRouteImportparentRoute: typeof SettingsRoute}+ '/_authenticated/$storeId/settings/taxes/': {+ id: '/_authenticated/$storeId/settings/taxes/'+ path: '/'+ fullPath: '/$storeId/settings/taxes/'+ preLoaderRoute: typeof SettingsTaxesIndexRouteImport+ parentRoute: typeof SettingsTaxesRoute+ }+ '/_authenticated/$storeId/settings/taxes/categories': {+ id: '/_authenticated/$storeId/settings/taxes/categories'+ path: '/categories'+ fullPath: '/$storeId/settings/taxes/categories'+ preLoaderRoute: typeof SettingsTaxesCategoriesRouteImport+ parentRoute: typeof SettingsTaxesRoute+ }+ '/_authenticated/$storeId/settings/taxes/exemption-reasons': {+ id: '/_authenticated/$storeId/settings/taxes/exemption-reasons'+ path: '/exemption-reasons'+ fullPath: '/$storeId/settings/taxes/exemption-reasons'+ preLoaderRoute: typeof SettingsTaxesExemptionReasonsRouteImport+ parentRoute: typeof SettingsTaxesRoute+ }+ '/_authenticated/$storeId/settings/taxes/rates': {+ id: '/_authenticated/$storeId/settings/taxes/rates'+ path: '/rates'+ fullPath: '/$storeId/settings/taxes/rates'+ preLoaderRoute: typeof SettingsTaxesRatesRouteImport+ parentRoute: typeof SettingsTaxesRoute+ }'/_authenticated/$storeId/settings/webhooks/': {id: '/_authenticated/$storeId/settings/webhooks/'path: '/webhooks'@@ -1988,6 +2044,24 @@ declare module '@tanstack/react-router' {}}+interface SettingsTaxesRouteChildren {+ SettingsTaxesCategoriesRoute: typeof SettingsTaxesCategoriesRoute+ SettingsTaxesExemptionReasonsRoute: typeof SettingsTaxesExemptionReasonsRoute+ SettingsTaxesRatesRoute: typeof SettingsTaxesRatesRoute+ SettingsTaxesIndexRoute: typeof SettingsTaxesIndexRoute+}++const SettingsTaxesRouteChildren: SettingsTaxesRouteChildren = {+ SettingsTaxesCategoriesRoute: SettingsTaxesCategoriesRoute,+ SettingsTaxesExemptionReasonsRoute: SettingsTaxesExemptionReasonsRoute,+ SettingsTaxesRatesRoute: SettingsTaxesRatesRoute,+ SettingsTaxesIndexRoute: SettingsTaxesIndexRoute,+}++const SettingsTaxesRouteWithChildren = SettingsTaxesRoute._addFileChildren(+ SettingsTaxesRouteChildren,+)+interface SettingsRouteChildren {SettingsAiAgentsRoute: typeof SettingsAiAgentsRouteSettingsAllowedOriginsRoute: typeof SettingsAllowedOriginsRoute@@ -2010,8 +2084,7 @@ interface SettingsRouteChildren {SettingsStaffRoute: typeof SettingsStaffRouteSettingsStockLocationsRoute: typeof SettingsStockLocationsRouteSettingsStoreRoute: typeof SettingsStoreRoute- SettingsTaxCategoriesRoute: typeof SettingsTaxCategoriesRoute- SettingsTaxRatesRoute: typeof SettingsTaxRatesRoute+ SettingsTaxesRoute: typeof SettingsTaxesRouteWithChildrenSettingsIndexRoute: typeof SettingsIndexRouteSettingsWebhooksWebhookEndpointIdRoute: typeof SettingsWebhooksWebhookEndpointIdRouteSettingsDeliveryProfilesIndexRoute: typeof SettingsDeliveryProfilesIndexRoute@@ -2047,8 +2120,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {SettingsStaffRoute: SettingsStaffRoute,SettingsStockLocationsRoute: SettingsStockLocationsRoute,SettingsStoreRoute: SettingsStoreRoute,- SettingsTaxCategoriesRoute: SettingsTaxCategoriesRoute,- SettingsTaxRatesRoute: SettingsTaxRatesRoute,+ SettingsTaxesRoute: SettingsTaxesRouteWithChildren,SettingsIndexRoute: SettingsIndexRoute,SettingsWebhooksWebhookEndpointIdRoute:SettingsWebhooksWebhookEndpointIdRoute,diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/getting-started.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/getting-started.tsxindex 80372e85eb..b115011d2e 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/getting-started.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/getting-started.tsx@@ -24,7 +24,7 @@ const TASK_LINKS: Record<string, string> = {setup_payment_method: '/$storeId/settings/payment-methods',add_products: '/$storeId/products',set_customer_support_email: '/$storeId/settings/emails',- setup_taxes_collection: '/$storeId/settings/tax-rates',+ setup_taxes_collection: '/$storeId/settings/taxes/rates',}export const Route = createFileRoute('/_authenticated/$storeId/getting-started')({diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/reasons.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/reasons.tsxindex 7b380098d5..d351612f86 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/reasons.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/reasons.tsx@@ -1,63 +1,10 @@-import { zodResolver } from '@hookform/resolvers/zod'-import {- Can,- mapSpreeErrorsToForm,- PageHeader,- Subject,- usePermissions,-} from '@spree/dashboard-core'-import {- ActiveBadge,- Badge,- Button,- Card,- CardContent,- CardHeader,- CardTitle,- Empty,- EmptyHeader,- EmptyMedia,- EmptyTitle,- Field,- FieldError,- FieldGroup,- FieldLabel,- Input,- RowActions,- Sheet,- SheetContent,- SheetDescription,- SheetFooter,- SheetHeader,- SheetTitle,- Skeleton,- Switch,- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow,- useConfirm,-} from '@spree/dashboard-ui'-import { PlusIcon, RotateCcwIcon, TriangleAlertIcon } from '@spree/dashboard-ui/icons'+import { PageHeader, Subject } from '@spree/dashboard-core'import { createFileRoute } from '@tanstack/react-router'-import { useState } from 'react'-import { Controller, type UseFormReturn, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import {- type Reason,- type ReasonKind,- useCreateReason,- useDeleteReason,- useReasons,- useUpdateReason,-} from '../../../../hooks/use-reasons'-import {- REASON_DEFAULTS,- type ReasonFormValues,- reasonFormSchema,-} from '../../../../schemas/reason'+ ReasonSection,+ type SectionConfig,+} from '../../../../components/spree/reasons/reason-section'export const Route = createFileRoute('/_authenticated/$storeId/settings/reasons')({component: ReasonsPage,@@ -68,9 +15,10 @@ export const Route = createFileRoute('/_authenticated/$storeId/settings/reasons'* short rows, and a merchant setting up returns wants to see the whole* vocabulary at once. They stay separate lists because they answer different* questions — why a customer sent something back, what the merchant got wrong,- * why money moved, and why an order never shipped at all.+ * why money moved, and why an order never shipped at all. Tax exemption+ * reasons live with the other tax settings.*/-const SECTIONS: Array<{ kind: ReasonKind; subject: string; titleKey: string; helpKey: string }> = [+const SECTIONS: SectionConfig[] = [{kind: 'return-reasons',subject: Subject.ReturnReason,@@ -114,289 +62,3 @@ function ReasonsPage() {</div>)}--function ReasonSection({- kind,- subject,- titleKey,- helpKey,-}: {- kind: ReasonKind- subject: string- titleKey: string- helpKey: string-}) {- const { t } = useTranslation()- const { data, isLoading, isError } = useReasons(kind)-- const [creating, setCreating] = useState(false)- const [editing, setEditing] = useState<Reason | null>(null)-- const reasons = data?.data ?? []-- return (- <>- <Card>- <CardHeader className="flex flex-row items-start justify-between gap-3 space-y-0">- <div>- <CardTitle>{t(titleKey)}</CardTitle>- <p className="mt-1 text-sm text-muted-foreground">{t(helpKey)}</p>- </div>- <Can I="create" a={subject}>- <Button size="sm" onClick={() => setCreating(true)}>- <PlusIcon className="size-4" />- {t('admin.reasons.add_cta')}- </Button>- </Can>- </CardHeader>- <CardContent className="p-0">- {isLoading ? (- <div className="p-4">- <Skeleton className="h-10 w-full" />- </div>- ) : isError ? (- // Distinct from the empty state: "no reasons yet" would tell an- // admin the list is empty when the request actually failed.- <Empty>- <EmptyHeader>- <EmptyMedia variant="icon">- <TriangleAlertIcon />- </EmptyMedia>- <EmptyTitle>{t('admin.errors.failed_to_load')}</EmptyTitle>- </EmptyHeader>- </Empty>- ) : reasons.length === 0 ? (- <Empty>- <EmptyHeader>- <EmptyMedia variant="icon">- <RotateCcwIcon />- </EmptyMedia>- <EmptyTitle>{t('admin.reasons.empty')}</EmptyTitle>- </EmptyHeader>- </Empty>- ) : (- <Table>- <TableHeader>- <TableRow>- <TableHead>{t('admin.fields.name.label')}</TableHead>- <TableHead>{t('admin.fields.status.label')}</TableHead>- <TableHead className="w-12" />- </TableRow>- </TableHeader>- <TableBody>- {reasons.map((reason) => (- <ReasonRow- key={reason.id}- kind={kind}- subject={subject}- reason={reason}- onEdit={setEditing}- />- ))}- </TableBody>- </Table>- )}- </CardContent>- </Card>-- {creating && <CreateReasonSheet kind={kind} onClose={() => setCreating(false)} />}- {editing && <EditReasonSheet kind={kind} reason={editing} onClose={() => setEditing(null)} />}- </>- )-}--function ReasonRow({- kind,- subject,- reason,- onEdit,-}: {- kind: ReasonKind- subject: string- reason: Reason- onEdit: (reason: Reason) => void-}) {- const { t } = useTranslation()- const confirm = useConfirm()- const { permissions } = usePermissions()- const deleteMutation = useDeleteReason(kind)-- async function handleDelete() {- const ok = await confirm({- title: t('admin.reasons.delete_confirm.title'),- message: t('admin.reasons.delete_confirm.message', { name: reason.name }),- variant: 'destructive',- confirmLabel: t('admin.actions.delete'),- })- if (!ok) return- await deleteMutation.mutateAsync(reason.id).catch(() => undefined)- }-- return (- <TableRow>- <TableCell>- <span className="flex items-center gap-2 font-medium">- {reason.name}- {!reason.can_be_deleted && (- <Badge variant="outline" title={t('admin.reasons.in_use_help')}>- {t('admin.reasons.in_use')}- </Badge>- )}- </span>- </TableCell>- <TableCell>- <ActiveBadge- active={reason.active}- activeLabel={t('admin.fields.active.label')}- inactiveLabel={t('admin.reasons.inactive')}- />- </TableCell>- <TableCell>- <RowActions- actions={[- {- key: 'edit',- visible: permissions.can('update', subject),- onSelect: () => onEdit(reason),- },- {- key: 'delete',- destructive: true,- visible: permissions.can('destroy', subject) && reason.can_be_deleted,- disabled: deleteMutation.isPending,- onSelect: handleDelete,- },- ]}- />- </TableCell>- </TableRow>- )-}--function CreateReasonSheet({ kind, onClose }: { kind: ReasonKind; onClose: () => void }) {- const { t } = useTranslation()- const createMutation = useCreateReason(kind)- const form = useForm<ReasonFormValues>({- resolver: zodResolver(reasonFormSchema),- defaultValues: REASON_DEFAULTS,- })-- async function onSubmit(values: ReasonFormValues) {- try {- await createMutation.mutateAsync(values)- onClose()- } catch (err) {- if (!mapSpreeErrorsToForm(err, form.setError)) throw err- }- }-- return (- <Sheet open onOpenChange={(next) => !next && onClose()}>- <SheetContent>- <SheetHeader>- <SheetTitle>{t('admin.reasons.add_sheet_title')}</SheetTitle>- <SheetDescription>{t('admin.reasons.create_description')}</SheetDescription>- </SheetHeader>- <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">- <ReasonFormFields form={form} />- </div>- <SheetFooter>- <Button type="button" variant="outline" onClick={onClose}>- {t('admin.actions.cancel')}- </Button>- <Button type="submit" disabled={createMutation.isPending}>- {t('admin.actions.create')}- </Button>- </SheetFooter>- </form>- </SheetContent>- </Sheet>- )-}--function EditReasonSheet({- kind,- reason,- onClose,-}: {- kind: ReasonKind- reason: Reason- onClose: () => void-}) {- const { t } = useTranslation()- const updateMutation = useUpdateReason(kind, reason.id)- const form = useForm<ReasonFormValues>({- resolver: zodResolver(reasonFormSchema),- defaultValues: { name: reason.name, active: reason.active },- })-- async function onSubmit(values: ReasonFormValues) {- try {- await updateMutation.mutateAsync(values)- onClose()- } catch (err) {- if (!mapSpreeErrorsToForm(err, form.setError)) throw err- }- }-- return (- <Sheet open onOpenChange={(next) => !next && onClose()}>- <SheetContent>- <SheetHeader>- <SheetTitle>{t('admin.reasons.edit_sheet_title')}</SheetTitle>- </SheetHeader>- <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">- <ReasonFormFields form={form} />- </div>- <SheetFooter>- <Button type="button" variant="outline" onClick={onClose}>- {t('admin.actions.cancel')}- </Button>- <Button type="submit" disabled={updateMutation.isPending}>- {t('admin.actions.save')}- </Button>- </SheetFooter>- </form>- </SheetContent>- </Sheet>- )-}--function ReasonFormFields({ form }: { form: UseFormReturn<ReasonFormValues> }) {- const { t } = useTranslation()- const { errors } = form.formState-- return (- <FieldGroup>- {errors.root?.message && (- <p className="text-sm text-destructive" role="alert">- {errors.root.message}- </p>- )}-- <Field>- <FieldLabel htmlFor="reason-name">{t('admin.fields.name.label')}</FieldLabel>- <Input- id="reason-name"- aria-invalid={!!errors.name}- placeholder={t('admin.reasons.name_placeholder')}- {...form.register('name')}- />- {errors.name && <FieldError>{errors.name.message}</FieldError>}- </Field>-- <Field orientation="horizontal">- <FieldLabel htmlFor="reason-active">{t('admin.reasons.active_label')}</FieldLabel>- <Controller- control={form.control}- name="active"- render={({ field }) => (- <Switch id="reason-active" checked={field.value} onCheckedChange={field.onChange} />- )}- />- </Field>- </FieldGroup>- )-}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes.tsxnew file mode 100644index 0000000000..da80691d04--- /dev/null+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes.tsx@@ -0,0 +1,26 @@+import { PageHeader } from '@spree/dashboard-core'+import { createFileRoute, Outlet } from '@tanstack/react-router'+import { useTranslation } from 'react-i18next'+import { TaxProviderSummary } from '../../../../components/spree/taxes/market-tax-providers'+import { TaxesTabs } from '../../../../components/spree/taxes/taxes-tabs'++export const Route = createFileRoute('/_authenticated/$storeId/settings/taxes')({+ component: TaxesLayout,+})++function TaxesLayout() {+ const { t } = useTranslation()++ return (+ <div className="flex flex-col gap-6">+ <PageHeader+ docsPath="settings/taxes"+ title={t('admin.taxes.title')}+ description={t('admin.taxes.description')}+ />+ <TaxProviderSummary />+ <TaxesTabs />+ <Outlet />+ </div>+ )+}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/tax-categories.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/categories.tsxsimilarity index 70%rename from packages/dashboard/src/routes/_authenticated/$storeId/settings/tax-categories.tsxrename to packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/categories.tsxindex e7ea858f0a..1010203e95 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/tax-categories.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/categories.tsx@@ -1,21 +1,15 @@import { zodResolver } from '@hookform/resolvers/zod'import type { TaxCategory, TaxCategoryCreateParams } from '@spree/admin-sdk'+import { Can, mapSpreeErrorsToForm, Subject, usePermissions } from '@spree/dashboard-core'import {- adminClient,- Can,- mapSpreeErrorsToForm,- ResourceTable,- resourceSearchSchema,- Subject,- usePermissions,-} from '@spree/dashboard-core'-import {+ ActiveBadge,Button,Field,FieldError,FieldGroup,FieldLabel,Input,+ Pagination,RowActions,Sheet,SheetContent,@@ -24,66 +18,64 @@ import {SheetHeader,SheetTitle,Switch,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,Textarea,useConfirm,- useRowClickBridge,} from '@spree/dashboard-ui'-import { PlusIcon } from '@spree/dashboard-ui/icons'+import { PercentIcon, PlusIcon } from '@spree/dashboard-ui/icons'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { useEffect } from 'react'import { Controller, type UseFormReturn, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { z } from 'zod/v4'+import { SettingsListCard } from '../../../../../components/spree/settings-list-card'import {useCreateTaxCategory,useDeleteTaxCategory,+ useTaxCategories,useTaxCategory,useUpdateTaxCategory,-} from '../../../../hooks/use-tax-categories'+} from '../../../../../hooks/use-tax-categories'import {TAX_CATEGORY_DEFAULTS,type TaxCategoryFormValues,taxCategoryFormSchema,taxCategoryValuesToParams,-} from '../../../../schemas/tax-category'-import '../../../../tables/tax-categories'+} from '../../../../../schemas/tax-category'-const taxCategoriesSearchSchema = resourceSearchSchema.extend({+const taxCategoriesSearchSchema = z.object({+ page: z.coerce.number().int().positive().optional(),edit: z.string().optional(),new: z.coerce.boolean().optional(),})-export const Route = createFileRoute('/_authenticated/$storeId/settings/tax-categories')({+export const Route = createFileRoute('/_authenticated/$storeId/settings/taxes/categories')({validateSearch: taxCategoriesSearchSchema,component: TaxCategoriesPage,})function TaxCategoriesPage() {const { t } = useTranslation()- const search = Route.useSearch() as z.infer<typeof taxCategoriesSearchSchema>+ const search = Route.useSearch()const navigate = useNavigate()const confirm = useConfirm()const deleteMutation = useDeleteTaxCategory()const { permissions } = usePermissions()+ const { data, isLoading, isError } = useTaxCategories({ page: search.page ?? 1 })+ const taxCategories = data?.data ?? []const editId = search.editconst isCreating = !!search.new- const closeSheet = () =>- navigate({- search: (prev: Record<string, unknown>) => {- const { edit: _e, new: _n, ...rest } = prev- return rest as never- },- })-- const openCreate = () =>- navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, new: true }) as never })-- const openEdit = (id: string) =>- navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, edit: id }) as never })+ const updateSearch = (patch: Partial<z.infer<typeof taxCategoriesSearchSchema>>) =>+ navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, ...patch }) as never })- useRowClickBridge('data-tax-category-id', openEdit)+ const closeSheet = () => updateSearch({ edit: undefined, new: undefined })async function handleDelete(taxCategory: TaxCategory) {const ok = await confirm({@@ -100,34 +92,85 @@ function TaxCategoriesPage() {return (<>- <ResourceTable<TaxCategory>- tableKey="tax-categories"- queryKey="tax-categories"- queryFn={(params) => adminClient.taxCategories.list(params)}- searchParams={search}- rowActions={(taxCategory) => (- <RowActions- actions={[- { key: 'edit', onSelect: () => openEdit(taxCategory.id) },- {- key: 'delete',- destructive: true,- visible: permissions.can('destroy', Subject.TaxCategory),- disabled: deleteMutation.isPending,- onSelect: () => handleDelete(taxCategory),- },- ]}- />- )}- actions={+ <SettingsListCard+ title={t('admin.settings_nav.items.tax_categories')}+ description={t('admin.table_descriptions.tax_categories')}+ action={<Can I="create" a={Subject.TaxCategory}>- <Button size="sm" className="h-[2.125rem]" onClick={openCreate}>+ <Button size="sm" onClick={() => updateSearch({ new: true })}><PlusIcon className="size-4" />{t('admin.tax_categories.add_cta')}</Button></Can>}- />+ isLoading={isLoading}+ isError={isError}+ isEmpty={taxCategories.length === 0}+ emptyIcon={<PercentIcon />}+ emptyTitle={t('admin.tax_categories.empty')}+ footer={+ data?.meta && data.meta.pages > 1 ? (+ <Pagination meta={data.meta} onPageChange={(page: number) => updateSearch({ page })} />+ ) : undefined+ }+ >+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>{t('admin.fields.name.label')}</TableHead>+ <TableHead>{t('admin.fields.tax_category.tax_code.label')}</TableHead>+ <TableHead>{t('admin.fields.tax_category.is_default.label')}</TableHead>+ <TableHead className="w-12" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {taxCategories.map((taxCategory) => (+ <TableRow key={taxCategory.id}>+ <TableCell>+ <button+ type="button"+ className="text-left font-medium"+ onClick={() => updateSearch({ edit: taxCategory.id })}+ >+ {taxCategory.name}+ </button>+ {taxCategory.description && (+ <p className="text-xs text-muted-foreground">{taxCategory.description}</p>+ )}+ </TableCell>+ <TableCell>+ {taxCategory.tax_code ? (+ <code className="text-sm">{taxCategory.tax_code}</code>+ ) : (+ '—'+ )}+ </TableCell>+ <TableCell>+ <ActiveBadge+ active={taxCategory.is_default}+ activeLabel={t('admin.fields.tax_category.is_default.label')}+ dashWhenInactive+ />+ </TableCell>+ <TableCell>+ <RowActions+ actions={[+ { key: 'edit', onSelect: () => updateSearch({ edit: taxCategory.id }) },+ {+ key: 'delete',+ destructive: true,+ visible: permissions.can('destroy', Subject.TaxCategory),+ disabled: deleteMutation.isPending,+ onSelect: () => handleDelete(taxCategory),+ },+ ]}+ />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </SettingsListCard>{isCreating && <CreateTaxCategorySheet open onOpenChange={(o) => !o && closeSheet()} />}{editId && <EditTaxCategorySheet id={editId} open onOpenChange={(o) => !o && closeSheet()} />}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/exemption-reasons.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/exemption-reasons.tsxnew file mode 100644index 0000000000..1e219ab65c--- /dev/null+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/exemption-reasons.tsx@@ -0,0 +1,19 @@+import { Subject } from '@spree/dashboard-core'+import { createFileRoute } from '@tanstack/react-router'+import { ReasonSection } from '../../../../../components/spree/reasons/reason-section'++export const Route = createFileRoute('/_authenticated/$storeId/settings/taxes/exemption-reasons')({+ component: TaxExemptionReasonsPage,+})++function TaxExemptionReasonsPage() {+ return (+ <ReasonSection+ kind="tax-exemption-reasons"+ subject={Subject.TaxExemptionReason}+ titleKey="admin.reasons.tax_exemption.title"+ helpKey="admin.reasons.tax_exemption.help"+ withCode+ />+ )+}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/index.tsxnew file mode 100644index 0000000000..55e7ff536b--- /dev/null+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/index.tsx@@ -0,0 +1,16 @@+import { usePermissions } from '@spree/dashboard-core'+import { createFileRoute, Navigate } from '@tanstack/react-router'+import { TAXES_TABS } from '../../../../../components/spree/taxes/taxes-tabs'++export const Route = createFileRoute('/_authenticated/$storeId/settings/taxes/')({+ component: TaxesIndex,+})++/** Opens the first tab the staff member may read. */+function TaxesIndex() {+ const { storeId } = Route.useParams()+ const { permissions } = usePermissions()+ const tab = TAXES_TABS.find((entry) => permissions.can('read', entry.subject)) ?? TAXES_TABS[0]++ return <Navigate to={`/$storeId/settings/taxes/${tab.value}`} params={{ storeId }} replace />+}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/tax-rates.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/rates.tsxsimilarity index 75%rename from packages/dashboard/src/routes/_authenticated/$storeId/settings/tax-rates.tsxrename to packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/rates.tsxindex f816375788..d64b92675e 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/tax-rates.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/rates.tsx@@ -1,18 +1,16 @@import { zodResolver } from '@hookform/resolvers/zod'import type { TaxRate } from '@spree/admin-sdk'import {- adminClient,Can,CountryCombobox,mapSpreeErrorsToForm,- ResourceTable,- resourceSearchSchema,StateCombobox,Subject,useCountryStates,usePermissions,} from '@spree/dashboard-core'import {+ ActiveBadge,Button,Field,FieldDescription,@@ -24,6 +22,7 @@ import {InputGroupAddon,InputGroupInput,InputGroupText,+ Pagination,RowActions,Select,SelectContent,@@ -37,66 +36,67 @@ import {SheetHeader,SheetTitle,Switch,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,useConfirm,- useRowClickBridge,} from '@spree/dashboard-ui'-import { PlusIcon } from '@spree/dashboard-ui/icons'+import { PlusIcon, ReceiptTextIcon } from '@spree/dashboard-ui/icons'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { useEffect } from 'react'import { Controller, type UseFormReturn, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { z } from 'zod/v4'-import { useTaxCategories } from '../../../../hooks/use-tax-categories'+import { JurisdictionLabel } from '../../../../../components/spree/jurisdiction-label'+import { SettingsListCard } from '../../../../../components/spree/settings-list-card'+import { TaxCategoryLabel } from '../../../../../components/spree/tax-category-label'+import { TaxRatesUsageNote } from '../../../../../components/spree/taxes/market-tax-providers'+import { useTaxCategories } from '../../../../../hooks/use-tax-categories'import {useCreateTaxRate,useDeleteTaxRate,useTaxRate,+ useTaxRates,useUpdateTaxRate,-} from '../../../../hooks/use-tax-rates'+} from '../../../../../hooks/use-tax-rates'import {TAX_RATE_DEFAULTS,type TaxRateFormValues,taxRateFormSchema,taxRateValuesToParams,-} from '../../../../schemas/tax-rate'-import '../../../../tables/tax-rates'+} from '../../../../../schemas/tax-rate'-const taxRatesSearchSchema = resourceSearchSchema.extend({+const taxRatesSearchSchema = z.object({+ page: z.coerce.number().int().positive().optional(),edit: z.string().optional(),new: z.coerce.boolean().optional(),})-export const Route = createFileRoute('/_authenticated/$storeId/settings/tax-rates')({+export const Route = createFileRoute('/_authenticated/$storeId/settings/taxes/rates')({validateSearch: taxRatesSearchSchema,component: TaxRatesPage,})function TaxRatesPage() {const { t } = useTranslation()- const search = Route.useSearch() as z.infer<typeof taxRatesSearchSchema>+ const search = Route.useSearch()const navigate = useNavigate()const confirm = useConfirm()const deleteMutation = useDeleteTaxRate()const { permissions } = usePermissions()+ const { data, isLoading, isError } = useTaxRates({ page: search.page ?? 1 })+ const taxRates = data?.data ?? []const editId = search.editconst isCreating = !!search.new- const closeSheet = () =>- navigate({- search: (prev: Record<string, unknown>) => {- const { edit: _e, new: _n, ...rest } = prev- return rest as never- },- })-- const openCreate = () =>- navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, new: true }) as never })-- const openEdit = (id: string) =>- navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, edit: id }) as never })+ const updateSearch = (patch: Partial<z.infer<typeof taxRatesSearchSchema>>) =>+ navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, ...patch }) as never })- useRowClickBridge('data-tax-rate-id', openEdit)+ const closeSheet = () => updateSearch({ edit: undefined, new: undefined })async function handleDelete(taxRate: TaxRate) {const ok = await confirm({@@ -111,34 +111,90 @@ function TaxRatesPage() {return (<>- <ResourceTable<TaxRate>- tableKey="tax-rates"- queryKey="tax-rates"- queryFn={(params) => adminClient.taxRates.list(params)}- searchParams={search}- rowActions={(taxRate) => (- <RowActions- actions={[- { key: 'edit', onSelect: () => openEdit(taxRate.id) },- {- key: 'delete',- destructive: true,- visible: permissions.can('destroy', Subject.TaxRate),- disabled: deleteMutation.isPending,- onSelect: () => handleDelete(taxRate),- },- ]}- />- )}- actions={+ <TaxRatesUsageNote />+ <SettingsListCard+ title={t('admin.settings_nav.items.tax_rates')}+ description={t('admin.taxes.rates_help')}+ action={<Can I="create" a={Subject.TaxRate}>- <Button size="sm" className="h-[2.125rem]" onClick={openCreate}>+ <Button size="sm" onClick={() => updateSearch({ new: true })}><PlusIcon className="size-4" />{t('admin.tax_rates.add_cta')}</Button></Can>}- />+ isLoading={isLoading}+ isError={isError}+ isEmpty={taxRates.length === 0}+ emptyIcon={<ReceiptTextIcon />}+ emptyTitle={t('admin.tax_rates.empty')}+ footer={+ data?.meta && data.meta.pages > 1 ? (+ <Pagination meta={data.meta} onPageChange={(page: number) => updateSearch({ page })} />+ ) : undefined+ }+ >+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>{t('admin.fields.name.label')}</TableHead>+ <TableHead>{t('admin.fields.tax_rate.amount.label')}</TableHead>+ <TableHead>{t('admin.fields.tax_rate.jurisdiction.label')}</TableHead>+ <TableHead>{t('admin.settings_nav.items.tax_categories')}</TableHead>+ <TableHead>{t('admin.fields.tax_rate.included_in_price.label')}</TableHead>+ <TableHead className="w-12" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {taxRates.map((taxRate) => (+ <TableRow key={taxRate.id}>+ <TableCell>+ <button+ type="button"+ className="text-left font-medium"+ onClick={() => updateSearch({ edit: taxRate.id })}+ >+ {taxRate.name}+ </button>+ </TableCell>+ <TableCell>+ {taxRate.rate_percent == null ? '—' : `${taxRate.rate_percent}%`}+ </TableCell>+ <TableCell>+ <JurisdictionLabel+ countryCode={taxRate.country_code}+ stateCode={taxRate.state_code}+ />+ </TableCell>+ <TableCell>+ <TaxCategoryLabel id={taxRate.tax_category_id} />+ </TableCell>+ <TableCell>+ <ActiveBadge+ active={taxRate.included_in_price}+ activeLabel={t('admin.fields.tax_rate.included_in_price.short')}+ dashWhenInactive+ />+ </TableCell>+ <TableCell>+ <RowActions+ actions={[+ { key: 'edit', onSelect: () => updateSearch({ edit: taxRate.id }) },+ {+ key: 'delete',+ destructive: true,+ visible: permissions.can('destroy', Subject.TaxRate),+ disabled: deleteMutation.isPending,+ onSelect: () => handleDelete(taxRate),+ },+ ]}+ />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </SettingsListCard>{isCreating && <CreateTaxRateSheet open onOpenChange={(o) => !o && closeSheet()} />}{editId && <EditTaxRateSheet id={editId} open onOpenChange={(o) => !o && closeSheet()} />}diff --git a/packages/dashboard/src/schemas/company.ts b/packages/dashboard/src/schemas/company.tsindex de0287ec45..fb8f850f6d 100644--- a/packages/dashboard/src/schemas/company.ts+++ b/packages/dashboard/src/schemas/company.ts@@ -62,7 +62,7 @@ export const TAX_IDENTIFIER_KINDS = ['eu_vat', 'gb_vat', 'ch_vat', 'au_abn', 'usexport const taxExemptionCertificateFormSchema = z.object({certificate_number: z.string().min(1, { error: requiredMessage('certificate_number') }),- reason_code: z.string().min(1, { error: requiredMessage('reason_code') }),+ tax_exemption_reason_id: z.string().min(1, { error: requiredMessage('tax_exemption_reason_id') }),country_code: countryCodeSchema.or(z.literal('')).optional(),state_code: z.string().optional(),issued_at: z.string().optional(),@@ -75,7 +75,7 @@ export type TaxExemptionCertificateFormValues = z.infer<typeof taxExemptionCertiexport const TAX_EXEMPTION_CERTIFICATE_DEFAULTS: TaxExemptionCertificateFormValues = {certificate_number: '',- reason_code: '',+ tax_exemption_reason_id: '',country_code: '',state_code: '',issued_at: '',@@ -84,26 +84,12 @@ export const TAX_EXEMPTION_CERTIFICATE_DEFAULTS: TaxExemptionCertificateFormValudocument_signed_id: null,}-/**- * Reason codes become the tax provider's entity use code. These are the ones in- * common circulation; the field stays free text because the set is the- * provider's, not Spree's.- */-export const TAX_EXEMPTION_REASON_CODES = [- 'resale',- 'government',- 'charitable',- 'educational',- 'manufacturing',- 'agricultural',-] as const-export function taxExemptionCertificateValuesToParams(values: TaxExemptionCertificateFormValues,): TaxExemptionCertificateCreateParams {return {certificate_number: values.certificate_number,- reason_code: values.reason_code,+ tax_exemption_reason_id: values.tax_exemption_reason_id,country_code: values.country_code || null,state_code: blankToNull(values.state_code),issued_at: blankToNull(values.issued_at),diff --git a/packages/dashboard/src/schemas/reason.ts b/packages/dashboard/src/schemas/reason.tsindex 80eef46c4f..8c6f2f4975 100644--- a/packages/dashboard/src/schemas/reason.ts+++ b/packages/dashboard/src/schemas/reason.ts@@ -1,10 +1,19 @@import { requiredMessage } from '@spree/dashboard-ui'import { z } from 'zod/v4'-/** Shared by every reason vocabulary — they all carry the same two fields. */+/** Shared by every reason vocabulary — they all carry a name and an active flag. */export const reasonFormSchema = z.object({name: z.string().min(1, { error: requiredMessage('name') }),active: z.boolean(),+ code: z.string().optional(),+})++/** Tax exemption reasons also carry the code certificates record and a tax engine reads. */+export const taxExemptionReasonFormSchema = reasonFormSchema.extend({+ code: z+ .string()+ .trim()+ .min(1, { error: requiredMessage('code') }),})export type ReasonFormValues = z.infer<typeof reasonFormSchema>@@ -12,4 +21,5 @@ export type ReasonFormValues = z.infer<typeof reasonFormSchema>export const REASON_DEFAULTS: ReasonFormValues = {name: '',active: true,+ code: '',}diff --git a/packages/dashboard/src/tables/tax-categories.tsx b/packages/dashboard/src/tables/tax-categories.tsxdeleted file mode 100644index f39d42df2f..0000000000--- a/packages/dashboard/src/tables/tax-categories.tsx+++ /dev/null@@ -1,52 +0,0 @@-import type { TaxCategory } from '@spree/admin-sdk'-import { defineTable } from '@spree/dashboard-core'-import { ActiveBadge, ResourceNameCell } from '@spree/dashboard-ui'-import { PercentIcon } from '@spree/dashboard-ui/icons'-import i18n from 'i18next'--defineTable<TaxCategory>('tax-categories', {- docsPath: 'settings/tax',- description: i18n.t('admin.table_descriptions.tax_categories'),- title: i18n.t('admin.settings_nav.items.tax_categories'),- searchParam: 'search',- searchPlaceholder: i18n.t('admin.tax_categories.search_placeholder'),- defaultSort: { field: 'name', direction: 'asc' },- emptyIcon: <PercentIcon className="size-8 text-muted-foreground" />,- emptyMessage: i18n.t('admin.tax_categories.empty'),- columns: [- {- key: 'name',- label: i18n.t('admin.fields.name.label'),- sortable: true,- default: true,- render: (tc) => (- <ResourceNameCell- id={tc.id}- dataAttr="data-tax-category-id"- name={tc.name}- secondary={tc.description}- />- ),- },- {- key: 'tax_code',- label: i18n.t('admin.fields.tax_category.tax_code.label'),- sortable: true,- filterable: true,- default: true,- render: (tc) => tc.tax_code ?? '—',- },- {- key: 'is_default',- label: i18n.t('admin.fields.tax_category.is_default.label'),- default: true,- render: (tc) => (- <ActiveBadge- active={tc.is_default}- activeLabel={i18n.t('admin.fields.tax_category.is_default.label')}- dashWhenInactive- />- ),- },- ],-})diff --git a/packages/dashboard/src/tables/tax-rates.tsx b/packages/dashboard/src/tables/tax-rates.tsxdeleted file mode 100644index daa2880333..0000000000--- a/packages/dashboard/src/tables/tax-rates.tsx+++ /dev/null@@ -1,74 +0,0 @@-import type { TaxRate } from '@spree/admin-sdk'-import { defineTable } from '@spree/dashboard-core'-import { ActiveBadge, ResourceNameCell } from '@spree/dashboard-ui'-import { ReceiptTextIcon } from '@spree/dashboard-ui/icons'-import i18n from 'i18next'-import { JurisdictionLabel } from '../components/spree/jurisdiction-label'-import { TaxCategoryLabel } from '../components/spree/tax-category-label'--defineTable<TaxRate>('tax-rates', {- docsPath: 'settings/tax',- description: i18n.t('admin.table_descriptions.tax_rates'),- title: i18n.t('admin.settings_nav.items.tax_rates'),- searchParam: 'search',- searchPlaceholder: i18n.t('admin.tax_rates.search_placeholder'),- defaultSort: { field: 'name', direction: 'asc' },- emptyIcon: <ReceiptTextIcon className="size-8 text-muted-foreground" />,- emptyMessage: i18n.t('admin.tax_rates.empty'),- columns: [- {- key: 'name',- label: i18n.t('admin.fields.name.label'),- sortable: true,- default: true,- render: (taxRate) => (- <ResourceNameCell id={taxRate.id} dataAttr="data-tax-rate-id" name={taxRate.name} />- ),- },- {- key: 'amount',- label: i18n.t('admin.fields.tax_rate.amount.label'),- sortable: true,- default: true,- render: (taxRate) => (taxRate.rate_percent == null ? '—' : `${taxRate.rate_percent}%`),- },- {- key: 'country_code',- label: i18n.t('admin.fields.tax_rate.jurisdiction.label'),- sortable: true,- filterable: true,- default: true,- render: (taxRate) => (- <JurisdictionLabel countryCode={taxRate.country_code} stateCode={taxRate.state_code} />- ),- },- {- key: 'included_in_price',- label: i18n.t('admin.fields.tax_rate.included_in_price.label'),- default: true,- render: (taxRate) => (- <ActiveBadge- active={taxRate.included_in_price}- activeLabel={i18n.t('admin.fields.tax_rate.included_in_price.short')}- dashWhenInactive- />- ),- },- {- key: 'show_rate_in_label',- label: i18n.t('admin.fields.tax_rate.show_rate_in_label.label'),- render: (taxRate) => (- <ActiveBadge- active={taxRate.show_rate_in_label}- activeLabel={i18n.t('admin.common.yes')}- dashWhenInactive- />- ),- },- {- key: 'tax_category_id',- label: i18n.t('admin.settings_nav.items.tax_categories'),- render: (taxRate) => <TaxCategoryLabel id={taxRate.tax_category_id} />,- },- ],-})diff --git a/packages/sdk-core/src/types.ts b/packages/sdk-core/src/types.tsindex bdb245521f..329c9447d8 100644--- a/packages/sdk-core/src/types.ts+++ b/packages/sdk-core/src/types.ts@@ -159,6 +159,8 @@ export interface PreferencePropertySchema {'x-spree-prefix'?: string/** A longer text, best edited in a multi-line field. */'x-spree-widget'?: 'textarea'+ /** Display labels for `enum` values that cannot name themselves, keyed by value. */+ 'x-spree-choice-labels'?: Record<string, string>}/**diff --git a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rbindex b0dcc27f67..2bd408bd08 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb@@ -90,6 +90,11 @@ module Spree# Request errorsrequest_too_large: 'request_too_large',+ # Tax engine errors — the same two codes the completion workflow+ # reports, so a client sees one vocabulary wherever tax failed.+ tax_provider_unavailable: 'tax_provider_unavailable',+ tax_calculation_refused: 'tax_calculation_refused',+# General errorsprocessing_error: 'processing_error',invalid_request: 'invalid_request'@@ -101,6 +106,12 @@ module Spreerescue_from CanCan::AccessDenied, with: :handle_access_deniedrescue_from Spree::Storefront::AccessDenied, with: :handle_access_deniedrescue_from Spree::Core::GatewayError, with: :handle_gateway_error+ # The backstop for every path that prices tax. Cart updates and+ # completion answer for themselves, with a message shaped to what the+ # customer was doing; anything else — adding an item, changing a+ # quantity, a recalculation — reaches here rather than escaping as a+ # 500 with an HTML body that a storefront cannot tell from a bug.+ rescue_from Spree::Tax::ProviderError, with: :handle_tax_provider_errorrescue_from ActionController::ParameterMissing, with: :handle_parameter_missingrescue_from ActiveRecord::RecordInvalid, with: :handle_record_invalidrescue_from Spree::Preferences::InvalidPreferences, with: :handle_invalid_preferences@@ -171,6 +182,25 @@ module Spreeendend+ # Renders a failed workflow or service result. A tax engine failure the+ # workflow caught itself (so it could roll the cart back) answers as+ # handle_tax_provider_error would have: 503 for an outage, the one+ # status the SDK retries, and 422 for a refusal. Anything else is+ # rendered with +code+.+ #+ # @param result [Spree::ServiceModule::Result]+ # @param code [String] the error code for any other failure+ def render_result_failure(result, code:)+ case result.error.code+ when ERROR_CODES[:tax_provider_unavailable]+ render_error(code: ERROR_CODES[:tax_provider_unavailable], message: result.error.to_s, status: :service_unavailable)+ when ERROR_CODES[:tax_calculation_refused]+ render_error(code: ERROR_CODES[:tax_calculation_refused], message: result.error.to_s, status: :unprocessable_content)+ else+ render_service_error(result.error, code: code)+ end+ end+# Legacy support - redirect to new error handlingdef render_errors(errors, status = :unprocessable_content)code = infer_error_code(errors, status)@@ -235,6 +265,25 @@ module Spree)end+ # Refused and unavailable are different instructions to the customer, so+ # they keep different codes: one names something to fix, the other is+ # worth retrying. Avalara's own wording is passed through for a refusal+ # because it names the problem better than we can; an outage says only+ # that, since its detail is about our endpoint and belongs in the error+ # tracker.+ def handle_tax_provider_error(exception)+ Rails.error.report(exception, context: error_context, source: 'spree.api.v3')++ refused = exception.is_a?(Spree::Tax::CalculationRefused)+ render_error(+ code: refused ? ERROR_CODES[:tax_calculation_refused] : ERROR_CODES[:tax_provider_unavailable],+ message: refused ? exception.message.to_s : I18n.t('spree.cart_line_item.tax_unavailable'),+ # A refusal is the request's fault, an outage is not. 503 is also+ # the one the SDK retries — it retries on status, not on our code.+ status: refused ? :unprocessable_content : :service_unavailable+ )+ end+def handle_parameter_missing(exception)Rails.error.report(exception, context: error_context, source: 'spree.api.v3')render_error(diff --git a/spree/api/app/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller.rbindex d08426fa9f..1f7f809d03 100644--- a/spree/api/app/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller.rb@@ -12,9 +12,8 @@ module Spreerequest_params :tax_exemption_certificate do |body|body.attribute :certificate_number, :string, required: true, on: :create,example: 'DE-RESALE-7'- body.attribute :reason_code, :string, required: true, on: :create,- example: 'resale',- description: "Becomes the tax provider's entity use code."+ body.attribute :tax_exemption_reason_id, :id, required: true, on: :create,+ description: "One of the store's active tax exemption reasons. The tax provider receives its `code`."body.attribute :issuing_authority, :string, nullable: true, example: 'Finanzamt Berlin'body.attribute :issued_at, :datetime, nullable: truebody.attribute :expires_at, :datetime, nullable: true@@ -100,11 +99,18 @@ module Spreeenddef collection_includes- [{ document_attachment: :blob }]+ [:tax_exemption_reason, { document_attachment: :blob }]end+ # Read through the store, so another store's reason is a 404+ # rather than a certificate pointing across stores.def permitted_params- params.permit(*declared_permitted_attributes)+ attributes = params.permit(*declared_permitted_attributes)+ return attributes if attributes[:tax_exemption_reason_id].blank?++ attributes.except(:tax_exemption_reason_id).merge(+ tax_exemption_reason: current_store.tax_exemption_reasons.find_by_prefix_id!(attributes[:tax_exemption_reason_id])+ )enddef build_resourcediff --git a/spree/api/app/controllers/spree/api/v3/admin/tax_exemption_reasons_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/tax_exemption_reasons_controller.rbnew file mode 100644index 0000000000..26acb41016--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/tax_exemption_reasons_controller.rb@@ -0,0 +1,58 @@+module Spree+ module Api+ module V3+ module Admin+ class TaxExemptionReasonsController < ResourceController+ scoped_resource :settings++ request_params :tax_exemption_reason do |body|+ body.include_attributes Spree::Api::V3::Admin::ReasonRequestSchema+ body.attribute :code, :string, required: true, on: :create, example: 'RESALE',+ description: 'What the tax provider receives for every certificate holding this reason — for Avalara, an entity use code such as `G`. ' \+ 'Saved in capitals. Changing it changes what those certificates send from then on.'+ body.attribute :metadata, :hash+ end++ protected++ def model_class+ Spree::TaxExemptionReason+ end++ def serializer_class+ Spree.api.admin_tax_exemption_reason_serializer+ end++ def permitted_params+ params.permit(*permitted_attributes)+ end++ # The certificate form picks from this list, so staff who manage+ # customers read it without the settings key. Writing stays a+ # settings matter.+ def scoped_resource_name+ reads_through_customers? ? :customers : super+ end++ def scope+ reads_through_customers? ? current_store.tax_exemption_reasons : super+ end++ def authorize_resource!(resource = @resource, action = action_name.to_sym)+ return authorize!(:show, Spree::TaxExemptionCertificate) if reads_through_customers?++ super+ end++ def reads_through_customers?+ return @reads_through_customers if defined?(@reads_through_customers)++ @reads_through_customers = action_kind == 'read' &&+ !holds_permission?('read_settings') &&+ holds_permission?('read_customers')+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rbindex d87e70c55a..2332df9e58 100644--- a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb@@ -123,7 +123,7 @@ module Spreesweep_unavailable_coupon_code!render_cartelse- render_service_error(result.error, code: ERROR_CODES[:validation_error])+ render_result_failure(result, code: ERROR_CODES[:validation_error])endendend@@ -181,11 +181,10 @@ module Spreeif result.success?@cart = result.valuerender_order+ elsif result.error.to_s.present?+ render_result_failure(result, code: ERROR_CODES[:cart_cannot_complete])else- render_service_error(- result.error.to_s.presence || 'Could not complete checkout',- code: ERROR_CODES[:cart_cannot_complete]- )+ render_service_error('Could not complete checkout', code: ERROR_CODES[:cart_cannot_complete])endrescue ActiveRecord::RecordNotFound# Gateway-race retry with the id the client got back: the webhookdiff --git a/spree/api/app/serializers/spree/api/v3/admin/tax_exemption_certificate_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/tax_exemption_certificate_serializer.rbindex da12cc07b4..09bd9517d4 100644--- a/spree/api/app/serializers/spree/api/v3/admin/tax_exemption_certificate_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/tax_exemption_certificate_serializer.rb@@ -5,7 +5,7 @@ module Spree# Admin-only: certificates are back-office evidence with no storefront# surface, so there is no store serializer to extend.class TaxExemptionCertificateSerializer < V3::BaseSerializer- typelize certificate_number: :string, reason_code: :string, status: [:string, enum: Spree::TaxExemptionCertificate.statuses, enum_type_name: 'TaxExemptionCertificateStatus'],+ typelize certificate_number: :string, tax_exemption_reason_id: :string, status: [:string, enum: Spree::TaxExemptionCertificate.statuses, enum_type_name: 'TaxExemptionCertificateStatus'],issuing_authority: [:string, nullable: true],issued_at: [:string, nullable: true], expires_at: [:string, nullable: true],verified_at: [:string, nullable: true],@@ -17,11 +17,15 @@ module Spreedocument_url: [:string, nullable: true],metadata: 'Record<string, unknown> | null'- attributes :certificate_number, :reason_code, :status, :issuing_authority, :metadata,+ attributes :certificate_number, :status, :issuing_authority, :metadata,issued_at: :iso8601, expires_at: :iso8601, verified_at: :iso8601,created_at: :iso8601, updated_at: :iso8601- prefixed_id_attributes :company+ prefixed_id_attributes :company, :tax_exemption_reason++ one :tax_exemption_reason,+ resource: proc { Spree.api.admin_tax_exemption_reason_serializer },+ if: proc { expand?('tax_exemption_reason') }# The jurisdiction the certificate holds in, in the same vocabulary the# tax lines use.diff --git a/spree/api/app/serializers/spree/api/v3/admin/tax_exemption_reason_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/tax_exemption_reason_serializer.rbnew file mode 100644index 0000000000..9485e03d46--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/tax_exemption_reason_serializer.rb@@ -0,0 +1,20 @@+module Spree+ module Api+ module V3+ module Admin+ # Admin-only: exemption reasons are recorded on certificates, which are+ # back-office evidence with no storefront surface.+ class TaxExemptionReasonSerializer < V3::BaseSerializer+ typelize name: :string, code: :string, active: :boolean, can_be_deleted: :boolean,+ metadata: 'Record<string, unknown> | null'++ attributes :name, :code, :active, :metadata, created_at: :iso8601, updated_at: :iso8601++ # Lets the dashboard hide destructive controls instead of offering a+ # delete that the model will refuse.+ attribute :can_be_deleted, &:can_be_deleted?+ end+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 491177e2c3..7e78235223 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -430,11 +430,12 @@ Spree::Core::Engine.add_routes do# preference, so there is nothing here to create.resources :payout_providers, only: [:index]- # Return / claim / refund / cancellation reasons (dropdowns + settings management)+ # Return / claim / refund / cancellation / tax exemption reasons (dropdowns + settings management)resources :return_reasonsresources :claim_reasonsresources :refund_reasonsresources :order_cancellation_reasons+ resources :tax_exemption_reasons# Marketsresources :marketsdiff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex 0cd6271c73..9282443565 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -32,7 +32,7 @@ module Spreeexchange exchange_line_item claim claim_line_item package_type policy tax_category tax_ratetax_identifier company company_membership company_invitation catalog catalog_price catalog_price_tiercatalog_product price_list_product catalog_assignment catalog_quantity_rule catalog_product_term- catalog_order_minimum tax_exemption_certificate admin_user actor seller_team_member product_submission+ catalog_order_minimum tax_exemption_certificate tax_exemption_reason admin_user actor seller_team_member product_submissionseller seller_requirement seller_requirement_submission seller_requirement_status commission_ratecommission_rule commission_line seller_transfer seller_payout seller_balance payment_split payment_capture_event addresschannel order_routing_rule product_publication market delivery_method delivery_method_servicediff --git a/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller_spec.rbindex 537b467463..2e6571a3a1 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller_spec.rb@@ -6,6 +6,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControlinclude_context 'API v3 Admin authenticated'let!(:company) { create(:company, store: store) }+ let!(:resale) { create(:tax_exemption_reason, store: store, code: 'RESALE', name: 'Resale') }let(:germany) { create(:country, iso: 'DE', name: 'Germany') }before { request.headers.merge!(headers) }@@ -22,14 +23,16 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControldescribe 'GET #index' doit 'lists the company certificates with whether each counts' docreate(:tax_exemption_certificate, :verified, company: company,- certificate_number: 'DE-1', reason_code: 'resale',+ certificate_number: 'DE-1', tax_exemption_reason: resale,country_code: germany&.iso)- get :index, params: { company_id: company.prefixed_id }, as: :json+ get :index, params: { company_id: company.prefixed_id, expand: 'tax_exemption_reason' }, as: :jsonexpect(response).to have_http_status(:ok)row = json_response['data'].firstexpect(row['id']).to start_with('cert_')+ expect(row['tax_exemption_reason_id']).to eq(resale.prefixed_id)+ expect(row['tax_exemption_reason']).to include('name' => 'Resale', 'code' => 'RESALE')expect(row['certificate_number']).to eq('DE-1')expect(row['status']).to eq('verified')expect(row['country_code']).to eq('DE')@@ -62,7 +65,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControlpost :create, params: {company_id: company.prefixed_id,certificate_number: 'DE-RESALE-7',- reason_code: 'resale',+ tax_exemption_reason_id: resale.prefixed_id,country_code: germany.iso}, as: :json@@ -72,6 +75,29 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControlexpect(company.tax_exemption_certificates.sole.country_code).to eq(germany.iso)end+ it 'refuses a reason the store has retired' do+ resale.update!(active: false)++ post :create, params: {+ company_id: company.prefixed_id,+ certificate_number: 'DE-RESALE-9',+ tax_exemption_reason_id: resale.prefixed_id+ }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response.dig('error', 'details', 'tax_exemption_reason')).to be_present+ end++ it "404s on another store's reason" do+ post :create, params: {+ company_id: company.prefixed_id,+ certificate_number: 'DE-RESALE-9',+ tax_exemption_reason_id: create(:tax_exemption_reason, store: create(:store)).prefixed_id+ }, as: :json++ expect(response).to have_http_status(:not_found)+ end+# A division's purchases read exemption through the legal entity; the# division itself holds no certificates.it 'refuses a certificate on a division node' do@@ -80,7 +106,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControlpost :create, params: {company_id: division.prefixed_id,certificate_number: 'DE-RESALE-8',- reason_code: 'resale'+ tax_exemption_reason_id: resale.prefixed_id}, as: :jsonexpect(response).to have_http_status(:unprocessable_content)@@ -89,7 +115,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControlit 'attaches an uploaded document' dopost :create, params: {company_id: company.prefixed_id,- certificate_number: 'DE-1', reason_code: 'resale',+ certificate_number: 'DE-1', tax_exemption_reason_id: resale.prefixed_id,document_signed_id: pdf_blob.signed_id}, as: :json@@ -104,7 +130,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControlpost :create, params: {company_id: company.prefixed_id,- certificate_number: 'DE-1', reason_code: 'resale',+ certificate_number: 'DE-1', tax_exemption_reason_id: resale.prefixed_id,document_signed_id: public_blob.signed_id}, as: :json@@ -117,7 +143,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControlit 'points the document at the download endpoint' dopost :create, params: {company_id: company.prefixed_id,- certificate_number: 'DE-1', reason_code: 'resale',+ certificate_number: 'DE-1', tax_exemption_reason_id: resale.prefixed_id,document_signed_id: pdf_blob.signed_id}, as: :json@@ -130,7 +156,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControlit 'reports no document url when nothing is attached' dopost :create, params: {- company_id: company.prefixed_id, certificate_number: 'DE-2', reason_code: 'resale'+ company_id: company.prefixed_id, certificate_number: 'DE-2', tax_exemption_reason_id: resale.prefixed_id}, as: :jsonexpect(json_response['document_url']).to be_nil@@ -140,7 +166,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControlit 'rejects a tampered signed id with a validation error' dopost :create, params: {company_id: company.prefixed_id,- certificate_number: 'DE-1', reason_code: 'resale',+ certificate_number: 'DE-1', tax_exemption_reason_id: resale.prefixed_id,document_signed_id: 'not-a-real-signed-id'}, as: :jsondiff --git a/spree/api/spec/controllers/spree/api/v3/admin/tax_exemption_reasons_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/tax_exemption_reasons_controller_spec.rbnew file mode 100644index 0000000000..ce573360ff--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/tax_exemption_reasons_controller_spec.rb@@ -0,0 +1,123 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::TaxExemptionReasonsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let!(:reason) { create(:tax_exemption_reason, name: 'Reseller (wholesale)', code: 'G') }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ it 'returns the store reasons with their codes' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['data']).to include(include('id' => reason.prefixed_id, 'code' => 'G'))+ end++ it 'excludes another store\'s reasons' do+ other = create(:tax_exemption_reason, store: create(:store))++ get :index, as: :json++ expect(json_response['data'].map { |r| r['id'] }).not_to include(other.prefixed_id)+ end++ # The certificate form picks from this list.+ context 'with a key that manages customers but not settings' do+ let(:customers_key) { create(:api_key, :secret, store: store, scopes: %w[read_customers write_customers]) }+ let(:headers) { { 'x-spree-api-key' => customers_key.plaintext_token } }++ it 'reads the reasons' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].map { |r| r['id'] }).to include(reason.prefixed_id)+ end++ it 'cannot change them' do+ patch :update, params: { id: reason.prefixed_id, name: 'Resale' }, as: :json++ expect(response).to have_http_status(:forbidden)+ end+ end++ context 'as a staffer whose role manages customers but not settings' do+ let(:staffer) do+ create(:admin_user, :without_admin_role).tap do |user|+ create(:role_user, user: user, role: create(:role, name: 'customers', permissions: %w[read_customers write_customers], resource: store))+ end+ end+ let(:headers) do+ { 'Authorization' => "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(staffer, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN)}" }+ end++ before { request.headers['X-Spree-Api-Key'] = nil }++ it 'reads the reasons and each one' do+ get :index, as: :json+ expect(json_response['data'].map { |r| r['id'] }).to include(reason.prefixed_id)++ get :show, params: { id: reason.prefixed_id }, as: :json+ expect(response).to have_http_status(:ok)+ end++ it 'cannot create one' do+ post :create, params: { name: 'Federal government', code: 'A' }, as: :json++ expect(response).to have_http_status(:forbidden)+ end+ end+ end++ describe 'POST #create' do+ it 'creates a reason' do+ expect { post :create, params: { name: 'Federal government', code: 'A' }, as: :json }.+ to change(store.tax_exemption_reasons, :count).by(1)++ expect(response).to have_http_status(:created)+ expect(json_response).to include('name' => 'Federal government', 'code' => 'A', 'active' => true)+ end++ it 'rejects a code the store already uses' do+ post :create, params: { name: 'Another resale', code: 'G' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'PATCH #update' do+ it 'renames the reason' do+ patch :update, params: { id: reason.prefixed_id, name: 'Resale' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(reason.reload.name).to eq('Resale')+ end++ it 'changes the code of a reason a certificate records' do+ create(:tax_exemption_certificate, company: create(:company, store: store), tax_exemption_reason: reason)++ patch :update, params: { id: reason.prefixed_id, code: 'n' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(reason.reload.code).to eq('N')+ end+ end++ describe 'DELETE #destroy' do+ it 'deletes an unused reason' do+ expect { delete :destroy, params: { id: reason.prefixed_id }, as: :json }.+ to change(Spree::TaxExemptionReason, :count).by(-1)+ end++ it 'refuses to delete a reason a certificate records' do+ create(:tax_exemption_certificate, company: create(:company, store: store), tax_exemption_reason: reason)++ expect { delete :destroy, params: { id: reason.prefixed_id }, as: :json }.+ not_to change(Spree::TaxExemptionReason, :count)+ expect(response).to have_http_status(:unprocessable_content)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/tax_providers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/tax_providers_controller_spec.rbindex 430ce371e5..98b14f2f82 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/tax_providers_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/tax_providers_controller_spec.rb@@ -13,7 +13,7 @@ RSpec.describe Spree::Api::V3::Admin::TaxProvidersController, type: :controllerexpect(response).to have_http_status(:ok)internal = json_response['data'].find { |provider| provider['id'] == 'internal' }- expect(internal['name']).to eq('Internal')+ expect(internal['name']).to eq('Spree tax rates')expect(internal['available']).to be(true)expect(internal['default']).to be(true)expect(internal['unsupported_capabilities'].map { |capability| capability['key'] }).to(diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rbindex cdc53ac278..557c91bb58 100644--- a/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb@@ -14,6 +14,37 @@ RSpec.describe Spree::Api::V3::Store::Carts::ItemsController, type: :controllerrequest.headers['Authorization'] = "Bearer #{jwt_token}"end+ # Adding to a cart prices tax, so a tax engine that fails has to answer as a+ # refusal a storefront can read. Escaping as a 500 with an HTML body is+ # indistinguishable from a platform bug, which is the failure this maps away.+ describe 'when the tax engine fails' do+ it 'refuses the change and says a retry is worth trying' do+ allow_any_instance_of(Spree::Cart).to receive(:tax_provider).+ and_raise(Spree::Tax::ProviderUnavailable.new('Failed to open TCP connection'))++ post :create, params: { cart_id: order.prefixed_id, variant_id: variant.prefixed_id, quantity: 1 }++ # 503, not 422: nothing is wrong with the request, and it is the status a+ # client retries — the SDK retries on status, not on our error code.+ expect(response).to have_http_status(:service_unavailable)+ expect(json_response['error']['code']).to eq('tax_provider_unavailable')+ # Our endpoint is named in the underlying message, so it stays in the+ # error tracker rather than going to the customer.+ expect(json_response['error']['message']).not_to include('TCP')+ end++ it 'passes on what the engine said when it refused the request itself' do+ allow_any_instance_of(Spree::Cart).to receive(:tax_provider).+ and_raise(Spree::Tax::CalculationRefused.new('Zip is not valid for the state'))++ post :create, params: { cart_id: order.prefixed_id, variant_id: variant.prefixed_id, quantity: 1 }++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('tax_calculation_refused')+ expect(json_response['error']['message']).to eq('Zip is not valid for the state')+ end+ end+describe 'POST #create' doit 'adds a line item and returns updated cart' doexpect dodiff --git a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rbindex 2496b5e961..6fa8c6ac4a 100644--- a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb@@ -666,6 +666,38 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller doexpect(response).to have_http_status(:ok)end+ # The update rolls the address back itself, so the outage never reaches+ # the API's own tax handler; the endpoint still has to answer as it would.+ context 'when the tax engine fails on the new address' do+ let(:address) { create(:address, customer: user, country: country, state: us_state) }++ def fail_tax_with(error)+ provider = instance_double(Spree::TaxProvider::Internal)+ allow(provider).to receive(:estimate).and_raise(error)+ allow_any_instance_of(Spree::Cart).to receive(:tax_provider).and_return(provider)+ end++ it 'answers an outage with 503 so the client retries' do+ fail_tax_with(Spree::Tax::ProviderUnavailable.new('Failed to open TCP connection'))++ patch :update, params: { id: order.prefixed_id, shipping_address_id: address.prefixed_id }++ expect(response).to have_http_status(:service_unavailable)+ expect(json_response['error']['code']).to eq('tax_provider_unavailable')+ expect(json_response['error']['message']).not_to include('TCP')+ end++ it 'answers a refusal with 422 and what the engine said' do+ fail_tax_with(Spree::Tax::CalculationRefused.new('Zip is not valid for the state'))++ patch :update, params: { id: order.prefixed_id, shipping_address_id: address.prefixed_id }++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('tax_calculation_refused')+ expect(json_response['error']['message']).to eq('Zip is not valid for the state')+ end+ end+it 'accepts shipping_address_id to use an existing address' doorder.update!(email: '[email protected]')existing_address = user.addresses.first || create(:address, customer: user, country: country, state: us_state)@@ -1165,6 +1197,38 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do.to change { Spree::StockReservation.for_order(order).count }.from(1).to(0)end+ # The workflow refuses the sale itself rather than letting the tax error+ # escape, so the endpoint maps its codes to the statuses the API's own tax+ # handler uses.+ context 'when the tax engine fails at completion' do+ let(:cart) { create(:cart_with_line_items, customer: user, store: store) }++ def complete_fails_with(code, message)+ error = Spree::ServiceModule::ResultError.new({ code: code, message: message })+ allow(Spree::Carts::Complete).to receive(:call).and_return(Spree::ServiceModule::Result.new(false, cart, error))+ end++ it 'answers an outage with 503 so the client retries' do+ complete_fails_with('tax_provider_unavailable', 'Tax could not be calculated right now.')++ post :complete, params: { id: cart.prefixed_id }++ expect(response).to have_http_status(:service_unavailable)+ expect(json_response['error']['code']).to eq('tax_provider_unavailable')+ expect(json_response['error']['message']).to eq('Tax could not be calculated right now.')+ end++ it 'answers a refusal with 422 and what the engine said' do+ complete_fails_with('tax_calculation_refused', 'Zip is not valid for the state.')++ post :complete, params: { id: cart.prefixed_id }++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('tax_calculation_refused')+ expect(json_response['error']['message']).to eq('Zip is not valid for the state.')+ end+ end+context 'when order cannot be completed' dolet(:incomplete_order) { create(:cart_with_line_items, customer: user, store: store) }diff --git a/spree/api/spec/integration/spree/api/v3/admin/companies/tax_exemption_certificates_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/companies/tax_exemption_certificates_spec.rbindex fae4c00699..9e27f40c22 100644--- a/spree/api/spec/integration/spree/api/v3/admin/companies/tax_exemption_certificates_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/companies/tax_exemption_certificates_spec.rb@@ -7,10 +7,11 @@ RSpec.describe 'Admin Tax Exemption Certificates API', type: :request, swagger_dlet(:Authorization) { "Bearer #{admin_jwt_token}" }let!(:company) { create(:company, store: store) }+ let!(:resale) { create(:tax_exemption_reason, store: store, code: 'RESALE', name: 'Resale') }let(:germany) { create(:country, iso: 'DE', name: 'Germany') }let!(:certificate) docreate(:tax_exemption_certificate, company: company,- certificate_number: 'DE-RESALE-1', reason_code: 'resale')+ certificate_number: 'DE-RESALE-1', tax_exemption_reason: resale)enddef pdf_blob@@ -75,7 +76,7 @@ RSpec.describe 'Admin Tax Exemption Certificates API', type: :request, swagger_dlet(:body) do{certificate_number: 'DE-RESALE-7',- reason_code: 'resale',+ tax_exemption_reason_id: resale.prefixed_id,country_code: germany.iso,document_signed_id: pdf_blob.signed_id}@@ -89,7 +90,7 @@ RSpec.describe 'Admin Tax Exemption Certificates API', type: :request, swagger_dendresponse '422', 'invalid request' do- let(:body) { { reason_code: 'resale' } }+ let(:body) { { tax_exemption_reason_id: resale.prefixed_id } }run_test!enddiff --git a/spree/api/spec/integration/spree/api/v3/admin/tax_exemption_reasons_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/tax_exemption_reasons_spec.rbnew file mode 100644index 0000000000..b78a2bfbb3--- /dev/null+++ b/spree/api/spec/integration/spree/api/v3/admin/tax_exemption_reasons_spec.rb@@ -0,0 +1,187 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'Admin Tax Exemption Reasons API', type: :request, swagger_doc: 'api-reference/admin.yaml' do+ include_context 'API v3 Admin'++ let(:Authorization) { "Bearer #{admin_jwt_token}" }+ let!(:reason) { create(:tax_exemption_reason, store: store, name: 'Reseller (wholesale)', code: 'G') }++ path '/api/v3/admin/tax_exemption_reasons' do+ get 'List tax exemption reasons' do+ tags 'Reasons'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Why a business buys without tax — the reasons a merchant can record on a+ tax exemption certificate. Each has the merchant's own `name` and a `code`,+ which certificates record and the tax provider receives.++ The vocabulary is the merchant's own — seeded with a starting set and+ edited from the dashboard. A provider whose engine reads the code lists+ the codes it understands on `GET /tax_providers`. Inactive rows stay on the+ certificates that already record them, but are not offered on new ones.+ DESC+ admin_scope :read, :settings++ admin_sdk_example 'tax-exemption-reasons/list'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'+ parameter name: :page, in: :query, type: :integer, required: false, description: 'Page number'+ parameter name: :limit, in: :query, type: :integer, required: false, description: 'Number of records per page'+ filter_parameters_for+ parameter name: :sort, in: :query, type: :string, required: false,+ description: 'Sort by field. Prefix with `-` for descending (e.g., `-created_at`).'++ response '200', 'tax exemption reasons found' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['data'].map { |r| r['id'] }).to include(reason.prefixed_id)+ end+ end++ response '401', 'unauthorized' do+ let(:'x-spree-api-key') { 'invalid' }+ let(:Authorization) { 'Bearer invalid' }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end++ post 'Create a tax exemption reason' do+ tags 'Reasons'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Adds a tax exemption reason to this store. Names and codes are unique per store.'+ admin_scope :write, :settings++ admin_sdk_example 'tax-exemption-reasons/create'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'+ request_body_for++ response '201', 'tax exemption reason created' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:body) { { name: 'Federal government', code: 'A' } }++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['name']).to eq('Federal government')+ expect(data['code']).to eq('A')+ expect(data['active']).to be(true)+ end+ end++ response '422', 'validation error' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:body) { { name: '' } }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ end++ path '/api/v3/admin/tax_exemption_reasons/{id}' do+ parameter name: :id, in: :path, type: :string, required: true, description: 'Tax exemption reason ID'++ get 'Get a tax exemption reason' do+ tags 'Reasons'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Returns a single tax exemption reason by prefixed ID.'+ admin_scope :read, :settings++ admin_sdk_example 'tax-exemption-reasons/get'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'++ response '200', 'tax exemption reason found' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:id) { reason.prefixed_id }++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['id']).to eq(reason.prefixed_id)+ expect(data['code']).to eq('G')+ end+ end++ response '404', 'tax exemption reason not found' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:id) { 'txr_nonexistent' }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end++ patch 'Update a tax exemption reason' do+ tags 'Reasons'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Renames a tax exemption reason or retires it. Deactivating keeps it on the+ certificates that already record it while removing it from the pickers. The+ code is fixed once a certificate records it.+ DESC+ admin_scope :write, :settings++ admin_sdk_example 'tax-exemption-reasons/update'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'+ request_body_for++ response '200', 'tax exemption reason updated' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:id) { reason.prefixed_id }+ let(:body) { { active: false } }++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['active']).to be(false)+ end+ end+ end++ delete 'Delete a tax exemption reason' do+ tags 'Reasons'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Removes a tax exemption reason the store no longer uses. A reason a+ certificate records is refused — deactivate it instead.+ DESC+ admin_scope :write, :settings++ admin_sdk_example 'tax-exemption-reasons/delete'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'++ response '204', 'tax exemption reason deleted' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:id) { reason.prefixed_id }++ run_test!+ end+ end+ end+enddiff --git a/spree/api/spec/swagger_helper.rb b/spree/api/spec/swagger_helper.rbindex 79d30bc4e6..f65439af57 100644--- a/spree/api/spec/swagger_helper.rb+++ b/spree/api/spec/swagger_helper.rb@@ -181,7 +181,7 @@ RSpec.configure do |config|{ name: 'Pricing', description: 'Prices and price lists for currency-, market-, and customer-group-specific pricing' },{ name: 'Products', description: 'Products, taxons/categories, product custom field values, and bulk product operations' },{ name: 'Policies', description: "The store's legal documents — terms of service, privacy, returns, shipping" },- { name: 'Reasons', description: 'Merchant-owned vocabularies for why a return, claim, refund or cancellation happened' },+ { name: 'Reasons', description: 'Merchant-owned vocabularies for why a return, claim, refund, cancellation or tax exemption happened' },{ name: 'Promotions', description: 'Promotions, promotion rules, promotion actions, and coupon codes' },{ name: 'Refunds', description: 'Order refunds' },{ name: 'Settings', description: 'Store-level settings — store profile, tags, and configuration' },diff --git a/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb b/spree/core/app/models/concerns/spree/preference_schema/json_schema.rbindex 6fa101aede..6d6ab2d548 100644--- a/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb+++ b/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb@@ -52,7 +52,14 @@ module Spreeschema = value_schema(definition)choices = definition[:choices]choices = choices.call if choices.respond_to?(:call)- schema['enum'] = choices.map { |choice| choice.is_a?(Symbol) ? choice.to_s : choice } if choices.present?+ if choices.present?+ # `{ value => label }` names values that cannot label themselves — an+ # endpoint URL is no i18n key, let alone something to show a merchant.+ labels = choices.to_h { |value, label| [value.to_s, label.to_s] } if choices.is_a?(Hash)+ values = choices.is_a?(Hash) ? choices.keys : Array(choices)+ schema['enum'] = values.map { |choice| choice.is_a?(Symbol) ? choice.to_s : choice }+ schema['x-spree-choice-labels'] = labels if labels+ enddefault = definition[:dynamic_default] ? nil : wire_default(default, definition)unset_reads_null = default.nil? && !definition[:dynamic_default]diff --git a/spree/core/app/models/concerns/spree/purchase/taxation.rb b/spree/core/app/models/concerns/spree/purchase/taxation.rbindex 686b72284e..d887992fee 100644--- a/spree/core/app/models/concerns/spree/purchase/taxation.rb+++ b/spree/core/app/models/concerns/spree/purchase/taxation.rb@@ -100,15 +100,30 @@ module Spreepre_tax_item_amount + fulfillments.sum(:pre_tax_amount)end- private-# The resolver is swappable, so what it returns is host code. An entry# whose per-line overrides cannot name their line is not a narrower claim# but a wider one — the provider would read it as the whole order being# exempt — so it is dropped rather than trusted. Charging tax is the safe# direction: under-exempting surfaces as a customer query, over-exempting# is tax the merchant owes and never collected.+ #+ # Public because a provider filing the sale needs the same evidence core+ # hands it as an +estimate+ argument: an external engine commits its+ # document after placement, and resolving again there could file an+ # exemption the estimate never applied.+ #+ # A placed order answers from its frozen snapshot for that reason, the way+ # +resolved_tax_identifier+ does. Resolving live months later is not the+ # same evidence: a certificate lapses on its own date with nothing written+ # to it, can be revoked, and goes with its company when that is deleted —+ # so a credit for an exempt sale would be filed as a consumer refund and+ # declare tax the sale never collected. Orders placed before the snapshot+ # existed have none, and still resolve live.+ #+ # @return [Array]def usable_exemptions+ return frozen_tax_exemptions if frozen_tax_exemptions?+resolved = Array(Spree.tax_resolve_exemptions_service.new.call(order: self).value)resolved.select do |exemption|@@ -127,6 +142,22 @@ module Spreeendend+ private++ # Carts always resolve live — a buyer's certificates legitimately change+ # while they shop, and the cart is priced again each time.+ #+ # Only nil is an absent snapshot. An empty one records that the sale found+ # no claim, and reading that as absent would let a certificate added later+ # explain a sale it was never part of.+ def frozen_tax_exemptions?+ is_a?(Spree::Order) && completed? && !applied_tax_exemptions.nil?+ end++ def frozen_tax_exemptions+ Array(applied_tax_exemptions).map { |snapshot| Spree::TaxExemption.from_snapshot(snapshot) }+ end+# Read through the legal entity, never the node — a division holds no# registrations of its own.def company_tax_identifierdiff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 9c6e22521e..2052586ca8 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -215,6 +215,7 @@ module Spreehas_many :claim_reasons, class_name: 'Spree::ClaimReason', inverse_of: :store, dependent: :destroyhas_many :refund_reasons, class_name: 'Spree::RefundReason', inverse_of: :store, dependent: :destroyhas_many :order_cancellation_reasons, class_name: 'Spree::OrderCancellationReason', inverse_of: :store, dependent: :destroy+ has_many :tax_exemption_reasons, class_name: 'Spree::TaxExemptionReason', inverse_of: :store, dependent: :destroy# :nullify (not :destroy) — clearing the collection must not cascade into# Promotion#not_used? / payment records; orphaned rows are detached, not deleted.diff --git a/spree/core/app/models/spree/tax_exemption.rb b/spree/core/app/models/spree/tax_exemption.rbindex ec800722e0..6d4b2b9ab8 100644--- a/spree/core/app/models/spree/tax_exemption.rb+++ b/spree/core/app/models/spree/tax_exemption.rb@@ -14,6 +14,9 @@ module Spree# Why the sale is exempt, in the provider's vocabulary — Avalara's# entityUseCode territory.attribute :reason_code, :string+ # The merchant's wording for the reason, kept with the claim so a placed+ # order still reads the way it did when it was taxed.+ attribute :reason_name, :stringattribute :certificate_number, :string# Where the claim holds. Nil country = everywhere the provider taxes,@@ -62,6 +65,29 @@ module Spreeoverride_for(item)&.reason_code.presence || reason_codeend+ # The claim as plain data, for freezing onto a placed order. Certificates+ # lapse, get revoked and are edited, so a provider filing or crediting that+ # sale later has to read the evidence the sale was priced with rather than+ # whatever resolves on the day.+ #+ # @return [Hash]+ def to_snapshot+ attributes.except('item_overrides').+ merge('item_overrides' => Array(item_overrides).map(&:to_snapshot))+ end++ # Unknown keys are dropped rather than raising: a snapshot is read back long+ # after it was written, possibly by a different version of Spree.+ #+ # @param snapshot [Hash]+ # @return [Spree::TaxExemption]+ def self.from_snapshot(snapshot)+ snapshot = snapshot.to_h.stringify_keys+ overrides = Array(snapshot['item_overrides']).map { |override| ItemOverride.from_snapshot(override) }++ new(snapshot.slice(*attribute_names).symbolize_keys.merge(item_overrides: overrides))+ end+private# An override that cannot say which line it applies to does not narrow thisdiff --git a/spree/core/app/models/spree/tax_exemption/item_override.rb b/spree/core/app/models/spree/tax_exemption/item_override.rbindex 9f947f5e5d..e7b43a5df4 100644--- a/spree/core/app/models/spree/tax_exemption/item_override.rb+++ b/spree/core/app/models/spree/tax_exemption/item_override.rb@@ -17,6 +17,20 @@ module Spreedef exempt?exemptend++ # @return [Hash]+ def to_snapshot+ attributes+ end++ # Unknown keys are dropped rather than raising: a snapshot is read back+ # long after it was written, possibly by a different version of Spree.+ #+ # @param snapshot [Hash]+ # @return [Spree::TaxExemption::ItemOverride]+ def self.from_snapshot(snapshot)+ new(snapshot.to_h.stringify_keys.slice(*attribute_names).symbolize_keys)+ endendendenddiff --git a/spree/core/app/models/spree/tax_exemption_certificate.rb b/spree/core/app/models/spree/tax_exemption_certificate.rbindex 8f8b794fba..5b6e5fb748 100644--- a/spree/core/app/models/spree/tax_exemption_certificate.rb+++ b/spree/core/app/models/spree/tax_exemption_certificate.rb@@ -22,6 +22,7 @@ module Spreehas_status :pending, :verified, :expired, :revoked, default: :pendingbelongs_to :company, class_name: 'Spree::Company', inverse_of: :tax_exemption_certificates+ belongs_to :tax_exemption_reason, class_name: 'Spree::TaxExemptionReason', inverse_of: :tax_exemption_certificatesbelongs_to :verified_by, class_name: Spree.admin_user_class.to_s, optional: true# Confidential, so the private service rather than the public one that@@ -29,12 +30,15 @@ module Spreehas_one_attached :document, service: Spree.private_storage_service_namesigned_id_attachments :document- validates :certificate_number, :reason_code, presence: true+ validates :certificate_number, presence: true# Certificates exist only on legal-entity nodes — a division's purchases# read exemption through its legal entity. A validation rather than a# schema difference, so a per-division registration can be allowed later# by relaxing this alone.validate :company_is_legal_entity+ # Checked when the reason is set, not on every save: a reason the merchant+ # retires later leaves the certificates that already record it valid.+ validate :reason_offered_by_store, if: :will_save_change_to_tax_exemption_reason_id?# A certificate is a scanned form, not an archive. Bounded because the# download action reads the whole blob into memory to serve it, so an@@ -64,7 +68,7 @@ module Spreewhere(state_code: [address.state_code.presence, nil].uniq)}- self.whitelisted_ransackable_attributes = %w[certificate_number reason_code status expires_at]+ self.whitelisted_ransackable_attributes = %w[certificate_number tax_exemption_reason_id status expires_at]delegate :store, :store_id, to: :company@@ -94,5 +98,12 @@ module Spreeerrors.add(:company, :must_be_legal_entity)end++ def reason_offered_by_store+ return if tax_exemption_reason.nil? || company.nil?+ return if tax_exemption_reason.active? && tax_exemption_reason.store_id == store_id++ errors.add(:tax_exemption_reason, :not_offered)+ endendenddiff --git a/spree/core/app/models/spree/tax_exemption_reason.rb b/spree/core/app/models/spree/tax_exemption_reason.rbnew file mode 100644index 0000000000..eefc3fda6c--- /dev/null+++ b/spree/core/app/models/spree/tax_exemption_reason.rb@@ -0,0 +1,62 @@+module Spree+ # Why a business buys without tax — "Resale", "Government", "Charitable+ # organisation". Certificates point at a reason the way products point at a+ # tax category: the `name` is the merchant's own wording, and the `code` is+ # what a tax engine reads. Spree's own engine only keeps the code for+ # reference, while an external one (Avalara's entity use codes) decides the+ # exemption by it, so changing the code changes what every certificate+ # holding the reason sends from then on.+ class TaxExemptionReason < Spree.base_class+ has_prefix_id :txr++ include Spree::NamedType+ include Spree::Metadata++ # Guarded by hand rather than with :restrict_with_error, which would also+ # refuse when the whole store is being destroyed.+ has_many :tax_exemption_certificates, class_name: 'Spree::TaxExemptionCertificate',+ inverse_of: :tax_exemption_reason, dependent: nil++ self.whitelisted_ransackable_attributes = %w[name code active]++ # Upper case because tax engines read codes case-insensitively: `g` and+ # `G` would be two reasons here and one to Avalara.+ normalizes :code, with: ->(value) { value.to_s.strip.upcase.presence }++ validates :code, presence: true, length: { maximum: 64 }+ validates_store_uniqueness :code++ before_destroy :ensure_unused++ # Finds the reason already holding the code, else the one holding the+ # name, so seeding a store never collides with a reason the merchant added+ # or renamed. Code first: it is what a tax engine reads, so a match on it+ # is the same reason whatever the merchant called it.+ #+ # @param code [String]+ # @param name [String]+ # @return [Spree::TaxExemptionReason]+ def self.find_or_create_by_code_or_name!(code:, name:)+ code = normalize_value_for(:code, code)++ find_by(code: code) || find_by(name: name) || create!(code: code, name: name)+ end++ # Mirrors the destroy guard, so the dashboard can hide the delete control+ # rather than offer one the model will refuse.+ #+ # @return [Boolean]+ def can_be_deleted?+ !tax_exemption_certificates.exists?+ end++ private++ def ensure_unused+ return if destroyed_by_association.present? || can_be_deleted?++ errors.add(:base, :in_use)+ throw :abort+ end+ end+enddiff --git a/spree/core/app/models/spree/tax_provider/base.rb b/spree/core/app/models/spree/tax_provider/base.rbindex 7df500dece..5394de7c9e 100644--- a/spree/core/app/models/spree/tax_provider/base.rb+++ b/spree/core/app/models/spree/tax_provider/base.rb@@ -41,6 +41,16 @@ module Spreename.demodulize.titleizeend+ # The exemption reason codes this engine understands, `{ code => label }`,+ # offered to a merchant adding a {Spree::TaxExemptionReason}. Nil for an+ # engine that does not read the code, Spree's own included: any code a+ # merchant chooses is then as good as another.+ #+ # @return [Hash{String => String}, nil]+ def self.exemption_reason_codes+ nil+ end+# The declared limits with the strings a merchant can act on. A capability# with no translation degrades to its humanized key rather than a missing# translation, so an extension that declares one without shipping strings@@ -69,6 +79,7 @@ module Spreename: display_name,available: available_for_store?(store),unsupported_capabilities: unsupported_capability_details,+ exemption_reason_codes: exemption_reason_codes&.map { |code, label| { value: code.to_s, label: label.to_s } },default: name == Spree.default_tax_provider.to_s}end@@ -86,8 +97,13 @@ module Spree# registration, nil for a consumer sale# @param exemptions [Array] exemption evidence to apply# @param context [Hash] untyped provider extras from set_tax_line_context- # @return [void] the written rows are the output; raise when the- # calculation cannot be completed+ # @return [void] the written rows are the output+ # @raise [Spree::Tax::ProviderUnavailable] when the engine could not+ # answer — refused, timed out, unreachable. Raise this (or a subclass,+ # as a provider's own request error may) rather than a bare error: core+ # turns it into a refusal the customer can retry, where anything else+ # reaches them as a broken checkout. A provider a merchant switched off+ # is not this — it has no opinion and writes no rows.def estimate(owner, items = nil, tax_date: nil, tax_identifier: nil, exemptions: [], context: {})raise NotImplementedError, "Please implement 'estimate' in your tax provider: #{self.class.name}"enddiff --git a/spree/core/app/models/spree/tax_provider/internal.rb b/spree/core/app/models/spree/tax_provider/internal.rbindex 7f30e35da5..16a82cc3ea 100644--- a/spree/core/app/models/spree/tax_provider/internal.rb+++ b/spree/core/app/models/spree/tax_provider/internal.rb@@ -7,6 +7,12 @@ module Spree# default tax category's rates — except customs duties, which +taxable_items+# withholds (see Spree::Purchase::Taxation).class Internal < Base+ # What a merchant sees when picking a market's tax engine: the class name+ # says nothing to someone who never read the code.+ def self.display_name+ I18n.t('spree.tax_providers.internal')+ end+# Rates are configured per country or state with no local-tax breakdown, no buyer# registration handling, no distance-selling thresholds, and delivery taxed# at its own method's rate rather than apportioned across the rates of the@@ -226,9 +232,14 @@ module Spree# a genuinely exempt supply depends on which exemption applied, which the# reason alone cannot say.def exemption_data(exemption, item)+ reason_code = exemption.reason_code_for(item)+{'exemption' => {- 'reason_code' => exemption.reason_code_for(item),+ 'reason_code' => reason_code,+ # A per-line override names only a code, so the entry's name would+ # describe a different reason.+ 'reason_name' => (exemption.reason_name if reason_code == exemption.reason_code),'certificate_number' => exemption.certificate_number}.compact}diff --git a/spree/core/app/services/spree/carts/split_by_seller.rb b/spree/core/app/services/spree/carts/split_by_seller.rbindex 8cad7441c6..062fc2b876 100644--- a/spree/core/app/services/spree/carts/split_by_seller.rb+++ b/spree/core/app/services/spree/carts/split_by_seller.rb@@ -34,10 +34,15 @@ module Spree# recorded about the purchase (copied from the cart), so every child gets# the same hash — and so does the group. Once split, each order's# metadata is its own: edits never propagate between siblings.+ #+ # `applied_tax_exemptions` rides along, or a sibling resolves again and+ # takes override ids that match nothing it owns. Line items keep their ids+ # here; a divided fulfillment and its money rows do not, so an override+ # naming one is stale — latent while nothing supplies overrides.CARRIED_TO_SIBLING = %w[email currency locale market_id channel_id company_idcustomer_id token accept_marketing preferred_stock_location_id- customer_note last_ip_address po_number metadata+ customer_note last_ip_address po_number metadata applied_tax_exemptions].freeze# @param order [Spree::Order] the paid draft order, adopted as thediff --git a/spree/core/app/services/spree/carts/update.rb b/spree/core/app/services/spree/carts/update.rbindex 3647bec383..42ca65c4f4 100644--- a/spree/core/app/services/spree/carts/update.rb+++ b/spree/core/app/services/spree/carts/update.rb@@ -28,10 +28,11 @@ module Spreesuccess(cart)rescue ActiveRecord::RecordNotFoundraise- rescue Spree::Pricing::PriceResolution::ProviderUnavailable => e- # A strict store could not confirm a price. The transaction has rolled- # back, so the address change is not committed either — better than- # saving a destination whose prices nobody stood behind.+ rescue Spree::Pricing::PriceResolution::ProviderUnavailable, Spree::Tax::ProviderError => e+ # A strict store could not confirm a price, or the tax engine did not+ # produce tax. The transaction has rolled back, so the address change is+ # not committed either — better than saving a destination whose prices+ # or tax nobody stood behind.## The in-memory cart still holds the rolled-back attributes, though, so# a caller that renders the object it passed in would show the customer@@ -48,7 +49,7 @@ module Spreeendcart.warnings |= warnings if warnings.present?- failure(cart, I18n.t('spree.cart_line_item.pricing_unavailable'))+ failure(cart, { code: unavailable_code_for(e), message: unavailable_message_for(e) })rescue ActiveRecord::RecordInvalid => efailure(cart, e.record.errors.full_messages.to_sentence)rescue StandardError => e@@ -229,6 +230,29 @@ module Spreeendend+ # Three ways an external service can leave a sale unpriced, and a+ # customer can only act on what they are told. A refused calculation+ # carries the engine's own words, because "the postcode is not valid for+ # that state" is something they can fix and "please try again" is not.+ # The same split the API's own handler makes: a refusal names something+ # to fix, an outage is worth retrying, and a price that could not be+ # confirmed is neither tax case.+ def unavailable_code_for(error)+ case error+ when Spree::Tax::CalculationRefused then 'tax_calculation_refused'+ when Spree::Tax::ProviderError then 'tax_provider_unavailable'+ else 'provider_unavailable'+ end+ end++ def unavailable_message_for(error)+ case error+ when Spree::Tax::CalculationRefused then error.message.to_s+ when Spree::Tax::ProviderError then I18n.t('spree.cart_line_item.tax_unavailable')+ else I18n.t('spree.cart_line_item.pricing_unavailable')+ end+ end+# Three-way dispatch on the cart→checkout transition:# entering checkout → Reserve, mid-checkout mutation → Extend, reverting to cart → Release.# A failed Reserve raises so the enclosing transaction rolls back and the@@ -256,10 +280,13 @@ module Spreeelsecart.recalculate_totals!end- rescue Spree::Pricing::PriceResolution::ProviderUnavailable+ rescue Spree::Pricing::PriceResolution::ProviderUnavailable, Spree::Tax::ProviderError# Deliberately not swallowed like the rest: a strict store refusing to# price must roll the whole update back, so `call` sees it and the- # address change does not commit around unconfirmed prices.+ # address change does not commit around unconfirmed prices. A tax engine+ # that cannot answer is the same problem one column over — swallowing it+ # showed the customer a total with tax missing and saved the address+ # anyway, so the mistake only surfaced when they tried to pay.raiserescue StandardError => eRails.error.report(e, context: { order_id: cart.id }, source: 'spree.checkout')diff --git a/spree/core/app/services/spree/seeds/store_resources.rb b/spree/core/app/services/spree/seeds/store_resources.rbindex 2a843cbbe6..726629c054 100644--- a/spree/core/app/services/spree/seeds/store_resources.rb+++ b/spree/core/app/services/spree/seeds/store_resources.rb@@ -18,6 +18,7 @@ module SpreeSpree::Events.disable doActiveRecord::Base.no_touching doTaxCategories.call(store: store)+ TaxExemptionReasons.call(store: store)Channels.call(store: store)Roles.call(store: store)DigitalDelivery.call(store: store)diff --git a/spree/core/app/services/spree/seeds/tax_exemption_reasons.rb b/spree/core/app/services/spree/seeds/tax_exemption_reasons.rbnew file mode 100644index 0000000000..b4a453fefe--- /dev/null+++ b/spree/core/app/services/spree/seeds/tax_exemption_reasons.rb@@ -0,0 +1,28 @@+module Spree+ module Seeds+ # The reasons a business can give for buying without tax. Neutral codes+ # that Spree's own engine keeps for reference; a store using an engine+ # that reads them (Avalara) changes each code to that engine's.+ class TaxExemptionReasons+ prepend Spree::ServiceModule::Base+ include StoreScoped++ REASONS = {+ 'RESALE' => 'Resale',+ 'GOVERNMENT' => 'Government',+ 'CHARITABLE' => 'Charitable organization',+ 'EDUCATIONAL' => 'Educational institution',+ 'MANUFACTURING' => 'Manufacturing',+ 'AGRICULTURAL' => 'Agricultural'+ }.freeze++ private++ def seed(store)+ REASONS.each do |code, name|+ store.tax_exemption_reasons.find_or_create_by_code_or_name!(code: code, name: name)+ end+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/tax/resolve_exemptions.rb b/spree/core/app/services/spree/tax/resolve_exemptions.rbindex 09cd37a001..dc1e580724 100644--- a/spree/core/app/services/spree/tax/resolve_exemptions.rb+++ b/spree/core/app/services/spree/tax/resolve_exemptions.rb@@ -29,9 +29,18 @@ module Spreereturn success([]) if company.nil? || address.nil?success(- company.tax_exemption_certificates.active.for_address(address).map do |certificate|+ company.tax_exemption_certificates.active.for_address(address).includes(:tax_exemption_reason).filter_map do |certificate|+ reason = certificate.tax_exemption_reason+ # A certificate recorded before reasons existed keeps its old code+ # until `spree:upgrade:tax_exemption_reasons` links it. One with+ # neither (its reason row removed outside the app) is skipped+ # rather than failing tax for every order of the company.+ reason_code = reason&.code || certificate.reason_code+ next if reason_code.blank?+Spree::TaxExemption.new(- reason_code: certificate.reason_code,+ reason_code: reason_code,+ reason_name: reason&.name,certificate_number: certificate.certificate_number,country_code: certificate.country_code,state_code: certificate.state_codediff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rbindex 6c3071aa3c..ae685da729 100644--- a/spree/core/app/workflows/spree/carts/complete.rb+++ b/spree/core/app/workflows/spree/carts/complete.rb@@ -77,6 +77,13 @@ module Spreedef complete_draft_orderresult = Spree.order_complete_workflow.call(order: cart, payment_pending: payment_pending)failure(result.value, result.error) if result.failure?++ # A draft leaves before FINALIZE, so the document that phase files is+ # filed here — otherwise it charged tax that never reached the return.+ # Never split, so it is the only order to file.+ @order = result.value+ external_step :commit_tax+halt!(result.value)end@@ -141,6 +148,26 @@ module Spreedef recalculate_in_lockSpree::Carts::PriceItems.apply(@confirmed_prices) if @confirmed_prices.present?cart.recalculate_totals!+ rescue Spree::Tax::ProviderError => error+ # The engine that decides this sale's tax did not produce any.+ # Completing anyway would place an order whose tax nobody computed, so+ # the sale is refused — as a failure the caller can render, not as an+ # exception that reads like a broken checkout.+ Rails.error.report(error, context: { order_id: cart.id }, source: 'spree.checkout')++ if error.is_a?(Spree::Tax::CalculationRefused)+ # The engine said no to this request. Its message names the problem —+ # the postcode, the missing company code — and asking the customer to+ # retry would be asking them to repeat something that cannot work.+ failure(cart, code: 'tax_calculation_refused', message: error.message.to_s)+ else+ # It could not be asked. Retrying may work, and the reason belongs in+ # the error tracker rather than the response: the raw message names+ # the endpoint and the transport, which tells a shopper nothing and+ # tells everyone else too much.+ failure(cart, code: 'tax_provider_unavailable',+ message: I18n.t('spree.cart_line_item.tax_unavailable'))+ endenddef verify_expected_total@@ -253,9 +280,10 @@ module Spreeline_item_map = copy_line_items!(cart, order)fulfillment_map = copy_fulfillments!(cart, order, line_item_map)- copy_typed_lines!(cart, order, line_item_map, fulfillment_map)+ fee_map = copy_typed_lines!(cart, order, line_item_map, fulfillment_map)copy_promotions!(cart, order)copy_tax_identifier!(cart, order)+ copy_tax_exemptions!(cart, order, line_item_map, fulfillment_map, fee_map)copy_po_document!(cart, order)repoint_money_records!(cart, order)@@ -290,6 +318,71 @@ module Spreeorder.create_tax_identifier!(attributes.merge('source' => source_of(resolved)))end+ # Freezes the exemption evidence the sale was priced with, beside the+ # registration and for the same reason. A certificate lapses on its own+ # date with nothing written to it, can be revoked, and is destroyed with+ # its company — so a provider re-resolving at commit or refund time would+ # file a credit for an exempt sale as a consumer refund and declare tax+ # that was never collected. Read from the cart, which is what was priced.+ #+ # An empty list is still written: "found no claim" and "placed before this+ # existed" are different facts, and the reader tells them apart.+ def copy_tax_exemptions!(cart, order, line_item_map, fulfillment_map, fee_map)+ translation = exemption_item_ids(line_item_map, fulfillment_map, fee_map)+ claims = cart.usable_exemptions.map { |claim| reown_claim(claim, translation) }++ order.update_column(:applied_tax_exemptions, claims)+ end++ # An override names its line by prefixed id, and completion mints new ones.+ # Left as the cart's it matches nothing — which widens the claim rather+ # than narrowing it, exempting every line instead of carving one out.+ def reown_claim(claim, translation)+ snapshot = claim.to_snapshot+ overrides = Array(snapshot['item_overrides'])+ return snapshot if overrides.empty?++ snapshot.merge(+ 'item_overrides' => overrides.map do |override|+ reowned = translation[override['item_id'].to_s]+ next override.merge('item_id' => reowned) if reowned++ # It narrowed nothing while the cart was priced either, so it is+ # left alone and reported rather than dropped.+ report_unmatched_override(override)+ override+ end+ )+ end++ # Cart prefixed id → order prefixed id, encoded from the ids the copy maps+ # already carry rather than by reloading the records.+ def exemption_item_ids(line_item_map, fulfillment_map, fee_map)+ translation = {}++ line_item_map.each do |cart_line_item, order_line_item|+ translation[cart_line_item.prefixed_id] = order_line_item.prefixed_id+ end+ { Spree::Fulfillment => fulfillment_map, Spree::Fee => fee_map }.each do |klass, ids|+ ids.each do |cart_id, order_id|+ translation[klass.prefixed_id_for(cart_id)] = klass.prefixed_id_for(order_id)+ end+ end++ translation+ end++ def report_unmatched_override(override)+ Rails.error.report(+ Spree::Tax::UnusableExemptionError.new(+ "A tax exemption override named #{override['item_id'].inspect}, which is not part of this sale"+ ),+ handled: true,+ context: { item_id: override['item_id'] },+ source: 'spree.core'+ )+ end+# The buyer's purchase order follows the number onto the order. The same# blob is attached to both records rather than uploaded twice — the cart# keeps its copy so a completion that rolls back leaves the buyer's@@ -366,6 +459,9 @@ module Spree# Fees before tax lines, because a fee is something tax is charged on: a# tax line copied first would reach the order still naming the cart's# fee, and that row is then destroyed with it.+ #+ # @return [Hash{Integer => Integer}] cart fee id → order fee id, which an+ # exemption override may namedef copy_typed_lines!(cart, order, line_item_map, fulfillment_map)line_item_id_map = line_item_map.transform_keys(&:id).transform_values(&:id)fee_map = {}@@ -392,6 +488,8 @@ module Spreefee_map[row.id] = copy.id if klass == Spree::Feeendend++ fee_mapenddef copy_promotions!(cart, order)@@ -458,7 +556,16 @@ module Spree# separate sale with its own tax, and an unfiled sibling is a hole in the# merchant's return that only surfaces at filing time.def commit_tax- placed_orders.each { |placed| placed.tax_provider.commit(placed) }+ placed_orders.each do |placed|+ placed.tax_provider.commit(placed)+ rescue Spree::Tax::ProviderError => error+ # Deliberately not a failure. The order is placed and paid; refusing+ # now would leave the customer charged for a sale the platform denies+ # having taken. Filing is idempotent and replayable, so the document+ # can follow — an unfiled sale is a reporting gap to chase, not a+ # reason to break the checkout that produced it.+ Rails.error.report(error, context: { order_id: placed.id }, source: 'spree.checkout')+ endend# What this checkout produced: the children of a split, or the one orderdiff --git a/spree/core/app/workflows/spree/orders/cancel.rb b/spree/core/app/workflows/spree/orders/cancel.rbindex e5a2031fcd..6bbaafe88a 100644--- a/spree/core/app/workflows/spree/orders/cancel.rb+++ b/spree/core/app/workflows/spree/orders/cancel.rb@@ -253,8 +253,16 @@ module Spree# Reverses the filed tax document. The canceled sale must stop appearing# in the merchant's tax liability.+ #+ # Reported rather than raised, as `Carts::Complete` treats its filing. The+ # cancellation and its payments are already settled by now, and the steps+ # after this one update statuses and announce `order.canceled` — so+ # raising abandoned a cancelled order half-recorded. Void is idempotent, so+ # a standing document can follow.def void_taxorder.tax_provider.void(order)+ rescue Spree::Tax::ProviderError => error+ Rails.error.report(error, context: { order_id: order.id }, source: 'spree.orders.cancel')endendenddiff --git a/spree/core/app/workflows/spree/orders/complete.rb b/spree/core/app/workflows/spree/orders/complete.rbindex 6a3d751d12..81199de255 100644--- a/spree/core/app/workflows/spree/orders/complete.rb+++ b/spree/core/app/workflows/spree/orders/complete.rb@@ -43,6 +43,7 @@ module Spreestep :split_by_sellerstep :finalize_fulfillmentsstep :place_order+ step :freeze_tax_exemptionsstep :use_coupon_codesstep :redeem_gift_cardstep :fulfill_auto_fulfillments@@ -151,6 +152,13 @@ module Spreeorder.update!(status: 'placed', completed_at: Time.current)end+ # Pins what the sale was priced with, as `Carts::Complete` does for a cart.+ # A draft is its own source, so nothing needs translating — and it is the+ # path company certificates take, which left it resolving live at credit.+ def freeze_tax_exemptions+ order.update_column(:applied_tax_exemptions, order.usable_exemptions.map(&:to_snapshot))+ end+def use_coupon_codesSpree::CouponCodes::CouponCodesHandler.new(order: order).use_all_codesenddiff --git a/spree/core/app/workflows/spree/returns/refund.rb b/spree/core/app/workflows/spree/returns/refund.rbindex 816247b874..0446a8f263 100644--- a/spree/core/app/workflows/spree/returns/refund.rb+++ b/spree/core/app/workflows/spree/returns/refund.rb@@ -65,6 +65,10 @@ module Spree# The refunded amount goes with them, because it can be less than those# lines are worth — a restocking fee, or an agreed part-refund. Without it# a provider would credit the tax on goods whose value the merchant kept.+ # Reported rather than raised, as filing and voiding are: the money has+ # moved and the return is marked refunded by now, and `return.refunded`+ # follows — so raising failed a refund that had gone through, and lost the+ # event with it.def refund_taxreceived = return_record.return_line_items.select { |line| line.refund_amount.positive? }return if received.empty?diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex e5741705c9..0aaf55c210 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -429,6 +429,12 @@ en:attributes:company:must_be_legal_entity: must be a legal entity, not a division+ tax_exemption_reason:+ not_offered: is not a tax exemption reason this store offers+ spree/tax_exemption_reason:+ attributes:+ base:+ in_use: is recorded on tax exemption certificates and cannot be deletedspree/tax_identifier:attributes:company:@@ -693,6 +699,7 @@ en:pricing_unavailable: Prices could not be confirmed. Please try again.quantity_must_be_positive: Quantity must be at least 1. Use DELETE to remove the item.quantity_rule_violated: "%{li_name} cannot be ordered in that quantity. Try %{quantities}."+ tax_unavailable: Tax could not be calculated. Please try again.catalogs:no_price_list_to_import: This catalog has no price list to import products from.product_not_in_store: One of those products belongs to another store.@@ -1790,6 +1797,8 @@ en:gb_vat: UK VATus_ein: US EINtax_provider_unavailable: The tax service could not work out the tax to give back. Try again in a few minutes.+ tax_providers:+ internal: Spree tax ratesterms_of_service: Terms of Servicethere_are_no_items_for_this_order: There are no items for this ordertiered_flat_rate: Tiered Flat Ratediff --git a/spree/core/db/migrate/20260904100001_add_applied_tax_exemptions_to_spree_orders.rb b/spree/core/db/migrate/20260904100001_add_applied_tax_exemptions_to_spree_orders.rbnew file mode 100644index 0000000000..7d56d1e1e0--- /dev/null+++ b/spree/core/db/migrate/20260904100001_add_applied_tax_exemptions_to_spree_orders.rb@@ -0,0 +1,16 @@+class AddAppliedTaxExemptionsToSpreeOrders < ActiveRecord::Migration[8.1]+ # The exemption claims a placed order was priced with, frozen at completion+ # beside its tax registration. Certificates lapse on their own date with+ # nothing written to them, can be revoked, and are destroyed with their+ # company — so resolving them again when a provider files or credits the sale+ # is not the evidence the sale was priced with.+ def change+ change_table :spree_orders, bulk: true do |t|+ if t.respond_to?(:jsonb)+ t.jsonb :applied_tax_exemptions+ else+ t.json :applied_tax_exemptions+ end+ end+ end+enddiff --git a/spree/core/db/migrate/20261016100001_create_spree_tax_exemption_reasons.rb b/spree/core/db/migrate/20261016100001_create_spree_tax_exemption_reasons.rbnew file mode 100644index 0000000000..862b64acfd--- /dev/null+++ b/spree/core/db/migrate/20261016100001_create_spree_tax_exemption_reasons.rb@@ -0,0 +1,21 @@+class CreateSpreeTaxExemptionReasons < ActiveRecord::Migration[8.1]+ def change+ create_table :spree_tax_exemption_reasons do |t|+ t.references :store, null: false, index: false+ t.string :name, null: false+ t.string :code, null: false+ t.boolean :active, null: false, default: true+ if t.respond_to?(:jsonb)+ t.jsonb :metadata+ else+ t.json :metadata+ end+ t.timestamps+ end++ add_index :spree_tax_exemption_reasons, [:store_id, :name], unique: true,+ name: 'idx_tax_exemption_reasons_on_store_and_name'+ add_index :spree_tax_exemption_reasons, [:store_id, :code], unique: true,+ name: 'idx_tax_exemption_reasons_on_store_and_code'+ end+enddiff --git a/spree/core/db/migrate/20261017100001_add_tax_exemption_reason_to_spree_tax_exemption_certificates.rb b/spree/core/db/migrate/20261017100001_add_tax_exemption_reason_to_spree_tax_exemption_certificates.rbnew file mode 100644index 0000000000..5525163771--- /dev/null+++ b/spree/core/db/migrate/20261017100001_add_tax_exemption_reason_to_spree_tax_exemption_certificates.rb@@ -0,0 +1,9 @@+class AddTaxExemptionReasonToSpreeTaxExemptionCertificates < ActiveRecord::Migration[8.1]+ def change+ # Nullable, and reason_code kept: certificates recorded before reasons+ # existed are linked by `spree:upgrade:tax_exemption_reasons`, which reads+ # their reason_code.+ add_reference :spree_tax_exemption_certificates, :tax_exemption_reason+ change_column_null :spree_tax_exemption_certificates, :reason_code, true+ end+enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex cfc3a0d791..4057b2d7a9 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -362,7 +362,6 @@ module Spree# @return [Class]singleton_class.delegate :password_validator, :password_validator=, to: :spree_config-# Commission rule kinds selectable on a commission rate.## @return [Array<Class>]@@ -684,5 +683,5 @@ require 'spree/core/model_extensions'require 'spree/core/ransack_configuration'require 'spree/core/pricing/context'require 'spree/core/pricing/price_resolution'-require 'spree/core/pricing/resolver'require 'spree/core/tax/provider_error'+require 'spree/core/pricing/resolver'diff --git a/spree/core/lib/spree/core/permissions/default_catalog.rb b/spree/core/lib/spree/core/permissions/default_catalog.rbindex 50ef873f76..f6211dc61a 100644--- a/spree/core/lib/spree/core/permissions/default_catalog.rb+++ b/spree/core/lib/spree/core/permissions/default_catalog.rb@@ -167,7 +167,7 @@ module SpreeSpree::StockLocation, Spree::DeliveryProfile,Spree::Market, Spree::TaxCategory, Spree::TaxRate, Spree::AllowedOrigin,Spree::RefundReason, Spree::ReturnReason, Spree::ClaimReason,- Spree::OrderCancellationReason, Spree::Channel,+ Spree::OrderCancellationReason, Spree::TaxExemptionReason, Spree::Channel,Spree::OrderRoutingRule, Spree::CustomFieldDefinition, Spree::Policy]})diff --git a/spree/core/lib/spree/service_module.rb b/spree/core/lib/spree/service_module.rbindex 524059de92..dd4e1f086b 100644--- a/spree/core/lib/spree/service_module.rb+++ b/spree/core/lib/spree/service_module.rb@@ -26,10 +26,21 @@ module SpreeResultError = Struct.new(:value) dodef to_sreturn value.full_messages.join(', ') if value&.respond_to?(:full_messages)+ # A failure carrying a code beside its message (`failure(cart, code:,+ # message:)`) reads as the message, not as the hash it travels in.+ return value[:message].to_s if value.is_a?(Hash) && value.key?(:message)value.to_send+ # The machine-readable reason a failure named, when it named one, so a+ # caller can answer an outage differently from a refusal.+ #+ # @return [String, nil]+ def code+ value[:code]&.to_s if value.is_a?(Hash)+ end+def to_hreturn value.messages if value&.respond_to?(:messages)diff --git a/spree/core/lib/spree/testing_support/factories/tax_exemption_certificate_factory.rb b/spree/core/lib/spree/testing_support/factories/tax_exemption_certificate_factory.rbindex e21940e639..17e389e097 100644--- a/spree/core/lib/spree/testing_support/factories/tax_exemption_certificate_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/tax_exemption_certificate_factory.rb@@ -2,9 +2,21 @@ FactoryBot.define dofactory :tax_exemption_certificate, class: Spree::TaxExemptionCertificate docompanysequence(:certificate_number) { |n| "CERT-#{n}" }- reason_code { 'resale' }status { 'pending' }+ transient do+ reason_code { 'RESALE' }+ end++ # A certificate may only record a reason its store offers, so the reason+ # is found or created in the company's store for whichever code a spec+ # picks.+ tax_exemption_reason do+ company.store.tax_exemption_reasons.find_or_create_by!(code: reason_code.to_s.upcase) do |reason|+ reason.name = reason_code.to_s.humanize+ end+ end+trait :verified dostatus { 'verified' }verified_at { Time.current }diff --git a/spree/core/lib/spree/testing_support/factories/tax_exemption_reason_factory.rb b/spree/core/lib/spree/testing_support/factories/tax_exemption_reason_factory.rbnew file mode 100644index 0000000000..f1c1f02b8b--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/tax_exemption_reason_factory.rb@@ -0,0 +1,8 @@+FactoryBot.define do+ factory :tax_exemption_reason, class: Spree::TaxExemptionReason do+ store { Spree::Store.find_by(default: true) || association(:store) }+ sequence(:name) { |n| "Tax Exemption Reason #{n}" }+ sequence(:code) { |n| "REASON_#{n}" }+ active { true }+ end+enddiff --git a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.ymlindex 19ca45eac2..61568532fe 100644--- a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml@@ -683,6 +683,22 @@ steps:Idempotent — a store that already has a default package type is leftalone, so a box edited since the upgrade is never overwritten.+ - id: tax_exemption_reasons+ name: "Give every store the default tax exemption reasons and link certificates to them"+ task: "spree:upgrade:tax_exemption_reasons"+ notes: |+ Company tax exemption certificates point at one of the store's+ exemption reasons, so a store without any cannot record a certificate.+ Existing reason codes are saved in capitals, the way tax engines compare+ them. Certificates recorded before reasons existed are linked to the+ reason matching their old reason code; a code no reason holds gets a+ reason of its own. Merchants using an external tax engine change each+ reason's code to that engine's under Settings → Taxes → Exemption+ reasons.++ Idempotent — a reason the merchant already has under the same code or+ name is left alone, and a certificate already linked is skipped.+- id: migrate_external_receives_to_purchase_ordersname: "Turn 5.x supplier receives into purchase orders, and give every transfer a store"task: "spree:upgrade:migrate_external_receives_to_purchase_orders"diff --git a/spree/core/lib/tasks/tax_exemption_reasons.rake b/spree/core/lib/tasks/tax_exemption_reasons.rakenew file mode 100644index 0000000000..dd832267b9--- /dev/null+++ b/spree/core/lib/tasks/tax_exemption_reasons.rake@@ -0,0 +1,48 @@+namespace :spree do+ namespace :upgrade do+ desc <<~DESC+ Gives every store the default tax exemption reasons, saves existing+ reason codes in capitals, and links each existing certificate to the+ reason matching its old reason code (Spree 6.0).++ A code no reason holds gets a reason of its own, named after the code.+ Idempotent: reasons the merchant already has are left alone, and a+ certificate already linked is skipped.+ DESC+ task tax_exemption_reasons: :environment do+ # Codes are stored in capitals since tax engines compare them that way;+ # a lookup by code reads capitals too, so a lower-case row would never+ # be found again. Runs before seeding so the seed finds these by code.+ Spree::TaxExemptionReason.find_each do |reason|+ code = Spree::TaxExemptionReason.normalize_value_for(:code, reason.code)+ next if code == reason.code++ if Spree::TaxExemptionReason.where(store_id: reason.store_id).where.not(id: reason.id).exists?(code: code)+ puts " Left tax exemption reason #{reason.prefixed_id} as #{reason.code}: #{code} is taken in its store"+ else+ reason.update_columns(code: code, updated_at: Time.current)+ end+ end++ Spree::Store.find_each do |store|+ Spree::Seeds::TaxExemptionReasons.call(store: store)+ end++ linked = 0++ Spree::TaxExemptionCertificate.where(tax_exemption_reason_id: nil).where.not(reason_code: [nil, '']).+ includes(company: :store).find_each do |certificate|+ reasons = certificate.company.store.tax_exemption_reasons+ code = Spree::TaxExemptionReason.normalize_value_for(:code, certificate.reason_code)+ name = code.humanize+ name = "#{name} (#{code})" if reasons.where.not(code: code).exists?(name: name)++ reason = reasons.find_or_create_by!(code: code) { |new_reason| new_reason.name = name }+ certificate.update_columns(tax_exemption_reason_id: reason.id, updated_at: Time.current)+ linked += 1+ end++ puts " Linked #{linked} tax exemption certificate(s) to their reason" if linked.positive?+ end+ end+enddiff --git a/spree/core/spec/lib/spree/service_module_spec.rb b/spree/core/spec/lib/spree/service_module_spec.rbindex 3ac0650235..3287d033c4 100644--- a/spree/core/spec/lib/spree/service_module_spec.rb+++ b/spree/core/spec/lib/spree/service_module_spec.rb@@ -216,4 +216,17 @@ describe Spree::ServiceModule doexpect { service.call }.to raise_error(Spree::ServiceModule::IncompatibleParamsPassed)endend++ describe Spree::ServiceModule::ResultError do+ it 'reads a failure carrying a code as its message, and exposes the code' do+ error = described_class.new({ code: 'tax_provider_unavailable', message: 'Tax could not be calculated' })++ expect(error.to_s).to eq('Tax could not be calculated')+ expect(error.code).to eq('tax_provider_unavailable')+ end++ it 'has no code for a plain message' do+ expect(described_class.new('Something went wrong').code).to be_nil+ end+ endenddiff --git a/spree/core/spec/lib/tasks/tax_exemption_reasons_spec.rb b/spree/core/spec/lib/tasks/tax_exemption_reasons_spec.rbnew file mode 100644index 0000000000..0556ff0361--- /dev/null+++ b/spree/core/spec/lib/tasks/tax_exemption_reasons_spec.rb@@ -0,0 +1,73 @@+require 'spec_helper'+require 'rake'++describe 'spree:upgrade:tax_exemption_reasons' do+ subject { Rake::Task['spree:upgrade:tax_exemption_reasons'] }++ before(:all) do+ Rake::Task.define_task(:environment)+ load Spree::Core::Engine.root.join('lib', 'tasks', 'tax_exemption_reasons.rake')+ end++ before { subject.reenable }++ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }++ # A code saved before codes were upper-cased. Written as SQL because the+ # normalizer upper-cases hash values even in update_all.+ def legacy_code(reason, code)+ Spree::TaxExemptionReason.where(id: reason.id).update_all(['code = ?', code])+ end++ # What a certificate recorded before reasons existed looks like.+ def legacy_certificate(reason_code)+ create(:tax_exemption_certificate, company: company).tap do |certificate|+ certificate.update_columns(tax_exemption_reason_id: nil, reason_code: reason_code)+ end+ end++ it 'gives the store the default reasons' do+ subject.invoke++ expect(store.tax_exemption_reasons.pluck(:code)).to include(*Spree::Seeds::TaxExemptionReasons::REASONS.keys)+ end++ it 'saves a lower-case code in capitals' do+ reason = create(:tax_exemption_reason, store: store, name: 'Diplomatic')+ legacy_code(reason, 'diplomatic')++ subject.invoke++ expect(reason.reload.code).to eq('DIPLOMATIC')+ end++ # MySQL compares codes without regard to case, so its unique index already+ # refuses a lower-case twin and the clash cannot exist there.+ it 'leaves a lower-case code alone when its capitals are taken',+ skip: (ActiveRecord::Base.connection.adapter_name.match?(/mysql/i) && 'MySQL codes are case-insensitive') do+ create(:tax_exemption_reason, store: store, code: 'DIPLOMATIC', name: 'Diplomatic')+ reason = create(:tax_exemption_reason, store: store, name: 'Embassy')+ legacy_code(reason, 'diplomatic')++ expect { subject.invoke }.to output(/DIPLOMATIC is taken/).to_stdout++ expect(reason.reload.code).to eq('diplomatic')+ end++ it 'links a certificate to the reason matching its old code' do+ certificate = legacy_certificate('resale')++ expect { subject.invoke }.to output(/Linked 1/).to_stdout++ expect(certificate.reload.tax_exemption_reason.code).to eq('RESALE')+ end++ it 'creates a reason for a code no reason holds' do+ certificate = legacy_certificate('diplomatic')++ expect { subject.invoke }.to output.to_stdout++ expect(certificate.reload.tax_exemption_reason).to have_attributes(code: 'DIPLOMATIC', name: 'Diplomatic')+ end+enddiff --git a/spree/core/spec/models/concerns/spree/publishable_spec.rb b/spree/core/spec/models/concerns/spree/publishable_spec.rbindex 6b5b4811ca..e62303dff6 100644--- a/spree/core/spec/models/concerns/spree/publishable_spec.rb+++ b/spree/core/spec/models/concerns/spree/publishable_spec.rb@@ -215,13 +215,13 @@ RSpec.describe Spree::Publishable, events: true dodescribe '#event_prefix' dobefore do- stub_const('Spree::Product', publishable_class)+ stub_const('Spree::TestProduct', publishable_class)endit 'returns the model name element' do- instance = Spree::Product.new+ instance = Spree::TestProduct.new- expect(instance.event_prefix).to eq('product')+ expect(instance.event_prefix).to eq('test_product')endenddiff --git a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rbindex 5c61580708..ced9972983 100644--- a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb+++ b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb@@ -207,5 +207,63 @@ RSpec.describe Spree::Purchase::Taxation doexpect(record.reload.resolved_tax_identifier).to eq(snapshot)endend++ # A certificate lapses on its own date with nothing written to it, so a+ # credit filed months later must read what the sale was priced with rather+ # than what resolves on the day.+ describe '#usable_exemptions on a placed order' do+ let(:record) { create(:completed_order_with_totals) }++ # A resolver answering something the snapshot never contains, so which+ # source was read is visible in the result rather than in a call count —+ # completing an order resolves exemptions of its own accord.+ before do+ live = Spree::TaxExemption.new(reason_code: 'resolved_live')+ allow(Spree).to receive(:tax_resolve_exemptions_service).and_return(+ class_double(Spree::Tax::ResolveExemptions,+ new: instance_double(Spree::Tax::ResolveExemptions, call: double(value: [live])))+ )+ end++ it 'answers from its frozen claims instead of resolving again' do+ record.update_column(:applied_tax_exemptions,+ [{ 'reason_code' => 'resale', 'certificate_number' => 'CERT-1',+ 'country_code' => 'US', 'state_code' => 'CA', 'item_overrides' => [] }])++ claim = record.reload.usable_exemptions.sole++ expect(claim).to be_a(Spree::TaxExemption)+ expect(claim.reason_code).to eq('resale')+ expect(claim.certificate_number).to eq('CERT-1')+ expect(claim.covers_jurisdiction?('US', 'CA')).to be(true)+ expect(claim.covers_jurisdiction?('US', 'NY')).to be(false)+ end++ it 'rebuilds the per-line carve-outs a claim was narrowed by' do+ line_item = record.line_items.first+ record.update_column(:applied_tax_exemptions,+ [{ 'reason_code' => 'resale', 'item_overrides' => [+ { 'item_id' => line_item.prefixed_id, 'exempt' => false, 'reason_code' => nil }+ ] }])++ claim = record.reload.usable_exemptions.sole++ expect(claim.covers_item?(line_item)).to be(false)+ end++ # An empty snapshot records "found no claim", not an absence. Read as+ # absent, a certificate added later would explain a sale it never touched.+ it 'keeps answering nothing when it froze nothing' do+ record.update_column(:applied_tax_exemptions, [])++ expect(record.reload.usable_exemptions).to eq([])+ end++ # Only nil is the legacy state — orders placed before the column existed.+ it 'resolves live only when it holds no snapshot at all' do+ expect(record.applied_tax_exemptions).to be_nil+ expect(record.usable_exemptions.map(&:reason_code)).to eq(['resolved_live'])+ end+ endendenddiff --git a/spree/core/spec/models/spree/preference_schema/json_schema_spec.rb b/spree/core/spec/models/spree/preference_schema/json_schema_spec.rbindex 25e50aad1e..7c8f966c8d 100644--- a/spree/core/spec/models/spree/preference_schema/json_schema_spec.rb+++ b/spree/core/spec/models/spree/preference_schema/json_schema_spec.rb@@ -41,6 +41,16 @@ describe Spree::PreferenceSchema::JsonSchema doit 'turns choices into an enum' doexpect(property(Spree::Promotion::Rules::Product, :match_policy)).to include('type' => 'string', 'enum' => %w[any all none])+ expect(property(Spree::Promotion::Rules::Product, :match_policy)).not_to have_key('x-spree-choice-labels')+ end++ it 'labels choices declared as value => label' do+ definition = { type: :string, choices: { 'https://one.example' => 'One', 'https://two.example' => 'Two' } }++ expect(described_class.property_schema(definition, default: 'https://one.example')).to include(+ 'enum' => %w[https://one.example https://two.example],+ 'x-spree-choice-labels' => { 'https://one.example' => 'One', 'https://two.example' => 'Two' }+ )endit 'marks a secret and never carries its default' dodiff --git a/spree/core/spec/models/spree/product/scopes_spec.rb b/spree/core/spec/models/spree/product/scopes_spec.rbindex 3878173ec4..80570632cb 100644--- a/spree/core/spec/models/spree/product/scopes_spec.rb+++ b/spree/core/spec/models/spree/product/scopes_spec.rb@@ -156,15 +156,12 @@ describe 'Product scopes', type: :model docreate_list(:product, 3, categories: [create(:category)])end+ # Products sharing a minimum position have no defined order between them.it 'orders products by ascending taxons minimum position' do- expect(ordered_products).to eq(- [- product_2, product_5, # position: 1- product_4, # position: 2- product_6, product_3, # position: 3- product_1 # position: 4- ]- )+ products = ordered_products.to_a++ expect(products.first(2)).to contain_exactly(product_2, product_5)+ expect(products.drop(2)).to eq([product_4, product_6, product_3, product_1])endenddiff --git a/spree/core/spec/models/spree/tax_exemption_certificate_spec.rb b/spree/core/spec/models/spree/tax_exemption_certificate_spec.rbindex 9757af8696..7fbe543b7a 100644--- a/spree/core/spec/models/spree/tax_exemption_certificate_spec.rb+++ b/spree/core/spec/models/spree/tax_exemption_certificate_spec.rb@@ -14,6 +14,31 @@ describe Spree::TaxExemptionCertificate, type: :model doexpect(create(:tax_exemption_certificate, company: company)).to be_pendingend+ describe 'reason' do+ let!(:reason) { create(:tax_exemption_reason, store: store, code: 'G') }++ it "must be one of the company's store's reasons" do+ foreign = create(:tax_exemption_reason, store: create(:store))+ certificate = described_class.new(company: company, certificate_number: 'C-1', tax_exemption_reason: foreign)++ expect(certificate).not_to be_valid+ expect(certificate.errors.details[:tax_exemption_reason]).to include(error: :not_offered)+ end++ it 'refuses a retired reason on a new certificate' do+ reason.update!(active: false)++ expect(described_class.new(company: company, certificate_number: 'C-1', tax_exemption_reason: reason)).not_to be_valid+ end++ it 'leaves a certificate valid when its reason is retired later' do+ certificate = create(:tax_exemption_certificate, company: company, tax_exemption_reason: reason)+ reason.update!(active: false)++ expect(certificate.reload).to be_valid+ end+ end+describe '.active' doit 'includes a verified certificate with no expiry' docertificate = create(:tax_exemption_certificate, :verified, company: company)diff --git a/spree/core/spec/models/spree/tax_exemption_reason_spec.rb b/spree/core/spec/models/spree/tax_exemption_reason_spec.rbnew file mode 100644index 0000000000..6f2118f2f5--- /dev/null+++ b/spree/core/spec/models/spree/tax_exemption_reason_spec.rb@@ -0,0 +1,58 @@+require 'spec_helper'++describe Spree::TaxExemptionReason, type: :model do+ it_behaves_like 'metadata'++ let(:store) { @default_store }+ let(:reason) { create(:tax_exemption_reason, store: store, code: 'G') }++ it 'keeps codes unique within a store, whatever their case' do+ reason++ expect(build(:tax_exemption_reason, store: store, code: ' g ')).not_to be_valid+ expect(build(:tax_exemption_reason, store: create(:store), code: 'G')).to be_valid+ end++ context 'when a certificate records it' do+ let!(:certificate) { create(:tax_exemption_certificate, company: create(:company, store: store), tax_exemption_reason: reason) }++ it 'can change its code, which the certificate follows' do+ expect(reason.update(code: 'N')).to be(true)+ expect(certificate.reload.tax_exemption_reason.code).to eq('N')+ end++ it 'cannot be deleted' do+ expect(reason.can_be_deleted?).to be(false)+ expect(reason.destroy).to be(false)+ expect(reason.errors.details[:base]).to include(error: :in_use)+ end+ end++ describe '.find_or_create_by_code_or_name!' do+ it 'finds a reason by its code' do+ reason++ expect(store.tax_exemption_reasons.find_or_create_by_code_or_name!(code: 'g', name: 'Resale')).to eq(reason)+ end++ it 'finds a reason by its name' do+ reason.update!(name: 'Resale')++ expect(store.tax_exemption_reasons.find_or_create_by_code_or_name!(code: 'RESALE', name: 'Resale')).to eq(reason)+ end++ it 'prefers the reason holding the code over one holding the name' do+ reason+ create(:tax_exemption_reason, store: store, code: 'WHOLESALE', name: 'Resale')++ expect(store.tax_exemption_reasons.find_or_create_by_code_or_name!(code: 'G', name: 'Resale')).to eq(reason)+ end++ it 'creates one when neither is taken' do+ created = store.tax_exemption_reasons.find_or_create_by_code_or_name!(code: 'e', name: 'Educational')++ expect(created).to be_persisted+ expect(created.code).to eq('E')+ end+ end+enddiff --git a/spree/core/spec/models/spree/tax_provider/base_spec.rb b/spree/core/spec/models/spree/tax_provider/base_spec.rbindex d4b39e89f9..c306560aec 100644--- a/spree/core/spec/models/spree/tax_provider/base_spec.rb+++ b/spree/core/spec/models/spree/tax_provider/base_spec.rb@@ -61,9 +61,10 @@ describe Spree::TaxProvider::Base, type: :model dohash = Spree::TaxProvider::Internal.to_api_hash(order.store)expect(hash[:id]).to eq('internal')- expect(hash[:name]).to eq('Internal')+ expect(hash[:name]).to eq('Spree tax rates')expect(hash[:available]).to be(true)expect(hash[:default]).to be(true)+ expect(hash[:exemption_reason_codes]).to be_nilexpect(hash[:unsupported_capabilities].map { |capability| capability[:key] }).to eq(%w[us_local_tax reverse_charge oss_thresholds proportional_delivery_tax])@@ -100,6 +101,16 @@ describe Spree::TaxProvider::Base, type: :model doexpect(SpreeTaxAvalara::TaxProvider.to_api_hash(order.store)[:name]).to eq('Avalara AvaTax')expect(SpreeTaxAvalara::TaxProvider.to_api_hash(order.store)[:default]).to be(false)end++ it 'offers the exemption reason codes an engine reads' do+ stub_const('SpecCodedProvider', Class.new(described_class) do+ def self.exemption_reason_codes+ { 'G' => 'RESALE' }+ end+ end)++ expect(SpecCodedProvider.to_api_hash(order.store)[:exemption_reason_codes]).to eq([{ value: 'G', label: 'RESALE' }])+ endenddescribe 'Spree.default_tax_provider' dodiff --git a/spree/core/spec/models/spree/tax_provider/internal_spec.rb b/spree/core/spec/models/spree/tax_provider/internal_spec.rbindex 3938e0bf7b..7442134093 100644--- a/spree/core/spec/models/spree/tax_provider/internal_spec.rb+++ b/spree/core/spec/models/spree/tax_provider/internal_spec.rb@@ -174,7 +174,7 @@ describe Spree::TaxProvider::Internal, type: :model dotax_line = order.tax_lines.reload.soleexpect(tax_line.amount).to eq(0)expect(tax_line.taxability_reason).to eq('customer_exempt')- expect(tax_line.data['exemption']).to eq('reason_code' => 'resale', 'certificate_number' => 'CERT-9')+ expect(tax_line.data['exemption']).to eq('reason_code' => 'RESALE', 'reason_name' => 'Resale', 'certificate_number' => 'CERT-9')endit 'taxes normally while the certificate is still awaiting verification' dodiff --git a/spree/core/spec/services/spree/carts/update_spec.rb b/spree/core/spec/services/spree/carts/update_spec.rbindex 3ed0dff199..b1c056eae7 100644--- a/spree/core/spec/services/spree/carts/update_spec.rb+++ b/spree/core/spec/services/spree/carts/update_spec.rb@@ -11,6 +11,28 @@ module Spreedescribe '#call' dosubject { described_class.call(cart: cart, params: params) }+ # Swallowing this used to save the address and show a total with no tax,+ # so the customer only met the problem when they tried to pay — and met it+ # as an exception. A destination whose tax nobody could compute is not a+ # destination worth keeping.+ it 'refuses an address change when the tax engine cannot be reached' do+ address = create(:address, state_code: 'NY', country_code: 'US', zipcode: '10001')+ cart_under_test = cart+ provider = instance_double(Spree::TaxProvider::Internal)+ allow(provider).to receive(:estimate).+ and_raise(Spree::Tax::ProviderUnavailable.new('could not be reached'))+ allow_any_instance_of(Spree::Cart).to receive(:tax_provider).and_return(provider)++ result = described_class.call(cart: cart_under_test,+ params: { shipping_address_id: address.prefixed_id })++ expect(result).to be_failure+ expect(result.error.to_s).to include('Tax could not be calculated')+ # The API answers this code with 503, the status a client retries.+ expect(result.error.code).to eq('tax_provider_unavailable')+ expect(cart_under_test.reload.ship_address_id).not_to eq(address.id)+ end+describe 'updating email' dolet(:params) { { email: '[email protected]' } }diff --git a/spree/core/spec/services/spree/seeds/all_spec.rb b/spree/core/spec/services/spree/seeds/all_spec.rbindex b761f9cd31..f4651b1038 100644--- a/spree/core/spec/services/spree/seeds/all_spec.rb+++ b/spree/core/spec/services/spree/seeds/all_spec.rb@@ -43,6 +43,7 @@ RSpec.describe Spree::Seeds::All doexpect(Spree::ReturnReason.where(store: store).count).to eq(Spree::Seeds::ReturnsEnvironment::RETURN_REASONS.count)expect(Spree::ClaimReason.where(store: store).count).to eq(Spree::Seeds::ReturnsEnvironment::CLAIM_REASONS.count)expect(Spree::RefundReason.where(store: store)).to exist+ expect(store.tax_exemption_reasons.pluck(:code)).to match_array(Spree::Seeds::TaxExemptionReasons::REASONS.keys)expect(Spree::ProductType.where(store: store)).to existenddiff --git a/spree/core/spec/services/spree/seeds/tax_exemption_reasons_spec.rb b/spree/core/spec/services/spree/seeds/tax_exemption_reasons_spec.rbnew file mode 100644index 0000000000..bf915b7c21--- /dev/null+++ b/spree/core/spec/services/spree/seeds/tax_exemption_reasons_spec.rb@@ -0,0 +1,21 @@+require 'spec_helper'++RSpec.describe Spree::Seeds::TaxExemptionReasons do+ let(:store) { @default_store }++ it 'keeps a reason the merchant renamed' do+ store.tax_exemption_reasons.create!(code: 'resale', name: 'Reseller (wholesale)')++ described_class.call(store: store)++ expect(store.tax_exemption_reasons.find_by(code: 'RESALE').name).to eq('Reseller (wholesale)')+ expect(store.tax_exemption_reasons.count).to eq(described_class::REASONS.size)+ end++ it 'keeps a reason the merchant recoded' do+ store.tax_exemption_reasons.create!(code: 'G', name: 'Resale')++ expect { described_class.call(store: store) }.not_to raise_error+ expect(store.tax_exemption_reasons.find_by(name: 'Resale').code).to eq('G')+ end+enddiff --git a/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb b/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rbindex 4d16fb7e98..04958b5d3f 100644--- a/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb+++ b/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb@@ -32,7 +32,8 @@ describe Spree::Tax::ResolveExemptions doexemption = described_class.call(order: order.reload).value.sole- expect(exemption.reason_code).to eq('resale')+ expect(exemption.reason_code).to eq('RESALE')+ expect(exemption.reason_name).to eq('Resale')expect(exemption.certificate_number).to eq('DE-RESALE-1')expect(exemption.country_code).to eq('DE')expect(exemption.state_code).to eq('BE')@@ -43,7 +44,22 @@ describe Spree::Tax::ResolveExemptions docreate(:tax_exemption_certificate, :verified, company: company, reason_code: 'government')expect(described_class.call(order: order.reload).value.map(&:reason_code)).- to contain_exactly('resale', 'government')+ to contain_exactly('RESALE', 'GOVERNMENT')+ end++ # Recorded before reasons existed and not yet linked by the upgrade step.+ it 'claims with the old code of a certificate not linked to a reason' do+ certificate = create(:tax_exemption_certificate, :verified, company: company)+ certificate.update_columns(tax_exemption_reason_id: nil, reason_code: 'G')++ expect(described_class.call(order: order.reload).value.sole).to have_attributes(reason_code: 'G', reason_name: nil)+ end++ it 'skips a certificate whose reason is gone, rather than failing' do+ certificate = create(:tax_exemption_certificate, :verified, company: company)+ certificate.update_columns(tax_exemption_reason_id: certificate.tax_exemption_reason_id.to_i + 1_000, reason_code: nil)++ expect(described_class.call(order: order.reload).value).to eq([])endit 'ignores a certificate awaiting verification' dodiff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rbindex b48b8e778a..0d75c56bb9 100644--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb@@ -191,6 +191,61 @@ module Spreeexpect(provider).to have_received(:commit).with(order)end+ # An engine that cannot answer must not read to a customer as a broken+ # checkout: before this, the exception escaped as a 500 and a storefront+ # could not tell an outage from a platform bug.+ it 'refuses the sale when the tax engine cannot be reached' do+ # Built before the stub: creating a line item estimates tax, so a+ # provider that raises would take the factory down instead of the sale.+ cart = ready_cart+ provider = instance_double(Spree::TaxProvider::Internal, commit: nil)+ allow(provider).to receive(:estimate).+ and_raise(Spree::Tax::ProviderUnavailable.new('could not be reached', provider_key: 'probe'))+ allow_any_instance_of(Spree::Cart).to receive(:tax_provider).and_return(provider)++ result = described_class.call(cart: cart)++ expect(result).to be_failure+ expect(result.error.value[:code]).to eq('tax_provider_unavailable')+ # The endpoint and the transport stay out of the response.+ expect(result.error.value[:message]).not_to include('could not be reached')+ expect(cart.reload).not_to be_completed+ end++ # The other half of the split: the engine answered and said no, so there+ # is nothing to retry and its own message is what the customer needs.+ it 'passes on what the engine said when it refuses the calculation' do+ cart = ready_cart+ provider = instance_double(Spree::TaxProvider::Internal, commit: nil)+ allow(provider).to receive(:estimate).and_raise(+ Spree::Tax::CalculationRefused.new('Zip is not valid for the state.', provider_key: 'probe')+ )+ allow_any_instance_of(Spree::Cart).to receive(:tax_provider).and_return(provider)++ result = described_class.call(cart: cart)++ expect(result).to be_failure+ expect(result.error.value[:code]).to eq('tax_calculation_refused')+ expect(result.error.value[:message]).to eq('Zip is not valid for the state.')+ end++ # The opposite call: the sale has happened and been paid for, so refusing+ # it now would deny a customer an order they were charged for. Filing is+ # idempotent, so the document can follow later.+ it 'still places the order when filing the sale fails' do+ cart = ready_cart+ provider = instance_double(Spree::TaxProvider::Internal, estimate: nil)+ allow(provider).to receive(:commit).+ and_raise(Spree::Tax::ProviderUnavailable.new('could not be reached'))+ allow_any_instance_of(Spree::Order).to receive(:tax_provider).and_return(provider)+ allow_any_instance_of(Spree::Cart).to receive(:tax_provider).and_return(provider)++ result = described_class.call(cart: cart)++ expect(result).to be_success+ expect(result.value).to be_completed+ end+it 'does not re-estimate while copying the cart onto the order' doprovider = instance_double(Spree::TaxProvider::Internal, estimate: nil, commit: nil)allow_any_instance_of(Spree::Order).to receive(:tax_provider).and_return(provider)@@ -352,6 +407,87 @@ module Spreeexpect(result.value.tax_identifier.value).to eq('GB123456789')end+ # The evidence has to survive the certificate it came from: it lapses on+ # its own date, so re-resolving at refund time would file a credit for an+ # exempt sale as a consumer refund.+ it 'freezes the exemptions the sale was priced with onto the order' do+ claim = Spree::TaxExemption.new(reason_code: 'RESALE', reason_name: 'Resale', certificate_number: 'CERT-9',+ country_code: 'US', state_code: 'CA')+ allow(Spree.tax_resolve_exemptions_service).to receive(:new).+ and_return(instance_double(Spree::Tax::ResolveExemptions,+ call: Spree::ServiceModule::Result.new(true, [claim], nil)))++ order = described_class.call(cart: ready_cart).value++ expect(order.applied_tax_exemptions).to eq(+ [{ 'reason_code' => 'RESALE', 'reason_name' => 'Resale', 'certificate_number' => 'CERT-9',+ 'country_code' => 'US', 'state_code' => 'CA', 'item_overrides' => [] }]+ )+ end++ # A draft leaves before FINALIZE, where the document is filed.+ it 'files a draft order with the tax engine' do+ draft = create(:order_ready_to_ship, store: store)+ draft.update_columns(status: 'draft', completed_at: nil)+ provider = instance_double(Spree::TaxProvider::Internal, commit: nil, estimate: nil)+ allow_any_instance_of(Spree::Order).to receive(:tax_provider).and_return(provider)++ expect(described_class.call(cart: draft)).to be_success+ expect(provider).to have_received(:commit).with(draft)+ end++ # An empty list, not nil: the reader has to tell "found no claim" apart+ # from an order placed before the column existed.+ it 'freezes an empty list when the sale claimed no exemption' do+ order = described_class.call(cart: ready_cart).value++ expect(order.applied_tax_exemptions).to eq([])+ end++ # Completion mints new prefixed ids, and an override that matches nothing+ # widens its claim instead of narrowing it — exempting every line.+ it 'renames a per-item carve-out onto the line the order now owns' do+ cart_line_item = ready_cart.line_items.first+ claim = Spree::TaxExemption.new(+ reason_code: 'resale',+ item_overrides: [Spree::TaxExemption::ItemOverride.new(item_id: cart_line_item.prefixed_id,+ exempt: false)]+ )+ allow(Spree.tax_resolve_exemptions_service).to receive(:new).+ and_return(instance_double(Spree::Tax::ResolveExemptions,+ call: Spree::ServiceModule::Result.new(true, [claim], nil)))++ order = described_class.call(cart: ready_cart).value+ order_line_item = order.line_items.first+ frozen = order.usable_exemptions.sole++ expect(order.applied_tax_exemptions.sole['item_overrides'].sole['item_id']).+ to eq(order_line_item.prefixed_id)+ expect(order_line_item.prefixed_id).not_to eq(cart_line_item.prefixed_id)+ expect(frozen.covers_item?(order_line_item)).to be(false)+ end++ # It narrowed nothing while the cart was priced either, so the order is+ # taxed the same way — and reported, since nobody can act on it.+ it 'reports a carve-out naming something the sale never had' do+ claim = Spree::TaxExemption.new(+ reason_code: 'resale',+ item_overrides: [Spree::TaxExemption::ItemOverride.new(item_id: 'li_notinthissale',+ exempt: false)]+ )+ allow(Spree.tax_resolve_exemptions_service).to receive(:new).+ and_return(instance_double(Spree::Tax::ResolveExemptions,+ call: Spree::ServiceModule::Result.new(true, [claim], nil)))+ allow(Rails.error).to receive(:report)++ order = described_class.call(cart: ready_cart).value++ expect(order.applied_tax_exemptions.sole['item_overrides'].sole['item_id']).+ to eq('li_notinthissale')+ expect(Rails.error).to have_received(:report).+ with(instance_of(Spree::Tax::UnusableExemptionError), hash_including(handled: true))+ end+it 'records a checkout override as such' docreate(:tax_identifier, owner: customer, kind: 'eu_vat', value: customer_vat)create(:tax_identifier, owner: ready_cart, kind: 'eu_vat', value: override_vat)diff --git a/spree/core/spec/workflows/spree/carts/complete_split_spec.rb b/spree/core/spec/workflows/spree/carts/complete_split_spec.rbindex 1fb2e6f5c5..bcf5c03c59 100644--- a/spree/core/spec/workflows/spree/carts/complete_split_spec.rb+++ b/spree/core/spec/workflows/spree/carts/complete_split_spec.rb@@ -101,6 +101,44 @@ module Spree# The buyer's reference and the paperwork behind it have to travel# together: the reference on every order with the document on only one+ # Each child pins claims of its own through Orders::Complete either way.+ # What the split must hand on is the *cart's* snapshot: resolving again+ # takes the resolver's cart-side override ids, which match nothing the+ # child owns — widening the claim over every line it holds.+ context 'when the sale was exempt for all but one line' do+ # A *sibling's* line: the adopted first partition keeps the cart's+ # snapshot anyway, so it would pass either way.+ let(:carved_out) { cart.line_items.reload.find { |item| item.seller_id == seller.id } }++ before do+ claim = Spree::TaxExemption.new(+ reason_code: 'resale', certificate_number: 'C-1',+ item_overrides: [Spree::TaxExemption::ItemOverride.new(item_id: carved_out.prefixed_id,+ exempt: false)]+ )+ allow(Spree.tax_resolve_exemptions_service).to receive(:new).+ and_return(instance_double(Spree::Tax::ResolveExemptions,+ call: Spree::ServiceModule::Result.new(true, [claim], nil)))+ end++ it 'hands every child the claims the cart was priced with' do+ group.orders.each do |order|+ expect(order.applied_tax_exemptions&.sole).to include('certificate_number' => 'C-1')+ end+ end++ it 'leaves the carve-out naming a line its own order holds' do+ # Completion copies line items, so the id no longer matches.+ owning = group.orders.find { |order| order.line_items.any? { |item| item.variant_id == carved_out.variant_id } }+ line_item = owning.line_items.find { |item| item.variant_id == carved_out.variant_id }+ named = owning.applied_tax_exemptions.sole['item_overrides'].sole['item_id']++ expect(named).to eq(line_item.prefixed_id)+ expect(named).not_to eq(carved_out.prefixed_id)+ expect(owning.usable_exemptions.sole.covers_item?(line_item)).to be(false)+ end+ end+# is the reconciliation problem the field exists to solve.context 'when the buyer supplied a purchase order' dobefore dodiff --git a/spree/core/spec/workflows/spree/orders/cancel_spec.rb b/spree/core/spec/workflows/spree/orders/cancel_spec.rbindex 96f6e82f0c..cdab2002f5 100644--- a/spree/core/spec/workflows/spree/orders/cancel_spec.rb+++ b/spree/core/spec/workflows/spree/orders/cancel_spec.rb@@ -130,6 +130,24 @@ module Spreeexpect(provider).to have_received(:void).with(order)end++ # The cancellation and its payments are settled before the void runs, and+ # the steps after it update statuses and announce it — so raising left a+ # cancelled order half-recorded and reported a failure.+ it 'cancels the order even when the tax engine cannot be reached' do+ provider = instance_double(Spree::TaxProvider::Internal, estimate: nil)+ allow(provider).to receive(:void).+ and_raise(Spree::Tax::ProviderUnavailable.new('Failed to open TCP connection'))+ allow(order).to receive(:tax_provider).and_return(provider)+ allow(Rails.error).to receive(:report)++ expect(result).to be_success+ expect(order.reload).to be_canceled+ # Void is idempotent, so a standing document can follow — but the gap+ # is reported rather than dropped.+ expect(Rails.error).to have_received(:report).+ with(instance_of(Spree::Tax::ProviderUnavailable), hash_including(source: 'spree.orders.cancel'))+ endend# A split checkout is the one flow where the refund amount is read: thediff --git a/spree/core/spec/workflows/spree/orders/complete_spec.rb b/spree/core/spec/workflows/spree/orders/complete_spec.rbindex a20056193d..506a82c8d5 100644--- a/spree/core/spec/workflows/spree/orders/complete_spec.rb+++ b/spree/core/spec/workflows/spree/orders/complete_spec.rb@@ -31,6 +31,38 @@ module Spreeexpect(line_item.price_source).to eq('manual')end+ # The path company certificates take: unpinned, it resolves live at credit.+ describe 'tax exemptions' do+ let(:draft) { create(:order_ready_to_ship, store: store).tap { |o| o.update_columns(status: 'draft', completed_at: nil) } }++ def resolving(claims)+ allow(Spree.tax_resolve_exemptions_service).to receive(:new).+ and_return(instance_double(Spree::Tax::ResolveExemptions,+ call: Spree::ServiceModule::Result.new(true, claims, nil)))+ end++ it 'pins the claims the draft was priced with' do+ resolving([Spree::TaxExemption.new(reason_code: 'resale', certificate_number: 'C-1',+ country_code: 'US', state_code: 'CA')])++ described_class.call(order: draft, payment_pending: true)++ expect(draft.reload.applied_tax_exemptions.sole).to include(+ 'reason_code' => 'resale', 'certificate_number' => 'C-1',+ 'country_code' => 'US', 'state_code' => 'CA'+ )+ end++ # An empty list, not nil: nil means "placed before this existed".+ it 'pins an empty list when it claimed nothing' do+ resolving([])++ described_class.call(order: draft, payment_pending: true)++ expect(draft.reload.applied_tax_exemptions).to eq([])+ end+ end+describe 'stock' dolet(:draft) { create(:order_ready_to_ship, store: store, line_items_count: 1) }let(:fulfillment) { draft.fulfillments.first }