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
Show why an order tax line is zero (#14530)
Damian Legawiec5d3520d800a1
diff --git a/.changeset/tax-line-exemption-reason.md b/.changeset/tax-line-exemption-reason.mdnew file mode 100644index 0000000000..2d211346ed--- /dev/null+++ b/.changeset/tax-line-exemption-reason.md@@ -0,0 +1,11 @@+---+"@spree/dashboard": patch+---++Show why an order tax line is zero.++The Taxes card now names the treatment (buyer exempt, zero-rated, and the+other recorded reasons) and, when the buyer is exempt, the certificate that+made it so. A completed order with no matching rate says so instead of+looking like a draft that has not been taxed yet, and the Summary card keeps+its tax row at zero so an exempt sale is still visible there.diff --git a/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsx b/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsxindex 03783a88d2..0ca945c6a2 100644--- a/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsx+++ b/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsx@@ -46,6 +46,11 @@ import {useOrderFees,useOrderTaxLines,} from '../../../hooks/use-order'+import {+ groupTaxLines,+ showsTaxabilityReason,+ type TaxLineGroup,+} from '../../../lib/tax-line-groups'import { FEE_KINDS } from '../../../schemas/order'/** The API accepts any kind string, so unknown values fall back to the raw value. */@@ -89,21 +94,40 @@ function AdjustmentDeleteCell({)}+/** The certificate line under an exempt tax row, or nothing. */+function taxExemptionDetail(group: TaxLineGroup): string | null {+ const number = group.exemption?.certificate_number+ if (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++ return reason+ ? i18n.t('admin.orders.detail.adjustment_lines.tax_exempt_certificate', {+ reason,+ number,+ })+ : i18n.t('admin.orders.detail.adjustment_lines.tax_exempt_certificate_number', {+ number,+ })+}+export function TaxLinesCard({ order }: { order: Order }) {const { t } = useTranslation()const orderId = order.id- const { data: taxLines } = useOrderTaxLines(orderId)-- // Tax rows grouped by label so a rate charged on many lines reads as one row.- const taxGroups = new Map<string, { label: string; amount: number }>()- for (const row of taxLines?.data ?? []) {- const existing = taxGroups.get(row.label)- if (existing) {- existing.amount += Number.parseFloat(row.amount)- } else {- taxGroups.set(row.label, { label: row.label, amount: Number.parseFloat(row.amount) })- }- }+ const { data: taxLines, isPending, isError, isSuccess } = useOrderTaxLines(orderId)+ const taxGroups = groupTaxLines(taxLines?.data ?? [])+ const emptyMessage = isPending+ ? t('admin.common.loading')+ : isError+ ? t('admin.errors.failed_to_load')+ : isSuccess && order.completed_at+ ? t('admin.orders.detail.adjustment_lines.taxes_unmatched')+ : t('admin.orders.detail.adjustment_lines.taxes_empty')return (<Card>@@ -111,11 +135,9 @@ export function TaxLinesCard({ order }: { order: Order }) {<CardTitle>{t('admin.orders.detail.adjustment_lines.taxes')}</CardTitle></CardHeader>- {taxGroups.size === 0 ? (+ {taxGroups.length === 0 ? (<CardContent>- <p className="text-sm text-muted-foreground">- {t('admin.orders.detail.adjustment_lines.taxes_empty')}- </p>+ <p className="text-sm text-muted-foreground">{emptyMessage}</p></CardContent>) : (<Table>@@ -128,18 +150,36 @@ export function TaxLinesCard({ order }: { order: Order }) {</TableRow></TableHeader><TableBody>- {[...taxGroups.values()].map((group) => (- <TableRow key={group.label}>- <TableCell>{group.label}</TableCell>- <TableCell className="text-right tabular-nums">- {formatPrice({- amount: group.amount.toFixed(2),- currency: order.currency,- display_amount: null,- })}- </TableCell>- </TableRow>- ))}+ {taxGroups.map((group) => {+ const detail = taxExemptionDetail(group)+ return (+ <TableRow key={group.key}>+ <TableCell>+ <div className="flex flex-col gap-0.5">+ <div className="flex flex-wrap items-center gap-2">+ <span>{group.label}</span>+ {showsTaxabilityReason(group) && (+ <Badge variant="secondary">+ {t(+ `admin.orders.detail.adjustment_lines.taxability_reason.${group.taxabilityReason}`,+ { defaultValue: group.taxabilityReason ?? undefined },+ )}+ </Badge>+ )}+ </div>+ {detail && <span className="text-xs text-muted-foreground">{detail}</span>}+ </div>+ </TableCell>+ <TableCell className="text-right tabular-nums">+ {formatPrice({+ amount: group.amount.toFixed(2),+ currency: order.currency,+ display_amount: null,+ })}+ </TableCell>+ </TableRow>+ )+ })}</TableBody></Table>)}diff --git a/packages/dashboard/src/components/spree/orders/order-summary-card.tsx b/packages/dashboard/src/components/spree/orders/order-summary-card.tsxindex 573267f3cd..e48fb88045 100644--- a/packages/dashboard/src/components/spree/orders/order-summary-card.tsx+++ b/packages/dashboard/src/components/spree/orders/order-summary-card.tsx@@ -164,7 +164,8 @@ export function OrderSummaryCard({ order }: { order: Order }) {/>)}- {Number.parseFloat(order.additional_tax_total) > 0 && (+ {(Number.parseFloat(order.additional_tax_total) > 0 ||+ (Boolean(order.completed_at) && Number.parseFloat(order.included_tax_total) === 0)) && (<SummaryRowlabel={t('admin.orders.detail.summary.tax_additional')}value={order.display_additional_tax_total}diff --git a/packages/dashboard/src/lib/tax-line-groups.test.ts b/packages/dashboard/src/lib/tax-line-groups.test.tsnew file mode 100644index 0000000000..b9fb772cb3--- /dev/null+++ b/packages/dashboard/src/lib/tax-line-groups.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it } from 'vitest'+import {+ type GroupableTaxLine,+ groupTaxLines,+ showsTaxabilityReason,+ taxLineExemption,+} from './tax-line-groups'++function taxLine(overrides: Partial<GroupableTaxLine> = {}): GroupableTaxLine {+ return {+ label: 'California Sales Tax 7.25%',+ amount: '8.70',+ taxability_reason: 'standard_rated',+ country_code: 'US',+ state_code: 'CA',+ data: {},+ ...overrides,+ }+}++describe('taxLineExemption', () => {+ it('reads the certificate snapshot from the provider payload', () => {+ expect(+ taxLineExemption(+ taxLine({+ data: {+ exemption: { reason_code: 'resale', certificate_number: 'CA-SR-100-284617' },+ },+ }),+ ),+ ).toEqual({ reason_code: 'resale', certificate_number: 'CA-SR-100-284617' })+ })++ it('returns null when the payload has no exemption', () => {+ expect(taxLineExemption(taxLine())).toBeNull()+ expect(taxLineExemption(taxLine({ data: null }))).toBeNull()+ expect(taxLineExemption(taxLine({ data: { exemption: 'resale' } }))).toBeNull()+ })+})++describe('groupTaxLines', () => {+ it('sums lines that share a label and the same treatment', () => {+ const groups = groupTaxLines([taxLine({ amount: '4.35' }), taxLine({ amount: '4.35' })])++ expect(groups).toHaveLength(1)+ expect(groups[0]?.amount).toBeCloseTo(8.7)+ expect(groups[0]?.taxabilityReason).toBe('standard_rated')+ })++ it('keeps an exempt row apart from a charged row with the same label', () => {+ const groups = groupTaxLines([+ taxLine({ amount: '8.70' }),+ taxLine({+ amount: '0.00',+ taxability_reason: 'customer_exempt',+ data: { exemption: { reason_code: 'resale', certificate_number: 'CA-SR-100-284617' } },+ }),+ ])++ expect(groups.map((group) => [group.taxabilityReason, group.amount])).toEqual([+ ['standard_rated', 8.7],+ ['customer_exempt', 0],+ ])+ expect(groups[1]?.exemption).toEqual({+ reason_code: 'resale',+ certificate_number: 'CA-SR-100-284617',+ })+ })++ it('keeps two certificates on the same rate as separate rows', () => {+ const groups = groupTaxLines([+ taxLine({+ amount: '0.00',+ taxability_reason: 'customer_exempt',+ data: { exemption: { reason_code: 'resale', certificate_number: 'CA-1' } },+ }),+ taxLine({+ amount: '0.00',+ taxability_reason: 'customer_exempt',+ data: { exemption: { reason_code: 'government', certificate_number: 'CA-2' } },+ }),+ ])++ expect(groups).toHaveLength(2)+ expect(groups[0]?.exemption?.certificate_number).toBe('CA-1')+ expect(groups[1]?.exemption?.certificate_number).toBe('CA-2')+ })+})++describe('showsTaxabilityReason', () => {+ it('hides the badge on a standard charged rate', () => {+ const [group] = groupTaxLines([taxLine()])+ expect(showsTaxabilityReason(group!)).toBe(false)+ })++ it('shows the badge for an exemption or a zero rate', () => {+ const [exempt] = groupTaxLines([+ taxLine({ amount: '0.00', taxability_reason: 'customer_exempt' }),+ ])+ const [zeroRated] = groupTaxLines([+ taxLine({ amount: '0.00', taxability_reason: 'zero_rated' }),+ ])++ expect(showsTaxabilityReason(exempt!)).toBe(true)+ expect(showsTaxabilityReason(zeroRated!)).toBe(true)+ })+})diff --git a/packages/dashboard/src/lib/tax-line-groups.ts b/packages/dashboard/src/lib/tax-line-groups.tsnew file mode 100644index 0000000000..1de46e2c04--- /dev/null+++ b/packages/dashboard/src/lib/tax-line-groups.ts@@ -0,0 +1,105 @@+/**+ * How tax rows are shown on an order: one rate charged on many lines+ * collapses to a single amount, but a different treatment (exempt vs+ * zero-rated vs standard) stays its own row so those cases do not look+ * identical.+ */++/** The tax-line fields the grouping reads. */+export interface GroupableTaxLine {+ label: string+ amount: string+ taxability_reason?: string | null+ country_code?: string | null+ state_code?: string | null+ data?: Record<string, unknown> | null+}++/** The exemption snapshot a tax provider stamps onto a line. */+export interface TaxLineExemption {+ reason_code?: string+ certificate_number?: string+}++/** One grouped tax row for the Taxes card. */+export interface TaxLineGroup {+ key: string+ label: string+ amount: number+ taxabilityReason: string | null+ exemption: TaxLineExemption | null+ countryCode: string | null+ stateCode: string | null+}++/**+ * The exemption claim the provider stored on this line, if any.+ *+ * @param row - A tax line as returned by the Admin API+ * @returns The certificate snapshot, or null when none was recorded+ */+export function taxLineExemption(row: GroupableTaxLine): TaxLineExemption | null {+ const raw = row.data?.exemption+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null++ const record = raw as Record<string, unknown>+ const reasonCode = typeof record.reason_code === 'string' ? record.reason_code : undefined+ const certificateNumber =+ typeof record.certificate_number === 'string' ? record.certificate_number : undefined+ if (!reasonCode && !certificateNumber) return null++ return { reason_code: reasonCode, certificate_number: certificateNumber }+}++/**+ * Groups tax lines that share a label *and* the same treatment. Two+ * California rates that one line paid and another was exempt from must+ * not collapse into a single $0.00 row.+ *+ * @param rows - Tax lines for one order+ * @returns Display groups in first-seen order+ */+export function groupTaxLines(rows: GroupableTaxLine[]): TaxLineGroup[] {+ const groups = new Map<string, TaxLineGroup>()++ for (const row of rows) {+ const exemption = taxLineExemption(row)+ const key = [+ row.label,+ row.taxability_reason ?? '',+ exemption?.certificate_number ?? '',+ exemption?.reason_code ?? '',+ ].join('\0')+ const parsed = Number.parseFloat(row.amount)+ const amount = Number.isFinite(parsed) ? parsed : 0+ const existing = groups.get(key)++ if (existing) {+ existing.amount += amount+ continue+ }++ groups.set(key, {+ key,+ label: row.label,+ amount,+ taxabilityReason: row.taxability_reason ?? null,+ exemption,+ countryCode: row.country_code ?? null,+ stateCode: row.state_code ?? null,+ })+ }++ return [...groups.values()]+}++/**+ * Whether the row's treatment is something an agent must see — a+ * standard positive charge is already explained by the rate label.+ *+ * @param group - A grouped tax row+ * @returns True when a reason badge should render+ */+export function showsTaxabilityReason(group: TaxLineGroup): boolean {+ return Boolean(group.taxabilityReason && group.taxabilityReason !== 'standard_rated')+}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 79cb9f4ce0..869a660bb6 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -2419,8 +2419,23 @@"percent_preview": "الخصم المقدر: {{amount}}","target_field": "ينطبق على","target_order": "الطلب بأكمله",+ "tax_exempt_certificate": "شهادة الإعفاء الضريبي: {{reason}} (رقم {{number}})",+ "tax_exempt_certificate_number": "رقم شهادة الإعفاء الضريبي: {{number}}",+ "taxability_reason": {+ "customer_exempt": "المشتري معفى",+ "export": "تصدير",+ "intra_community_supply": "توريد داخل الجماعة",+ "not_collecting": "غير محصّلة",+ "not_subject_to_tax": "غير خاضع للضريبة",+ "product_exempt": "المنتج معفى",+ "reduced_rated": "نسبة مخفضة",+ "reverse_charge": "الاحتساب العكسي",+ "standard_rated": "النسبة القياسية",+ "zero_rated": "نسبة صفرية"+ },"taxes": "الضرائب","taxes_empty": "لا توجد ضرائب على هذا الطلب بعد.",+ "taxes_unmatched": "لا توجد نسبة ضريبية تطابق هذا العنوان.","value_field": "القيمة","value_type_field": "النوع","value_type_flat": "مبلغ",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 931e8065c6..de79332bfe 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -2405,8 +2405,23 @@"percent_preview": "Voraussichtlicher Rabatt: {{amount}}","target_field": "Gilt für","target_order": "Gesamte Bestellung",+ "tax_exempt_certificate": "{{reason}}-Bescheinigung {{number}}",+ "tax_exempt_certificate_number": "Bescheinigung {{number}}",+ "taxability_reason": {+ "customer_exempt": "Käufer befreit",+ "export": "Ausfuhr",+ "intra_community_supply": "Innergemeinschaftliche Lieferung",+ "not_collecting": "Keine Erhebung",+ "not_subject_to_tax": "Nicht steuerbar",+ "product_exempt": "Produkt befreit",+ "reduced_rated": "Ermäßigter Satz",+ "reverse_charge": "Reverse Charge",+ "standard_rated": "Regelsatz",+ "zero_rated": "Nullsteuersatz (0 %)"+ },"taxes": "Steuern","taxes_empty": "Noch keine Steuern für diese Bestellung.",+ "taxes_unmatched": "Für diese Adresse gilt kein Steuersatz.","value_field": "Wert","value_type_field": "Typ","value_type_flat": "Betrag",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 704f2d4cc3..a5757d19fe 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -2405,8 +2405,23 @@"percent_preview": "Estimated discount: {{amount}}","target_field": "Applies to","target_order": "Whole order",+ "tax_exempt_certificate": "{{reason}} certificate {{number}}",+ "tax_exempt_certificate_number": "Certificate {{number}}",+ "taxability_reason": {+ "customer_exempt": "Buyer exempt",+ "export": "Export",+ "intra_community_supply": "Intra-community supply",+ "not_collecting": "Not collecting",+ "not_subject_to_tax": "Not subject to tax",+ "product_exempt": "Product exempt",+ "reduced_rated": "Reduced rate",+ "reverse_charge": "Reverse charge",+ "standard_rated": "Standard rate",+ "zero_rated": "Zero-rated"+ },"taxes": "Taxes","taxes_empty": "No taxes on this order yet.",+ "taxes_unmatched": "No tax rate matched this address.","value_field": "Value","value_type_field": "Type","value_type_flat": "Amount",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex d07bf8e32b..32c2f8034b 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -2405,8 +2405,23 @@"percent_preview": "Remise estimée : {{amount}}","target_field": "S'applique à","target_order": "Commande entière",+ "tax_exempt_certificate": "Attestation d'exonération — {{reason}} — {{number}}",+ "tax_exempt_certificate_number": "Attestation d'exonération — {{number}}",+ "taxability_reason": {+ "customer_exempt": "Acheteur exonéré",+ "export": "Exportation",+ "intra_community_supply": "Livraison intra-communautaire",+ "not_collecting": "Non collectée",+ "not_subject_to_tax": "Hors champ",+ "product_exempt": "Produit exonéré",+ "reduced_rated": "Taux réduit",+ "reverse_charge": "Autoliquidation",+ "standard_rated": "Taux normal",+ "zero_rated": "Taux zéro"+ },"taxes": "Taxes","taxes_empty": "Aucune taxe sur cette commande pour le moment.",+ "taxes_unmatched": "Aucun taux de taxe ne correspond à cette adresse.","value_field": "Valeur","value_type_field": "Type","value_type_flat": "Montant",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 1157003490..a65c4a366d 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -2423,8 +2423,23 @@"percent_preview": "Szacowany rabat: {{amount}}","target_field": "Dotyczy","target_order": "Całe zamówienie",+ "tax_exempt_certificate": "Zaświadczenie {{reason}} {{number}}",+ "tax_exempt_certificate_number": "Zaświadczenie {{number}}",+ "taxability_reason": {+ "customer_exempt": "Nabywca zwolniony",+ "export": "Eksport",+ "intra_community_supply": "Dostawa wewnątrzwspólnotowa",+ "not_collecting": "Niepobierany",+ "not_subject_to_tax": "Poza zakresem",+ "product_exempt": "Produkt zwolniony",+ "reduced_rated": "Stawka obniżona",+ "reverse_charge": "Odwrotne obciążenie",+ "standard_rated": "Stawka podstawowa",+ "zero_rated": "Stawka zerowa"+ },"taxes": "Podatki","taxes_empty": "Brak podatków dla tego zamówienia.",+ "taxes_unmatched": "Żadna stawka podatku nie pasuje do tego adresu.","value_field": "Wartość","value_type_field": "Typ","value_type_flat": "Kwota",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex e7864b066e..55e37a8aaa 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -2399,8 +2399,23 @@"percent_preview": "预计折扣:{{amount}}","target_field": "适用于","target_order": "整个订单",+ "tax_exempt_certificate": "{{reason}} 证明 {{number}}",+ "tax_exempt_certificate_number": "证明 {{number}}",+ "taxability_reason": {+ "customer_exempt": "买方免税",+ "export": "出口",+ "intra_community_supply": "共同体内供应",+ "not_collecting": "不征收",+ "not_subject_to_tax": "不在征税范围",+ "product_exempt": "产品免税",+ "reduced_rated": "优惠税率",+ "reverse_charge": "反向征收",+ "standard_rated": "标准税率",+ "zero_rated": "零税率"+ },"taxes": "税费","taxes_empty": "该订单暂无税费。",+ "taxes_unmatched": "没有税率匹配该地址。","value_field": "数值","value_type_field": "类型","value_type_flat": "金额",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsxindex 6cf1e558d4..6ea5622719 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx@@ -109,7 +109,8 @@ function OrderTotalsCard({ order, items }: { order: Order; items: OrderEditItemV/>)}- {Number.parseFloat(order.additional_tax_total) > 0 && (+ {(Number.parseFloat(order.additional_tax_total) > 0 ||+ (Boolean(order.completed_at) && Number.parseFloat(order.included_tax_total) === 0)) && (<TotalRowlabel={t('admin.orders.detail.summary.tax_additional')}value={order.display_additional_tax_total}