Files
InvoiceShelf/resources/scripts/features/shared/document-form/use-document-calculations.ts
T
Darko Gjorgjijoski 13aa087faf Add compound tax support (#753)
* test(taxes): cover compound_tax API semantics and validate it as boolean

* feat(taxes): restore the compound tax toggle in tax type settings

* feat(taxes): compute document-level compound tax amounts

Two-pass recalculation: simple taxes on the discounted subtotal, compound
taxes on the subtotal plus all simple taxes (v2 parity; branch order
fixed -> compound -> inclusive back-out -> simple). Amounts now also
recalculate on tax add/remove and on the tax-inclusive toggle, which
previously never triggered recalculation.

* feat(taxes): support compound taxes in per-item mode

Per-item tax rows now carry the compound flag and charge compound taxes
on the item's discounted base plus its simple taxes, through the same
calcTaxAmount branch order as document-level taxes. The item row splits
its tax sums into simple and compound so a compound row can never widen
its own base.

Also fixes two pre-existing bugs: the per-item tax dropdown read
window.__taxTypes, which nothing ever assigned, so it always rendered
empty (tax types are now fetched by the items table and passed down);
and removing a tax row hard-zeroed the item's totals instead of
re-syncing them.

* fix(invoices): skip placeholder tax rows when persisting item taxes

The document form keeps one empty placeholder tax row per item in
per-item tax mode. Its empty name is nullified by the framework's
empty-string middleware, so inserting it violated the NOT NULL
constraint and turned every per-item save into a 500. The equivalent
v2 guard keyed on a null amount, which the v3 stub (amount: 0) evades;
keying on the missing tax_type_id catches it.
2026-08-14 00:17:52 +02:00

199 lines
5.3 KiB
TypeScript

import { computed, type Ref } from 'vue'
import type { Tax } from '../../../types/domain/tax'
export interface DocumentItem {
id: number | string
name: string
description: string | null
quantity: number
price: number
discount: number
discount_val: number
discount_type: 'fixed' | 'percentage'
tax: number
total: number
sub_total?: number
totalTax?: number
totalSimpleTax?: number
totalCompoundTax?: number
taxes?: Partial<Tax>[]
item_id?: number | null
unit_name?: string | null
invoice_id?: number | null
estimate_id?: number | null
[key: string]: unknown
}
export interface DocumentFormData {
id: number | null
customer: Record<string, unknown> | null
customer_id: number | null
items: DocumentItem[]
taxes: DocumentTax[]
discount: number
discount_val: number
discount_type: 'fixed' | 'percentage'
tax_per_item: string | null
tax_included: boolean | null
discount_per_item: string | null
notes: string | null
template_name: string | null
exchange_rate?: number | null
currency_id?: number
selectedCurrency?: Record<string, unknown> | string
[key: string]: unknown
}
export interface DocumentTax {
id: number | string
tax_type_id: number
name: string
amount: number
percent: number | null
calculation_type: string | null
fixed_amount: number
compound_tax: boolean
type?: string
[key: string]: unknown
}
export interface DocumentStore {
getSubTotal: number
getNetTotal: number
getTotalSimpleTax: number
getTotalCompoundTax: number
getTotalTax: number
getSubtotalWithDiscount: number
getTotal: number
[key: string]: unknown
}
export interface UseDocumentCalculationsOptions {
items: Ref<DocumentItem[]>
taxes: Ref<DocumentTax[]>
discountVal: Ref<number>
taxPerItem: Ref<string | null>
taxIncluded: Ref<boolean | null>
}
export function useDocumentCalculations(options: UseDocumentCalculationsOptions) {
const { items, taxes, discountVal, taxPerItem, taxIncluded } = options
const subTotal = computed<number>(() => {
return items.value.reduce((sum: number, item: DocumentItem) => {
return sum + (item.total ?? 0)
}, 0)
})
const totalSimpleTax = computed<number>(() => {
return taxes.value.reduce((sum: number, tax: DocumentTax) => {
if (!tax.compound_tax) {
return sum + (tax.amount ?? 0)
}
return sum
}, 0)
})
const totalCompoundTax = computed<number>(() => {
return taxes.value.reduce((sum: number, tax: DocumentTax) => {
if (tax.compound_tax) {
return sum + (tax.amount ?? 0)
}
return sum
}, 0)
})
const totalTax = computed<number>(() => {
if (taxPerItem.value === 'NO' || taxPerItem.value === null) {
return totalSimpleTax.value + totalCompoundTax.value
}
return items.value.reduce((sum: number, item: DocumentItem) => {
return sum + (item.tax ?? 0)
}, 0)
})
const subtotalWithDiscount = computed<number>(() => {
return subTotal.value - discountVal.value
})
const netTotal = computed<number>(() => {
return subtotalWithDiscount.value - totalTax.value
})
const total = computed<number>(() => {
if (taxIncluded.value) {
return subtotalWithDiscount.value
}
return subtotalWithDiscount.value + totalTax.value
})
return {
subTotal,
totalSimpleTax,
totalCompoundTax,
totalTax,
subtotalWithDiscount,
netTotal,
total,
}
}
/** Calculate item-level subtotal (price * quantity) */
export function calcItemSubtotal(price: number, quantity: number): number {
return Math.round(price * quantity)
}
/** Calculate item-level discount value */
export function calcItemDiscountVal(
subtotal: number,
discount: number,
discountType: 'fixed' | 'percentage',
): number {
const absSubtotal = Math.abs(subtotal)
if (discountType === 'percentage') {
return Math.round((absSubtotal * discount) / 100)
}
return Math.min(Math.round(discount * 100), absSubtotal)
}
/** Calculate item-level total after discount */
export function calcItemTotal(subtotal: number, discountVal: number): number {
return subtotal - discountVal
}
/**
* Calculate tax amount for a given total and tax config.
*
* A compound tax is charged on the base plus every simple (non-compound) tax
* already applied, and is never backed out of a tax-inclusive total.
*
* @param total Base amount in cents (document subtotal after discount, or an item total after discount)
* @param percent Percentage rate, when the tax is percentage based
* @param fixedAmount Flat amount in cents, when the tax is fixed
* @param calculationType `'fixed'` or `'percentage'`
* @param taxIncluded Whether the base already includes the tax (back it out)
* @param compoundTax Whether the tax is charged on top of the simple taxes
* @param simpleTaxTotal Sum of the non-compound tax amounts in cents
*/
export function calcTaxAmount(
total: number,
percent: number | null,
fixedAmount: number | null,
calculationType: string | null,
taxIncluded: boolean | null,
compoundTax = false,
simpleTaxTotal = 0,
): number {
if (calculationType === 'fixed' && fixedAmount != null) {
return fixedAmount
}
if (!total || !percent) return 0
if (compoundTax) {
return Math.round(((total + simpleTaxTotal) * percent) / 100)
}
if (taxIncluded) {
return Math.round(total - total / (1 + percent / 100))
}
return Math.round((total * percent) / 100)
}