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

@@ -406,6 +406,7 @@ $month_change = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['la
<td class="text-end itflow-money text-nowrap">
<span class="fw-semibold <?= $row_amount < 0 ? 'text-success-emphasis' : '' ?>"><?= escapeHtml(billingMoney($row_amount, $row_currency)) ?></span>
<?php if ($row_amount < 0) { ?><div class="small text-body-secondary">Refund</div><?php } ?>
<?php if (floatval($row['expense_tax_amount']) != 0) { ?><div class="small text-body-secondary">incl. <?= escapeHtml(billingMoney(abs(floatval($row['expense_tax_amount'])), $row_currency)) ?> tax</div><?php } ?>
</td>
<td class="text-end">
<div class="dropdown dropstart">

View File

@@ -76,6 +76,9 @@ ob_start();
</div>
<div class="text-end">
<div class="fs-4 fw-semibold itflow-money <?= $amount < 0 ? 'text-success' : 'text-white' ?>"><?= escapeHtml(billingMoney($amount, $currency)) ?></div>
<?php if (floatval($row['expense_tax_amount']) != 0) { ?>
<div class="small text-body-secondary">incl. <?= escapeHtml(billingMoney(abs(floatval($row['expense_tax_amount'])), $currency)) ?> tax</div>
<?php } ?>
</div>
</div>
<button type="button" class="btn-close btn-close-white ms-3" data-bs-dismiss="modal" aria-label="Close"></button>
@@ -130,6 +133,12 @@ ob_start();
<i class="fas fa-fw fa-list"></i>
<span><?= expenseCategoryDot($row['category_color']) ?><?= escapeHtml($row['category_name'] ?: 'No category') ?></span>
</div>
<?php if (floatval($row['expense_tax_amount']) != 0) { ?>
<div class="itflow-glance-item" title="Tax included">
<i class="fas fa-fw fa-percent"></i>
<span><?= escapeHtml(billingMoney(abs(floatval($row['expense_tax_amount'])), $currency)) ?> tax<?= $row['tax_name'] !== null ? ' at ' . escapeHtml(taxLabel($row)) : '' ?>, on <?= escapeHtml(billingMoney(abs($amount) - abs(floatval($row['expense_tax_amount'])), $currency)) ?></span>
</div>
<?php } ?>
<?php if ($mileage_trips) { ?>
<div class="itflow-glance-item" title="Mileage">
<i class="fas fa-fw fa-car-side"></i>

View File

@@ -9,11 +9,12 @@
* $form_vendor_id the vendor a new one starts with (0 to pick)
* $form_client_id the client a new one starts with (0 for none)
*
* Posts date, amount, vendor, category, account ('personal' with paid_by
* when an agent paid it themselves), payment_method, client_id, reference,
* description, billable and markup, the receipt as `file`, and refund_of
* (refund) or receipt_remove (edit). Picking a vendor on a new expense fills in the
* category, account and payment method of the last expense with them,
* Posts date, amount, tax_id and tax_amount (expense_tax_fields.php),
* vendor, category, account ('personal' with paid_by when an agent paid it
* themselves), payment_method, client_id, reference, description, billable
* and markup, the receipt as `file`, and refund_of (refund) or
* receipt_remove (edit). Picking a vendor on a new expense fills in the
* category, account, payment method and tax of the last expense with them,
* unless those were changed by hand.
*
* Should not be accessed directly.
@@ -165,6 +166,15 @@ $form_markup = $form_row && !$form_refund ? floatval($form_row['expense_markup']
</div>
</div>
<?php
$tax_form_id = $form_id;
$tax_selected = $form_row ? intval($form_row['expense_tax_id']) : 0;
$tax_amount = $form_edit ? floatval($form_row['expense_tax_amount']) : null;
$tax_currency = $form_currency;
$tax_lock = (bool) $form_lock;
require __DIR__ . '/expense_tax_fields.php';
?>
<div class="col-md-7">
<label class="form-label">Paid from <strong class="text-danger">*</strong></label>
<div class="input-group">
@@ -389,7 +399,8 @@ $form_markup = $form_row && !$form_refund ? floatval($form_row['expense_markup']
var fields = {
category: root.querySelector('[data-expense-category]'),
account: root.querySelector('[data-expense-account]'),
method: root.querySelector('[data-expense-method]')
method: root.querySelector('[data-expense-method]'),
tax: root.querySelector('[data-expense-tax-rate]')
};
var touched = {};
var filling = false;

View File

@@ -0,0 +1,90 @@
<?php
/*
* The tax included in what an expense cost - its rate, and the amount,
* worked out from the amount as it is typed until it is changed by hand to
* what the receipt says. For expense_form.php and recurring_expense_form.php,
* which set before including:
*
* $tax_form_id the form's root element id (the amount is its input[name=amount])
* $tax_selected the rate picked (0 for none)
* $tax_amount the tax saved, or null to work it out
* $tax_currency the currency shown beside it
* $tax_lock true when the amount can't change (cleared on a reconciled statement)
*
* Posts tax_id and tax_amount (expenseTaxFromInput()).
*/
isset($mysqli) || die("Direct file access is not allowed");
$tax_choices = billingTaxes();
?>
<div class="col-md-7">
<label class="form-label">Tax included</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-percent"></i></span>
<select class="form-select" name="tax_id" data-expense-tax-rate>
<?= taxOptionsHtml($tax_choices, intval($tax_selected)) ?>
</select>
</div>
</div>
<div class="col-md-5">
<label class="form-label">Tax</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-balance-scale"></i></span>
<input type="text" class="form-control text-end" inputmode="decimal" pattern="-?[0-9,]*\.?[0-9]{0,2}" name="tax_amount" placeholder="0.00"
value="<?= $tax_amount === null || floatval($tax_amount) == 0 ? '' : number_format(abs(floatval($tax_amount)), 2, '.', '') ?>" data-expense-tax-amount <?= !empty($tax_lock) ? 'readonly' : '' ?>>
<span class="input-group-text"><?= escapeHtml($tax_currency) ?></span>
</div>
<div class="form-text">Part of the amount - change it to what the receipt says.</div>
</div>
<script>
(function () {
// The tax follows the amount and rate until it is typed over
var root = document.getElementById(<?= json_encode($tax_form_id) ?>);
if (!root || root.dataset.taxWired) {
return;
}
root.dataset.taxWired = '1';
var amount = root.querySelector('input[name="amount"]');
var rate = root.querySelector('[data-expense-tax-rate]');
var tax = root.querySelector('[data-expense-tax-amount]');
function number(value) {
var n = Number(String(value || '').replace(/[\s,$]/g, ''));
return isNaN(n) ? 0 : n;
}
// What the rate makes of the amount - as taxIncluded() does
function worked() {
var option = rate.options[rate.selectedIndex];
var percent = option ? number(option.getAttribute('data-percent')) : 0;
var gross = Math.abs(number(amount.value));
if (!percent || !gross) {
return '';
}
var net = Math.round(gross / (1 + percent / 100) * 100) / 100;
return (Math.round((gross - net) * 100) / 100).toFixed(2);
}
// A saved tax that isn't what the rate makes of it was typed from a receipt
var byHand = tax.value !== '' && tax.value !== worked();
function update() {
if (byHand || tax.readOnly) {
return;
}
tax.value = worked();
}
tax.addEventListener('input', function () {
byHand = tax.value.trim() !== '';
});
rate.addEventListener('change', function () {
// A new rate works it out again
byHand = false;
update();
});
amount.addEventListener('input', update);
if (tax.value === '') {
update();
}
})();
</script>

View File

@@ -56,6 +56,9 @@ ob_start();
</div>
<div class="text-end">
<div class="fs-4 fw-semibold itflow-money text-white"><?= escapeHtml(billingMoney($amount, $currency)) ?></div>
<?php if (floatval($row['recurring_expense_tax_amount']) != 0) { ?>
<div class="small text-body-secondary" title="<?= $row['tax_name'] !== null ? escapeHtml(taxLabel($row)) : 'Tax included' ?>">incl. <?= escapeHtml(billingMoney(floatval($row['recurring_expense_tax_amount']), $currency)) ?> tax</div>
<?php } ?>
<div class="small text-body-secondary"><?= escapeHtml(strtolower(recurringInvoiceFrequencies()[$row['recurring_expense_frequency']] ?? 'monthly')) ?></div>
</div>
</div>

View File

@@ -8,8 +8,9 @@
* $form_vendor_id the vendor a new one starts with (0 to pick)
* $form_client_id the client a new one starts with (0 for none)
*
* Posts vendor, amount, frequency, next_date, end_date, category, account,
* payment_method, client_id, reference and description. The schedule reads
* Posts vendor, amount, tax_id and tax_amount (expense_tax_fields.php),
* frequency, next_date, end_date, category, account, payment_method,
* client_id, reference and description. The schedule reads
* back in words as it is set; picking a vendor on a new one fills in what
* the last expense with them used, unless that was changed by hand.
*
@@ -98,6 +99,15 @@ while ($row = mysqli_fetch_assoc($sql)) {
</div>
</div>
<?php
$tax_form_id = $form_id;
$tax_selected = $form_edit ? intval($form_row['recurring_expense_tax_id']) : 0;
$tax_amount = $form_edit ? floatval($form_row['recurring_expense_tax_amount']) : null;
$tax_currency = $form_currency;
$tax_lock = false;
require __DIR__ . '/../expense/expense_tax_fields.php';
?>
<div class="col-md-4">
<label class="form-label">How often <strong class="text-danger">*</strong></label>
<div class="input-group">
@@ -323,7 +333,8 @@ while ($row = mysqli_fetch_assoc($sql)) {
var fields = {
category: root.querySelector('[data-expense-category]'),
account: root.querySelector('[data-expense-account]'),
method: root.querySelector('[data-expense-method]')
method: root.querySelector('[data-expense-method]'),
tax: root.querySelector('[data-expense-tax-rate]')
};
var touched = {};
var filling = false;

View File

@@ -485,6 +485,11 @@ if (isExportRequest('export_clients')) {
$export = beginExport('clients', $format, "$session_company_name-$export_label", $export_label, summarizeExportFilters($filter_summary));
while ($row = mysqli_fetch_assoc($sql)) {
$tax_client = taxClient($row['client_id']);
$row['client_tax_rate'] = intval($tax_client['default_id']) ? taxLabel(taxRow($tax_client['default_id'])) : '';
$row['client_tax_exempt_display'] = $tax_client['exempt'] ? 'Yes' : '';
$row['client_tax_exempt_number'] = $tax_client['exempt'] ? $tax_client['number'] : '';
$row['client_tax_exempt_expires'] = $tax_client['exempt'] ? $tax_client['expires'] : '';
addExportRow($export, $row);
}

View File

@@ -368,6 +368,8 @@ if (isExportRequest('export_expenses')) {
while ($row = mysqli_fetch_assoc($sql)) {
$row['expense_receipt_display'] = $row['expense_receipt'] ? 'Yes' : 'No';
$row['expense_tax_rate'] = intval($row['expense_tax_id']) ? taxLabel(taxRow($row['expense_tax_id'])) : (floatval($row['expense_tax_amount']) != 0 ? 'Other' : '');
$row['expense_before_tax'] = round(floatval($row['expense_amount']) - floatval($row['expense_tax_amount']), 2);
$markup = rtrim(rtrim(number_format(floatval($row['expense_markup']), 2, '.', ''), '0'), '.') . '%';
$row['expense_billing_display'] = $row['expense_invoice_id'] ? "Billed, $markup markup" : (intval($row['expense_billable']) ? "To bill, $markup markup" : '');
$row['expense_billed_on'] = $row['expense_invoice_id'] && $row['invoice_number'] !== null ? $row['invoice_prefix'] . $row['invoice_number'] : '';

View File

@@ -561,6 +561,18 @@ if (isExportRequest('export_invoices')) {
while ($row = mysqli_fetch_assoc($sql)) {
$row['invoice_number_display'] = $row['invoice_prefix'] . $row['invoice_number'];
// Subtotal, tax and tax by part are opt-in too
if (isset($export['columns']['invoice_subtotal']) || isset($export['columns']['invoice_tax']) || isset($export['columns']['invoice_tax_parts'])) {
$invoice_items = billingItems('invoice', $row['invoice_id']);
$row['invoice_subtotal'] = round(array_sum(array_column($invoice_items, 'item_subtotal')), 2);
$row['invoice_tax'] = round(array_sum(array_column($invoice_items, 'item_tax')), 2);
$tax_parts = [];
foreach (billingTaxParts($invoice_items)['parts'] as $label => $amount) {
$tax_parts[] = "$label: " . number_format($amount, 2, '.', '');
}
$row['invoice_tax_parts'] = implode('; ', $tax_parts);
}
// Paid / balance are opt-in columns - only pay for the lookup if asked
if (isset($export['columns']['amount_paid']) || isset($export['columns']['invoice_balance'])) {
$invoice_id = intval($row['invoice_id']);

View File

@@ -489,7 +489,7 @@ if (isExportRequest('export_quotes')) {
$sql = mysqli_query(
$mysqli,
"SELECT client_name, quote_amount, quote_monthly_amount, quote_date, quote_number, quote_prefix, quote_scope,
"SELECT client_name, quote_id, quote_amount, quote_discount_amount, quote_monthly_amount, quote_date, quote_number, quote_prefix, quote_scope,
quote_status FROM quotes
LEFT JOIN clients ON quote_client_id = client_id
LEFT JOIN categories ON quote_category_id = category_id
@@ -510,6 +510,11 @@ if (isExportRequest('export_quotes')) {
while ($row = mysqli_fetch_assoc($sql)) {
$row['quote_number_display'] = $row['quote_prefix'] . $row['quote_number'];
if (isset($export['columns']['quote_tax'])) {
// The tax on what it bills up front, beside its amount
$quote_groups = quoteLineGroups(billingItems('quote', $row['quote_id']), floatval($row['quote_discount_amount']));
$row['quote_tax'] = round(floatval($quote_groups['']['tax'] ?? 0), 2);
}
addExportRow($export, $row);
}

View File

@@ -360,7 +360,7 @@ if (isExportRequest('export_recurring_invoices')) {
$sql = mysqli_query(
$mysqli,
"SELECT client_name, recurring_invoice_amount, recurring_invoice_created_at,
"SELECT client_name, recurring_invoice_id, recurring_invoice_amount, recurring_invoice_created_at,
recurring_invoice_frequency, recurring_invoice_number, recurring_invoice_prefix,
recurring_invoice_scope FROM recurring_invoices
LEFT JOIN clients ON recurring_invoice_client_id = client_id
@@ -384,6 +384,9 @@ if (isExportRequest('export_recurring_invoices')) {
while ($row = mysqli_fetch_assoc($sql)) {
$row['recurring_invoice_number_display'] = $row['recurring_invoice_prefix'] . $row['recurring_invoice_number'];
$row['recurring_invoice_frequency_display'] = recurringInvoiceFrequencies()[$row['recurring_invoice_frequency']] ?? ucfirst((string) $row['recurring_invoice_frequency']);
if (isset($export['columns']['recurring_invoice_tax'])) {
$row['recurring_invoice_tax'] = round(array_sum(array_column(billingItems('recurring', $row['recurring_invoice_id']), 'item_tax')), 2);
}
addExportRow($export, $row);
}

View File

@@ -1,116 +1,119 @@
<?php
/*
* Tax Collected - the tax on paid invoices, by tax and month or quarter, with
* the sales it was charged on beside it - what a sales tax return asks for.
* Tax Collected - the tax on sales by part of each rate (a state's and a
* county's apart), with the sales it was charged on and the taxable, exempt
* and non-taxable sales beside it, by month or quarter - what a sales tax,
* GST or VAT return asks for. Then the tax paid on purchases and what is
* left to pay, and the exempt sales by client with their certificates.
*
* Cash basis, the same as getMonthlyTax(): tax counts when the payment
* arrives, in proportion to how much of the invoice that payment covered, so
* a part-paid invoice has only that part of its tax counted. Each invoice's
* line items are added up per tax first, so an invoice with several payments
* never multiplies its own tax.
* Invoiced counts each invoice sent in the month of its date; Paid counts
* each payment, carrying its share of its invoice (functions/tax.php:
* taxReportSales()). Sales are net of discounts, before tax.
*/
require_once "includes/inc_report.php";
reportEnforce('tax_summary');
[$year, $years] = reportYear("SELECT YEAR(payment_date) AS y FROM payments");
$basis = isset(TAX_REPORT_BASES[$_GET['basis'] ?? '']) ? $_GET['basis'] : 'paid';
[$year, $years] = reportYear($basis === 'invoiced'
? "SELECT YEAR(invoice_date) AS y FROM invoices WHERE invoice_status IN ('Sent', 'Viewed', 'Partial', 'Paid') UNION SELECT YEAR(expense_date) FROM expenses WHERE expense_tax_amount != 0"
: "SELECT YEAR(payment_date) AS y FROM payments UNION SELECT YEAR(expense_date) FROM expenses WHERE expense_tax_amount != 0");
$view = ($_GET['view'] ?? 'quarter') === 'month' ? 'month' : 'quarter';
$current_year = $year === intval(date('Y'));
$columns = reportYearColumns($view);
/** Tax and taxable sales collected between two dates - [tax id => ['tax' => [1..12], 'sales' => [1..12]]]. */
function taxCollected($from, $to) {
global $mysqli;
$sql = mysqli_query($mysqli, "
SELECT item_tax.item_tax_id AS tax_id, MONTH(payment_date) AS m,
SUM(item_tax.tax_total * payment_amount / invoice_amount) AS tax,
SUM(item_tax.sales_total * payment_amount / invoice_amount) AS sales
FROM payments
JOIN invoices ON invoice_id = payment_invoice_id
JOIN (
SELECT item_invoice_id, item_tax_id, SUM(item_tax) AS tax_total, SUM(item_subtotal) AS sales_total
FROM invoice_items
WHERE item_tax_id > 0
GROUP BY item_invoice_id, item_tax_id
) AS item_tax ON item_tax.item_invoice_id = invoice_id
WHERE payment_date >= '$from' AND payment_date < '$to' + INTERVAL 1 DAY AND invoice_amount > 0
GROUP BY item_tax.item_tax_id, m");
$taxes = [];
while ($row = mysqli_fetch_assoc($sql)) {
$id = intval($row['tax_id']);
$taxes[$id] = $taxes[$id] ?? ['tax' => array_fill(1, 12, 0.0), 'sales' => array_fill(1, 12, 0.0)];
$taxes[$id]['tax'][intval($row['m'])] += floatval($row['tax']);
$taxes[$id]['sales'][intval($row['m'])] += floatval($row['sales']);
}
return $taxes;
}
$to = $current_year ? date('Y-m-d') : "$year-12-31";
$collected = taxCollected("$year-01-01", $to);
$prev_collected = taxCollected(($year - 1) . '-01-01', $current_year ? dashboardShiftMonths(date('Y-m-d'), -12) : ($year - 1) . '-12-31');
$sales = taxReportSales("$year-01-01", $to, $basis);
$purchases = taxReportPurchases("$year-01-01", $to);
$prev = taxReportSales(($year - 1) . '-01-01', $current_year ? dashboardShiftMonths(date('Y-m-d'), -12) : ($year - 1) . '-12-31', $basis);
$compare = $current_year ? 'the same time last year' : (string) ($year - 1);
// Every tax not archived, and any archived one that collected something
$taxes = [];
$ids = array_keys($collected);
$sql = mysqli_query($mysqli, "SELECT tax_id, tax_name, tax_percent, tax_archived_at FROM taxes
WHERE tax_archived_at IS NULL" . ($ids ? " OR tax_id IN (" . implode(',', array_map('intval', $ids)) . ")" : '') . "
ORDER BY tax_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$taxes[intval($row['tax_id'])] = $row;
$sum = function (array $months) {
return array_sum($months);
};
$tax_months = taxReportMonths();
foreach ($sales['parts'] as $part) {
foreach ($part['months'] as $m => $amount) {
$tax_months[$m] += $amount;
}
}
$paid_months = taxReportMonths();
foreach ($purchases['parts'] as $part) {
foreach ($part['months'] as $m => $amount) {
$paid_months[$m] += $amount;
}
}
$net_months = array_map(function ($collected, $paid) {
return $collected - $paid;
}, $tax_months, $paid_months);
$net_months = array_combine(range(1, 12), $net_months);
$tax_total = $sum($tax_months);
$paid_total = $sum($paid_months);
$prev_tax_total = array_sum(array_column($prev['parts'], 'total'));
$has_purchases = (bool) $purchases['parts'];
// A table row for each figure: [group, name, sub, months, emphasis]
$grid = [];
foreach ($sales['parts'] as $label => $part) {
$grid[] = ['Tax collected', $label, '', $part['months'], false];
}
$grid[] = ['Tax collected', 'Total tax collected', '', $tax_months, true];
$grid[] = ['Sales, before tax and net of discounts', 'Total sales', '', $sales['sales'], true];
$grid[] = ['Sales, before tax and net of discounts', 'Taxable', 'Lines with tax on them', $sales['taxable'], false];
$grid[] = ['Sales, before tax and net of discounts', 'Exempt', 'No tax, for clients who are tax exempt', $sales['exempt'], false];
$grid[] = ['Sales, before tax and net of discounts', 'Non-taxable', 'No tax, for clients who are not exempt', $sales['nontaxable'], false];
if ($has_purchases) {
foreach ($purchases['parts'] as $label => $part) {
$grid[] = ['Tax paid on purchases', $label, '', $part['months'], false];
}
$grid[] = ['Tax paid on purchases', 'Total tax paid', '', $paid_months, true];
$grid[] = ['Tax paid on purchases', 'Purchases it was paid on', 'Before tax', $purchases['purchases'], false];
$grid[] = ['Collected less paid', 'Net tax', 'For GST, HST and VAT returns that take off tax paid', $net_months, true];
}
$lines = [];
$tax_total = 0.0;
$sales_total = 0.0;
$prev_tax_total = 0.0;
foreach ($taxes as $id => $tax) {
$amounts = $collected[$id] ?? ['tax' => array_fill(1, 12, 0.0), 'sales' => array_fill(1, 12, 0.0)];
$prev = array_sum($prev_collected[$id]['tax'] ?? []);
$lines[$id] = [
'name' => $tax['tax_name'], 'percent' => floatval($tax['tax_percent']), 'archived' => !empty($tax['tax_archived_at']),
'tax' => reportSumColumns($amounts['tax'], $columns), 'sales' => reportSumColumns($amounts['sales'], $columns),
'tax_total' => array_sum($amounts['tax']), 'sales_total' => array_sum($amounts['sales']), 'prev' => $prev,
'tax_months' => $amounts['tax'],
];
$tax_total += $lines[$id]['tax_total'];
$sales_total += $lines[$id]['sales_total'];
$prev_tax_total += $prev;
}
if (reportExporting()) {
$csv_columns = ['name' => ['label' => 'Tax'], 'what' => ['label' => 'Figure']];
if (reportExporting() && ($_GET['table'] ?? 'tax') === 'tax') {
$csv_columns = ['group' => ['label' => 'Section'], 'name' => ['label' => 'Figure'], 'registration' => ['label' => 'Registration']];
foreach ($columns as $i => [$label]) {
$csv_columns["c$i"] = ['label' => $label, 'type' => 'money'];
}
$csv_columns['total'] = ['label' => (string) $year, 'type' => 'money'];
$rows = [];
foreach ($lines as $line) {
foreach (['tax' => 'Tax collected', 'sales' => 'Taxable sales'] as $key => $what) {
$row = ['name' => $line['name'] . ' (' . taxPercentText($line['percent']) . '%)', 'what' => $what, 'total' => $line[$key . '_total']];
foreach ($columns as $i => $column) {
$row["c$i"] = $line[$key][$i];
}
$rows[] = $row;
foreach ($grid as [$group, $name, $sub, $months]) {
$row = ['group' => $group, 'name' => $name, 'registration' => $group === 'Tax collected' ? ($sales['numbers'][$name] ?? '') : '', 'total' => round(array_sum($months), 2)];
foreach (reportSumColumns($months, $columns) as $i => $value) {
$row["c$i"] = round($value, 2);
}
$rows[] = $row;
}
reportCsv("Tax Collected $year", $csv_columns, $rows);
reportCsv('Tax Collected ' . $year . ' ' . TAX_REPORT_BASES[$basis], $csv_columns, $rows);
}
if (reportExporting('exempt')) {
$rows = [];
foreach ($sales['exempt_clients'] as $client) {
$rows[] = ['client' => $client['name'], 'number' => $client['number'], 'expires' => $client['expires'], 'amount' => round($client['amount'], 2)];
}
reportCsv("Exempt Sales $year", [
'client' => ['label' => 'Client'], 'number' => ['label' => 'Certificate'], 'expires' => ['label' => 'Expires'], 'amount' => ['label' => 'Exempt sales', 'type' => 'money'],
], $rows);
}
require_once "includes/inc_report_layout.php";
$percent_text = function ($percent) {
return taxPercentText($percent) . '%';
};
$span = count($columns) + 2;
$basis_note = $basis === 'invoiced'
? 'Counted on each invoice\'s date once it is sent, paid or not. Drafts, cancelled and non-billable invoices are left out.'
: 'Counted as payments come in: each payment carries its share of its invoice\'s tax and sales, so a part-paid invoice counts only the part paid.';
$stats = [
['label' => 'Tax collected', 'value' => reportMoney($tax_total), 'sub' => reportChangeHtml($tax_total, $prev_tax_total, 'up', $compare)],
['label' => 'Taxable sales', 'value' => reportMoney($sales_total), 'sub' => '<span class="text-body-tertiary">The paid sales the tax was on</span>'],
['label' => 'Taxable sales', 'value' => reportMoney($sum($sales['taxable'])), 'sub' => '<span class="text-body-tertiary">Of ' . escapeHtml(reportMoney($sum($sales['sales']))) . ' in sales</span>'],
['label' => 'Exempt sales', 'value' => reportMoney($sum($sales['exempt'])), 'sub' => '<span class="text-body-tertiary">' . count($sales['exempt_clients']) . ' exempt client' . (count($sales['exempt_clients']) === 1 ? '' : 's') . '</span>'],
['label' => 'Non-taxable sales', 'value' => reportMoney($sum($sales['nontaxable'])), 'sub' => '<span class="text-body-tertiary">No tax on the line</span>'],
];
foreach (array_slice($lines, 0, 3, true) as $line) {
$stats[] = ['label' => $line['name'], 'value' => reportMoney($line['tax_total']), 'sub' => '<span class="text-body-tertiary">At ' . escapeHtml($percent_text($line['percent'])) . '</span>'];
if ($has_purchases) {
$stats[] = ['label' => 'Tax paid on purchases', 'value' => reportMoney($paid_total), 'sub' => '<span class="text-body-tertiary">On ' . $purchases['expenses'] . ' expense' . ($purchases['expenses'] === 1 ? '' : 's') . '</span>'];
$stats[] = ['label' => 'Net tax', 'value' => reportMoney($tax_total - $paid_total), 'sub' => '<span class="text-body-tertiary">Collected less paid</span>'];
}
?>
@@ -119,47 +122,52 @@ foreach (array_slice($lines, 0, 3, true) as $line) {
<?php reportHeader('tax_summary', [
'year' => [$year, $years],
'controls' => reportSegmentControl('view', $view, ['quarter' => 'Quarterly', 'month' => 'Monthly']),
'subtitle' => $current_year ? "$year to date" : (string) $year,
'controls' => reportSegmentControl('basis', $basis, TAX_REPORT_BASES) . reportSegmentControl('view', $view, ['quarter' => 'Quarterly', 'month' => 'Monthly']),
'subtitle' => ($current_year ? "$year to date" : (string) $year) . ' · ' . TAX_REPORT_BASES[$basis],
'export' => $sales['exempt_clients'] ? ['tax' => 'Tax by ' . $view, 'exempt' => 'Exempt sales by client'] : ['tax' => 'Tax by ' . $view],
'note' => escapeHtml($basis_note) . ' Sales are before tax and net of discounts.',
'print_meta' => TAX_REPORT_BASES[$basis] . ' basis',
]); ?>
<?= reportStats($stats) ?>
<?php if (!$taxes) { ?>
<div class="card"><div class="card-body"><?= reportEmpty('No taxes are set up. Add them in Admin > Taxes, and the tax on paid invoices shows here.', 'fa-percent', 'secondary') ?></div></div>
<?php if (!$sales['invoices'] && !$has_purchases) { ?>
<div class="card"><div class="card-body"><?= reportEmpty($basis === 'invoiced' ? "No invoices were sent in $year." : "No payments came in during $year.", 'fa-percent', 'secondary') ?></div></div>
<?php } else { ?>
<?= reportSectionOpen('Tax collected by month', escapeHtml((string) $year)) ?>
<div class="card-body">
<?php
$months_shown = $current_year ? intval(date('n')) : 12;
$series = [];
$i = 0;
foreach ($lines as $line) {
if ($line['tax_total'] <= 0) {
continue;
<?php if ($tax_total != 0) { ?>
<?= reportSectionOpen('Tax collected by month', escapeHtml((string) $year)) ?>
<div class="card-body">
<?php
$months_shown = $current_year ? intval(date('n')) : 12;
$series = [];
$i = 0;
foreach ($sales['parts'] as $label => $part) {
if (abs($part['total']) < 0.005) {
continue;
}
$series[] = ['label' => $label, 'data' => array_map(function ($m) use ($part, $months_shown) {
return $m <= $months_shown ? round($part['months'][$m], 2) : null;
}, range(1, 12)), 'tone' => reportPalette($i++), 'stack' => 'tax'];
}
$series[] = ['label' => $line['name'], 'data' => array_map(function ($m) use ($line, $months_shown) {
return $m <= $months_shown ? round($line['tax_months'][$m], 2) : null;
}, range(1, 12)), 'tone' => reportPalette($i++), 'stack' => 'tax'];
}
echo reportChart([
'type' => 'bar',
'labels' => array_map(function ($m) { return date('M', mktime(0, 0, 0, $m, 1)); }, range(1, 12)),
'series' => $series,
'stacked' => true,
'format' => 'money',
], 'sm', 'Tax collected per month, by tax');
?>
echo reportChart([
'type' => 'bar',
'labels' => array_map(function ($m) { return date('M', mktime(0, 0, 0, $m, 1)); }, range(1, 12)),
'series' => $series,
'stacked' => true,
'format' => 'money',
], 'sm', 'Tax collected per month, by part');
?>
</div>
</div>
</div>
<?php } ?>
<?= reportSectionOpen('By tax', $view === 'quarter' ? 'By calendar quarter' : 'By month') ?>
<?= reportSectionOpen('By ' . ($view === 'quarter' ? 'quarter' : 'month'), $view === 'quarter' ? 'Calendar quarters' : '') ?>
<div class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0 itflow-report-table itflow-report-grid">
<thead class="table-light">
<tr>
<th>Tax</th>
<th><?= TAX_REPORT_BASES[$basis] ?> basis</th>
<?php foreach ($columns as [$label, $first, $last]) { ?>
<th class="text-end"<?php if ($view === 'quarter') { ?> title="<?= date('M', mktime(0, 0, 0, $first, 1)) ?> – <?= date('M', mktime(0, 0, 0, $last, 1)) ?>"<?php } ?>><?= $label ?></th>
<?php } ?>
@@ -167,42 +175,70 @@ foreach (array_slice($lines, 0, 3, true) as $line) {
</tr>
</thead>
<tbody>
<tr class="itflow-report-group-row"><td colspan="<?= $span ?>">Tax collected</td></tr>
<?php foreach ($lines as $line) { ?>
<tr>
<td class="itflow-report-sub"><?= escapeHtml($line['name']) ?> <span class="text-body-secondary small"><?= escapeHtml($percent_text($line['percent'])) ?></span><?php if ($line['archived']) { ?> <span class="badge bg-secondary-subtle text-secondary-emphasis fw-normal">Archived</span><?php } ?></td>
<?php foreach ($columns as $i => $column) { ?>
<td class="text-end"><?= abs($line['tax'][$i]) < 0.005 ? '<span class="itflow-report-zero">–</span>' : reportMoney($line['tax'][$i]) ?></td>
<?php
$group_shown = '';
foreach ($grid as [$group, $name, $sub, $months, $strong]) {
if ($group !== $group_shown) {
$group_shown = $group; ?>
<tr class="itflow-report-group-row"><td colspan="<?= $span ?>"><?= escapeHtml($group) ?></td></tr>
<?php }
$cells = reportSumColumns($months, $columns);
$registration = $group === 'Tax collected' ? ($sales['numbers'][$name] ?? '') : ''; ?>
<tr<?= $strong ? ' class="fw-semibold"' : '' ?>>
<td class="<?= $strong ? '' : 'itflow-report-sub' ?>">
<?= escapeHtml($name) ?>
<?php if ($sub !== '') { ?><div class="small text-body-secondary fw-normal"><?= escapeHtml($sub) ?></div><?php } ?>
<?php if ($registration !== '') { ?><div class="small text-body-secondary fw-normal">No. <?= escapeHtml($registration) ?></div><?php } ?>
</td>
<?php foreach ($cells as $value) { ?>
<td class="text-end<?= $strong ? '' : ' text-body-secondary' ?>"><?= abs($value) < 0.005 ? '<span class="itflow-report-zero">–</span>' : reportMoney($value) ?></td>
<?php } ?>
<td class="text-end fw-semibold"><?= reportMoney($line['tax_total']) ?></td>
</tr>
<?php } ?>
<tr class="fw-semibold">
<td>Total tax</td>
<?php foreach ($columns as $i => $column) { ?>
<td class="text-end"><?= reportMoney(array_sum(array_map(function ($l) use ($i) { return $l['tax'][$i]; }, $lines))) ?></td>
<?php } ?>
<td class="text-end"><?= reportMoney($tax_total) ?></td>
</tr>
<tr class="itflow-report-group-row"><td colspan="<?= $span ?>">Sales the tax was charged on</td></tr>
<?php foreach ($lines as $line) { ?>
<tr>
<td class="itflow-report-sub"><?= escapeHtml($line['name']) ?></td>
<?php foreach ($columns as $i => $column) { ?>
<td class="text-end text-body-secondary"><?= abs($line['sales'][$i]) < 0.005 ? '<span class="itflow-report-zero">–</span>' : reportMoney($line['sales'][$i]) ?></td>
<?php } ?>
<td class="text-end"><?= reportMoney($line['sales_total']) ?></td>
<td class="text-end fw-semibold"><?= reportMoney(array_sum($months)) ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="card-footer small text-body-secondary">
Counted when invoices are paid: each payment carries its share of the invoice's tax, so a part-paid invoice counts only the part that came in.
Taxable sales are the line items each tax was charged on, before tax. Check figures with your accountant before filing.
Tax shows by part, so a rate made of a state's and a county's part counts each where it is due. A rate that changed shows its old and new percents apart.
Exempt sales are untaxed lines for clients marked tax exempt now. Check the figures with your accountant before filing.
</div>
</div>
<?php if ($sales['exempt_clients']) { ?>
<?= reportSectionOpen('Exempt sales by client', count($sales['exempt_clients']) . ' client' . (count($sales['exempt_clients']) === 1 ? '' : 's')) ?>
<div class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0 itflow-report-table">
<thead class="table-light">
<tr>
<th>Client</th>
<th>Certificate</th>
<th>Expires</th>
<th class="text-end">Exempt sales</th>
</tr>
</thead>
<tbody>
<?php foreach ($sales['exempt_clients'] as $client_id => $client) { ?>
<tr>
<td><?= reportClientLink($client_id, $client['name']) ?></td>
<td><?= $client['number'] !== '' ? escapeHtml($client['number']) : '<span class="text-warning-emphasis">None on file</span>' ?></td>
<td>
<?php if ($client['expires'] === '') { ?>
<span class="text-body-secondary">–</span>
<?php } else { ?>
<?= escapeHtml(date('M j, Y', strtotime($client['expires']))) ?>
<?php if ($client['expired']) { ?><span class="badge rounded-pill bg-warning-subtle text-warning-emphasis fw-normal ms-1">Expired</span><?php } ?>
<?php } ?>
</td>
<td class="text-end"><?= reportMoney($client['amount']) ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<?php } ?>
<?php } ?>
</div>