Taxes stage 2: Tax Collected report rebuilt for filing with an Invoiced basis (each sent invoice in the month of its date) or Paid basis (each payment carrying its share of its invoice), tax by part of each rate with registration numbers so a state's and a county's parts count apart and parts named alike add up in one row, sales before tax and net of discounts split into taxable, exempt and non-taxable, tax paid on purchases by part and net tax collected less paid, exempt sales by client with certificate and expiry, quarterly or monthly with a chart and CSV export of the tax table or the exempt sales, archived payments left out; expenses and recurring expenses record the tax included in them with a rate worked out from the amount as typed or typed over from the receipt, a tax amount with no rate allowed, refunds giving their tax back, recurring expenses copying it to each expense recorded, vendor defaults filling it in, and the list and quick looks showing it; exports gain invoice subtotal, discount, tax and tax by part, quote and recurring invoice tax, expense before tax, tax and tax rate, and client tax rate and exemption columns; API adds a taxes read endpoint with each rate's parts, subtotal, tax, tax by part and registration numbers on invoice and quote reads, and each line's rate on invoice item reads; Admin > Taxes explains naming parts alike and links the report; demo data names Allegheny County's state part PA Sales Tax and taxes the company's own-use purchases; removes the unused getMonthlyTax and getQuarterlyTax; database 3.1.2 adds expense and recurring expense tax rate and amount; changelog updated

This commit is contained in:
johnnyq
2026-10-17 13:27:53 -04:00
parent afaaa5fc32
commit cd565b73c7
29 changed files with 797 additions and 224 deletions

View File

