From fee0a5cb804ebb83debb20a572e9c7dd5305dc5e Mon Sep 17 00:00:00 2001 From: johnnyq Date: Fri, 16 Oct 2026 12:37:50 -0400 Subject: [PATCH] Invoices, quotes and recurring invoices makeover stage 1: one shared document page for all three with inline line editing (product pick, live line totals, drag to reorder, lines locked once paid or answered), shared New/Edit form, late recurring invoices offer to skip to the next date without billing missed runs, Add Payment shows remaining balance and account balances, Batch Payment lists the invoices it will pay, Add Tickets takes several at once, new PDF layout for invoices, quotes and packing slips with pay/answer QR codes and paid/answered stamps, Letter or A4 by country, guest invoice Pay Now with other open invoices, guest quote Accept/Decline then signed copy or PO upload. Line amounts rounded to the cent on save, expired quotes can no longer be accepted from the link, Batch Payment skips non-billable invoices, recurring list creation-date filter removed. Fixes discount reset to zero on invoice/quote edit, stock not moving on invoice item quantity change, invoice status not updating on payment edit, autopay left behind on recurring invoice delete. Consolidates line items, totals, statuses and PDFs into functions/billing.php, includes/billing_paper.php, agent/post/billing.php and functions/billing_pdf.php with a single billing_items_order ajax reorder; removes the three item edit modals, link_invoice_to_ticket, guest_quote_upload_file_modal.php and js/product_autocomplete.js --- CHANGELOG.md | 48 + agent/ajax.php | 67 +- agent/invoice.php | 1172 ++++++----------- agent/invoices.php | 729 +++++----- agent/modals/billing/billing_form.php | 253 ++++ agent/modals/billing/billing_item.php | 135 ++ agent/modals/client/client_statement.php | 2 +- agent/modals/invoice/invoice_add.php | 103 +- agent/modals/invoice/invoice_add_ticket.php | 122 +- .../invoice/invoice_bulk_edit_category.php | 46 +- agent/modals/invoice/invoice_copy.php | 49 +- agent/modals/invoice/invoice_edit.php | 101 +- agent/modals/invoice/invoice_email.php | 29 +- agent/modals/invoice/invoice_export.php | 2 + agent/modals/invoice/invoice_item_edit.php | 103 -- agent/modals/invoice/invoice_mark_sent.php | 73 +- agent/modals/invoice/invoice_payments.php | 183 +-- .../modals/invoice/invoice_recurring_add.php | 50 +- agent/modals/payment/payment_add.php | 187 +-- agent/modals/payment/payment_bulk_add.php | 205 +-- agent/modals/payment/payment_edit.php | 149 +-- agent/modals/payment/payment_form.php | 140 ++ .../payment/payment_saved_method_add.php | 82 +- agent/modals/quote/quote_add.php | 99 +- agent/modals/quote/quote_copy.php | 98 +- agent/modals/quote/quote_edit.php | 95 +- agent/modals/quote/quote_email.php | 28 +- agent/modals/quote/quote_item_edit.php | 103 -- agent/modals/quote/quote_mark_sent.php | 73 +- agent/modals/quote/quote_to_invoice.php | 60 +- .../recurring_invoice_add.php | 104 +- .../recurring_invoice_edit.php | 130 +- .../recurring_invoice_item_edit.php | 103 -- agent/post/billing.php | 172 +++ agent/post/invoice.php | 665 +--------- agent/post/invoice_model.php | 6 +- agent/post/payment.php | 13 +- agent/post/quote.php | 391 +----- agent/post/quote_model.php | 4 +- agent/post/recurring_invoice.php | 181 +-- agent/quote.php | 933 ++++--------- agent/quotes.php | 424 +++--- agent/recurring_invoice.php | 800 ++++------- agent/recurring_invoices.php | 434 +++--- css/itflow_custom.css | 355 +++++ functions.php | 1 + functions/app.php | 4 +- functions/billing.php | 839 ++++++++++++ functions/billing_pdf.php | 305 +++++ guest/guest_post.php | 455 +------ guest/guest_quote_upload_file_modal.php | 25 - guest/guest_view_invoice.php | 645 +++------ guest/guest_view_quote.php | 401 ++---- includes/billing_paper.php | 286 ++++ js/billing_items.js | 233 ++++ js/product_autocomplete.js | 80 -- 56 files changed, 5573 insertions(+), 7002 deletions(-) create mode 100644 agent/modals/billing/billing_form.php create mode 100644 agent/modals/billing/billing_item.php delete mode 100644 agent/modals/invoice/invoice_item_edit.php create mode 100644 agent/modals/payment/payment_form.php delete mode 100644 agent/modals/quote/quote_item_edit.php delete mode 100644 agent/modals/recurring_invoice/recurring_invoice_item_edit.php create mode 100644 agent/post/billing.php create mode 100644 functions/billing.php create mode 100644 functions/billing_pdf.php delete mode 100644 guest/guest_quote_upload_file_modal.php create mode 100644 includes/billing_paper.php create mode 100644 js/billing_items.js delete mode 100644 js/product_autocomplete.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a20a8a71b..7fefe3ea0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,14 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Opening a link now takes a click on Reveal. This is so mail filters and chat apps that open every link cannot use up a one-time link. - Ended links stay listed for 90 days, with who opened them. They used to be deleted overnight. - Only the agent who made a link is told when it is opened. It used to notify every agent. +- Billing: + - Line amounts are rounded to the cent when a line is saved. Tax used to be stored unrounded, so a total could be a cent off what was printed. Lines already on file keep their amounts until they are edited. + - Taking a service line off an invoice no longer adds stock to the service. Only products kept in stock move stock, as before when they were added. + - A quote that has run out can no longer be accepted from its link. Extend its date, or send a new one. + - Batch Payment only pays invoices that are still owed (sent, viewed or part paid). It used to include non-billable invoices too, and marked them paid. + - Invoice and quote PDFs have a new layout, and print on Letter paper in the United States and Canada and A4 elsewhere. They were always A4. + - The recurring invoices list no longer has a date filter. It filtered by the date each one was created. + - Links to the invoices list with `?status=Draft`, `Unpaid` or `Overdue` still work, and `Paid` and `Cancelled` are new. - Notifications now follow access too. An agent only sees notifications for clients and areas they can open, so someone without sales access no longer sees invoice and quote notifications. - Drop-downs: Tom Select is gone, replaced by ITFlow's own picker. It works the way you are used to: type to search, tick several in a multi-select, and type a new value in fields that allow it, such as ticket watchers. See Developer Updates if you have custom pages that used Tom Select. - Several small windows are gone because the change is now made where the value is shown: @@ -164,6 +172,27 @@ If you are coming from 26.08 or earlier, the database update still has to be run - You are notified when a link you made is opened (you can switch this off per link), and always when one locks. - The key is the part of the link after the #, which browsers never send to the server, so it stays out of web server and proxy logs. Logins, notes and what clients send back are encrypted with that key, which is not stored, so the database alone cannot open them. - Admin > Settings > Security sets the longest a link may last, up to 90 days, and whether shared passwords and secure notes must have a passphrase or a code. +- **Billing** (rebuilt) + - Invoices, quotes and recurring invoices have new lists and pages, and every billing window is redone. + - Lists: + - Invoices: what you are owed, what of that is overdue, what is sitting in drafts and what came in over the last 30 days, each opening the invoices behind it. Filter by Draft, Unpaid, Overdue, Paid or Cancelled, by category, client and date. Each row shows what is still owed and how long until it is due, or how many days late it is. + - Quotes: what is out waiting for an answer, what has been accepted and not invoiced yet, what you won over the last 90 days and your win rate. Filter by Draft, Awaiting answer, Expired, Accepted, Invoiced or Declined. Each row shows how long a quote has left. + - Recurring invoices: your monthly recurring revenue (yearly ones count as a twelfth), what bills in the next 30 days, how many are running, and any that need a look. Filter by Active, Next 7 days, Late, Paused or All. Each row shows the amount, what it brings in a month, when it next bills, and whether it is on autopay. + - Pages: the invoice, quote or recurring invoice is shown the way the client sees it, with the next thing to do at the top: + - Invoice: Send (or Mark Sent) a draft, Add Payment on one that is owed, with Charge Saved Card when the client has a card on file. On the side: what has been paid and what is left with a progress bar, the payments (edit, refund through Stripe or delete them there), the tickets billed on it, and its history as a timeline. + - Quote: Send, then Accepted or Declined when the client answers by phone or email, then Make Invoice. A quote that ran out without an answer says so, with an Extend button. On the side: the files the client sent back, and its history. + - Recurring invoice: Invoice Now, Pause and Resume. On the side: the schedule with the next few dates and whether invoices go out by themselves, autopay, the invoices it has made and whether they were paid, and its history. When its next date has passed it won't bill until that moves on, so the page says so and offers to move it on to the next date without billing the missed ones. + - Lines are edited on the page: + - Type a product's name or code to fill in its description, price and tax. What the line comes to shows as you type, and Enter adds it. The page comes back ready for the next line. + - Drag a line to move it. Edit or remove it from its menu. An invoice's lines are locked once it is paid, cancelled or non-billable, and a quote's once it is answered. + - Taxes show by name on the totals, such as PA Sales Tax 6%, instead of one Tax line. + - Windows: New and Edit have the same fields for all three, with the discount on both. A new invoice shows its due date from the client's terms, and a quote's valid-until date has 15, 30, 60 and 90 day shortcuts. + - Add Payment starts at what is owed, says what is left after the payment as you type, and shows each account's balance. Batch Payment lists the invoices it will pay, oldest first. + - Send, Copy, Make Recurring, Make Invoice, Mark Sent and Add Tickets (any number at once) say what they will do before you do it. + - PDFs: one new look for invoices, quotes and packing slips, with your logo, taxes by name and page numbers. An invoice still owed carries a QR code to open it online and pay, and a quote waiting for an answer one to accept it. Paid, cancelled, accepted and declined ones are stamped. + - The client's view of an invoice: what is owed and by when, with Pay Now, the PDF, the payments made, and everything else they owe with a link to each. + - The client's view of a quote: Accept and Decline, with how long it is good for. Once accepted, they can send back a signed copy or a purchase order. + - A new recurring invoice can be set to leave a draft to check, and take a discount, from the start. - **Tickets** - The ticket list has views for Open, Mine, Unassigned, Needs reply, Waiting, Overdue, Scheduled, Closed and All. - Each row shows whose move it is (yours or the client's) along with SLA and due badges, and status, priority and agent change right in the row. @@ -330,6 +359,13 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Shared links: a mail filter or chat preview opening a one-time link used it up before the person it was for could open it. - Shared links: anyone holding a login link could keep getting its 2FA codes until the link expired, even after its one view was used. Codes now go only to the browser that opened it, for 30 minutes. - Shared links: the link's key, and for a login the key that decrypts it, were in the address, so they ended up in web server logs. +- Billing: editing an invoice or a quote set its discount to zero, and a discount given on a new quote was ignored. +- Billing: changing the quantity of a stocked product on an invoice did not move its stock. +- Billing: editing a payment's amount did not update the invoice, so it could stay Partial when paid in full or Paid when not. +- Billing: deleting a recurring invoice left its autopay behind. +- Billing: an invoice made from a quote was due counting from today instead of the invoice date, and with no terms when the client had none set. +- Billing: the client's view of a quote offered Accept on a viewed quote that had run out, and the invoice and quote views put the browser's HTML into the history. +- Billing: copying an invoice logged its old number with the prefix twice. - Copy buttons in many places, such as pages that already had a window open, showed Copied! but copied nothing. Copy guest URL on invoices and quotes jumped the page to the top, and copying an empty field wiped your clipboard. - Tickets: an agent without sales access who edited a ticket turned billable off. Email reply was offered when no mail server was set up. The timer threw an error on resolved tickets, and the due date was not shown. - Assets: editing some asset types wiped the OS, firmware, purchase and warranty fields. The add form broke when there were no OS values, and bulk assigning a contact or location could change assets of another client. @@ -466,6 +502,18 @@ If you are coming from 26.08 or earlier, the database update still has to be run - `agent/post/share.php` handles `share_revoke`, `share_revoke_all`, `share_bulk_revoke`, `share_request_save` (`credentialFormSet()`) and `share_request_discard`. - Notifications go to `item_created_by` only. Links with no owner fall back to `appNotify()`. - Removed: `agent/modals/share_modal.php`, `agent/js/share_modal.js`, `agent/modals/credential/credential_share.php`, `share_generate_link` in `agent/ajax.php`, `get_share_totp_token` in `guest/guest_ajax.php`, and `deactivate_shared_item` in `post/misc.php`. +- Billing: + - `functions/billing.php` (loaded by `functions.php`) serves invoices, quotes and recurring invoices through one map, `billingTypes()`: each kind's table, column prefix, items table and key, history column, page, list and URL parameter. `billingRow()` reads one with its client and category (scoped to the agent's clients unless told otherwise), and `billingItems()`, `billingTotals()`, `billingNumber()`, `billingMoney()` and `billingHistory()` work on any of the three. + - Lines: `billingItemSave()` adds or edits a line (amounts rounded by `billingLineAmounts()`, stock moved by the difference for invoice lines of `product_type` product), `billingItemDelete()` removes one, `billingItemsOrder()` reorders, and `billingRecalc()` sets the total from the lines less the discount and, for an invoice already paid against, runs `updateInvoiceStatusFromPayments()`. `billingCanEditItems()` is the lock. The edit handlers for all three kinds now use `billingRecalc()`. + - State and pills: `invoiceState()` (open, overdue, draft, paid, cancelled or non-billable, with balance and days), `invoiceDuePill()`, `invoiceStatusBadge()`, `invoiceCanPay()`, `quoteExpired()`, `quoteStatusBadge()`, `quoteExpiryPill()`, `getQuoteBadgeColor()`, `recurringInvoiceNextPill()`, `recurringInvoiceStep()` (a period on, month-end clamped the way MySQL's `DATE_ADD` is), `recurringInvoiceUpcoming()` and `recurringInvoiceCatchUp()`. `paymentAccounts()` returns every account with its balance in one query. + - `includes/billing_paper.php` draws the document for the agent pages and the guest pages from a `$paper` array, with the line controls when `edit` is set. The add-a-line inputs post through `form="billingAddLine"`. + - `agent/post/billing.php` handles `billing_item_save` (POST `type`, `doc_id`, optional `item_id`, `name`, `description`, `qty`, `price`, `tax_id`, `product_id`), `billing_item_delete` (GET), `recurring_invoice_set_status` and `recurring_invoice_catch_up`. `billing_items_order` in `agent/ajax.php` takes `type`, `doc_id` and `items` (ids, comma separated) and checks client access. + - `js/billing_items.js`: `itflowBillingItems()` on the pages and `itflowBillingLineForm()` for any line form (the Edit Line window). + - Windows: `agent/modals/billing/billing_item.php` (Edit Line), `agent/modals/billing/billing_form.php` (the fields shared by New and Edit for all three kinds, posting the names the existing handlers read) and `agent/modals/payment/payment_form.php` (shared by Add Payment, Batch Payment and Edit Payment). `agent/modals/invoice/invoice_add_ticket.php` is now an ajax window, and `add_ticket_to_invoice` takes `ticket_ids[]`. + - PDFs: `billingPdf($type, $row, $variant)` returns the file name and data, and `billingPdfSend()` sends it. The drawing is in `functions/billing_pdf.php` (the `BillingPdf` TCPDF class and `billingPdfRender()`), loaded only when a PDF is made. `export_invoice_pdf`, `export_invoice_packing_slip`, `export_quote_pdf` and the guest downloads use it. The guest downloads compare the URL key with `hash_equals()` and return 404 when it is wrong. + - Guest pages: `billingGuestViewed()` marks a sent document viewed, logs the view in plain text and notifies. `billingClientOpenInvoices()` is the client's statement. + - CSS: the `.itflow-paper-*` and `.itflow-billing-*` classes in `css/itflow_custom.css`, with print rules that print only the document. + - Removed: `add_invoice_item`, `edit_invoice_item`, `delete_invoice_item`, `add_quote_item`, `edit_quote_item`, `delete_quote_item`, `add_recurring_invoice_item`, `edit_recurring_invoice_item`, `delete_recurring_invoice_item` and `link_invoice_to_ticket` (it wrote a column that does not exist), `update_invoice_items_order`, `update_quote_items_order` and `update_recurring_invoice_items_order` in `agent/ajax.php`, `agent/modals/invoice/invoice_item_edit.php`, `agent/modals/quote/quote_item_edit.php`, `agent/modals/recurring_invoice/recurring_invoice_item_edit.php`, `guest/guest_quote_upload_file_modal.php` and `js/product_autocomplete.js`. - Sidebar brand: `agent/css/sidebar_brand_fix.css` and `agent/js/sidebar_brand_fix.js` from 26.10 are replaced by CSS in `css/itflow_custom.css`. `includes/load_company_settings.php` now sets `$session_company_logo`. - `alertMessageHtml()` no longer double-encodes, and save messages built from `escapeSql()` values use `stripslashes()` at the flash. - CSS: `[hidden] { display: none !important; }` at the top of `css/itflow_custom.css`, so the `hidden` attribute wins over `d-flex` and the other display utilities. `.pagination` wraps. diff --git a/agent/ajax.php b/agent/ajax.php index c5c3cfd34..b8bcad70b 100644 --- a/agent/ajax.php +++ b/agent/ajax.php @@ -1470,68 +1470,29 @@ if (isset($_POST['update_project_template_ticket_order'])) { exit; } -if (isset($_POST['update_quote_items_order'])) { - // Update multiple quote items order +/* + * The order of the lines on an invoice, quote or recurring invoice, after a + * drag - "items" is the line ids top to bottom, comma separated. + */ +if (isset($_POST['billing_items_order'])) { validateCSRFToken(); enforceUserPermission('module_sales', 2); - $positions = $_POST['positions']; - $quote_id = intval($_POST['quote_id']); + header('Content-Type: application/json'); - foreach ($positions as $position) { - $id = intval($position['id']); - $order = intval($position['order']); - - mysqli_query($mysqli, "UPDATE quote_items SET item_order = $order WHERE item_quote_id = $quote_id AND item_id = $id"); + $type = (string) ($_POST['type'] ?? ''); + $doc = billingType($type) ? billingRow($type, intval($_POST['doc_id'] ?? 0)) : null; + if (!$doc || !hasClientAccess(intval($doc['client_id'])) || !billingCanEditItems($type, $doc)) { + http_response_code(403); + echo json_encode(['status' => 'error', 'message' => "Those lines can't be moved now."]); + exit; } - // return a response - echo json_encode(['status' => 'success']); - exit; -} + $item_ids = array_filter(array_map('intval', explode(',', (string) ($_POST['items'] ?? '')))); + billingItemsOrder($type, intval($doc[billingType($type)['col'] . '_id']), $item_ids); -if (isset($_POST['update_invoice_items_order'])) { - // Update multiple invoice items order - - validateCSRFToken(); - - enforceUserPermission('module_sales', 2); - - $positions = $_POST['positions']; - $invoice_id = intval($_POST['invoice_id']); - - foreach ($positions as $position) { - $id = intval($position['id']); - $order = intval($position['order']); - - mysqli_query($mysqli, "UPDATE invoice_items SET item_order = $order WHERE item_invoice_id = $invoice_id AND item_id = $id"); - } - - // return a response - echo json_encode(['status' => 'success']); - exit; -} - -if (isset($_POST['update_recurring_invoice_items_order'])) { - // Update multiple recurring invoice items order - - validateCSRFToken(); - - enforceUserPermission('module_sales', 2); - - $positions = $_POST['positions']; - $recurring_invoice_id = intval($_POST['recurring_invoice_id']); - - foreach ($positions as $position) { - $id = intval($position['id']); - $order = intval($position['order']); - - mysqli_query($mysqli, "UPDATE recurring_invoice_items SET item_order = $order WHERE item_recurring_invoice_id = $recurring_invoice_id AND item_id = $id"); - } - - // return a response echo json_encode(['status' => 'success']); exit; } diff --git a/agent/invoice.php b/agent/invoice.php index 6636e1afc..f53633fe0 100644 --- a/agent/invoice.php +++ b/agent/invoice.php @@ -1,827 +1,391 @@ There is no Invoice here
Back to Invoices"; - require_once "../includes/footer.php"; - - exit(); - } - - $row = mysqli_fetch_assoc($sql); - $invoice_id = intval($row['invoice_id']); - $invoice_prefix = escapeHtml($row['invoice_prefix']); - $invoice_number = intval($row['invoice_number']); - $invoice_scope = escapeHtml($row['invoice_scope']); - $invoice_status = escapeHtml($row['invoice_status']); - $invoice_date = escapeHtml($row['invoice_date']); - $invoice_due = escapeHtml($row['invoice_due']); - $invoice_amount = floatval($row['invoice_amount']); - $invoice_discount = floatval($row['invoice_discount_amount']); - $invoice_credit = floatval($row['invoice_credit_amount']); - $invoice_currency_code = escapeHtml($row['invoice_currency_code']); - $invoice_note = escapeHtml($row['invoice_note']); - $invoice_url_key = escapeHtml($row['invoice_url_key']); - $invoice_created_at = escapeHtml($row['invoice_created_at']); - $category_id = intval($row['invoice_category_id']); - $client_id = intval($row['client_id']); - $client_name = escapeHtml($row['client_name']); - $location_address = escapeHtml($row['location_address']); - $location_city = escapeHtml($row['location_city']); - $location_state = escapeHtml($row['location_state']); - $location_zip = escapeHtml($row['location_zip']); - $location_country = escapeHtml($row['location_country']); - $contact_email = escapeHtml($row['contact_email']); - $contact_phone_country_code = escapeHtml($row['contact_phone_country_code']); - $contact_phone = escapeHtml(formatPhoneNumber($row['contact_phone'], $contact_phone_country_code)); - $contact_extension = escapeHtml($row['contact_extension']); - $contact_mobile_country_code = escapeHtml($row['contact_mobile_country_code']); - $contact_mobile = escapeHtml(formatPhoneNumber($row['contact_mobile'], $contact_mobile_country_code)); - $client_website = escapeHtml($row['client_website']); - $client_currency_code = escapeHtml($row['client_currency_code']); - $client_net_terms = intval($row['client_net_terms']); - if ($client_net_terms == 0) { - $client_net_terms = $config_default_net_terms; - } - - // Override Tab Title // No Sanitizing needed as this var will opnly be used in the tab title - $tab_title = $row['client_name']; - $page_title = "{$row['invoice_prefix']}{$row['invoice_number']}"; - - $sql = mysqli_query($mysqli, "SELECT company_address, company_city, company_country, company_email, company_id, company_logo, - company_name, company_phone, company_phone_country_code, company_state, company_tax_id, - company_website, company_zip FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_id = intval($row['company_id']); - $company_name = escapeHtml($row['company_name']); - $company_country = escapeHtml($row['company_country']); - $company_address = escapeHtml($row['company_address']); - $company_city = escapeHtml($row['company_city']); - $company_state = escapeHtml($row['company_state']); - $company_zip = escapeHtml($row['company_zip']); - $company_phone_country_code = escapeHtml($row['company_phone_country_code']); - $company_phone = escapeHtml(formatPhoneNumber($row['company_phone'], $company_phone_country_code)); - $company_email = escapeHtml($row['company_email']); - $company_website = escapeHtml($row['company_website']); - $company_tax_id = escapeHtml($row['company_tax_id']); - if ($config_invoice_show_tax_id && !empty($company_tax_id)) { - $company_tax_id_display = "Tax ID: $company_tax_id"; - } else { - $company_tax_id_display = ""; - } - $company_logo = escapeHtml($row['company_logo']); - - // Must use the same rule as the Send Email picker in - // modals/invoice/invoice_email.php, or the button offers a modal that then - // reports there is nobody to send to. - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT(contact_id) AS emailable_contacts FROM contacts - WHERE contact_client_id = $client_id - AND contact_archived_at IS NULL - AND contact_email IS NOT NULL - AND contact_email != '' - " . documentContactFilterSql('invoice'))); - $emailable_contacts = intval($row['emailable_contacts']); - - $sql_history = mysqli_query($mysqli, "SELECT history_created_at, history_description, history_status FROM history WHERE history_invoice_id = $invoice_id ORDER BY history_id DESC"); - - $sql_payments = mysqli_query($mysqli, "SELECT account_name, payment_amount, payment_currency_code, payment_method, payment_date, payment_id, - payment_reference FROM payments, accounts WHERE payment_account_id = account_id AND payment_invoice_id = $invoice_id ORDER BY payments.payment_id DESC"); - - $sql_tickets = mysqli_query($mysqli, " - SELECT - tickets.*, - SEC_TO_TIME(SUM(TIME_TO_SEC(STR_TO_DATE(ticket_reply_time_worked, '%H:%i:%s')))) AS 'total_time_worked' - FROM - tickets - LEFT JOIN - ticket_replies ON tickets.ticket_id = ticket_replies.ticket_reply_ticket_id - WHERE - ticket_invoice_id = $invoice_id - GROUP BY - tickets.ticket_id - ORDER BY - ticket_id DESC - "); - - //Get billable, and unbilled tickets to add to invoice - $sql_tickets_billable = mysqli_query( - $mysqli, " - SELECT ticket_id, ticket_subject, ticket_number, ticket_prefix, ticket_status - FROM - tickets - WHERE - ticket_client_id = $client_id - AND - ticket_billable = 1 - AND - ticket_invoice_id = 0 - AND - ticket_status IN (4, 5); - "); - - //Add up all the payments for the invoice and get the total amount paid to the invoice - $sql_amount_paid = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS amount_paid FROM payments WHERE payment_invoice_id = $invoice_id"); - $row = mysqli_fetch_assoc($sql_amount_paid); - $amount_paid = floatval($row['amount_paid']); - - $balance = $invoice_amount - $amount_paid; - - // Get Credit Balance - $sql_credit_balance = mysqli_query($mysqli, "SELECT SUM(credit_amount) AS credit_balance FROM credits WHERE credit_client_id = $client_id"); - $row = mysqli_fetch_assoc($sql_credit_balance); - - $credit_balance = floatval($row['credit_balance']); - - //check to see if overdue - if ($invoice_status !== "Paid" && $invoice_status !== "Draft" && $invoice_status !== "Cancelled" && $invoice_status !== "Non-Billable") { - $unixtime_invoice_due = strtotime($invoice_due) + 86400; - if ($unixtime_invoice_due < time()) { - $invoice_overdue = "Overdue"; - } - } - - //Set Badge color based off of invoice status - $invoice_badge_color = getInvoiceBadgeColor($invoice_status); - - //Product autocomplete - $json_products = getProductsForAutocomplete($mysqli); - - // Saved Payment Methods - $sql_saved_payment_methods = mysqli_query($mysqli, " - SELECT 1 FROM client_saved_payment_methods - LEFT JOIN payment_providers - ON client_saved_payment_methods.saved_payment_provider_id = payment_providers.payment_provider_id - WHERE saved_payment_client_id = $client_id - AND payment_provider_active = 1; - "); - - ?> - - - -
- -
- -
- -
- = 2) { ?> - - - - - - - - -
- - - 0 && ($invoice_status === 'Sent' || $invoice_status === 'Viewed')) { ?> - - - - -
- - - - - - Mark Non-Billable - - - - -
- - - -
- -
- -
- -
- -
- " alt="Company logo"> -
- -
"> -
    -
  • -
  • ') ?>
  • -
  • -
  • - -
  • - -
-
- -
-

INVOICE

-
- -
- - - - - - - - - - - - - -
Invoice #:
Date:
Due:
-
- -
-
-
-
Bill To:
-
    -
  • -
  • ') ?>
  • -
  • -
-
-
- - - -
-
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - > - - - - - - - - - - - - - - - -
ItemDescriptionQtyUnit PriceTaxAmount
- - -
- - - -
- - -
- - - - - - - - - - - -
-
-
-
-
-
-
-
-
- Notes: - -
-
-= 2) { ?> - - -
- - -
-
-
-
-
- - - - - - - - 0) { - ?> - - - - - - 0) { - ?> - - - - - - 0) { ?> - - - - - - - - - - 0) { ?> - - - - - - - - - - - -
Subtotal:
Discount:-
Credit:-
Tax:
Total:
Paid:
Balance:
-
-
-
-
-
-
-
-
-
-
- History -
- - -
-
-
- - - - - - - - - - - - - - - - - - -
DateStatusDescription
-
-
-
-
"> -
-
- Payments -
- - -
-
-
-
- - - - - - - - = 3 && lookupUserPermission("module_financial") >= 3) { ?> - - - - - - - - - - - - = 3 && lookupUserPermission("module_financial") >= 3) { ?> - - - - - -
DateAmountReferenceAccount
- - - - -
-
-
-
-
-
"> -
-
- Tickets -
- 0) { ?> - - - - - - - - - - - -
-
- -
-
- - - - - - - - - - - - - - - - - - - - - - -
#DateSubjectTime Worked
-
-
-
-
- - = 2 && !empty($config_smtp_provider) && $emailable_contacts > 0) { ?> - -
- - - -
- - = 2; +$can_delete = lookupUserPermission('module_sales') >= 3; +$can_take_payment = $can_edit && lookupUserPermission('module_financial') >= 2 && invoiceCanPay($invoice, $state); +$can_manage_payments = lookupUserPermission('module_sales') >= 3 && lookupUserPermission('module_financial') >= 3; +$can_edit_lines = billingCanEditItems('invoice', $invoice); +$mail_ready = !empty($config_smtp_provider) && billingEmailableContacts('invoice', $client_id) > 0; +$saved_card = $can_take_payment && in_array($status, ['Sent', 'Viewed'], true) && invoiceHasSavedCard($client_id); +$unbilled_tickets = $can_edit ? count(invoiceUnbilledTickets($client_id)) : 0; +$guest_url = billingGuestUrl('invoice', $invoice); +$csrf = $_SESSION['csrf_token']; + +// Made by a recurring invoice? +$recurring = intval($invoice['invoice_recurring_invoice_id']) + ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT recurring_invoice_id, recurring_invoice_prefix, recurring_invoice_number FROM recurring_invoices WHERE recurring_invoice_id = " . intval($invoice['invoice_recurring_invoice_id']))) + : null; + +$progress = $state['paid'] > 0 && $totals['total'] > 0 ? min(100, round($state['paid'] / $totals['total'] * 100)) : 0; + +// Override Tab Title // No Sanitizing needed as this var will only be used in the tab title +$tab_title = $invoice['client_name']; +$page_title = $number; + +$paper = [ + 'type' => 'invoice', + 'row' => $invoice, + 'items' => $items, + 'totals' => $totals, + 'paid' => $state['paid'], + 'balance' => $state['balance'], + 'edit' => $can_edit_lines, + 'notes_edit' => $can_edit, + 'taxes' => $can_edit_lines ? billingTaxes($invoice['invoice_created_at']) : [], + 'logo_url' => billingCompany()['logo_url'], + 'csrf' => $csrf, +]; + ?> + + + +
+
+ + +
+

+ Invoice + + +

+
+ + + + + From + + Created +
+
+ +
+ +
+ + + + + + + +
+ + + +
+ + + + + +
+ + + + + + + + + Non-Billable + + + + + + + + +
+
+
+ +
+ + +
+ +
+ + +
+ +
+
+

Payment

+
+
+
+
+
+
+
+
of
+
+
+
+
+
+
Paid
in ' . count($payments) . ' payment' . (count($payments) === 1 ? '' : 's') . '' : '' ?>
+
Due
+
+ + +
+ +
+ +
+
Terms
days
+ +
Client
Not sent yet - the client can't see it
+ +
+
+
+ +
+
+

Payments

+ + + +
+ +
+ +
+
+
+
+ +
+
+ + + +
+ +
+ +
No payments yet.
+ +
+ + +
+
+

Tickets

+ + + +
+ +
+ +
+
+ +
worked
+
+ + + + + +
+ +
+ +
unbilled ticket for could go on this invoice.
+ +
+ + +
+
+

History

+
+ +
+ +
+
+ + + +
+ + + +
+ + - - - - - + + - - += 2; +$can_delete = lookupUserPermission('module_sales') >= 3; +$can_pay = $can_edit && lookupUserPermission('module_financial') >= 2; +$mail_ready = !empty($config_smtp_provider); -$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('invoice_id') AS num FROM invoices WHERE invoice_status = 'Viewed' $client_query")); -$viewed_count = $row['num']; - -$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('invoice_id') AS num FROM invoices WHERE invoice_status = 'Partial' $client_query")); -$partial_count = $row['num']; - -$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('invoice_id') AS num FROM invoices WHERE invoice_status = 'Draft' $client_query")); -$draft_count = $row['num']; - -$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('invoice_id') AS num FROM invoices WHERE invoice_status = 'Cancelled' $client_query")); -$cancelled_count = $row['num']; - -$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('invoice_id') AS num FROM invoices WHERE invoice_status NOT LIKE 'Draft' AND invoice_status NOT LIKE 'Paid' AND invoice_status NOT LIKE 'Cancelled' AND invoice_status NOT LIKE 'Non-Billable' AND invoice_due < CURDATE() $client_query")); -$overdue_count = $row['num']; - -$sql_total_draft_amount = mysqli_query($mysqli, "SELECT SUM(invoice_amount) AS total_draft_amount FROM invoices WHERE invoice_status = 'Draft' $client_query"); -$row = mysqli_fetch_assoc($sql_total_draft_amount); -$total_draft_amount = floatval($row['total_draft_amount']); - -$sql_total_sent_amount = mysqli_query($mysqli, "SELECT SUM(invoice_amount) AS total_sent_amount FROM invoices WHERE invoice_status = 'Sent' $client_query"); -$row = mysqli_fetch_assoc($sql_total_sent_amount); -$total_sent_amount = floatval($row['total_sent_amount']); - -$sql_total_viewed_amount = mysqli_query($mysqli, "SELECT SUM(invoice_amount) AS total_viewed_amount FROM invoices WHERE invoice_status = 'Viewed' $client_query"); -$row = mysqli_fetch_assoc($sql_total_viewed_amount); -$total_viewed_amount = floatval($row['total_viewed_amount']); - -$sql_total_cancelled_amount = mysqli_query($mysqli, "SELECT SUM(invoice_amount) AS total_cancelled_amount FROM invoices WHERE invoice_status = 'Cancelled' $client_query"); -$row = mysqli_fetch_assoc($sql_total_cancelled_amount); -$total_cancelled_amount = floatval($row['total_cancelled_amount']); - -$sql_total_partial_amount = mysqli_query($mysqli, "SELECT SUM(invoice_amount) AS total_partial_amount FROM invoices WHERE invoice_status = 'Partial' $client_query"); -$row = mysqli_fetch_assoc($sql_total_partial_amount); -$total_partial_amount = floatval($row['total_partial_amount']); - -$sql_total_partial_paid_amount = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS total_partial_paid_amount FROM payments, invoices WHERE payment_invoice_id = invoice_id AND invoice_status = 'Partial' $client_query"); -$row = mysqli_fetch_assoc($sql_total_partial_paid_amount); -$total_partial_paid_amount = floatval($row['total_partial_paid_amount']); - -$sql_total_overdue_partial_amount = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS total_overdue_partial_amount FROM payments, invoices WHERE payment_invoice_id = invoice_id AND invoice_status = 'Partial' AND invoice_due < CURDATE() $client_query"); -$row = mysqli_fetch_assoc($sql_total_overdue_partial_amount); -$total_overdue_partial_amount = floatval($row['total_overdue_partial_amount']); - -$sql_total_overdue_amount = mysqli_query($mysqli, "SELECT SUM(invoice_amount) AS total_overdue_amount FROM invoices WHERE invoice_status != 'Draft' AND invoice_status != 'Paid' AND invoice_status != 'Cancelled' AND invoice_status != 'Non-Billable' AND invoice_due < CURDATE() $client_query"); -$row = mysqli_fetch_assoc($sql_total_overdue_amount); -$total_overdue_amount = floatval($row['total_overdue_amount']); - -$real_overdue_amount = $total_overdue_amount - $total_overdue_partial_amount; -$total_unpaid_amount = $total_sent_amount + $total_viewed_amount + $total_partial_amount - $total_partial_paid_amount; -$unpaid_count = $sent_count + $viewed_count + $partial_count; - -$overdue_query = ''; -//Invoice status from GET -if (isset($_GET['status']) && ($_GET['status']) == 'Draft') { - $status_query = "invoice_status = 'Draft'"; -} elseif (isset($_GET['status']) && ($_GET['status']) == 'Unpaid') { - $status_query = "invoice_status = 'Sent' OR invoice_status = 'Viewed' OR invoice_status = 'Partial'"; -} elseif (isset($_GET['status']) && ($_GET['status']) == 'Overdue') { - $status_query = "invoice_status = 'Sent' OR invoice_status = 'Viewed' OR invoice_status = 'Partial'"; - $overdue_query = "AND (invoice_due < CURDATE())"; -} else { - $status_query = "invoice_status LIKE '%'"; +// Client Filter (all clients) +$client = ''; +if (!$client_url && !empty($_GET['client'])) { + $client = intval($_GET['client']); + $client_query = "AND invoice_client_id = $client"; } +// From a recurring invoice +$recurring_filter = intval($_GET['recurring_invoice_id'] ?? 0); +$recurring_query = $recurring_filter ? "AND invoice_recurring_invoice_id = $recurring_filter" : ''; +$recurring_filter_row = $recurring_filter ? billingRow('recurring', $recurring_filter) : null; + // Category Filter -if (isset($_GET['category']) & !empty($_GET['category'])) { - $category_query = 'AND (category_id = ' . intval($_GET['category']) . ')'; - $category_filter = intval($_GET['category']); -} else { - // Default - any - $category_query = ''; - $category_filter = ''; +$category_filter = intval($_GET['category'] ?? 0); +$category_query = $category_filter ? "AND invoice_category_id = $category_filter" : ''; + +$open_sql = "invoice_status IN ('Sent', 'Viewed', 'Partial')"; +$statuses = [ + '' => ['label' => 'All', 'where' => ''], + 'Draft' => ['label' => 'Draft', 'icon' => 'fa-pencil-ruler', 'where' => "invoice_status = 'Draft'", 'title' => 'Not sent yet - the client can\'t see them'], + 'Unpaid' => ['label' => 'Unpaid', 'icon' => 'fa-hand-holding-usd', 'where' => $open_sql, 'title' => 'Sent, and not paid in full'], + 'Overdue' => ['label' => 'Overdue', 'icon' => 'fa-exclamation-circle', 'where' => "$open_sql AND invoice_due < CURDATE()", 'title' => 'Past their due date and not paid in full'], + 'Paid' => ['label' => 'Paid', 'icon' => 'fa-check-circle', 'where' => "invoice_status = 'Paid'"], + 'Cancelled' => ['label' => 'Cancelled', 'icon' => 'fa-ban', 'where' => "invoice_status IN ('Cancelled', 'Non-Billable')", 'title' => 'Cancelled, or closed off as non-billable'], +]; +$status = isset($statuses[$_GET['status'] ?? '']) ? ($_GET['status'] ?? '') : ''; +$status_query = $statuses[$status]['where'] ? 'AND ' . $statuses[$status]['where'] : ''; + +// Only these sort - filter_header.php hands through any lowercase word +$sortable_columns = ['invoice_number' => 'invoice_number', 'invoice_scope' => 'invoice_scope', 'client_name' => 'client_name', 'invoice_date' => 'invoice_date', + 'invoice_due' => 'invoice_due', 'invoice_amount' => 'invoice_amount', 'balance' => 'balance', 'invoice_status' => 'invoice_status', 'category_name' => 'category_name']; +if (!isset($sortable_columns[$sort])) { + $sort = 'invoice_number'; } -$sql = mysqli_query( - $mysqli, - "SELECT SQL_CALC_FOUND_ROWS category_id, category_name, client_currency_code, client_id, client_name, client_net_terms, - invoice_amount, invoice_created_at, invoice_currency_code, invoice_date, - invoice_discount_amount, invoice_due, invoice_id, invoice_number, invoice_prefix, - invoice_scope, invoice_status, recurring_invoice_id, recurring_invoice_number, - recurring_invoice_prefix, IFNULL(invoice_payments.amount_paid, 0) AS amount_paid FROM invoices +$paid_join = "LEFT JOIN (SELECT payment_invoice_id, SUM(payment_amount) AS paid FROM payments GROUP BY payment_invoice_id) AS invoice_payments ON payment_invoice_id = invoice_id"; +$scope_query = clientScopeSql('invoice_client_id'); +$search_query = "AND (CONCAT(invoice_prefix, invoice_number) LIKE '%$q%' OR invoice_scope LIKE '%$q%' OR client_name LIKE '%$q%' OR invoice_status LIKE '%$q%' OR invoice_amount LIKE '%$q%' OR category_name LIKE '%$q%')"; +$date_query = "AND DATE(invoice_date) BETWEEN '$dtf' AND '$dtt'"; +$filters = "$scope_query $client_query $recurring_query $category_query $date_query $search_query"; + +$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS invoices.*, client_name, category_name, category_color, + recurring_invoice_prefix, recurring_invoice_number, + COALESCE(invoice_payments.paid, 0) AS paid, invoice_amount - COALESCE(invoice_payments.paid, 0) AS balance + FROM invoices LEFT JOIN clients ON invoice_client_id = client_id LEFT JOIN categories ON invoice_category_id = category_id LEFT JOIN recurring_invoices ON invoice_recurring_invoice_id = recurring_invoice_id - LEFT JOIN (SELECT payment_invoice_id, SUM(payment_amount) AS amount_paid - FROM payments - GROUP BY payment_invoice_id) AS invoice_payments ON payment_invoice_id = invoice_id - WHERE ($status_query) - $overdue_query - $category_query - AND DATE(invoice_date) BETWEEN '$dtf' AND '$dtt' - AND (CONCAT(invoice_prefix,invoice_number) LIKE '%$q%' OR invoice_scope LIKE '%$q%' OR client_name LIKE '%$q%' OR invoice_status LIKE '%$q%' OR invoice_amount LIKE '%$q%' OR category_name LIKE '%$q%') - " . clientScopeSql('invoice_client_id') . " - $client_query - ORDER BY $sort $order LIMIT $record_from, $record_to" -); + $paid_join + WHERE 1 $filters $status_query + ORDER BY {$sortable_columns[$sort]} $order, invoice_id DESC LIMIT $record_from, $record_to"); $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); +$invoices = []; +while ($row = mysqli_fetch_assoc($sql)) { + $invoices[] = $row; +} + +// How many of each, for the pills - what the filters above leave, before the pill +$count_sql = []; +foreach ($statuses as $key => $s) { + $count_sql[] = $key === '' ? 'COUNT(*)' : "COALESCE(SUM({$s['where']}), 0)"; +} +$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT " . implode(', ', $count_sql) . " FROM invoices + LEFT JOIN clients ON invoice_client_id = client_id LEFT JOIN categories ON invoice_category_id = category_id WHERE 1 $filters")); +$counts = []; +foreach (array_keys($statuses) as $i => $key) { + $counts[$key] = intval($row[$i]); +} + +// The money along the top - everything in this scope, not narrowed by search, date or pill +$money_scope = "$scope_query $client_query $recurring_query"; +$money = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT + COALESCE(SUM(CASE WHEN $open_sql AND balance > 0 THEN balance END), 0) AS owed, + COALESCE(SUM(CASE WHEN $open_sql AND balance > 0 THEN 1 END), 0) AS owed_count, + COALESCE(SUM(CASE WHEN $open_sql AND balance > 0 AND invoice_due < CURDATE() THEN balance END), 0) AS overdue, + COALESCE(SUM(CASE WHEN $open_sql AND balance > 0 AND invoice_due < CURDATE() THEN 1 END), 0) AS overdue_count, + COALESCE(SUM(CASE WHEN invoice_status = 'Draft' THEN invoice_amount END), 0) AS draft, + COALESCE(SUM(CASE WHEN invoice_status = 'Draft' THEN 1 END), 0) AS draft_count + FROM (SELECT invoice_status, invoice_due, invoice_amount, invoice_amount - COALESCE(invoice_payments.paid, 0) AS balance + FROM invoices $paid_join WHERE 1 $money_scope) AS scoped")); +$collected = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COALESCE(SUM(payment_amount), 0) AS amount, COUNT(*) AS payments FROM payments + JOIN invoices ON payment_invoice_id = invoice_id + WHERE payment_date >= CURDATE() - INTERVAL 30 DAY $money_scope")); + +$filter_url = function ($changes) { + $params = array_merge($_GET, $changes); + unset($params['page']); + return '?' . http_build_query(array_filter($params, function ($v) { return $v !== '' && $v !== null; })); +}; + +// Clients with a card on file, for Charge Saved Card - one query, not one a row +$saved_card_clients = []; +$sql_saved = mysqli_query($mysqli, "SELECT DISTINCT saved_payment_client_id FROM client_saved_payment_methods + JOIN payment_providers ON saved_payment_provider_id = payment_provider_id WHERE payment_provider_active = 1"); +while ($row = mysqli_fetch_row($sql_saved)) { + $saved_card_clients[intval($row[0])] = true; +} + +$stat_money = function ($amount) use ($session_company_currency) { + return escapeHtml(billingMoney($amount, $session_company_currency)); +}; + ?> -
-
- - -
-

-

Draft

-
-
- -
+ +
+ - - -
- - -
-

-

Unpaid

-
-
- -
+
- - -
-

Invoices

+

Invoices

- = 2) { ?> - + + - -