@@ -643,47 +643,6 @@ function checkForUpdates() {
}
function getMonthlyTax($tax_name, $month, $year, $mysqli) {
// Cash basis - tax is booked to the month the money arrived, in proportion to
// how much of the invoice that payment covered. Driving off payments (rather
// than invoice_items) counts each payment exactly once, and pre-aggregating
// the line items stops a multi-payment invoice multiplying its own tax.
$sql = "SELECT SUM(invoice_tax.tax_total * (payments.payment_amount / invoices.invoice_amount)) AS monthly_tax
FROM payments
INNER JOIN invoices ON invoices.invoice_id = payments.payment_invoice_id
INNER JOIN (SELECT item_invoice_id, SUM(item_tax) AS tax_total
FROM invoice_items
WHERE item_tax_id = (SELECT tax_id FROM taxes WHERE tax_name = '$tax_name')
GROUP BY item_invoice_id) AS invoice_tax
ON invoice_tax.item_invoice_id = invoices.invoice_id
WHERE YEAR(payments.payment_date) = $year AND MONTH(payments.payment_date) = $month
AND invoices.invoice_amount > 0";
$result = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_assoc($result);
return $row['monthly_tax'] ?? 0;
}
function getQuarterlyTax($tax_name, $quarter, $year, $mysqli) {
// Calculate start and end months for the quarter
$start_month = ($quarter - 1) * 3 + 1;
$end_month = $start_month + 2;
// SQL to calculate quarterly tax - see getMonthlyTax for why it is shaped this way
$sql = "SELECT SUM(invoice_tax.tax_total * (payments.payment_amount / invoices.invoice_amount)) AS quarterly_tax
FROM payments
INNER JOIN invoices ON invoices.invoice_id = payments.payment_invoice_id
INNER JOIN (SELECT item_invoice_id, SUM(item_tax) AS tax_total
FROM invoice_items
WHERE item_tax_id = (SELECT tax_id FROM taxes WHERE tax_name = '$tax_name')
GROUP BY item_invoice_id) AS invoice_tax
ON invoice_tax.item_invoice_id = invoices.invoice_id
WHERE YEAR(payments.payment_date) = $year AND MONTH(payments.payment_date) BETWEEN $start_month AND $end_month
AND invoices.invoice_amount > 0";
$result = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_assoc($result);
return $row['quarterly_tax'] ?? 0;
}
function addToMailQueue($data) {
global $mysqli;

View File

@@ -288,23 +288,13 @@ function billingTaxParts(array $items) {
if ($tax == 0) {
continue;
}
$row = taxRow($item['item_tax_id'] ?? 0);
if (!$row) {
$label = trim(($item['tax_name'] ?? 'Tax') . (isset($item['tax_percent']) && $item['tax_percent'] !== null ? ' ' . taxPercentText($item['tax_percent']) . '%' : ''));
$parts[$label] = round(($parts[$label] ?? 0) + $tax, 2);
continue;
}
$split = taxAmounts(floatval($item['item_subtotal']), $row)['parts'];
$whole = array_sum(array_column($split, 'amount'));
$left = $tax;
foreach ($split as $i => $part) {
if ($part['registration'] !== '') {
$registrations[$part['registration_for']] = $part['registration'];
}
$amount = $i === count($split) - 1 || $whole == 0 ? $left : round($tax * $part['amount'] / $whole, 2);
$left = round($left - $amount, 2);
$parts[$part['label']] = round(($parts[$part['label']] ?? 0) + $amount, 2);
// A rate no longer on file shows by the name and percent the line still has
$label = trim(($item['tax_name'] ?? 'Tax') . (isset($item['tax_percent']) && $item['tax_percent'] !== null ? ' ' . taxPercentText($item['tax_percent']) . '%' : ''));
$split = taxSplit($tax, taxRow($item['item_tax_id'] ?? 0), floatval($item['item_subtotal']), $label);
foreach ($split['parts'] as $part => $amount) {
$parts[$part] = round(($parts[$part] ?? 0) + $amount, 2);
}
$registrations += $split['registrations'];
}
return ['parts' => $parts, 'registrations' => $registrations];
}
@@ -569,6 +559,35 @@ function billingRemoveTax($type, $doc_id) {
return $lines;
}
/**
* A document's tax for the API - its subtotal, tax, the tax by part
* ([{name, amount}]) and the registration numbers it is charged under, keyed
* with the document's column prefix (invoice_subtotal, quote_tax...). A
* quote's are for what it bills up front.
*/
function billingApiTaxFields($type, array $row) {
$c = billingType($type)['col'];
$items = billingItems($type, $row["{$c}_id"]);
$totals = billingTotals($type, $row, $items);
$subtotal = $totals['subtotal'];
$tax = $totals['tax'];
$parts = $totals['taxes'];
if ($type === 'quote' && !empty($totals['recurring'])) {
$once = $totals['groups'][''] ?? ['subtotal' => 0.0, 'tax' => 0.0, 'taxes' => []];
[$subtotal, $tax, $parts] = [$once['subtotal'], $once['tax'], $once['taxes']];
}
$out = [];
foreach ($parts as $name => $amount) {
$out[] = ['name' => $name, 'amount' => round($amount, 2)];
}
return [
"{$c}_subtotal" => round($subtotal, 2),
"{$c}_tax" => round($tax, 2),
"{$c}_taxes" => $out,
"{$c}_tax_registrations" => billingTaxRegistrationLines($totals),
];
}
/** Subtotal, discount, tax and total for showing - from the lines, and the stored total. */
function billingTotals($type, $row, array $items) {
$c = billingType($type)['col'];

View File

@@ -36,7 +36,7 @@ function expenseRow($expense_id, $scoped = true) {
$scope = $scoped ? clientScopeSql('expenses.expense_client_id') : '';
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT expenses.*, vendor_name, vendor_description, vendor_archived_at,
category_name, category_color, category_icon, category_archived_at, accounts.account_name, accounts.account_archived_at, accounts.account_currency_code,
client_name, client_abbreviation, creator.user_name AS created_by_name, transfer_id,
client_name, client_abbreviation, creator.user_name AS created_by_name, transfer_id, taxes.tax_name, taxes.tax_percent,
recurring_expense_frequency, recurring_expense_amount, recurring_expense_currency_code,
invoice_prefix, invoice_number, invoice_status, item_subtotal AS billed_subtotal,
refunded.expense_date AS refund_of_date, refunded.expense_amount AS refund_of_amount, refunded.expense_description AS refund_of_description,
@@ -49,6 +49,7 @@ function expenseRow($expense_id, $scoped = true) {
LEFT JOIN categories ON category_id = expenses.expense_category_id
LEFT JOIN accounts ON accounts.account_id = expenses.expense_account_id
LEFT JOIN clients ON client_id = expenses.expense_client_id
LEFT JOIN taxes ON taxes.tax_id = expenses.expense_tax_id
LEFT JOIN users AS creator ON creator.user_id = expenses.expense_created_by
LEFT JOIN users AS payer ON payer.user_id = expenses.expense_paid_by
LEFT JOIN transfers ON transfer_expense_id = expenses.expense_id
@@ -203,13 +204,14 @@ function expenseCategoryDot($color) {
}
/**
* The last expense with each vendor - its category, account and payment
* method, by vendor id. New Expense fills these in when a vendor is picked.
* The last expense with each vendor - its category, account, payment
* method and tax, by vendor id. New Expense fills these in when a vendor is
* picked.
*/
function expenseVendorDefaults() {
global $mysqli;
$defaults = [];
$sql = mysqli_query($mysqli, "SELECT e.expense_vendor_id, e.expense_category_id, e.expense_account_id, e.expense_payment_method
$sql = mysqli_query($mysqli, "SELECT e.expense_vendor_id, e.expense_category_id, e.expense_account_id, e.expense_payment_method, e.expense_tax_id
FROM expenses AS e
JOIN (SELECT expense_vendor_id, MAX(expense_id) AS last_id FROM expenses WHERE expense_vendor_id > 0 AND expense_amount > 0 GROUP BY expense_vendor_id) AS last
ON last.last_id = e.expense_id");
@@ -218,6 +220,7 @@ function expenseVendorDefaults() {
'category' => intval($row['expense_category_id']),
'account' => intval($row['expense_account_id']),
'method' => (string) $row['expense_payment_method'],
'tax' => intval($row['expense_tax_id']),
];
}
return $defaults;
@@ -260,6 +263,46 @@ function expenseCategories($keep_id = 0) {
* category or account is only kept when it is already the expense's.
* Returns the expense id, or 0 with $error.
*/
/**
* The tax included in what an expense cost, from a form - [rate id, amount],
* or null with $error. tax_id is one of the taxes (0 for none, or a tax with
* no rate of ours); tax_amount is worked out from the rate when left empty.
* The tax takes the amount's sign, so money back gives its tax back too.
* Without either field, $keep stands - unless the amount changed and the tax
* came from the rate, when it is worked out again.
*/
function expenseTaxFromInput(array $in, $amount, array $keep = [0, 0.0], &$error = '') {
$amount = round(floatval($amount), 2);
if (!array_key_exists('tax_id', $in) && !array_key_exists('tax_amount', $in)) {
[$tax_id, $tax_amount] = $keep;
$tax_id = intval($tax_id);
$tax_amount = round(floatval($tax_amount), 2);
if ($tax_id && taxRow($tax_id) && abs($tax_amount) >= abs($amount)) {
$tax_amount = taxIncluded(abs($amount), $tax_id) * ($amount < 0 ? -1 : 1);
}
return [$tax_id, $tax_amount];
}
$tax_id = intval($in['tax_id'] ?? 0);
if ($tax_id && !taxRow($tax_id)) {
$error = 'Pick one of your taxes';
return null;
}
$text = str_replace([',', ' ', '$'], '', trim((string) ($in['tax_amount'] ?? '')));
if ($text === '') {
$tax_amount = $tax_id ? taxIncluded(abs($amount), $tax_id) : 0.0;
} elseif (!is_numeric($text)) {
$error = 'The tax is an amount, such as 12.50';
return null;
} else {
$tax_amount = round(abs(floatval($text)), 2);
}
if ($tax_amount >= abs($amount)) {
$error = 'The tax is part of what it cost, so less than the amount';
return null;
}
return [$tax_id, $amount < 0 ? -$tax_amount : $tax_amount];
}
function expenseSave(array $in, $expense_id = 0, &$error = '') {
global $mysqli, $session_company_currency, $session_user_id;
$error = '';
@@ -352,6 +395,14 @@ function expenseSave(array $in, $expense_id = 0, &$error = '') {
$reference = mb_substr(trim((string) ($in['reference'] ?? '')), 0, 200);
$description = trim((string) ($in['description'] ?? ''));
// The tax included in it - money back starts on the rate of what it refunds
$tax_keep = $existing ? [$existing['expense_tax_id'], $existing['expense_tax_amount']] : ($refund_of ? [$original['expense_tax_id'], -taxIncluded(abs($amount), $original['expense_tax_id'])] : [0, 0.0]);
$tax = expenseTaxFromInput($in, $amount, $tax_keep, $error);
if ($tax === null) {
return 0;
}
[$tax_id, $tax_amount] = $tax;
// Billed on to the client - only an expense for a client, not a refund. One
// already on an invoice stays billed, to that client, until it comes off it.
$billed = $existing && !empty($existing['expense_invoice_id']);
@@ -368,7 +419,7 @@ function expenseSave(array $in, $expense_id = 0, &$error = '') {
}
$markup = round(max(0, min(1000, $markup)), 2);
$set = "expense_date = '$date', expense_amount = $amount, expense_vendor_id = $vendor, expense_category_id = $category,
$set = "expense_date = '$date', expense_amount = $amount, expense_tax_id = $tax_id, expense_tax_amount = $tax_amount, expense_vendor_id = $vendor, expense_category_id = $category,
expense_account_id = $account, expense_paid_by = $paid_by, expense_client_id = $client_id, expense_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ",
expense_reference = '" . escapeSql($reference) . "', expense_description = '" . escapeSql($description) . "',
expense_billable = $billable, expense_markup = $markup";
@@ -567,7 +618,7 @@ function recurringExpenseRow($recurring_expense_id, $scoped = true) {
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT recurring_expenses.*, vendor_name, vendor_description, vendor_archived_at,
category_name, category_color, category_icon, category_archived_at, account_name, account_archived_at, account_currency_code,
client_name, client_abbreviation, recurring_invoice_prefix, recurring_invoice_number, recurring_invoice_amount, recurring_invoice_frequency,
recurring_invoice_status, recurring_invoice_archived_at,
recurring_invoice_status, recurring_invoice_archived_at, tax_name, tax_percent,
(SELECT COUNT(*) FROM expenses WHERE expense_recurring_expense_id = $id) AS made_count,
(SELECT COALESCE(SUM(expense_amount), 0) FROM expenses WHERE expense_recurring_expense_id = $id AND YEAR(expense_date) = YEAR(CURDATE())) AS made_year
FROM recurring_expenses
@@ -576,6 +627,7 @@ function recurringExpenseRow($recurring_expense_id, $scoped = true) {
LEFT JOIN accounts ON account_id = recurring_expense_account_id
LEFT JOIN clients ON client_id = recurring_expense_client_id
LEFT JOIN recurring_invoices ON recurring_invoice_id = recurring_expense_recurring_invoice_id
LEFT JOIN taxes ON tax_id = recurring_expense_tax_id
WHERE recurring_expense_id = $id $scope
LIMIT 1"));
return $row ?: null;
@@ -781,6 +833,11 @@ function recurringExpenseSave(array $in, $recurring_expense_id = 0, &$error = ''
}
$reference = mb_substr(trim((string) ($in['reference'] ?? '')), 0, 255);
$description = trim((string) ($in['description'] ?? ''));
$tax = expenseTaxFromInput($in, $amount, $existing ? [$existing['recurring_expense_tax_id'], $existing['recurring_expense_tax_amount']] : [0, 0.0], $error);
if ($tax === null) {
return 0;
}
[$tax_id, $tax_amount] = $tax;
// For a client: billed on as each one is recorded, or covered by one of their recurring invoices
$billing = $client_id ? (string) ($in['billing'] ?? '') : '';
@@ -814,7 +871,7 @@ function recurringExpenseSave(array $in, $recurring_expense_id = 0, &$error = ''
$status = intval($existing['recurring_expense_status']);
}
$set = "recurring_expense_vendor_id = $vendor, recurring_expense_amount = $amount, recurring_expense_frequency = '$frequency', recurring_expense_anchor_day = $anchor,
$set = "recurring_expense_vendor_id = $vendor, recurring_expense_amount = $amount, recurring_expense_tax_id = $tax_id, recurring_expense_tax_amount = $tax_amount, recurring_expense_frequency = '$frequency', recurring_expense_anchor_day = $anchor,
recurring_expense_next_date = '$next', recurring_expense_end_date = " . ($end === '' ? 'NULL' : "'$end'") . ", recurring_expense_status = $status,
recurring_expense_category_id = $category, recurring_expense_account_id = $account, recurring_expense_client_id = $client_id,
recurring_expense_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ",
@@ -866,6 +923,7 @@ function recurringExpenseRecord($recurring_expense_id, $by_user_id = 0, $run = n
$method = (string) $row['recurring_expense_payment_method'];
mysqli_query($mysqli, "INSERT INTO expenses SET expense_date = '$date', expense_amount = " . floatval($row['recurring_expense_amount']) . ",
expense_tax_id = " . intval($row['recurring_expense_tax_id']) . ", expense_tax_amount = " . floatval($row['recurring_expense_tax_amount']) . ",
expense_currency_code = '" . escapeSql($row['recurring_expense_currency_code']) . "', expense_vendor_id = " . intval($row['recurring_expense_vendor_id']) . ",
expense_client_id = " . intval($row['recurring_expense_client_id']) . ", expense_category_id = " . intval($row['recurring_expense_category_id']) . ",
expense_account_id = " . intval($row['recurring_expense_account_id']) . ", expense_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ",

View File

@@ -66,6 +66,10 @@ function getExportColumns($export_type) {
'client_currency_code' => ['label' => 'Currency'],
'client_net_terms' => ['label' => 'Payment Terms', 'format' => 'number'],
'client_tax_id_number' => ['label' => 'Tax ID'],
'client_tax_rate' => ['label' => 'Tax Rate', 'default' => false],
'client_tax_exempt_display' => ['label' => 'Tax Exempt', 'default' => false],
'client_tax_exempt_number' => ['label' => 'Exemption Certificate', 'default' => false],
'client_tax_exempt_expires' => ['label' => 'Exemption Expires', 'default' => false],
'client_abbreviation' => ['label' => 'Abbreviation'],
],
@@ -321,6 +325,10 @@ function getExportColumns($export_type) {
'invoices' => [
'invoice_number_display' => ['label' => 'Invoice Number'],
'invoice_scope' => ['label' => 'Scope', 'weight' => 3],
'invoice_subtotal' => ['label' => 'Subtotal', 'format' => 'money', 'default' => false],
'invoice_discount_amount' => ['label' => 'Discount', 'format' => 'money', 'default' => false],
'invoice_tax' => ['label' => 'Tax', 'format' => 'money', 'default' => false],
'invoice_tax_parts' => ['label' => 'Tax by Part', 'weight' => 2, 'default' => false],
'invoice_amount' => ['label' => 'Amount', 'format' => 'money'],
'invoice_date' => ['label' => 'Issued Date'],
'invoice_due' => ['label' => 'Due Date'],
@@ -335,6 +343,7 @@ function getExportColumns($export_type) {
'quote_number_display' => ['label' => 'Quote Number'],
'quote_scope' => ['label' => 'Scope', 'weight' => 3],
'quote_amount' => ['label' => 'Amount', 'format' => 'money'],
'quote_tax' => ['label' => 'Tax', 'format' => 'money', 'default' => false],
'quote_monthly_amount' => ['label' => 'Monthly', 'format' => 'money'],
'quote_date' => ['label' => 'Date'],
'quote_status' => ['label' => 'Status'],
@@ -345,6 +354,7 @@ function getExportColumns($export_type) {
'recurring_invoice_number_display' => ['label' => 'Recurring Number'],
'recurring_invoice_scope' => ['label' => 'Scope', 'weight' => 3],
'recurring_invoice_amount' => ['label' => 'Amount', 'format' => 'money'],
'recurring_invoice_tax' => ['label' => 'Tax', 'format' => 'money', 'default' => false],
'recurring_invoice_frequency_display' => ['label' => 'Frequency'],
'recurring_invoice_created_at' => ['label' => 'Date Created'],
'client_name' => ['label' => 'Client', 'weight' => 2, 'default' => false],
@@ -379,6 +389,9 @@ function getExportColumns($export_type) {
'expenses' => [
'expense_date' => ['label' => 'Date'],
'expense_amount' => ['label' => 'Amount', 'format' => 'money'],
'expense_before_tax' => ['label' => 'Before Tax', 'format' => 'money', 'default' => false],
'expense_tax_amount' => ['label' => 'Tax', 'format' => 'money', 'default' => false],
'expense_tax_rate' => ['label' => 'Tax Rate', 'default' => false],
'vendor_name' => ['label' => 'Vendor', 'weight' => 2],
'expense_description' => ['label' => 'Description', 'weight' => 3],
'category_name' => ['label' => 'Category'],

View File

@@ -71,7 +71,7 @@ function reportCatalog() {
],
'tax_summary' => [
'title' => 'Tax Collected', 'icon' => 'fa-percent', 'module' => 'module_financial', 'feature' => ['accounting'],
'description' => 'Tax collected on paid invoices, and the sales it was collected on, by month or quarter.',
'description' => 'Tax on sales by part of each rate, invoiced or paid, with taxable, exempt and non-taxable sales and the tax paid on purchases, by month or quarter.',
],
'mileage' => [
'title' => 'Mileage', 'icon' => 'fa-route', 'module' => 'module_financial', 'feature' => ['accounting'],

View File

@@ -139,6 +139,48 @@ function taxAmounts($base, $tax) {
return ['tax' => $total, 'parts' => $parts];
}
/**
* The tax included in an amount at a rate - what of $gross is tax, to the
* cent, the rest being what the tax was on. $tax: a rate's id, or its taxRow().
*/
function taxIncluded($gross, $tax) {
$row = is_array($tax) ? $tax : taxRow($tax);
$gross = round(floatval($gross), 2);
if (!$row || floatval($row['tax_percent']) == 0) {
return 0.0;
}
return round($gross - round($gross / (1 + floatval($row['tax_percent']) / 100), 2), 2);
}
/**
* A tax amount shared over its rate's parts, as they come to on $base -
* ['parts' => label => amount, adding up to $amount, 'registrations' => what
* each number is for => number, 'numbers' => label => its number]. With
* no rate ($row null), it is all one part, $no_rate_label.
*/
function taxSplit($amount, $row, $base, $no_rate_label = 'Tax') {
$amount = round(floatval($amount), 2);
if (!$row) {
return ['parts' => [$no_rate_label => $amount], 'registrations' => [], 'numbers' => []];
}
$split = taxAmounts($base, $row)['parts'];
$whole = array_sum(array_column($split, 'amount'));
$left = $amount;
$parts = [];
$registrations = [];
$numbers = [];
foreach ($split as $i => $part) {
$share = $i === count($split) - 1 || $whole == 0 ? $left : round($amount * $part['amount'] / $whole, 2);
$left = round($left - $share, 2);
$parts[$part['label']] = round(($parts[$part['label']] ?? 0) + $share, 2);
if ($part['registration'] !== '') {
$registrations[$part['registration_for']] = $part['registration'];
$numbers[$part['label']] = $part['registration'];
}
}
return ['parts' => $parts, 'registrations' => $registrations, 'numbers' => $numbers];
}
/** The rate a rate was changed to, following each change to the one in use now - or 0 when it was archived without one. */
function taxCurrent($tax_id) {
$seen = [];
@@ -665,3 +707,159 @@ function taxOptionsHtml(array $taxes, $selected = 0, $usual_label = '', $usual_p
function taxSelectOptions($selected = 0, $since = null) {
return taxOptionsHtml(billingTaxes($since), $selected);
}
/*
* ---------- the Tax Collected report ----------
*/
/** The bases the tax on sales can be counted on - when invoiced, or when paid. */
const TAX_REPORT_BASES = ['invoiced' => 'Invoiced', 'paid' => 'Paid'];
/** Twelve months of nothing, for adding to. */
function taxReportMonths() {
return array_fill(1, 12, 0.0);
}
/**
* What one invoice comes to for tax: each line net of its share of the
* discount, sorted into taxable, non-taxable (no tax for a client who isn't
* exempt) and exempt (no tax for a client who is exempt now), and its tax by
* part. $items: the invoice's lines with item_subtotal, item_tax, item_tax_id,
* tax_name and tax_percent.
*/
function taxReportInvoice(array $items, $discount, $exempt) {
$out = ['sales' => 0.0, 'taxable' => 0.0, 'nontaxable' => 0.0, 'exempt' => 0.0, 'parts' => [], 'numbers' => []];
$shares = billingDiscountShares($items, $discount);
foreach ($items as $item) {
$net = floatval($item['item_subtotal']) - ($shares[intval($item['item_id'])] ?? 0);
$tax = round(floatval($item['item_tax']), 2);
$out['sales'] += $net;
if ($tax != 0) {
$out['taxable'] += $net;
$label = trim(($item['tax_name'] ?? 'Tax') . ($item['tax_percent'] !== null ? ' ' . taxPercentText($item['tax_percent']) . '%' : ''));
$split = taxSplit($tax, taxRow($item['item_tax_id']), floatval($item['item_subtotal']), $label);
foreach ($split['parts'] as $part => $amount) {
$out['parts'][$part] = ($out['parts'][$part] ?? 0) + $amount;
}
$out['numbers'] += $split['numbers'];
} elseif ($exempt) {
$out['exempt'] += $net;
} else {
$out['nontaxable'] += $net;
}
}
return $out;
}
/**
* Tax on sales from $from to $to (Y-m-d, within one year), by month. On the
* invoiced basis each invoice sent counts in the month of its date; on the
* paid basis each payment carries its share of its invoice - a part-paid
* invoice counts only the part that came in. Drafts, cancelled and
* non-billable invoices count only for payments made on them.
*
* ['parts' => label => ['months', 'total'], 'numbers' => label => the
* registration it is charged under, 'sales' / 'taxable' / 'nontaxable' / 'exempt' =>
* months, 'exempt_clients' => client id => ['name', 'number', 'expires',
* 'expired', 'amount'], 'invoices' => how many].
*/
function taxReportSales($from, $to, $basis = 'paid') {
global $mysqli;
$from = escapeSql($from);
$to = escapeSql($to);
if ($basis === 'invoiced') {
$sql = mysqli_query($mysqli, "SELECT invoice_id, invoice_discount_amount, invoice_client_id, MONTH(invoice_date) AS m, 1 AS w
FROM invoices WHERE invoice_status IN ('Sent', 'Viewed', 'Partial', 'Paid') AND invoice_date >= '$from' AND invoice_date <= '$to'");
} else {
$sql = mysqli_query($mysqli, "SELECT invoice_id, invoice_discount_amount, invoice_client_id, MONTH(payment_date) AS m, payment_amount / invoice_amount AS w
FROM payments JOIN invoices ON invoice_id = payment_invoice_id
WHERE payment_archived_at IS NULL AND invoice_amount > 0 AND payment_date >= '$from' AND payment_date <= '$to'");
}
$rows = [];
while ($row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
}
// Every invoice's lines in a few queries, not one each
$items = [];
$ids = array_values(array_unique(array_map(function ($row) {
return intval($row['invoice_id']);
}, $rows)));
foreach (array_chunk($ids, 500) as $chunk) {
$sql = mysqli_query($mysqli, "SELECT item_id, item_invoice_id, item_subtotal, item_tax, item_tax_id, tax_name, tax_percent
FROM invoice_items LEFT JOIN taxes ON tax_id = item_tax_id WHERE item_invoice_id IN (" . implode(',', $chunk) . ")");
while ($item = mysqli_fetch_assoc($sql)) {
$items[intval($item['item_invoice_id'])][] = $item;
}
}
// Clients exempt now, with their certificates
$exempt_clients = [];
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_tax_exempt_number, client_tax_exempt_expires FROM clients WHERE client_tax_exempt = 1");
while ($row = mysqli_fetch_assoc($sql)) {
$expires = (string) $row['client_tax_exempt_expires'];
$exempt_clients[intval($row['client_id'])] = ['name' => $row['client_name'], 'number' => (string) $row['client_tax_exempt_number'], 'expires' => $expires,
'expired' => $expires !== '' && $expires < date('Y-m-d'), 'amount' => 0.0];
}
$out = ['parts' => [], 'numbers' => [], 'sales' => taxReportMonths(), 'taxable' => taxReportMonths(), 'nontaxable' => taxReportMonths(),
'exempt' => taxReportMonths(), 'exempt_clients' => [], 'invoices' => count($ids)];
$done = [];
foreach ($rows as $row) {
$invoice_id = intval($row['invoice_id']);
$client_id = intval($row['invoice_client_id']);
$m = intval($row['m']);
$w = floatval($row['w']);
if (!isset($done[$invoice_id])) {
$done[$invoice_id] = taxReportInvoice($items[$invoice_id] ?? [], $row['invoice_discount_amount'], isset($exempt_clients[$client_id]));
}
$invoice = $done[$invoice_id];
foreach (['sales', 'taxable', 'nontaxable', 'exempt'] as $key) {
$out[$key][$m] += $invoice[$key] * $w;
}
foreach ($invoice['parts'] as $part => $amount) {
$out['parts'][$part] = $out['parts'][$part] ?? ['months' => taxReportMonths(), 'total' => 0.0];
$out['parts'][$part]['months'][$m] += $amount * $w;
$out['parts'][$part]['total'] += $amount * $w;
}
$out['numbers'] += $invoice['numbers'];
if ($invoice['exempt'] != 0) {
$out['exempt_clients'][$client_id] = $out['exempt_clients'][$client_id] ?? $exempt_clients[$client_id];
$out['exempt_clients'][$client_id]['amount'] += $invoice['exempt'] * $w;
}
}
ksort($out['parts'], SORT_NATURAL | SORT_FLAG_CASE);
uasort($out['exempt_clients'], function ($a, $b) {
return $b['amount'] <=> $a['amount'];
});
return $out;
}
/**
* Tax paid on purchases from $from to $to, by month - the tax included in
* expenses, by part of its rate ('Other tax' for an amount with no rate of
* ours). ['parts' => label => ['months', 'total'], 'purchases' => months -
* what those expenses came to before tax, 'expenses' => how many].
*/
function taxReportPurchases($from, $to) {
global $mysqli;
$from = escapeSql($from);
$to = escapeSql($to);
$out = ['parts' => [], 'purchases' => taxReportMonths(), 'expenses' => 0];
$sql = mysqli_query($mysqli, "SELECT MONTH(expense_date) AS m, expense_amount, expense_tax_amount, expense_tax_id FROM expenses
WHERE expense_tax_amount != 0 AND expense_archived_at IS NULL AND expense_date >= '$from' AND expense_date <= '$to'");
while ($row = mysqli_fetch_assoc($sql)) {
$m = intval($row['m']);
$tax = floatval($row['expense_tax_amount']);
$net = floatval($row['expense_amount']) - $tax;
$out['purchases'][$m] += $net;
$out['expenses']++;
foreach (taxSplit($tax, taxRow($row['expense_tax_id']), $net, 'Other tax')['parts'] as $part => $amount) {
$out['parts'][$part] = $out['parts'][$part] ?? ['months' => taxReportMonths(), 'total' => 0.0];
$out['parts'][$part]['months'][$m] += $amount;
$out['parts'][$part]['total'] += $amount;
}
}
ksort($out['parts'], SORT_NATURAL | SORT_FLAG_CASE);
return $out;
}