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

This commit is contained in:
johnnyq
2026-10-16 12:37:50 -04:00
parent c51323b88e
commit fee0a5cb80
56 changed files with 5573 additions and 7002 deletions

View File

@@ -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.

View File

@@ -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;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,17 @@
<?php
/*
* Invoices - one client's, or every invoice the agent can see.
*
* Along the top, the money: what is owed, what of that is late, what is
* sitting in drafts, and what came in over the last 30 days - each opens
* the invoices behind it. The pills filter by where an invoice stands. Each
* row has what is still owed on it and, while it is owed, how long until
* it is due or how late it is. ?status= takes Draft, Unpaid, Overdue,
* Paid and Cancelled - the dashboard, client pages and reports link with
* it. ?recurring_invoice_id= shows the invoices a recurring invoice made.
*/
// Default Column Sortby/Order Filter
$sort = "invoice_number";
$order = "DESC";
@@ -11,184 +23,181 @@ if (isset($_GET['client_id'])) {
$client_url = "client_id=$client_id&";
} else {
require_once "includes/inc_all.php";
$client_query = clientScopeSql('invoice_client_id');
$client_query = '';
$client_url = '';
}
// Perms
enforceUserPermission('module_sales');
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('invoice_id') AS num FROM invoices WHERE invoice_status = 'Sent' $client_query"));
$sent_count = $row['num'];
$can_edit = lookupUserPermission('module_sales') >= 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));
};
?>
<div class="row">
<div class="col-lg-4">
<!-- small box -->
<a href="?<?= $url_query_strings_sort ?>&status=Draft" class="small-box bg-secondary">
<div class="inner">
<h3><?= numfmt_format_currency($currency_format, $total_draft_amount, $session_company_currency) ?></h3>
<p><?= $draft_count ?> Draft</p>
</div>
<div class="icon">
<i class="fa fa-pencil-ruler"></i>
</div>
<!-- The money -->
<div class="row g-3 mb-3">
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $status === 'Unpaid' ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['status' => 'Unpaid'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-hand-holding-usd me-1"></i>Owed to you</div>
<div class="itflow-billing-stat-value"><?= $stat_money($money['owed']) ?></div>
<div class="itflow-billing-stat-note"><?= intval($money['owed_count']) ?> unpaid invoice<?= intval($money['owed_count']) === 1 ? '' : 's' ?></div>
</a>
</div>
<!-- ./col -->
<div class="col-lg-4">
<!-- small box -->
<a href="?<?= $url_query_strings_sort ?>&status=Unpaid" class="small-box bg-info">
<div class="inner text-white">
<h3><?= numfmt_format_currency($currency_format, $total_unpaid_amount, $session_company_currency) ?></h3>
<p><?= $unpaid_count ?> Unpaid</p>
</div>
<div class="icon">
<i class="fa fa-hand-holding-usd"></i>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $status === 'Overdue' ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['status' => 'Overdue'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-exclamation-circle me-1"></i>Overdue</div>
<div class="itflow-billing-stat-value <?= $money['overdue'] > 0 ? 'text-danger-emphasis' : '' ?>"><?= $stat_money($money['overdue']) ?></div>
<div class="itflow-billing-stat-note"><?= intval($money['overdue_count']) ?> past due<?= $money['owed'] > 0 ? ' &middot; ' . round($money['overdue'] / $money['owed'] * 100) . '% of what is owed' : '' ?></div>
</a>
</div>
<!-- ./col -->
<div class="col-lg-4">
<!-- small box -->
<a href="?<?= $url_query_strings_sort ?>&status=Overdue" class="small-box bg-danger">
<div class="inner">
<h3><?= numfmt_format_currency($currency_format, $real_overdue_amount, $session_company_currency) ?></h3>
<p><?= $overdue_count ?> Overdue</p>
</div>
<div class="icon">
<i class="fa fa-exclamation-triangle"></i>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $status === 'Draft' ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['status' => 'Draft'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-pencil-ruler me-1"></i>In drafts</div>
<div class="itflow-billing-stat-value"><?= $stat_money($money['draft']) ?></div>
<div class="itflow-billing-stat-note"><?= intval($money['draft_count']) ?> not sent yet</div>
</a>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $status === 'Paid' ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['status' => 'Paid'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-coins me-1"></i>Collected, 30 days</div>
<div class="itflow-billing-stat-value text-success-emphasis"><?= $stat_money($collected['amount']) ?></div>
<div class="itflow-billing-stat-note"><?= intval($collected['payments']) ?> payment<?= intval($collected['payments']) === 1 ? '' : 's' ?></div>
</a>
</div>
<!-- ./col -->
</div>
<div class="card">
<div class="card-header bg-dark py-2">
<h3 class="card-title mt-2"><i class="fa fa-fw fa-file-invoice me-2"></i>Invoices</h3>
<h3 class="card-title mt-2"><i class="fa fa-fw fa-file-invoice-dollar me-2"></i>Invoices</h3>
<div class="card-tools">
<div class="btn-group">
<?php if (lookupUserPermission("module_sales") >= 2) { ?>
<button type="button" class="btn btn-primary ajax-modal"
data-modal-url="modals/invoice/invoice_add.php?<?= $client_url ?>">
<i class="fas fa-plus me-2"></i>New Invoice
</button>
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/invoice/invoice_add.php?<?= $client_url ?>">
<i class="fas fa-plus me-2"></i>New Invoice
</button>
<?php } ?>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown"></button>
<div class="dropdown-menu">
<a class="dropdown-item text-dark ajax-modal" href="#"
data-modal-url="<?= buildExportModalUrl('modals/invoice/invoice_export.php', ['client_id', 'status', 'category', 'q'], ['dtf' => $dtf, 'dtt' => $dtt]) ?>">
<i class="fa fa-fw fa-download me-2"></i>Export
<button type="button" class="btn btn-primary dropdown-toggle <?= $can_edit ? 'dropdown-toggle-split' : '' ?>" data-bs-toggle="dropdown"><?= $can_edit ? '' : '<i class="fas fa-ellipsis-h"></i>' ?></button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="<?= buildExportModalUrl('modals/invoice/invoice_export.php', ['client_id', 'status', 'category', 'q'], ['dtf' => $dtf, 'dtt' => $dtt, 'client_id' => $client ?: '']) ?>">
<i class="fa fa-fw fa-download text-secondary me-2"></i>Export
</a>
<?php if ($client_url && lookupUserPermission("module_sales") >= 2 && !empty($config_smtp_provider)) { ?>
<?php if ($client_url && $can_edit && $mail_ready) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/client/client_statement.php?client_id=<?= $client_id ?>">
<i class="fa fa-fw fa-file-alt text-secondary me-2"></i>Send Statement
</a>
<?php } ?>
<?php if ($client_url && $can_pay && $money['owed'] > 0) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-dark ajax-modal" href="#"
data-modal-url="modals/client/client_statement.php?client_id=<?= $client_id ?>">
<i class="fa fa-fw fa-file-alt me-2"></i>Send Account Statement
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/payment/payment_bulk_add.php?client_id=<?= $client_id ?>">
<i class="fa fa-fw fa-layer-group text-secondary me-2"></i>Batch Payment
</a>
<?php } ?>
</div>
@@ -198,312 +207,239 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
<div class="card-header py-3">
<form autocomplete="off">
<input type="hidden" name="status" value="<?php if (isset($_GET['status'])) { echo escapeHtml($_GET['status']); } ?>">
<?php if ($client_url) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } ?>
<div class="row g-2 align-items-end">
<div class="col-sm-4">
<div>
<div class="input-group">
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) {echo stripslashes(escapeHtml($q));} ?>" placeholder="Search Invoices">
<button class="btn btn-secondary" title="More filters" type="button" data-bs-toggle="collapse" data-bs-target="#advancedFilter"><i class="fas fa-filter"></i></button>
<button class="btn btn-primary" title="Search"><i class="fa fa-search"></i></button>
</div>
<input type="hidden" name="status" value="<?= escapeHtml($status) ?>">
<?php if ($recurring_filter) { ?>
<input type="hidden" name="recurring_invoice_id" value="<?= $recurring_filter ?>">
<?php } ?>
<div class="row g-2 align-items-center">
<div class="<?= $client_url ? 'col-lg-4' : 'col-lg-3' ?> col-md-6">
<div class="input-group">
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search number, scope, client, amount...">
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
</div>
</div>
<div class="col-sm-3">
<div>
<select class="form-select select2" name="category" onchange="this.form.submit()">
<option value="">- All Categories -</option>
<div class="col-lg-2 col-md-6">
<input type="text" id="dateFilter" class="form-control" autocomplete="off" title="Invoice date" aria-label="Invoice date">
<input type="hidden" name="canned_date" id="canned_date" value="<?= escapeHtml($_GET['canned_date'] ?? '') ?>">
<input type="hidden" name="dtf" id="dtf" value="<?= escapeHtml($dtf ?? '') ?>">
<input type="hidden" name="dtt" id="dtt" value="<?= escapeHtml($dtt ?? '') ?>">
</div>
<div class="col-lg-3 col-md-6">
<select class="form-select select2" name="category" onchange="this.form.submit()">
<option value="">- Any category -</option>
<?php
$sql_categories_filter = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories
WHERE category_type = 'Income' AND EXISTS (SELECT 1 FROM invoices WHERE invoice_category_id = category_id) ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql_categories_filter)) {
$category_option_id = intval($row['category_id']); ?>
<option <?= $category_filter === $category_option_id ? 'selected' : '' ?> value="<?= $category_option_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= escapeHtml($row['category_name']) ?></option>
<?php } ?>
</select>
</div>
<?php if (!$client_url) { ?>
<div class="col-lg-2 col-md-6">
<select class="form-select select2" name="client" onchange="this.form.submit()">
<option value="">- All Clients -</option>
<?php
$sql_categories_filter = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND EXISTS (SELECT 1 FROM invoices WHERE invoice_category_id = category_id) ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql_categories_filter)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<option <?php if ($category_filter == $category_id) { echo "selected"; } ?> value="<?= $category_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name ?></option>
<?php
}
?>
$sql_clients_filter = mysqli_query($mysqli, "SELECT DISTINCT client_id, client_name, client_abbreviation FROM clients
JOIN invoices ON invoice_client_id = client_id
WHERE 1 " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql_clients_filter)) {
$client_option_id = intval($row['client_id']); ?>
<option <?= $client === $client_option_id ? 'selected' : '' ?> value="<?= $client_option_id ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= escapeHtml($row['client_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-md-5">
<div class="btn-group float-end">
<div class="dropdown ms-2" id="bulkActionButton" hidden>
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-layer-group me-2"></i>Bulk Action (<span id="selectedCount">0</span>)
</button>
<div class="dropdown-menu">
<?php if ($client_url && $balance > 0) { ?>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/payment/payment_bulk_add.php?<?= $client_url ?>">
<i class="fa fa-credit-card me-2"></i>Batch Payment
<?php } ?>
<div class="<?= $client_url ? 'col-lg-3' : 'col-lg-2' ?> col-md-6">
<div class="d-flex justify-content-end gap-2">
<?php if ($can_edit) { ?>
<div class="dropdown" id="bulkActionButton" hidden>
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-layer-group me-2"></i>Bulk Action (<span id="selectedCount">0</span>)
</button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/invoice/invoice_bulk_edit_category.php" data-bulk="true">
<i class="fas fa-fw fa-tag me-2"></i>Set Category
</a>
<div class="dropdown-divider"></div>
<?php } ?>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/invoice/invoice_bulk_edit_category.php"
data-bulk="true">
<i class="fas fa-fw fa-list-ul me-2"></i>Set Category
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="collapse mt-3 <?php if (isset($_GET['dtf']) && $_GET['dtf'] !== '1970-01-01') { echo"show"; } ?>" id="advancedFilter">
<div class="row g-3">
<div class="col-md-3">
<div>
<label class="form-label">Date range</label>
<input type="text" id="dateFilter" class="form-control" autocomplete="off">
<input type="hidden" name="canned_date" id="canned_date" value="<?= escapeHtml($_GET['canned_date']) ?? '' ?>">
<input type="hidden" name="dtf" id="dtf" value="<?= escapeHtml($dtf ?? '') ?>">
<input type="hidden" name="dtt" id="dtt" value="<?= escapeHtml($dtt ?? '') ?>">
</div>
<?php } ?>
</div>
</div>
</div>
</form>
<!-- Where they stand - counted over what the filters above leave -->
<nav class="nav nav-pills itflow-asset-tabs mt-2 flex-nowrap overflow-auto">
<?php foreach ($statuses as $key => $s) {
$alarm = $key === 'Overdue' && $counts[$key]; ?>
<a class="nav-link text-nowrap <?= $status === $key ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['status' => $key])) ?>"<?= !empty($s['title']) ? ' title="' . escapeHtml($s['title']) . '"' : '' ?>>
<?php if (!empty($s['icon'])) { ?><i class="fas fa-fw <?= $s['icon'] ?> me-1"></i><?php } ?><?= $s['label'] ?>
<span class="badge rounded-pill ms-1 <?= $alarm ? 'text-bg-danger' : '' ?>"><?= $counts[$key] ?></span>
</a>
<?php } ?>
</nav>
<?php if ($recurring_filter) { ?>
<div class="small text-body-secondary mt-2">
<i class="fas fa-filter me-1"></i>Made by <?= $recurring_filter_row ? '<a href="recurring_invoice.php?recurring_invoice_id=' . $recurring_filter . '">' . escapeHtml(billingNumber('recurring', $recurring_filter_row)) . '</a>' : 'a recurring invoice' ?>
<a class="ms-2" href="<?= escapeHtml($filter_url(['recurring_invoice_id' => ''])) ?>">Clear</a>
</div>
<?php } ?>
</div>
<form id="bulkActions" action="post.php" method="post">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<div class="table-responsive">
<table class="table table-striped table-borderless table-hover mb-0">
<thead class="text-dark <?php if ($num_rows[0] == 0) { echo "d-none"; } ?> text-nowrap">
<tr>
<td class="checkbox-column border-end">
<table class="table table-hover align-middle mb-0 itflow-billing-table">
<thead class="<?= $num_rows[0] ? '' : 'd-none' ?> text-nowrap table-light">
<tr>
<?php if ($can_edit) { ?>
<th class="checkbox-column border-end">
<div class="form-check">
<input class="form-check-input" id="selectAllCheckbox" type="checkbox" onclick="checkAll(this)">
<input class="form-check-input" id="selectAllCheckbox" type="checkbox" onclick="checkAll(this)" title="Select all on this page">
</div>
</td>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=invoice_number&order=<?= $disp ?>">
Number <?php if ($sort == 'invoice_number') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=invoice_scope&order=<?= $disp ?>">
Scope <?php if ($sort == 'invoice_scope') { echo $order_icon; } ?>
</a>
</th>
<?php if (!$client_url) { ?>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=client_name&order=<?= $disp ?>">
Client <?php if ($sort == 'client_name') { echo $order_icon; } ?>
</a>
</th>
<?php } ?>
<th class="text-end">
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=invoice_amount&order=<?= $disp ?>">
Amount <?php if ($sort == 'invoice_amount') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=invoice_date&order=<?= $disp ?>">
Date <?php if ($sort == 'invoice_date') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=invoice_due&order=<?= $disp ?>">
Due <?php if ($sort == 'invoice_due') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=category_name&order=<?= $disp ?>">
Category <?php if ($sort == 'category_name') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=invoice_status&order=<?= $disp ?>">
Status <?php if ($sort == 'invoice_status') { echo $order_icon; } ?>
</a>
</th>
<th>Recurring</th>
<th class="text-center">Action</th>
</tr>
<?php } ?>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=invoice_number&order=<?= $disp ?>">Invoice <?php if ($sort == 'invoice_number') { echo $order_icon; } ?></a></th>
<?php if (!$client_url) { ?>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=client_name&order=<?= $disp ?>">Client <?php if ($sort == 'client_name') { echo $order_icon; } ?></a></th>
<?php } ?>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=invoice_date&order=<?= $disp ?>">Date <?php if ($sort == 'invoice_date') { echo $order_icon; } ?></a></th>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=invoice_due&order=<?= $disp ?>">Due <?php if ($sort == 'invoice_due') { echo $order_icon; } ?></a></th>
<th class="text-end"><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=invoice_amount&order=<?= $disp ?>">Total <?php if ($sort == 'invoice_amount') { echo $order_icon; } ?></a></th>
<th class="text-end"><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=balance&order=<?= $disp ?>">Balance <?php if ($sort == 'balance') { echo $order_icon; } ?></a></th>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=invoice_status&order=<?= $disp ?>">Status <?php if ($sort == 'invoice_status') { echo $order_icon; } ?></a></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql)) {
<?php foreach ($invoices as $row) {
$invoice_id = intval($row['invoice_id']);
$invoice_prefix = escapeHtml($row['invoice_prefix']);
$invoice_number = escapeHtml($row['invoice_number']);
$invoice_scope = escapeHtml($row['invoice_scope']);
if (empty($invoice_scope)) {
$invoice_scope_display = "-";
} else {
$invoice_scope_display = $invoice_scope;
}
$invoice_status = escapeHtml($row['invoice_status']);
$invoice_date = escapeHtml($row['invoice_date']);
$invoice_due = escapeHtml($row['invoice_due']);
$invoice_discount = floatval($row['invoice_discount_amount']);
$invoice_amount = floatval($row['invoice_amount']);
$amount_paid = floatval($row['amount_paid']);
$invoice_balance = $invoice_amount - $amount_paid;
$invoice_currency_code = escapeHtml($row['invoice_currency_code']);
$invoice_created_at = escapeHtml($row['invoice_created_at']);
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
$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;
}
$recurring_invoice_id = intval($row['recurring_invoice_id']);
$recurring_invoice_prefix = escapeHtml($row['recurring_invoice_prefix']);
$recurring_invoice_number = escapeHtml($row['recurring_invoice_number']);
if($recurring_invoice_id) {
$recurring_invoice_display = "<i class='fas fa-fw fa-redo-alt text-secondary me-1'></i><a href='recurring_invoice.php?recurring_invoice_id=$recurring_invoice_id'>$recurring_invoice_prefix$recurring_invoice_number</a>";
} else {
$recurring_invoice_display = "-";
}
$now = time();
if (($invoice_status == "Sent" || $invoice_status == "Partial" || $invoice_status == "Viewed") && strtotime($invoice_due) + 86400 < $now) {
$overdue_color = "text-danger fw-bold";
} else {
$overdue_color = "";
}
$invoice_badge_color = getInvoiceBadgeColor($invoice_status);
// 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;
");
$row_client_id = intval($row['invoice_client_id']);
$row_number = billingNumber('invoice', $row);
$row_status = (string) $row['invoice_status'];
$row_state = invoiceState($row, $row['paid']);
$row_currency = (string) $row['invoice_currency_code'];
$row_url = "invoice.php?{$client_url}invoice_id=$invoice_id";
$row_can_pay = $can_pay && invoiceCanPay($row, $row_state);
?>
<tr>
<td class="checkbox-column bg-light border-end">
<div class="form-check">
<input class="form-check-input bulk-select" type="checkbox" name="invoice_ids[]" value="<?= $invoice_id ?>">
<?php if ($can_edit) { ?>
<td class="checkbox-column bg-light border-end">
<div class="form-check">
<input class="form-check-input bulk-select" type="checkbox" name="invoice_ids[]" value="<?= $invoice_id ?>" aria-label="Select <?= escapeHtml($row_number) ?>">
</div>
</td>
<?php } ?>
<td class="itflow-billing-number">
<a class="fw-semibold" href="<?= $row_url ?>"><?= escapeHtml($row_number) ?></a>
<?php if (intval($row['invoice_recurring_invoice_id'])) { ?>
<a class="text-body-secondary small ms-1" href="recurring_invoice.php?recurring_invoice_id=<?= intval($row['invoice_recurring_invoice_id']) ?>" title="Made by <?= escapeHtml($row['recurring_invoice_prefix'] . $row['recurring_invoice_number']) ?>"><i class="fas fa-redo-alt"></i></a>
<?php } ?>
<div class="small text-body-secondary text-truncate" style="max-width: 22rem;">
<?= escapeHtml(implode(' · ', array_filter([$row['invoice_scope'], $row['category_name']]))) ?: '&nbsp;' ?>
</div>
</td>
<td class="text-bold">
<a href="invoice.php?client_id=<?= $client_id ?>&invoice_id=<?= $invoice_id ?>">
<?= "$invoice_prefix$invoice_number" ?>
</a>
</td>
<td><?= $invoice_scope_display ?></td>
<?php if (!$client_url) { ?>
<td class="text-bold"><a href="invoices.php?client_id=<?= $client_id ?>"><?= $client_name ?></a></td>
<td><a class="text-reset" href="invoices.php?client_id=<?= $row_client_id ?>"><?= escapeHtml($row['client_name']) ?></a></td>
<?php } ?>
<td class="text-end font-monospace">
<?= numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) ?>
<?php if ($amount_paid > 0 && $invoice_balance > 0) { ?>
<br><small class="text-danger"><?= numfmt_format_currency($currency_format, $invoice_balance, $invoice_currency_code) ?> due</small>
<td class="text-nowrap"><?= escapeHtml($row['invoice_date']) ?></td>
<td class="text-nowrap">
<?= escapeHtml($row['invoice_due']) ?>
<?php $due_pill = invoiceDuePill($row_state); if ($due_pill) { ?><div><?= $due_pill ?></div><?php } ?>
</td>
<td class="text-end itflow-money"><?= escapeHtml(billingMoney($row['invoice_amount'], $row_currency)) ?></td>
<td class="text-end itflow-money">
<?php if (in_array($row_state['state'], ['open', 'overdue'], true)) { ?>
<span class="fw-semibold <?= $row_state['state'] === 'overdue' ? 'text-danger-emphasis' : '' ?>"><?= escapeHtml(billingMoney($row_state['balance'], $row_currency)) ?></span>
<?php if ($row_state['paid'] > 0) { ?><div class="small text-body-secondary"><?= escapeHtml(billingMoney($row_state['paid'], $row_currency)) ?> paid</div><?php } ?>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>
</td>
<td><?= $invoice_date ?></td>
<td class="<?= $overdue_color ?>"><?= $invoice_due ?></td>
<td><?= $category_name ?></td>
<td>
<?php if ($invoice_status == 'Paid' || $invoice_status == 'Partial') { ?>
<a class="ajax-modal" href="#" title="View payments"
data-modal-url="modals/invoice/invoice_payments.php?invoice_id=<?= $invoice_id ?>">
<span class="p-2 badge text-bg-<?= $invoice_badge_color ?>">
<?= $invoice_status ?>
</span>
</a>
<?php } else { ?>
<span class="p-2 badge text-bg-<?= $invoice_badge_color ?>">
<?= $invoice_status ?>
</span>
<?php } ?>
<td class="text-nowrap">
<?php if ($row['paid'] > 0) { ?>
<a href="#" class="ajax-modal text-decoration-none" title="Payments" data-modal-url="modals/invoice/invoice_payments.php?invoice_id=<?= $invoice_id ?>"><?= invoiceStatusBadge($row_status) ?></a>
<?php } else { ?>
<?= invoiceStatusBadge($row_status) ?>
<?php } ?>
</td>
<td><?= $recurring_invoice_display ?></td>
<td>
<div class="dropdown dropstart text-center">
<button class="btn btn-secondary btn-sm" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-ellipsis-h"></i>
</button>
<td class="text-end">
<div class="dropdown dropstart">
<button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown"><i class="fas fa-fw fa-ellipsis-v"></i></button>
<div class="dropdown-menu">
<?php if ($invoice_status !== 'Paid' && $invoice_status !== 'Cancelled' && $invoice_status !== 'Draft' && $invoice_status !== 'Non-Billable' && $invoice_amount != 0) { ?>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/payment/payment_add.php?id=<?= $invoice_id ?>">
<i class="fa fa-fw fa-credit-card me-2"></i>Add Payment
</a>
<a class="dropdown-item" href="<?= $row_url ?>"><i class="fas fa-fw fa-eye text-secondary me-2"></i>Open</a>
<a class="dropdown-item" href="post.php?export_invoice_pdf=<?= $invoice_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" target="_blank"><i class="fas fa-fw fa-file-pdf text-secondary me-2"></i>Download PDF</a>
<?php if ($row_can_pay) { ?>
<div class="dropdown-divider"></div>
<?php if (mysqli_num_rows($sql_saved_payment_methods) > 0 && ($invoice_status === 'Sent' || $invoice_status === 'Viewed')) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/payment/payment_saved_method_add.php?id=<?= $invoice_id ?>"><i class="fas fa-fw fa-wallet me-2"></i>Pay with Saved Card</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/payment/payment_add.php?id=<?= $invoice_id ?>">
<i class="fas fa-fw fa-credit-card text-secondary me-2"></i>Add Payment
</a>
<?php if (isset($saved_card_clients[$row_client_id]) && in_array($row_status, ['Sent', 'Viewed'], true)) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/payment/payment_saved_method_add.php?id=<?= $invoice_id ?>">
<i class="fas fa-fw fa-wallet text-secondary me-2"></i>Charge Saved Card
</a>
<?php } ?>
<?php } ?>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/invoice/invoice_edit.php?id=<?= $invoice_id ?>">
<i class="fas fa-fw fa-edit me-2"></i>Edit
</a>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/invoice/invoice_copy.php?id=<?= $invoice_id ?>">
<i class="fas fa-fw fa-copy me-2"></i>Copy
</a>
<div class="dropdown-divider"></div>
<?php if (!empty($config_smtp_provider)) { ?>
<button type="submit" class="dropdown-item confirm-link" form="quickSendInvoice"
data-confirm-title="Send this invoice now?"
data-confirm-text="It goes to the default contacts without opening the picker."
data-confirm-button="Send"
name="invoice_id" value="<?= $invoice_id ?>">
<i class="fas fa-fw fa-bolt me-2"></i>Quick Send
</button>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/invoice/invoice_email.php?invoice_id=<?= $invoice_id ?>">
<i class="fas fa-fw fa-paper-plane me-2"></i>Send Email<span class="text-muted">...</span>
</a>
<?php if ($can_edit) { ?>
<div class="dropdown-divider"></div>
<?php if ($mail_ready && !in_array($row_status, ['Cancelled', 'Non-Billable'], true)) { ?>
<button type="submit" class="dropdown-item confirm-link" form="quickSendInvoice" name="invoice_id" value="<?= $invoice_id ?>"
data-confirm-title="Send <?= escapeHtml($row_number) ?> now?" data-confirm-text="It goes to the client's primary and billing contacts." data-confirm-button="Send">
<i class="fas fa-fw fa-bolt text-secondary me-2"></i>Quick Send
</button>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/invoice/invoice_email.php?invoice_id=<?= $invoice_id ?>">
<i class="fas fa-fw fa-paper-plane text-secondary me-2"></i>Send Email<span class="text-body-secondary">...</span>
</a>
<?php } ?>
<?php if ($row_status === 'Draft') { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/invoice/invoice_mark_sent.php?invoice_id=<?= $invoice_id ?>">
<i class="fas fa-fw fa-check text-secondary me-2"></i>Mark Sent<span class="text-body-secondary">...</span>
</a>
<?php } ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/invoice/invoice_edit.php?id=<?= $invoice_id ?>">
<i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/invoice/invoice_copy.php?id=<?= $invoice_id ?>">
<i class="fas fa-fw fa-copy text-secondary me-2"></i>Copy
</a>
<?php } ?>
<?php if ($invoice_status == 'Draft') { ?>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/invoice/invoice_mark_sent.php?invoice_id=<?= $invoice_id ?>">
<i class="fas fa-fw fa-check me-2"></i>Mark Sent
</a>
<div class="dropdown-divider"></div>
<?php if ($can_delete) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_invoice=<?= $invoice_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-text="<?= escapeHtml($row_number) ?> goes for good, with its lines, payments and history.">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_invoice=<?= $invoice_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
</div>
</div>
</td>
</tr>
<?php
}
?>
<?php } ?>
</tbody>
</table>
</div>
</form>
<?php if (!$num_rows[0]) { ?>
<div class="itflow-asset-empty">
<i class="fas fa-file-invoice-dollar fa-2x mb-2 opacity-50"></i>
<div><?= $q || $status || $category_filter || $recurring_filter || $dtf !== '1970-01-01' ? 'No invoices match.' : 'No invoices yet.' ?></div>
</div>
<?php } ?>
<?php require_once "../includes/filter_footer.php"; ?>
</div>
<?php if (lookupUserPermission("module_sales") >= 2 && !empty($config_smtp_provider)) { ?>
<?php if ($can_edit && $mail_ready) { ?>
<?php
/*
* One hidden form for the whole page, targeted by the Quick Send buttons via
* their form="" attribute. It cannot be a form per button: agent/invoices.php
* wraps its table in a bulkActions form, and a nested form is invalid
* HTML - the browser drops the inner one and the click silently submits the
* bulk action instead. The button carries the id as its own name/value, which
* a submit button contributes to the submission.
* their form="" attribute. It cannot be a form per button: the table is in
* the bulkActions form, and a nested form is invalid HTML - the browser
* drops the inner one and the click submits the bulk action instead. The
* button carries the id as its own name/value.
*/
?>
<form id="quickSendInvoice" action="post.php" method="post" class="d-none">
@@ -515,5 +451,4 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
<script src="../js/bulk_actions.js"></script>
<?php
require_once "../includes/footer.php";
<?php require_once "../includes/footer.php";

View File

@@ -0,0 +1,253 @@
<?php
/*
* The details of an invoice, quote or recurring invoice - shared by the New
* and Edit windows for all three. Set before including:
*
* $form_type invoice | quote | recurring
* $form_row billingRow() when editing, null for a new one
* $form_client_id the client a new one is for (0 = pick it here)
*
* Posts the fields the existing handlers read: client_id, scope, category,
* and then by kind - invoice: date, due (edit), invoice_discount; quote:
* date, expire, quote_discount; recurring: frequency, start_date (new) or
* next_date (edit), recurring_invoice_discount, auto_send, status (edit).
*
* Should not be accessed directly.
*/
isset($mysqli) || die("Direct file access is not allowed");
$form_t = billingType($form_type);
$form_c = $form_t['col'];
$form_edit = !empty($form_row);
$form_id = 'billingForm' . ucfirst($form_type) . ($form_edit ? intval($form_row["{$form_c}_id"]) : 'New');
$form_value = function ($column, $default = '') use ($form_row, $form_c) {
return $form_row ? (string) ($form_row["{$form_c}_$column"] ?? $default) : $default;
};
$form_currency = $form_edit ? (string) $form_row["{$form_c}_currency_code"] : (string) $session_company_currency;
$form_category_id = intval($form_value('category_id', '0'));
$form_categories = billingCategories($form_edit ? $form_value('created_at') : null);
$form_discount = floatval($form_value('discount_amount', '0'));
// Net terms - the client's, or the default - for a new invoice's due date
$form_terms = intval($config_default_net_terms);
if ($form_client_id) {
$form_terms = intval(getFieldById('clients', $form_client_id, 'client_net_terms')) ?: $form_terms;
}
$form_clients = [];
if (!$form_edit && !$form_client_id) {
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, client_net_terms FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$form_clients[] = $row;
}
}
$form_scope_placeholder = [
'invoice' => 'Managed services - October, onsite visit 12 March, new laptop for Sam',
'quote' => 'Firewall replacement, Microsoft 365 migration, new starter kit',
'recurring' => 'Monthly managed services, backup and hosting',
][$form_type];
?>
<div class="row g-3" id="<?= $form_id ?>" data-billing-form="<?= $form_type ?>" data-terms="<?= $form_terms ?>">
<?php if (!$form_edit && !$form_client_id) { ?>
<div class="col-12">
<label class="form-label">Client <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-building"></i></span>
<select class="form-select select2" name="client_id" required data-billing-client>
<option value="">- Select a client -</option>
<?php foreach ($form_clients as $form_client) { ?>
<option value="<?= intval($form_client['client_id']) ?>" data-terms="<?= intval($form_client['client_net_terms']) ?: intval($config_default_net_terms) ?>"<?= selectOptionClient($form_client['client_id'], $form_client['client_name'], $form_client['client_abbreviation'] ?? '') ?>><?= escapeHtml($form_client['client_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<?php } elseif (!$form_edit) { ?>
<input type="hidden" name="client_id" value="<?= intval($form_client_id) ?>">
<?php } ?>
<div class="col-12">
<label class="form-label">Scope</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
<input type="text" class="form-control" name="scope" maxlength="255" placeholder="<?= escapeHtml($form_scope_placeholder) ?>" value="<?= escapeHtml($form_value('scope')) ?>" <?= $form_edit ? '' : 'autofocus' ?>>
</div>
<div class="form-text">What it is for, in a few words - shown on it and in lists.</div>
</div>
<div class="col-12">
<label class="form-label">Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="category" required>
<option value="">- Category -</option>
<?php foreach ($form_categories as $category_id => $category) { ?>
<option value="<?= intval($category_id) ?>" <?= $form_category_id === intval($category_id) ? 'selected' : '' ?><?= selectOptionColor($category['category_color'] ?? '', $category['category_icon'] ?? '') ?>><?= escapeHtml($category['category_name']) ?></option>
<?php } ?>
</select>
<button class="btn btn-secondary ajax-modal" title="New category" type="button" data-modal-url="../admin/modals/category/category_add.php?category=Income">
<i class="fas fa-fw fa-plus"></i>
</button>
</div>
</div>
<?php if ($form_type === 'invoice') { ?>
<div class="col-sm-6">
<label class="form-label">Invoice date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= escapeHtml($form_value('date', date('Y-m-d'))) ?>" required data-billing-date>
</div>
</div>
<div class="col-sm-6">
<label class="form-label">Due <?= $form_edit ? '<strong class="text-danger">*</strong>' : '' ?></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar-check"></i></span>
<?php if ($form_edit) { ?>
<input type="date" class="form-control" name="due" max="2999-12-31" value="<?= escapeHtml($form_value('due')) ?>" required data-billing-due>
<?php } else { ?>
<input type="date" class="form-control" value="<?= date('Y-m-d', strtotime("+$form_terms days")) ?>" disabled data-billing-due>
<?php } ?>
</div>
<?php if (!$form_edit) { ?>
<div class="form-text" data-billing-terms-note><?= $form_terms ?> days from the invoice date - <?= $form_client_id ? "the client's" : 'the default' ?> terms.</div>
<?php } ?>
</div>
<?php } elseif ($form_type === 'quote') { ?>
<div class="col-sm-6">
<label class="form-label">Quote date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= escapeHtml($form_value('date', date('Y-m-d'))) ?>" required data-billing-date>
</div>
</div>
<div class="col-sm-6">
<label class="form-label">Valid until <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-hourglass-half"></i></span>
<input type="date" class="form-control" name="expire" max="2999-12-31" value="<?= escapeHtml($form_value('expire', date('Y-m-d', strtotime('+30 days')))) ?>" required data-billing-expire>
</div>
<div class="form-text">
<?php foreach ([15, 30, 60, 90] as $days) { ?>
<a href="#" class="me-2" data-billing-expire-days="<?= $days ?>"><?= $days ?> days</a>
<?php } ?>
</div>
</div>
<?php } else { ?>
<div class="col-sm-6">
<label class="form-label">Billed <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-sync-alt"></i></span>
<select class="form-select" name="frequency" required>
<?php foreach (recurringInvoiceFrequencies() as $frequency => $label) { ?>
<option value="<?= $frequency ?>" <?= $form_value('frequency', 'month') === $frequency ? 'selected' : '' ?>><?= $label ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-sm-6">
<label class="form-label"><?= $form_edit ? 'Next invoice' : 'First invoice' ?> <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar-day"></i></span>
<input type="date" class="form-control" name="<?= $form_edit ? 'next_date' : 'start_date' ?>" max="2999-12-31"
value="<?= escapeHtml($form_edit ? $form_value('next_date') : date('Y-m-01', strtotime('first day of next month'))) ?>" required>
</div>
<div class="form-text">Made on this date, then every period after.</div>
</div>
<?php } ?>
<div class="col-sm-6">
<label class="form-label">Discount</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tags"></i></span>
<input type="text" class="form-control text-end" inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}"
name="<?= ['invoice' => 'invoice_discount', 'quote' => 'quote_discount', 'recurring' => 'recurring_invoice_discount'][$form_type] ?>"
placeholder="0.00" value="<?= $form_discount != 0 ? number_format($form_discount, 2, '.', '') : '' ?>">
<span class="input-group-text"><?= escapeHtml($form_currency) ?></span>
</div>
<div class="form-text">Taken off the total, after the lines.</div>
</div>
<?php if ($form_type === 'recurring') { ?>
<div class="col-sm-6">
<label class="form-label">When it is made</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-paper-plane"></i></span>
<select class="form-select" name="auto_send">
<option value="1" <?= $form_value('auto_send', '1') === '1' ? 'selected' : '' ?>>Send it automatically</option>
<option value="0" <?= $form_value('auto_send', '1') === '0' ? 'selected' : '' ?>>Leave a draft to check</option>
</select>
</div>
<?php if (empty($config_recurring_auto_send_invoice)) { ?>
<div class="form-text text-warning-emphasis">Sending recurring invoices is off in the billing settings - they are made as drafts.</div>
<?php } ?>
</div>
<?php if ($form_edit) { ?>
<div class="col-12">
<div class="form-check form-switch">
<input type="hidden" name="status" value="0">
<input class="form-check-input" type="checkbox" role="switch" name="status" value="1" id="<?= $form_id ?>Active" <?= intval($form_value('status', '1')) ? 'checked' : '' ?>>
<label class="form-check-label" for="<?= $form_id ?>Active">Active - invoices are made on schedule</label>
</div>
</div>
<?php } ?>
<?php } ?>
</div>
<script>
(function () {
var root = document.getElementById(<?= json_encode($form_id) ?>);
if (!root || root.hasAttribute('data-wired')) {
return;
}
root.setAttribute('data-wired', '1');
function ymd(d) {
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
}
function plus(value, days) {
var parts = String(value || '').split('-');
var d = parts.length === 3 ? new Date(+parts[0], +parts[1] - 1, +parts[2]) : new Date();
d.setDate(d.getDate() + days);
return ymd(d);
}
var date = root.querySelector('[data-billing-date]');
// A new invoice: the due date follows the date and the client's terms
var due = root.querySelector('[data-billing-due][disabled]');
var client = root.querySelector('[data-billing-client]');
var note = root.querySelector('[data-billing-terms-note]');
function terms() {
var option = client && client.options[client.selectedIndex];
return option && option.getAttribute('data-terms') ? Number(option.getAttribute('data-terms')) : Number(root.getAttribute('data-terms') || 0);
}
function follow() {
if (due && date) {
due.value = plus(date.value, terms());
if (note) {
note.textContent = terms() + ' days from the invoice date - ' + (client && client.value ? "the client's" : 'the default') + ' terms.';
}
}
}
if (due) {
date.addEventListener('change', follow);
if (client) {
client.addEventListener('change', follow);
}
}
// A quote: valid for so many days from its date
root.querySelectorAll('[data-billing-expire-days]').forEach(function (link) {
link.addEventListener('click', function (e) {
e.preventDefault();
var expire = root.querySelector('[data-billing-expire]');
expire.value = plus(date ? date.value : '', Number(link.getAttribute('data-billing-expire-days')));
});
});
})();
</script>

View File

@@ -0,0 +1,135 @@
<?php
/*
* Edit a line on an invoice, quote or recurring invoice - its name and
* description, quantity, price and tax, with what it comes to as you type.
* ?type=invoice|quote|recurring&doc_id=&item_id=
*
* A line from a product keeps its link to the product; on an invoice,
* changing the quantity of a stocked product moves the stock with it.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$type = (string) ($_GET['type'] ?? '');
$doc_id = intval($_GET['doc_id'] ?? 0);
$item_id = intval($_GET['item_id'] ?? 0);
$doc = billingType($type) ? billingRow($type, $doc_id) : null;
if (!$doc) {
exit(json_encode(['error' => 'That document no longer exists.']));
}
$client_id = intval($doc['client_id']);
enforceClientAccess();
if (!billingCanEditItems($type, $doc)) {
exit(json_encode(['error' => billingNumber($type, $doc) . " can't be changed now - " . ($type === 'quote' ? 'it has been answered or invoiced.' : 'it is paid, cancelled or non-billable.')]));
}
$item = null;
foreach (billingItems($type, $doc_id) as $line) {
if (intval($line['item_id']) === $item_id) {
$item = $line;
}
}
if (!$item) {
exit(json_encode(['error' => 'That line no longer exists.']));
}
$t = billingType($type);
$currency = (string) $doc["{$t['col']}_currency_code"];
$taxes = billingTaxes($item['item_created_at']);
$product_name = intval($item['item_product_id']) ? getFieldById('products', intval($item['item_product_id']), 'product_name') : '';
$product_type = intval($item['item_product_id']) ? getFieldById('products', intval($item['item_product_id']), 'product_type') : '';
$quantity = billingQuantity($item['item_quantity']);
$price = number_format(floatval($item['item_price']), 2, '.', '');
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-edit me-2"></i>Edit Line <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber($type, $doc)) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off" data-billing-line-form>
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="billing_item_save" value="1">
<input type="hidden" name="type" value="<?= escapeHtml($type) ?>">
<input type="hidden" name="doc_id" value="<?= $doc_id ?>">
<input type="hidden" name="item_id" value="<?= $item_id ?>">
<div class="modal-body">
<div class="row g-3">
<div class="col-12">
<label class="form-label">Item <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-cube"></i></span>
<input type="text" class="form-control" name="name" maxlength="200" value="<?= escapeHtml($item['item_name']) ?>" required data-line-name>
</div>
<?php if ($product_name !== '' && $product_name !== null) { ?>
<div class="form-text"><i class="fas fa-link me-1"></i>From the <?= $product_type === 'product' ? 'product' : 'service' ?> <strong><?= escapeHtml($product_name) ?></strong><?= $type === 'invoice' && $product_type === 'product' ? ' - changing the quantity moves its stock' : '' ?>.</div>
<?php } ?>
</div>
<div class="col-12">
<label class="form-label">Description</label>
<div class="input-group">
<span class="input-group-text align-items-start pt-2"><i class="fa fa-fw fa-align-left"></i></span>
<textarea class="form-control" name="description" rows="3" placeholder="What it is, the period it covers, serial numbers - shown under the item" data-line-description><?= escapeHtml($item['item_description']) ?></textarea>
</div>
</div>
<div class="col-sm-4">
<label class="form-label">Quantity <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-hashtag"></i></span>
<input type="text" class="form-control text-end" name="qty" inputmode="decimal" value="<?= $quantity ?>" required data-line-qty>
</div>
</div>
<div class="col-sm-4">
<label class="form-label">Price <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control text-end" name="price" inputmode="decimal" value="<?= $price ?>" required data-line-price>
</div>
<div class="form-text">Each, in <?= escapeHtml($currency) ?>. A credit can be negative.</div>
</div>
<div class="col-sm-4">
<label class="form-label">Tax</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-line-tax>
<option value="0" data-percent="0">No tax</option>
<?php foreach ($taxes as $tax_id => $tax) { ?>
<option value="<?= intval($tax_id) ?>" data-percent="<?= floatval($tax['tax_percent']) ?>" <?= intval($item['item_tax_id']) === intval($tax_id) ? 'selected' : '' ?>><?= escapeHtml($tax['tax_name'] . ' ' . billingQuantity($tax['tax_percent']) . '%') ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="d-flex justify-content-between align-items-center mt-3 pt-3 border-top">
<span class="text-body-secondary">The line comes to</span>
<span class="fs-5 fw-semibold itflow-money" data-line-preview><?= escapeHtml(billingMoney($item['item_total'], $currency)) ?></span>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<script>
(function () {
var form = document.querySelector('form[data-billing-line-form]:not([data-wired])');
if (!form) {
return;
}
form.setAttribute('data-wired', '1');
if (typeof itflowBillingLineForm === 'function') {
itflowBillingLineForm(form, { currency: <?= json_encode($currency) ?>, locale: <?= json_encode(str_replace('_', '-', (string) $session_company_locale)) ?> });
}
})();
</script>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -71,7 +71,7 @@ ob_start();
<div class="modal-header bg-dark">
<h5 class="modal-title text-white">
<i class="fa fa-fw fa-file-alt me-2"></i>Send Account Statement
<span class="text-muted ms-1"><?= $client_name ?></span>
<span class="fw-normal text-white-50 ms-1"><?= $client_name ?></span>
</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>

View File

@@ -1,103 +1,40 @@
<?php
/*
* New invoice - who it is for, what it is for, its category, date and any
* discount. It starts as a draft, due on the client's terms; the lines go on
* the invoice page.
* ?client_id= starts it for that client; without one, pick the client here.
*/
require_once '../../../includes/modal_header.php';
$client_id = intval($_GET['client_id'] ?? 0);
enforceUserPermission('module_sales', 2);
$form_type = 'invoice';
$form_row = null;
$form_client_id = intval($_GET['client_id'] ?? 0);
if ($form_client_id) {
$client_id = $form_client_id;
enforceClientAccess();
}
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-file-invoice me-2"></i>New Invoice</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-file-invoice-dollar me-2"></i>New Invoice<?php if ($form_client_id) { ?> <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(getFieldById('clients', $form_client_id, 'client_name')) ?></span><?php } ?></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<div class="modal-body">
<?php if ($client_id) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php }else{ ?>
<div class="mb-3">
<label>Client <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<select class="form-select select2" name="client_id" required>
<option value="">- Select a Client -</option>
<?php
//select unarchived clients
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$client_id_select = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
?>
<option value="<?= $client_id_select ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= "$client_name" ?></option>
<?php
}
?>
</select>
</div>
</div>
<?php } ?>
<div class="mb-3">
<label>Scope</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
<input type="text" class="form-control" name="scope" placeholder="Quick description" maxlength="255">
</div>
</div>
<div class="mb-3">
<label>Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="category" required>
<option value="">- Category -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND category_archived_at IS NULL ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<option value="<?= $category_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name ?></option>
<?php
}
?>
</select>
<button class="btn btn-secondary ajax-modal" title="New category" type="button"
data-modal-url="../admin/modals/category/category_add.php?category=Income">
<i class="fas fa-fw fa-plus"></i>
</button>
</div>
</div>
<div class="mb-3">
<label>Invoice Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date("Y-m-d") ?>" required>
</div>
</div>
<div class='mb-3'>
<label>Discount Amount</label>
<div class='input-group'>
<span class='input-group-text'><i class='fa fa-fw fa-dollar-sign'></i></span>
<input type='text' class='form-control' inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}" name='invoice_discount' placeholder='0.00'>
</div>
</div>
<?php require __DIR__ . '/../billing/billing_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_invoice" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Create</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
<button type="submit" name="add_invoice" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Create</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -1,64 +1,68 @@
<?php
<div class="modal" id="addTicketModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-file-invoice me-2"></i>Add Unbilled Ticket to Invoice</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Ticket Number</th>
<th>Scope</th>
<th>Add to Invoice</th>
</tr>
</thead>
<?php while ($row = mysqli_fetch_assoc($sql_tickets_billable)) {
$ticket_id = intval($row['ticket_id']);
$ticket_subject = escapeHtml($row['ticket_subject']);
$ticket_number = intval($row['ticket_number']);
$ticket_prefix = escapeHtml($row['ticket_prefix']);
$ticket_status = escapeHtml($row['ticket_status']);
/*
* Put tickets on an invoice - the client's billable tickets that are
* resolved or closed and not on an invoice yet, with the time worked on
* each. Tick any number. ?invoice_id=
*/
switch ($ticket_status) {
case 'Closed':
$ticket_status_class = 'bg-dark';
break;
case 'Auto Close':
$ticket_status_class = 'bg-warning';
break;
default:
$ticket_status_class = 'bg-secondary';
break;
}
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
?>
<tr>
<td>
<a href="ticket.php?ticket_id=<?= $ticket_id ?>">
<span class="badge rounded-pill <?= $ticket_status_class ?> p-3"><?= "$ticket_prefix$ticket_number" ?></span>
</a>
</td>
<td><?= $ticket_subject ?></td>
<td>
<form action="post.php" method="post">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="invoice_id" value="<?= $invoice_id ?>">
<input type="hidden" name="ticket_id" value="<?= $ticket_id ?>">
<button class="btn btn-link p-0" type="submit" name="add_ticket_to_invoice" title="Add ticket to invoice">
<i class="fas fa-fw fa-plus-circle"></i>
</button>
</form>
</td>
</tr>
<?php } ?>
</table>
</div>
</div>
</div>
</div>
$invoice_id = intval($_GET['invoice_id'] ?? 0);
$invoice = billingRow('invoice', $invoice_id);
if (!$invoice) {
exit(json_encode(['error' => 'That invoice no longer exists.']));
}
$client_id = intval($invoice['client_id']);
enforceClientAccess();
$tickets = invoiceUnbilledTickets($client_id);
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-life-ring me-2"></i>Add Tickets <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber('invoice', $invoice)) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="invoice_id" value="<?= $invoice_id ?>">
<div class="modal-body p-0">
<?php if ($tickets) { ?>
<div class="px-3 py-2 small text-body-secondary border-bottom">
<?= escapeHtml($invoice['client_name']) ?>'s billable tickets, resolved or closed, that aren't on an invoice. Adding one marks it billed - its time isn't added as a line.
</div>
<div class="list-group list-group-flush" style="max-height: 24rem; overflow-y: auto;">
<?php foreach ($tickets as $ticket) {
$ticket_id = intval($ticket['ticket_id']); ?>
<label class="list-group-item list-group-item-action d-flex align-items-center gap-3">
<input class="form-check-input flex-shrink-0 mt-0" type="checkbox" name="ticket_ids[]" value="<?= $ticket_id ?>">
<div class="flex-grow-1 min-w-0">
<div class="text-truncate"><span class="font-monospace small text-body-secondary me-2"><?= escapeHtml($ticket['ticket_prefix'] . $ticket['ticket_number']) ?></span><?= escapeHtml($ticket['ticket_subject']) ?></div>
<div class="small text-body-secondary">Opened <?= escapeHtml(date('Y-m-d', strtotime($ticket['ticket_created_at']))) ?></div>
</div>
<span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal" title="Time worked"><i class="far fa-clock me-1"></i><?= billingDuration($ticket['seconds']) ?></span>
</label>
<?php } ?>
</div>
<?php } else { ?>
<div class="itflow-asset-empty">
<i class="fas fa-life-ring fa-2x mb-2 opacity-50"></i>
<div>No unbilled tickets - <?= escapeHtml($invoice['client_name']) ?>'s billable tickets are all on an invoice, or still open.</div>
</div>
<?php } ?>
</div>
<div class="modal-footer">
<?php if ($tickets) { ?>
<button type="submit" name="add_ticket_to_invoice" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Add</button>
<?php } ?>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i><?= $tickets ? 'Cancel' : 'Close' ?></button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,51 +1,43 @@
<?php
/*
* Set the income category on the invoices ticked on the invoices list.
*/
require_once '../../../includes/modal_header.php';
$invoice_ids = array_map('intval', $_GET['invoice_ids'] ?? []);
enforceUserPermission('module_sales', 2);
$invoice_ids = array_values(array_filter(array_map('intval', (array) ($_GET['invoice_ids'] ?? []))));
$count = count($invoice_ids);
$categories = billingCategories();
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-list me-2"></i>Set Category for <strong><?= $count ?></strong> Invoices</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-tag me-2"></i>Set Category <span class="fw-normal text-white-50 ms-1"><?= $count ?> invoice<?= $count === 1 ? '' : 's' ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<?php foreach ($invoice_ids as $invoice_id) { ?><input type="hidden" name="invoice_ids[]" value="<?= $invoice_id ?>"><?php } ?>
<div class="modal-body">
<div class="mb-3">
<label>Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-list"></i></span>
<select class="form-select select2" name="bulk_category_id">
<?php
$sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND category_archived_at IS NULL ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<option value="<?= $category_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name ?></option>
<?php
}
?>
</select>
</div>
<label class="form-label">Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="bulk_category_id" required>
<?php foreach ($categories as $category_id => $category) { ?>
<option value="<?= intval($category_id) ?>"<?= selectOptionColor($category['category_color'] ?? '', $category['category_icon'] ?? '') ?>><?= escapeHtml($category['category_name']) ?></option>
<?php } ?>
</select>
</div>
<div class="form-text">Reports group income by it.</div>
</div>
<div class="modal-footer">
<button type="submit" name="bulk_edit_invoice_category" class="btn btn-primary text-bold"><i class="fa fa-fw fa-check me-2"></i>Set Category</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
<button type="submit" name="bulk_edit_invoice_category" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Set Category</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -1,50 +1,51 @@
<?php
/*
* Copy an invoice - a new draft for the same client with the same lines,
* scope, category, discount and notes, on the date given and due on the
* client's terms. ?id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$invoice_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT client_name, invoice_client_id, invoice_number, invoice_prefix FROM invoices LEFT JOIN clients ON invoice_client_id = client_id WHERE invoice_id = $invoice_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$invoice_prefix = escapeHtml($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$client_name = escapeHtml($row['client_name']);
$client_id = intval($row['invoice_client_id']);
$doc_type = 'invoice';
$doc = billingRow($doc_type, intval($_GET['id'] ?? 0));
if (!$doc) {
exit(json_encode(['error' => 'That invoice no longer exists.']));
}
$client_id = intval($doc['client_id']);
enforceClientAccess();
$doc_number = billingNumber($doc_type, $doc);
$lines = count(billingItems('invoice', intval($doc['invoice_id'])));
$terms = intval($doc['client_net_terms']) ?: intval($config_default_net_terms);
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-copy me-2"></i>Copying invoice: <strong><?= "$invoice_prefix$invoice_number" ?></strong> - <?= $client_name ?></h5>
<h5 class="modal-title"><i class="fas fa-fw fa-copy me-2"></i>Copy Invoice <span class="fw-normal text-white-50 ms-1"><?= escapeHtml($doc_number) ?> &middot; <?= escapeHtml($doc['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="invoice_id" value="<?= $invoice_id ?>">
<input type="hidden" name="invoice_id" value="<?= intval($doc['invoice_id']) ?>">
<div class="modal-body">
<div class="mb-3">
<label>Invoice Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date("Y-m-d") ?>" required>
</div>
<p class="text-body-secondary small">A new draft for <?= escapeHtml($doc['client_name']) ?> with the same <?= $lines ?> line<?= $lines === 1 ? '' : 's' ?>, scope, discount and notes - <?= escapeHtml(billingMoney($doc['invoice_amount'], $doc['invoice_currency_code'])) ?>.</p>
<label class="form-label">Invoice date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date('Y-m-d') ?>" required>
</div>
<div class="form-text">Due <?= $terms ?> days after it - the client's terms.</div>
</div>
<div class="modal-footer">
<button type="submit" name="add_invoice_copy" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Copy</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
<button type="submit" name="add_invoice_copy" class="btn btn-primary text-bold"><i class="fas fa-copy me-2"></i>Copy</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,109 +1,42 @@
<?php
/*
* Edit an invoice's details - scope, category, dates and discount. Its
* lines are edited on the invoice itself. ?id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$invoice_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, invoice_category_id, invoice_created_at, invoice_date,
invoice_discount_amount, invoice_due, invoice_number, invoice_prefix, invoice_scope FROM invoices LEFT JOIN clients ON invoice_client_id = client_id WHERE invoice_id = $invoice_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$invoice_prefix = escapeHtml($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$invoice_scope = escapeHtml($row['invoice_scope']);
$invoice_date = escapeHtml($row['invoice_date']);
$invoice_due = escapeHtml($row['invoice_due']);
$invoice_discount = floatval($row['invoice_discount_amount']);
$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']);
$form_type = 'invoice';
$form_row = billingRow($form_type, intval($_GET['id'] ?? 0));
if (!$form_row) {
exit(json_encode(['error' => 'That invoice no longer exists.']));
}
$client_id = intval($form_row['client_id']);
enforceClientAccess();
$form_client_id = $client_id;
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-file-invoice me-2"></i>Editing invoice: <strong><?= "$invoice_prefix$invoice_number" ?></strong> - <?= $client_name ?></h5>
<h5 class="modal-title"><i class="fas fa-fw fa-file-invoice-dollar me-2"></i>Edit Invoice <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber($form_type, $form_row)) ?> &middot; <?= escapeHtml($form_row['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="invoice_id" value="<?= $invoice_id ?>">
<div class="modal-body" <?php if (lookupUserPermission('module_sales') <= 1) { echo 'inert'; } ?>>
<div class="mb-3">
<label>Invoice Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= $invoice_date ?>" required>
</div>
</div>
<div class="mb-3">
<label>Invoice Due <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar-alt"></i></span>
<input type="date" class="form-control" name="due" max="2999-12-31" value="<?= $invoice_due ?>" required>
</div>
</div>
<div class="mb-3">
<label>Income Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="category" required>
<option value="">- Category -</option>
<?php
$sql_income_category = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND (category_archived_at > '$invoice_created_at' OR category_archived_at IS NULL) ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql_income_category)) {
$category_id_select = intval($row['category_id']);
$category_name_select = escapeHtml($row['category_name']);
?>
<option <?php if ($category_id == $category_id_select) {
echo "selected";
} ?> value="<?= $category_id_select ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name_select ?></option>
<?php
}
?>
</select>
<button class="btn btn-secondary ajax-modal" title="New category" type="button"
data-modal-url="../admin/modals/category/category_add.php?category=Income">
<i class="fas fa-fw fa-plus"></i>
</button>
</div>
</div>
<div class='mb-3'>
<label>Discount Amount</label>
<div class='input-group'>
<span class='input-group-text'><i class='fa fa-fw fa-dollar-sign'></i></span>
<input type='text' class='form-control' inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}" name='invoice_discount' placeholder='0.00' value="<?= number_format($invoice_discount, 2, '.', '') ?>">
</div>
</div>
<div class="mb-3">
<label>Scope</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
<input type="text" class="form-control" name="scope" placeholder="Quick description" maxlength="255" value="<?= $invoice_scope ?>">
</div>
</div>
<input type="hidden" name="invoice_id" value="<?= intval($form_row['invoice_id']) ?>">
<div class="modal-body">
<?php require __DIR__ . '/../billing/billing_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="edit_invoice" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -9,6 +9,9 @@ $invoice_id = intval($_GET['invoice_id']);
$sql = mysqli_query($mysqli, "SELECT invoice_client_id, invoice_number, invoice_prefix, invoice_status
FROM invoices WHERE invoice_id = $invoice_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
exit(json_encode(['error' => 'That invoice no longer exists.']));
}
$invoice_prefix = escapeHtml($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$invoice_status = escapeHtml($row['invoice_status']);
@@ -16,6 +19,8 @@ $client_id = intval($row['invoice_client_id']);
enforceClientAccess();
$doc = billingRow('invoice', $invoice_id);
// Billing-facing contacts only - see documentContactFilterSql(). Everyone
// shown is also checked by default, which is the behaviour the old one-click
// Send Email link had baked in; the checkboxes are here to drop one, not to
@@ -55,9 +60,7 @@ ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-white">
<i class="fa fa-fw fa-paper-plane me-2"></i>Email Invoice <?= "$invoice_prefix$invoice_number" ?>
</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-paper-plane me-2"></i>Send Invoice <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber('invoice', $doc)) ?> &middot; <?= escapeHtml($doc['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
@@ -68,7 +71,7 @@ ob_start();
<?php if ($contact_count == 0) { ?>
<p class="text-muted mb-0">
<p class="text-body-secondary mb-0">
This client has no primary or billing contact with an email address, so there is
nobody to send an invoice to. Flag a contact as billing, or use Mark Sent to record
that the invoice went out some other way.
@@ -76,7 +79,21 @@ ob_start();
<?php } else { ?>
<label class="mb-2">Send to <strong class="text-danger">*</strong></label>
<!-- What goes out -->
<?php $doc_state = invoiceState($doc, invoicePaid($invoice_id)); ?>
<div class="d-flex align-items-center gap-3 p-3 mb-3 rounded bg-body-tertiary">
<?= billingTile('invoice') ?>
<div class="flex-grow-1 min-w-0">
<div class="fw-semibold"><?= escapeHtml(billingNumber('invoice', $doc)) ?><?= trim((string) $doc['invoice_scope']) !== '' ? ' - ' . escapeHtml($doc['invoice_scope']) : '' ?></div>
<div class="small text-body-secondary">An email with a link to view<?= billingOnlinePayments() && !in_array($doc['invoice_status'], ['Paid', 'Cancelled', 'Non-Billable'], true) ? ', pay' : '' ?> and download it as a PDF.</div>
</div>
<div class="text-end">
<div class="fw-semibold itflow-money"><?= escapeHtml(billingMoney($doc_state['balance'] > 0 ? $doc_state['balance'] : $doc['invoice_amount'], $doc['invoice_currency_code'])) ?></div>
<div class="small text-body-secondary"><?= $doc_state['balance'] > 0 ? 'due ' . escapeHtml($doc['invoice_due']) : 'total' ?></div>
</div>
</div>
<label class="form-label">Send to <strong class="text-danger">*</strong></label>
<div class="list-group mb-3">
@@ -116,7 +133,7 @@ ob_start();
</div>
<?php if ($invoice_status !== 'Draft') { ?>
<p class="text-muted mb-0">
<p class="text-body-secondary small mb-0">
<i class="fa fa-fw fa-info-circle me-1"></i>This invoice is
<strong><?= $invoice_status ?></strong>, so sending it will not change its status.
</p>

View File

@@ -60,6 +60,8 @@ ob_start();
<option <?php if ($status_filter === 'Draft') { echo "selected"; } ?> value="Draft">Draft</option>
<option <?php if ($status_filter === 'Unpaid') { echo "selected"; } ?> value="Unpaid">Unpaid</option>
<option <?php if ($status_filter === 'Overdue') { echo "selected"; } ?> value="Overdue">Overdue</option>
<option <?php if ($status_filter === 'Paid') { echo "selected"; } ?> value="Paid">Paid</option>
<option <?php if ($status_filter === 'Cancelled') { echo "selected"; } ?> value="Cancelled">Cancelled or non-billable</option>
</select>
</div>
</div>

View File

@@ -1,103 +0,0 @@
<?php
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$item_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT invoice_client_id, item_created_at, item_description, item_name, item_price,
item_product_id, item_quantity, item_tax_id FROM invoice_items LEFT JOIN invoices ON invoice_id = item_invoice_id WHERE item_id = $item_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$item_name = escapeHtml($row['item_name']);
$item_description = escapeHtml($row['item_description']);
$item_quantity = floatval($row['item_quantity']);
$item_price = floatval($row['item_price']);
$item_created_at = escapeHtml($row['item_created_at']);
$tax_id = intval($row['item_tax_id']);
$product_id = intval($row['item_product_id']);
$client_id = intval($row['invoice_client_id']);
enforceClientAccess();
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-edit me-2"></i>Editing Line Item: <strong><?= $item_name ?></strong></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="item_id" value="<?= $item_id ?>">
<input type="hidden" name="product_id" value="<?= $product_id ?>">
<div class="modal-body">
<div class="mb-3">
<label>Item <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-box"></i></span>
<input type="text" class="form-control" name="name" maxlength="200" value="<?= $item_name ?>" placeholder="Enter item name" required>
</div>
</div>
<div class="row g-2">
<div class="col-sm">
<div class="mb-3">
<label>Quantity <strong class="text-danger">*</strong></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" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" name="qty" value="<?= number_format($item_quantity, 2) ?>" placeholder="0.00" required>
</div>
</div>
</div>
<div class="col-sm">
<div class="mb-3">
<label>Price <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control" inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}" name="price" value="<?= number_format($item_price, 2, '.', '') ?>" placeholder="0.00" required>
</div>
</div>
</div>
</div>
<div class="mb-3">
<label>Description</label>
<div class="input-group">
<textarea class="form-control" rows="5" name="description" placeholder="Enter a description"><?= $item_description ?></textarea>
</div>
</div>
<div class="mb-3">
<label>Tax <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="tax_id" required>
<option value="0">No Tax</option>
<?php
$taxes_sql = mysqli_query($mysqli, "SELECT tax_id, tax_name, tax_percent FROM taxes WHERE (tax_archived_at > '$item_created_at' OR tax_archived_at IS NULL) ORDER BY tax_name ASC");
while ($row = mysqli_fetch_assoc($taxes_sql)) {
$tax_id_select = intval($row['tax_id']);
$tax_name = escapeHtml($row['tax_name']);
$tax_percent = floatval($row['tax_percent']);
?>
<option <?php if ($tax_id_select == $tax_id) { echo "selected"; } ?> value="<?= $tax_id_select ?>"><?= "$tax_name $tax_percent%" ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="edit_invoice_item" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,62 +1,61 @@
<?php
/*
* Mark a invoice sent - for one that went out some other way than
* ITFlow's email: posted, handed over, sent from your own mail. How, and a
* note, go in its history. ?invoice_id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$invoice_id = intval($_GET['invoice_id']);
$sql = mysqli_query($mysqli, "SELECT invoice_client_id, invoice_number, invoice_prefix
FROM invoices WHERE invoice_id = $invoice_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$invoice_prefix = escapeHtml($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$client_id = intval($row['invoice_client_id']);
$doc_type = 'invoice';
$doc = billingRow($doc_type, intval($_GET['invoice_id'] ?? 0));
if (!$doc) {
exit(json_encode(['error' => 'That invoice no longer exists.']));
}
$client_id = intval($doc['client_id']);
enforceClientAccess();
$doc_number = billingNumber($doc_type, $doc);
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-white">
<i class="fa fa-fw fa-check me-2"></i>Mark Invoice <?= "$invoice_prefix$invoice_number" ?> Sent
</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-check me-2"></i>Mark Sent <span class="fw-normal text-white-50 ms-1"><?= escapeHtml($doc_number) ?> &middot; <?= escapeHtml($doc['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="invoice_id" value="<?= $invoice_id ?>">
<input type="hidden" name="invoice_id" value="<?= intval($doc['invoice_id']) ?>">
<div class="modal-body">
<div class="mb-3">
<label>How was it sent? <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-paper-plane"></i></span>
<select class="form-select" name="sent_method" required>
<?php foreach (getSentMethods() as $sent_method) { ?>
<option value="<?= escapeHtml($sent_method) ?>"><?= escapeHtml($sent_method) ?></option>
<?php } ?>
</select>
<p class="text-body-secondary small">For a invoice that went out some other way than ITFlow's email. It stops being a draft - it counts as owed from now, and the client can open and pay it from its link.</p>
<div class="row g-3">
<div class="col-12">
<label class="form-label">How was it sent? <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-paper-plane"></i></span>
<select class="form-select" name="sent_method" required>
<?php foreach (getSentMethods() as $sent_method) { ?>
<option value="<?= escapeHtml($sent_method) ?>"><?= escapeHtml($sent_method) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-12">
<label class="form-label">Note</label>
<div class="input-group">
<span class="input-group-text align-items-start pt-2"><i class="fa fa-fw fa-sticky-note"></i></span>
<textarea class="form-control" name="note" rows="3" maxlength="500" placeholder="Tracking number, who it went to, anything worth keeping"></textarea>
</div>
</div>
</div>
<div class="mb-3">
<label>Note</label>
<textarea class="form-control" name="note" rows="3" maxlength="500"
placeholder="Optional - tracking number, who it went to, anything worth keeping"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="mark_invoice_sent" class="btn btn-primary text-bold">
<i class="fa fa-fw fa-check me-2"></i>Mark Sent
</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal">
<i class="fa fa-fw fa-times me-2"></i>Cancel
</button>
<button type="submit" name="mark_invoice_sent" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Mark Sent</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -1,154 +1,79 @@
<?php
/*
* An invoice's payments at a glance, from the invoices list - each payment,
* what has been paid and what is left. ?invoice_id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales');
$invoice_id = intval($_GET['invoice_id']);
$sql = mysqli_query($mysqli, "SELECT invoice_amount, invoice_client_id, invoice_currency_code, invoice_number, invoice_prefix,
invoice_status FROM invoices WHERE invoice_id = $invoice_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$invoice_prefix = escapeHtml($row['invoice_prefix']);
$invoice_number = escapeHtml($row['invoice_number']);
$invoice_status = escapeHtml($row['invoice_status']);
$invoice_amount = floatval($row['invoice_amount']);
$invoice_currency_code = escapeHtml($row['invoice_currency_code']);
$client_id = intval($row['invoice_client_id']);
$invoice_id = intval($_GET['invoice_id'] ?? 0);
$invoice = billingRow('invoice', $invoice_id);
if (!$invoice) {
exit(json_encode(['error' => 'That invoice no longer exists.']));
}
$client_id = intval($invoice['client_id']);
enforceClientAccess();
$invoice_badge_color = getInvoiceBadgeColor($invoice_status);
$sql_payments = mysqli_query(
$mysqli,
"SELECT account_archived_at, account_name, payment_amount, payment_currency_code, payment_date,
payment_id, payment_method, payment_reference FROM payments
LEFT JOIN accounts ON payment_account_id = account_id
WHERE payment_invoice_id = $invoice_id
AND payment_archived_at IS NULL
ORDER BY payment_date ASC, payment_id ASC"
);
// Amount paid, so the modal shows what is still outstanding alongside the payments
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT SUM(payment_amount) AS amount_paid FROM payments WHERE payment_invoice_id = $invoice_id AND payment_archived_at IS NULL"));
$amount_paid = floatval($row['amount_paid']);
$balance = $invoice_amount - $amount_paid;
$payments = invoicePayments($invoice_id);
$state = invoiceState($invoice, invoicePaid($invoice_id));
$currency = (string) $invoice['invoice_currency_code'];
$total = floatval($invoice['invoice_amount']);
$progress = $state['paid'] > 0 && $total > 0 ? min(100, round($state['paid'] / $total * 100)) : 0;
$can_edit = lookupUserPermission('module_sales') >= 2 && lookupUserPermission('module_financial') >= 2;
$can_manage = lookupUserPermission('module_sales') >= 3 && lookupUserPermission('module_financial') >= 3;
$can_pay = $can_edit && invoiceCanPay($invoice, $state);
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-white">
<i class="fa fa-fw fa-credit-card me-2"></i>Payments for <?= "$invoice_prefix$invoice_number" ?>
<span class="p-2 ms-2 badge text-bg-<?= $invoice_badge_color ?>"><?= $invoice_status ?></span>
</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-credit-card me-2"></i>Payments <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber('invoice', $invoice)) ?> &middot; <?= escapeHtml($invoice['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<?php if (mysqli_num_rows($sql_payments) == 0) { ?>
<p class="text-muted mb-0">No payments have been recorded against this invoice.</p>
<?php } else { ?>
<div class="table-responsive">
<table class="table table-striped table-borderless mb-0">
<thead class="text-dark text-nowrap">
<tr>
<th>Date</th>
<th class="text-end">Amount</th>
<th>Method</th>
<th>Reference</th>
<th>Account</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql_payments)) {
$payment_id = intval($row['payment_id']);
$payment_date = escapeHtml($row['payment_date']);
$payment_amount = floatval($row['payment_amount']);
$payment_currency_code = escapeHtml($row['payment_currency_code']);
$payment_method = escapeHtml($row['payment_method']);
$payment_reference = escapeHtml($row['payment_reference']);
if (empty($payment_reference)) {
$payment_reference_display = "-";
} else {
$payment_reference_display = $payment_reference;
}
$account_name = escapeHtml($row['account_name']);
$account_archived_at = escapeHtml($row['account_archived_at']);
if (empty($account_archived_at)) {
$account_archived_display = "";
} else {
$account_archived_display = "Archived - ";
}
?>
<tr>
<td>
<?php if (lookupUserPermission("module_sales") >= 2) { ?>
<a class="ajax-modal" href="#"
data-modal-size = "lg"
data-modal-url = "modals/payment/payment_edit.php?id=<?= $payment_id ?>">
<?= $payment_date ?>
</a>
<?php } else { ?>
<?= $payment_date ?>
<?php } ?>
</td>
<td class="text-end font-monospace"><?= numfmt_format_currency($currency_format, $payment_amount, $payment_currency_code) ?></td>
<td><?= $payment_method ?></td>
<td><?= $payment_reference_display ?></td>
<td><?= "$account_archived_display$account_name" ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<div class="d-flex justify-content-between align-items-end mb-2">
<div>
<div class="itflow-billing-stat-label"><?= $state['balance'] > 0 ? 'Still owed' : 'Paid in full' ?></div>
<div class="itflow-billing-stat-value <?= $state['state'] === 'overdue' ? 'text-danger-emphasis' : '' ?>"><?= escapeHtml(billingMoney($state['balance'] > 0 ? $state['balance'] : $state['paid'], $currency)) ?></div>
</div>
<?php } ?>
<hr>
<div class="row">
<div class="col-6 text-end ms-auto">
<table class="table table-sm table-borderless mb-0">
<tr>
<td>Invoice Total:</td>
<td class="text-end font-monospace"><?= numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) ?></td>
</tr>
<tr>
<td>Amount Paid:</td>
<td class="text-end font-monospace"><?= numfmt_format_currency($currency_format, $amount_paid, $invoice_currency_code) ?></td>
</tr>
<tr class="text-bold">
<td>Balance:</td>
<td class="text-end font-monospace"><?= numfmt_format_currency($currency_format, $balance, $invoice_currency_code) ?></td>
</tr>
</table>
<div class="text-end small text-body-secondary">
<?= escapeHtml(billingMoney($state['paid'], $currency)) ?> paid of <?= escapeHtml(billingMoney($total, $currency)) ?>
<div><?= invoiceStatusBadge($invoice['invoice_status'], $state['state'] === 'overdue') ?></div>
</div>
</div>
<div class="progress itflow-billing-progress mb-3" role="progressbar" aria-label="Paid" aria-valuenow="<?= $progress ?>" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar bg-success" style="width: <?= $progress ?>%"></div>
</div>
<?php if ($payments) { ?>
<div class="list-group">
<?php foreach ($payments as $payment) { ?>
<div class="list-group-item d-flex align-items-center gap-3">
<span class="itflow-asset-icon itflow-asset-icon-sm bg-success-subtle text-success-emphasis" aria-hidden="true"><i class="fas fa-fw fa-check"></i></span>
<div class="flex-grow-1 min-w-0">
<div class="fw-semibold itflow-money"><?= escapeHtml(billingMoney($payment['payment_amount'], $payment['payment_currency_code'])) ?></div>
<div class="small text-body-secondary text-truncate"><?= escapeHtml(implode(' · ', array_filter([$payment['payment_method'], $payment['payment_reference'], $payment['account_name']]))) ?></div>
</div>
<div class="small text-body-secondary text-nowrap"><?= escapeHtml($payment['payment_date']) ?></div>
<?php if ($can_manage) { ?>
<a class="btn btn-sm btn-link text-body-secondary ajax-modal" href="#" data-modal-url="modals/payment/payment_edit.php?id=<?= intval($payment['payment_id']) ?>" title="Edit payment"><i class="fas fa-fw fa-edit"></i></a>
<?php } ?>
</div>
<?php } ?>
</div>
<?php } else { ?>
<div class="text-body-secondary">No payments yet.</div>
<?php } ?>
</div>
<div class="modal-footer">
<a href="invoice.php?client_id=<?= $client_id ?>&invoice_id=<?= $invoice_id ?>" class="btn btn-primary text-bold">
<i class="fa fa-fw fa-file-invoice-dollar me-2"></i>Open Invoice
</a>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Close</button>
<?php if ($can_pay) { ?>
<button type="button" class="btn btn-success ajax-modal me-auto" data-modal-url="modals/payment/payment_add.php?id=<?= $invoice_id ?>"><i class="fas fa-plus me-2"></i>Add Payment</button>
<?php } ?>
<a href="invoice.php?invoice_id=<?= $invoice_id ?>" class="btn btn-primary text-bold"><i class="fas fa-file-invoice-dollar me-2"></i>Open Invoice</a>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Close</button>
</div>
<?php

View File

@@ -1,44 +1,50 @@
<?php
/*
* Make a recurring invoice from an invoice - its lines, scope, category
* and notes, billed every month or year from a period after the invoice's
* date. ?invoice_id=
*/
require_once '../../../includes/modal_header.php';
$invoice_id = intval($_GET['invoice_id']);
$sql = mysqli_query($mysqli, "SELECT invoice_client_id, invoice_number, invoice_prefix FROM invoices WHERE invoice_id = $invoice_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$invoice_prefix = escapeHtml($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$client_id = intval($row['invoice_client_id']);
enforceUserPermission('module_sales', 2);
$doc_type = 'invoice';
$doc = billingRow($doc_type, intval($_GET['invoice_id'] ?? 0));
if (!$doc) {
exit(json_encode(['error' => 'That invoice no longer exists.']));
}
$client_id = intval($doc['client_id']);
enforceClientAccess();
$doc_number = billingNumber($doc_type, $doc);
$lines = count(billingItems('invoice', intval($doc['invoice_id'])));
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-copy me-2"></i>Invoice <?= "$invoice_prefix$invoice_number" ?> to Recurring Invoice</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-redo-alt me-2"></i>Make Recurring <span class="fw-normal text-white-50 ms-1"><?= escapeHtml($doc_number) ?> &middot; <?= escapeHtml($doc['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="invoice_id" value="<?= $invoice_id ?>">
<input type="hidden" name="invoice_id" value="<?= intval($doc['invoice_id']) ?>">
<div class="modal-body">
<div class="mb-3">
<label>Frequency <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-clock"></i></span>
<select class="form-select select2" name="frequency" required>
<option value="">- Frequency -</option>
<option value="month">Monthly</option>
<option value="year">Yearly</option>
</select>
</div>
<p class="text-body-secondary small">Bill <?= escapeHtml($doc['client_name']) ?> for the same <?= $lines ?> line<?= $lines === 1 ? '' : 's' ?> - <?= escapeHtml(billingMoney($doc['invoice_amount'], $doc['invoice_currency_code'])) ?> - again and again. The first one is made a period after <?= escapeHtml($doc_number) ?>'s date, <?= escapeHtml($doc['invoice_date']) ?>; change that and the lines on the recurring invoice after.</p>
<label class="form-label">Billed <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-sync-alt"></i></span>
<select class="form-select" name="frequency" required>
<?php foreach (recurringInvoiceFrequencies() as $frequency => $label) { ?>
<option value="<?= $frequency ?>"><?= $label ?> - first on <?= escapeHtml(recurringInvoiceStep($doc['invoice_date'], $frequency)) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="add_invoice_recurring" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Create Recurring Invoice</button>
<button type="submit" name="add_invoice_recurring" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Make Recurring</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -1,173 +1,70 @@
<?php
/*
* Add a payment to an invoice - what was paid, when, how, and into which
* account, starting at what is owed, with what is left after as you type.
* A receipt can go to the client's primary contact. ?id= (the invoice)
*/
require_once '../../../includes/modal_header.php';
$invoice_id = intval($_GET['id']);
$sql = mysqli_query(
$mysqli,
"SELECT client_id, client_name, contact_email, contact_name, invoice_amount,
invoice_id, invoice_number, invoice_prefix, invoice_currency_code FROM invoices
LEFT JOIN clients ON invoice_client_id = client_id
LEFT JOIN contacts ON client_id = contact_client_id AND contact_primary = 1
WHERE invoice_id = $invoice_id
LIMIT 1"
);
$row = mysqli_fetch_assoc($sql);
$invoice_id = intval($row['invoice_id']);
$invoice_prefix = escapeHtml($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$invoice_amount = floatval($row['invoice_amount']);
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$client_currency_code = escapeHtml($row['invoice_currency_code']);
$contact_name = escapeHtml($row['contact_name']);
$contact_email = escapeHtml($row['contact_email']);
//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;
enforceUserPermission('module_sales', 2);
enforceUserPermission('module_financial', 2);
$invoice_id = intval($_GET['id'] ?? 0);
$invoice = billingRow('invoice', $invoice_id);
if (!$invoice) {
exit(json_encode(['error' => 'That invoice no longer exists.']));
}
$client_id = intval($invoice['client_id']);
enforceClientAccess();
$state = invoiceState($invoice, invoicePaid($invoice_id));
if (!invoiceCanPay($invoice, $state)) {
exit(json_encode(['error' => billingNumber('invoice', $invoice) . ' has nothing owed on it - it is ' . strtolower($invoice['invoice_status']) . '.']));
}
$contact_email = (string) mysqli_fetch_row(mysqli_query($mysqli, "SELECT contact_email FROM contacts WHERE contact_client_id = $client_id AND contact_primary = 1 AND contact_archived_at IS NULL LIMIT 1"))[0];
$pay = [
'id' => 'payForm' . $invoice_id,
'amount' => $state['balance'],
'owed' => $state['balance'],
'currency' => $invoice['invoice_currency_code'],
'email' => $contact_email,
];
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-credit-card me-2"></i><?= "$invoice_prefix$invoice_number" ?>: Make Payment</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-credit-card me-2"></i>Add Payment <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber('invoice', $invoice)) ?> &middot; <?= escapeHtml($invoice['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="invoice_id" value="<?= $invoice_id ?>">
<input type="hidden" name="balance" value="<?= $balance ?>">
<input type="hidden" name="currency_code" value="<?= $client_currency_code ?>">
<input type="hidden" name="balance" value="<?= number_format($state['balance'], 2, '.', '') ?>">
<input type="hidden" name="currency_code" value="<?= escapeHtml($invoice['invoice_currency_code']) ?>">
<div class="modal-body">
<div class="row g-2">
<div class="col-md">
<div class="mb-3">
<label>Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date("Y-m-d") ?>" required>
</div>
</div>
<div class="d-flex align-items-center gap-3 p-3 mb-3 rounded bg-body-tertiary">
<?= billingTile('invoice') ?>
<div class="flex-grow-1 min-w-0">
<div class="fw-semibold"><?= escapeHtml(billingNumber('invoice', $invoice)) ?><?= trim((string) $invoice['invoice_scope']) !== '' ? ' - ' . escapeHtml($invoice['invoice_scope']) : '' ?></div>
<div class="small"><?= invoiceDuePill($state) ?: '<span class="text-body-secondary">Due ' . escapeHtml($invoice['invoice_due']) . '</span>' ?></div>
</div>
<div class="col-md">
<div class="mb-3">
<label>Amount <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" name="amount" value="<?= number_format($balance, 2, '.', '') ?>" placeholder="0.00" required>
</div>
</div>
</div>
</div>
<div class="mb-3">
<label>Account <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="account" required>
<option value="">- Select an Account -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT account_currency_code, account_id, account_name, opening_balance FROM accounts WHERE account_archived_at IS NULL ORDER BY account_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$account_id = intval($row['account_id']);
$account_name = escapeHtml($row['account_name']);
$opening_balance = floatval($row['opening_balance']);
$account_currency = escapeHtml($row['account_currency_code']);
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS total_payments FROM payments WHERE payment_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_payments);
$total_payments = floatval($row['total_payments']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS total_revenues FROM revenues WHERE revenue_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_revenues);
$total_revenues = floatval($row['total_revenues']);
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS total_expenses FROM expenses WHERE expense_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_expenses);
$total_expenses = floatval($row['total_expenses']);
$account_balance = $opening_balance + $total_payments + $total_revenues - $total_expenses;
?>
<option <?php if ($config_default_payment_account == $account_id) { echo "selected"; } ?>
value="<?= $account_id ?>">
<?= $account_name ?> [<?= numfmt_format_currency($currency_format, $account_balance, $account_currency) ?>]
</option>
<?php
}
?>
</select>
<div class="text-end">
<div class="fw-semibold itflow-money"><?= escapeHtml(billingMoney($state['balance'], $invoice['invoice_currency_code'])) ?></div>
<div class="small text-body-secondary">owed<?= $state['paid'] > 0 ? ' of ' . escapeHtml(billingMoney($invoice['invoice_amount'], $invoice['invoice_currency_code'])) : '' ?></div>
</div>
</div>
<div class="mb-3">
<label>Payment Method <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-money-check-alt"></i></span>
<select class="form-select select2" name="payment_method" required>
<option value="">- Method of Payment -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT payment_method_name FROM payment_methods ORDER BY payment_method_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$payment_method_name = escapeHtml($row['payment_method_name']);
?>
<option <?php if ($config_default_payment_method == $payment_method_name) { echo "selected"; } ?>><?= $payment_method_name ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="mb-3">
<label>Reference</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-alt"></i></span>
<input type="text" class="form-control" name="reference" placeholder="Check #, Trans #, etc" maxlength="200">
</div>
</div>
<?php if (!empty($config_smtp_provider) && !empty($contact_email)) { ?>
<div class="mb-3">
<label>Email Receipt</label>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="customControlAutosizing" name="email_receipt" value="1" checked>
<label class="form-check-label" for="customControlAutosizing"><?= $contact_email ?></label>
</div>
</div>
<?php } ?>
<?php require __DIR__ . '/payment_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_payment" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Pay</button>
<button type="submit" name="add_payment" class="btn btn-success text-bold"><i class="fas fa-check me-2"></i>Add Payment</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,170 +1,83 @@
<?php
/*
* Batch payment - one payment from a client spread over their unpaid
* invoices, oldest first, each paid in full until it runs out. Shows the
* invoices it will go to. ?client_id=
*/
require_once '../../../includes/modal_header.php';
$client_id = intval($_GET['client_id']);
$sql = mysqli_query(
$mysqli,
"SELECT client_currency_code, client_name, contact_email, contact_name FROM clients
LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1
WHERE client_id = $client_id"
);
$row = mysqli_fetch_assoc($sql);
$client_name = escapeHtml($row['client_name']);
$client_currency_code = escapeHtml($row['client_currency_code']);
$contact_name = escapeHtml($row['contact_name']);
$contact_email = escapeHtml($row['contact_email']);
//Add up all the payments for the invoice and get the total amount paid to the invoice
$sql_invoice_amounts = mysqli_query($mysqli, "SELECT SUM(invoice_amount) AS invoice_amounts FROM invoices WHERE invoice_client_id = $client_id AND invoice_status != 'Draft' AND invoice_status != 'Cancelled' AND invoice_status != 'Non-Billable'");
$row = mysqli_fetch_assoc($sql_invoice_amounts);
$invoice_amounts = floatval($row['invoice_amounts']);
$sql_amount_paid = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS amount_paid FROM payments, invoices WHERE payment_invoice_id = invoice_id AND invoice_client_id = $client_id");
$row = mysqli_fetch_assoc($sql_amount_paid);
$amount_paid = floatval($row['amount_paid']);
$balance = $invoice_amounts - $amount_paid;
enforceUserPermission('module_sales', 2);
enforceUserPermission('module_financial', 2);
$client_id = intval($_GET['client_id'] ?? 0);
enforceClientAccess();
$client = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT client_name, client_currency_code FROM clients WHERE client_id = $client_id"));
if (!$client) {
exit(json_encode(['error' => 'That client no longer exists.']));
}
// What the batch pays, in the order the batch pays it
$open = [];
$owed = 0;
$sql = mysqli_query($mysqli, "SELECT invoice_id, invoice_prefix, invoice_number, invoice_scope, invoice_due, invoice_amount, invoice_currency_code,
invoice_amount - COALESCE((SELECT SUM(payment_amount) FROM payments WHERE payment_invoice_id = invoice_id), 0) AS balance
FROM invoices WHERE invoice_client_id = $client_id AND invoice_status IN ('Sent', 'Viewed', 'Partial')
ORDER BY invoice_number ASC");
while ($row = mysqli_fetch_assoc($sql)) {
if (floatval($row['balance']) > 0) {
$open[] = $row;
$owed += floatval($row['balance']);
}
}
$owed = round($owed, 2);
if (!$open) {
exit(json_encode(['error' => $client['client_name'] . ' has no unpaid invoices.']));
}
$currency = (string) ($open[0]['invoice_currency_code'] ?: $client['client_currency_code']);
$contact_email = (string) mysqli_fetch_row(mysqli_query($mysqli, "SELECT contact_email FROM contacts WHERE contact_client_id = $client_id AND contact_primary = 1 AND contact_archived_at IS NULL LIMIT 1"))[0];
$pay = [
'id' => 'payBatch' . $client_id,
'amount' => $owed,
'owed' => $owed,
'currency' => $currency,
'email' => $contact_email,
'full_text' => count($open) === 1 ? 'Pays it in full.' : 'Pays all ' . count($open) . ' in full.',
];
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-credit-card me-2"></i>Make Batch Payment</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-layer-group me-2"></i>Batch Payment <span class="fw-normal text-white-50 ms-1"><?= escapeHtml($client['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<input type="hidden" name="balance" value="<?= $balance ?>">
<input type="hidden" name="currency_code" value="<?= $client_currency_code ?>">
<input type="hidden" name="balance" value="<?= number_format($owed, 2, '.', '') ?>">
<input type="hidden" name="currency_code" value="<?= escapeHtml($currency) ?>">
<div class="modal-body">
<div class="alert alert-info">
<h5>Batch Payment Notice</h5>
Batch Payment will settle invoices in order from the oldest to the newest.
</div>
<div class="row g-2">
<div class="col-md">
<div class="mb-3">
<label>Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date("Y-m-d") ?>" required>
</div>
<p class="small text-body-secondary">One payment spread over <?= escapeHtml($client['client_name']) ?>'s unpaid invoices, oldest first - each is paid in full until the payment runs out, and the last one it reaches may be part paid.</p>
<div class="list-group list-group-flush border rounded mb-3" style="max-height: 12rem; overflow-y: auto;">
<?php foreach ($open as $row) {
$row_state = invoiceState(['invoice_status' => 'Sent', 'invoice_amount' => $row['invoice_amount'], 'invoice_due' => $row['invoice_due']], floatval($row['invoice_amount']) - floatval($row['balance'])); ?>
<div class="list-group-item d-flex align-items-center gap-2 py-2">
<span class="fw-semibold"><?= escapeHtml($row['invoice_prefix'] . $row['invoice_number']) ?></span>
<span class="small text-body-secondary text-truncate flex-grow-1"><?= escapeHtml($row['invoice_scope']) ?></span>
<?= invoiceDuePill($row_state) ?>
<span class="itflow-money small fw-semibold"><?= escapeHtml(billingMoney($row['balance'], $row['invoice_currency_code'])) ?></span>
</div>
</div>
<div class="col-md">
<div class="mb-3">
<label>Amount <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" name="amount" value="<?= number_format($balance, 2, '.', '') ?>" placeholder="0.00" required>
</div>
</div>
</div>
<?php } ?>
</div>
<div class="mb-3">
<label>Account <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="account" required>
<option value="">- Select an Account -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT account_id, account_name, opening_balance FROM accounts WHERE account_archived_at IS NULL ORDER BY account_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$account_id = intval($row['account_id']);
$account_name = escapeHtml($row['account_name']);
$opening_balance = floatval($row['opening_balance']);
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS total_payments FROM payments WHERE payment_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_payments);
$total_payments = floatval($row['total_payments']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS total_revenues FROM revenues WHERE revenue_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_revenues);
$total_revenues = floatval($row['total_revenues']);
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS total_expenses FROM expenses WHERE expense_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_expenses);
$total_expenses = floatval($row['total_expenses']);
$account_balance = $opening_balance + $total_payments + $total_revenues - $total_expenses;
?>
<option <?php if ($config_default_payment_account == $account_id) { echo "selected"; } ?>
value="<?= $account_id ?>">
<?= $account_name ?> [$<?= number_format($account_balance, 2) ?>]
</option>
<?php
}
?>
</select>
</div>
</div>
<div class="mb-3">
<label>Payment Method <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-money-check-alt"></i></span>
<select class="form-select select2" name="payment_method" required>
<option value="">- Method of Payment -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT payment_method_name FROM payment_methods ORDER BY payment_method_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$payment_method_name = escapeHtml($row['payment_method_name']);
?>
<option <?php if ($config_default_payment_method == $payment_method_name) { echo "selected"; } ?>><?= $payment_method_name ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="mb-3">
<label>Reference</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-alt"></i></span>
<input type="text" class="form-control" name="reference" placeholder="Check #, Trans #, etc" maxlength="200">
</div>
</div>
<?php if (!empty($config_smtp_provider) && !empty($contact_email)) { ?>
<div class="mb-3">
<label>Email Receipt</label>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="customControlAutosizing" name="email_receipt" value="1" checked>
<label class="form-check-label" for="customControlAutosizing"><?= $contact_email ?></label>
</div>
</div>
<?php } ?>
<?php require __DIR__ . '/payment_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_bulk_payment" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Pay</button>
<button type="submit" name="add_bulk_payment" class="btn btn-success text-bold"><i class="fas fa-check me-2"></i>Add Payment</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -1,142 +1,57 @@
<?php
/*
* Edit a payment - its amount, date, method, reference and account. The
* invoice it is on follows: paid, part paid or owing again. ?id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$payment_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT invoice_client_id, payment_account_id, payment_amount, payment_date, payment_method,
payment_reference FROM payments LEFT JOIN invoices ON invoice_id = payment_invoice_id WHERE payment_id = $payment_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$payment_date = escapeHtml($row['payment_date']);
$payment_method = escapeHtml($row['payment_method']);
$payment_amount = floatval($row['payment_amount']);
$payment_reference = escapeHtml($row['payment_reference']);
$payment_account_id = intval($row['payment_account_id']);
$client_id = intval($row['invoice_client_id']);
enforceUserPermission('module_sales', 3);
enforceUserPermission('module_financial', 3);
$payment_id = intval($_GET['id'] ?? 0);
$payment = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT payments.*, invoice_id FROM payments LEFT JOIN invoices ON invoice_id = payment_invoice_id WHERE payment_id = $payment_id LIMIT 1"));
$invoice = $payment ? billingRow('invoice', intval($payment['payment_invoice_id'])) : null;
if (!$payment || !$invoice) {
exit(json_encode(['error' => 'That payment no longer exists.']));
}
$client_id = intval($invoice['client_id']);
enforceClientAccess();
$paid_elsewhere = invoicePaid($invoice['invoice_id']) - floatval($payment['payment_amount']);
$pay = [
'id' => 'payEdit' . $payment_id,
'amount' => $payment['payment_amount'],
'owed' => round(floatval($invoice['invoice_amount']) - $paid_elsewhere, 2),
'currency' => $payment['payment_currency_code'] ?: $invoice['invoice_currency_code'],
'date' => $payment['payment_date'],
'account_id' => intval($payment['payment_account_id']),
'method' => $payment['payment_method'],
'reference' => $payment['payment_reference'],
'email' => '',
];
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-credit-card me-2"></i>Edit Payment</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-credit-card me-2"></i>Edit Payment <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber('invoice', $invoice)) ?> &middot; <?= escapeHtml($invoice['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="payment_id" value="<?= $payment_id ?>">
<div class="modal-body">
<div class="row g-2">
<div class="col-md">
<div class="mb-3">
<label>Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= $payment_date ?>" required>
</div>
</div>
</div>
<div class="col-md">
<div class="mb-3">
<label>Amount <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" name="amount" value="<?= $payment_amount ?>" placeholder="0.00" required>
</div>
</div>
</div>
</div>
<div class="mb-3">
<label>Account <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="account" required>
<option value="">- Select an Account -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT account_id, account_name, opening_balance FROM accounts WHERE account_archived_at IS NULL ORDER BY account_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$account_id = intval($row['account_id']);
$account_name = escapeHtml($row['account_name']);
$opening_balance = floatval($row['opening_balance']);
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS total_payments FROM payments WHERE payment_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_payments);
$total_payments = floatval($row['total_payments']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS total_revenues FROM revenues WHERE revenue_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_revenues);
$total_revenues = floatval($row['total_revenues']);
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS total_expenses FROM expenses WHERE expense_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_expenses);
$total_expenses = floatval($row['total_expenses']);
$account_balance = $opening_balance + $total_payments + $total_revenues - $total_expenses;
?>
<option <?php if ($payment_account_id == $account_id) { echo "selected"; } ?>
value="<?= $account_id ?>">
<?= $account_name ?> [$<?= number_format($account_balance, 2) ?>]
</option>
<?php
}
?>
</select>
</div>
</div>
<div class="mb-3">
<label>Payment Method <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-money-check-alt"></i></span>
<select class="form-select select2" name="payment_method" required>
<option value="">- Method of Payment -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT payment_method_name FROM payment_methods ORDER BY payment_method_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$payment_method_name = escapeHtml($row['payment_method_name']);
?>
<option <?php if ($payment_method == $payment_method_name) { echo "selected"; } ?>><?= $payment_method_name ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="mb-3">
<label>Reference</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-alt"></i></span>
<input type="text" class="form-control" name="reference" value="<?= $payment_reference ?>" placeholder="Check #, Trans #, etc" maxlength="200">
</div>
</div>
<?php require __DIR__ . '/payment_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="edit_payment" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save Changes</button>
<button type="submit" name="edit_payment" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -0,0 +1,140 @@
<?php
/*
* The fields of a payment - shared by Add Payment, Batch Payment and Edit
* Payment. Set $pay before including:
*
* amount the amount to start with
* owed what is owed, for "Pay in full" and what is left after (null to leave out)
* currency the currency
* date, account_id, method, reference to start with (editing)
* email the primary contact's email, for the receipt ('' to leave out)
* full_text what to say when the amount pays everything owed
* id a unique id for the form's parts
*
* Posts date, amount, account, payment_method, reference and email_receipt.
*
* Should not be accessed directly.
*/
isset($mysqli) || die("Direct file access is not allowed");
$pay_accounts = paymentAccounts($pay['account_id'] ?? 0);
$pay_methods = paymentMethods();
$pay_account_id = intval($pay['account_id'] ?? $config_default_payment_account);
$pay_method = (string) ($pay['method'] ?? $config_default_payment_method);
$pay_owed = $pay['owed'] ?? null;
?>
<div class="row g-3" id="<?= $pay['id'] ?>" data-pay-form data-owed="<?= $pay_owed === null ? '' : number_format($pay_owed, 2, '.', '') ?>">
<div class="col-sm-6">
<label class="form-label">Amount <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control text-end fw-semibold" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" name="amount"
value="<?= number_format(floatval($pay['amount']), 2, '.', '') ?>" placeholder="0.00" required data-pay-amount>
<span class="input-group-text"><?= escapeHtml($pay['currency']) ?></span>
</div>
<?php if ($pay_owed !== null) { ?>
<div class="form-text" data-pay-note>
<?= escapeHtml($pay['full_text'] ?? 'Pays it in full.') ?> <a href="#" class="ms-1 d-none" data-pay-full>Pay in full</a>
</div>
<?php } ?>
</div>
<div class="col-sm-6">
<label class="form-label">Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= escapeHtml($pay['date'] ?? date('Y-m-d')) ?>" required>
</div>
</div>
<div class="col-sm-6">
<label class="form-label">Method <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-money-check-alt"></i></span>
<select class="form-select select2" name="payment_method" required>
<option value="">- How it was paid -</option>
<?php foreach ($pay_methods as $method) { ?>
<option <?= $pay_method === $method ? 'selected' : '' ?>><?= escapeHtml($method) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-sm-6">
<label class="form-label">Reference</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-hashtag"></i></span>
<input type="text" class="form-control" name="reference" placeholder="Check number, transaction ID" maxlength="200" value="<?= escapeHtml($pay['reference'] ?? '') ?>">
</div>
</div>
<div class="col-12">
<label class="form-label">Into account <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="account" required>
<option value="">- Select an account -</option>
<?php foreach ($pay_accounts as $account_id => $account) { ?>
<option value="<?= $account_id ?>" <?= $pay_account_id === $account_id ? 'selected' : '' ?> data-icon="fas fa-piggy-bank"
data-description="<?= escapeHtml(billingMoney($account['balance'], $account['account_currency_code'])) ?><?= $account['account_archived_at'] ? ' - archived' : '' ?>"><?= escapeHtml($account['account_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<?php if (!empty($pay['email']) && !empty($config_smtp_provider)) { ?>
<div class="col-12">
<div class="form-check form-switch">
<input type="checkbox" class="form-check-input" role="switch" id="<?= $pay['id'] ?>Receipt" name="email_receipt" value="1" checked>
<label class="form-check-label" for="<?= $pay['id'] ?>Receipt">Email a receipt to <?= escapeHtml($pay['email']) ?></label>
</div>
</div>
<?php } ?>
</div>
<?php if ($pay_owed !== null) { ?>
<script>
(function () {
var root = document.getElementById(<?= json_encode($pay['id']) ?>);
if (!root || root.hasAttribute('data-wired')) {
return;
}
root.setAttribute('data-wired', '1');
var owed = Number(root.getAttribute('data-owed'));
var amount = root.querySelector('[data-pay-amount]');
var note = root.querySelector('[data-pay-note]');
var full = root.querySelector('[data-pay-full]');
var currency = <?= json_encode((string) $pay['currency']) ?>;
var locale = <?= json_encode(str_replace('_', '-', (string) $session_company_locale)) ?>;
function money(value) {
try {
return new Intl.NumberFormat(locale, { style: 'currency', currency: currency }).format(value);
} catch (e) {
return value.toFixed(2);
}
}
function update() {
var value = Number(String(amount.value).replace(/[\s,$]/g, ''));
var left = Math.round((owed - value) * 100) / 100;
var text;
if (isNaN(value) || value <= 0) {
text = 'Enter what was paid.';
} else if (left > 0) {
text = money(left) + ' left to pay after this.';
} else if (left === 0) {
text = <?= json_encode((string) ($pay['full_text'] ?? 'Pays it in full.')) ?>;
} else {
text = 'That is ' + money(-left) + ' more than is owed.';
}
note.firstChild.textContent = text + ' ';
full.classList.toggle('d-none', left === 0);
}
amount.addEventListener('input', update);
full.addEventListener('click', function (e) {
e.preventDefault();
amount.value = owed.toFixed(2);
update();
});
update();
})();
</script>
<?php } ?>

View File

@@ -1,64 +1,70 @@
<?php
/*
* Charge a card the client saved - the invoice's balance, through the
* provider the card is with. ?id= (the invoice)
*/
require_once '../../../includes/modal_header.php';
$invoice_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT invoice_amount, invoice_client_id, invoice_number, invoice_prefix FROM invoices WHERE invoice_id = $invoice_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$invoice_prefix = escapeHtml($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$invoice_amount = floatval($row['invoice_amount']);
$client_id = intval($row['invoice_client_id']);
enforceUserPermission('module_sales', 2);
enforceUserPermission('module_financial', 2);
$invoice_id = intval($_GET['id'] ?? 0);
$invoice = billingRow('invoice', $invoice_id);
if (!$invoice) {
exit(json_encode(['error' => 'That invoice no longer exists.']));
}
$client_id = intval($invoice['client_id']);
enforceClientAccess();
$state = invoiceState($invoice, invoicePaid($invoice_id));
$cards = [];
$sql = mysqli_query($mysqli, "SELECT saved_payment_id, saved_payment_description, payment_provider_name FROM client_saved_payment_methods
JOIN payment_providers ON payment_provider_id = saved_payment_provider_id
WHERE saved_payment_client_id = $client_id AND payment_provider_active = 1 ORDER BY saved_payment_description ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$cards[] = $row;
}
if (!$cards) {
exit(json_encode(['error' => $invoice['client_name'] . ' has no card on file with a payment provider that is turned on.']));
}
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-credit-card me-2"></i><?= "$invoice_prefix$invoice_number" ?>: Make Payment</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-wallet me-2"></i>Charge Saved Card <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber('invoice', $invoice)) ?> &middot; <?= escapeHtml($invoice['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="invoice_id" value="<?= $invoice_id ?>">
<div class="modal-body">
<h2>Paying <strong><?= $invoice_amount ?></strong> Amount</h2>
<div class="mb-3">
<label>Payment Method <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-money-check-alt"></i></span>
<select class="form-select select2" name="saved_payment_id" required>
<option value="">- Saved Payment Methods -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT saved_payment_description, saved_payment_id FROM client_saved_payment_methods WHERE saved_payment_client_id = $client_id ORDER BY saved_payment_description ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$saved_payment_id = intval($row['saved_payment_id']);
$saved_payment_description = escapeHtml($row['saved_payment_description']);
?>
<option value="<?= $saved_payment_id ?>"><?= $saved_payment_description ?></option>
<?php
}
?>
</select>
</div>
<div class="text-center p-3 mb-3 rounded bg-body-tertiary">
<div class="itflow-billing-stat-label">Charging</div>
<div class="itflow-billing-stat-value"><?= escapeHtml(billingMoney($invoice['invoice_amount'], $invoice['invoice_currency_code'])) ?></div>
</div>
<label class="form-label">Card <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-credit-card"></i></span>
<select class="form-select" name="saved_payment_id" required>
<?php foreach ($cards as $card) { ?>
<option value="<?= intval($card['saved_payment_id']) ?>"><?= escapeHtml($card['saved_payment_description']) ?> (<?= escapeHtml($card['payment_provider_name']) ?>)</option>
<?php } ?>
</select>
</div>
<div class="form-text">Charged straight away - the payment is recorded on the invoice and a receipt goes to the client.</div>
</div>
<div class="modal-footer">
<button type="submit" name="add_payment_stripe" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Pay</button>
<button type="submit" name="add_payment_stripe" class="btn btn-success text-bold confirm-link" data-confirm-title="Charge the card?"
data-confirm-text="<?= escapeHtml(billingMoney($invoice['invoice_amount'], $invoice['invoice_currency_code'])) ?> is taken from the card now." data-confirm-button="Charge">
<i class="fas fa-bolt me-2"></i>Charge
</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,101 +1,40 @@
<?php
/*
* New quote - who it is for, what it is for, its category, date, how long
* it is good for and any discount. It starts as a draft; the lines go on
* the quote page.
* ?client_id= starts it for that client; without one, pick the client here.
*/
require_once '../../../includes/modal_header.php';
$client_id = intval($_GET['client_id'] ?? 0);
enforceUserPermission('module_sales', 2);
$form_type = 'quote';
$form_row = null;
$form_client_id = intval($_GET['client_id'] ?? 0);
if ($form_client_id) {
$client_id = $form_client_id;
enforceClientAccess();
}
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-comment-dollar me-2"></i>New Quote</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-comment-dollar me-2"></i>New Quote<?php if ($form_client_id) { ?> <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(getFieldById('clients', $form_client_id, 'client_name')) ?></span><?php } ?></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<div class="modal-body">
<?php if ($client_id) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } else { ?>
<div class="mb-3">
<label>Client <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<select class="form-select select2" name="client_id" required>
<option value="">- Select a Client -</option>
<?php
//select unarchived clients
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$client_id_select = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
?>
<option value="<?= $client_id_select ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= $client_name ?></option>
<?php } ?>
</select>
</div>
</div>
<?php } ?>
<div class="mb-3">
<label>Scope</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
<input type="text" class="form-control" name="scope" placeholder="Quick description" maxlength="255">
</div>
</div>
<div class="mb-3">
<label>Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="category" required>
<option value="">- Category -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND category_archived_at IS NULL ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<option value="<?= $category_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name ?></option>
<?php } ?>
</select>
<button class="btn btn-secondary ajax-modal" title="New category" type="button"
data-modal-url="../admin/modals/category/category_add.php?category=Income">
<i class="fas fa-fw fa-plus"></i>
</button>
</div>
</div>
<div class="mb-3">
<label>Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date("Y-m-d") ?>" required>
</div>
</div>
<div class="mb-3">
<label>Expire <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="expire" min="<?= date("Y-m-d") ?>" max="2999-12-31" value="<?= date("Y-m-d", strtotime("+30 days")) ?>" required>
</div>
</div>
<?php require __DIR__ . '/../billing/billing_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_quote" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Create</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -1,78 +1,76 @@
<?php
/*
* Copy a quote - a new draft with the same lines, scope, category, discount
* and notes, for this client or another, on the dates given. ?id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$quote_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, quote_number, quote_prefix FROM quotes LEFT JOIN clients ON quote_client_id = client_id WHERE quote_id = $quote_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$quote_prefix = escapeHtml($row['quote_prefix']);
$quote_number = intval($row['quote_number']);
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$doc_type = 'quote';
$doc = billingRow($doc_type, intval($_GET['id'] ?? 0));
if (!$doc) {
exit(json_encode(['error' => 'That quote no longer exists.']));
}
$client_id = intval($doc['client_id']);
enforceClientAccess();
$doc_number = billingNumber($doc_type, $doc);
$lines = count(billingItems('quote', intval($doc['quote_id'])));
$clients = [];
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$clients[] = $row;
}
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-copy me-2"></i>Copying quote: <strong><?= "$quote_prefix$quote_number" ?></strong> - <?= $client_name ?></h5>
<h5 class="modal-title"><i class="fas fa-fw fa-copy me-2"></i>Copy Quote <span class="fw-normal text-white-50 ms-1"><?= escapeHtml($doc_number) ?> &middot; <?= escapeHtml($doc['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="quote_id" value="<?= $quote_id ?>">
<input type="hidden" name="quote_id" value="<?= intval($doc['quote_id']) ?>">
<div class="modal-body">
<?php if (isset($_GET['client_id'])) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } else { ?>
<div class="mb-3">
<label>Client <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-users"></i></span>
<select class="form-select select2" name="client_id" required>
<?php
$sql_client_select = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql_client_select)) {
$client_id_select = intval($row['client_id']);
$client_name_select = escapeHtml($row['client_name']);
?>
<option <?php if ($client_id == $client_id_select) { echo "selected"; } ?> value="<?= $client_id_select ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= $client_name_select ?></option>
<?php } ?>
</select>
<p class="text-body-secondary small">A new draft with the same <?= $lines ?> line<?= $lines === 1 ? '' : 's' ?>, scope, discount and notes - <?= escapeHtml(billingMoney($doc['quote_amount'], $doc['quote_currency_code'])) ?>. Quote the same work for another client by picking them here.</p>
<div class="row g-3">
<div class="col-12">
<label class="form-label">For <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-building"></i></span>
<select class="form-select select2" name="client_id" required>
<?php foreach ($clients as $client_option) { ?>
<option value="<?= intval($client_option['client_id']) ?>" <?= intval($client_option['client_id']) === $client_id ? 'selected' : '' ?><?= selectOptionClient($client_option['client_id'], $client_option['client_name'], $client_option['client_abbreviation'] ?? '') ?>><?= escapeHtml($client_option['client_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<?php } ?>
<div class="mb-3">
<label>Set Date for New Quote <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="col-sm-6">
<label class="form-label">Quote date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date("Y-m-d") ?>" required>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date('Y-m-d') ?>" required>
</div>
</div>
<div class="col-sm-6">
<label class="form-label">Valid until <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-hourglass-half"></i></span>
<input type="date" class="form-control" name="expire" min="<?= date('Y-m-d') ?>" max="2999-12-31" value="<?= date('Y-m-d', strtotime('+30 days')) ?>" required>
</div>
</div>
</div>
<div class="mb-3">
<label>Expire <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="expire" min="<?= date("Y-m-d") ?>" max="2999-12-31" value="<?= date("Y-m-d", strtotime("+30 days")) ?>" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="add_quote_copy" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Copy</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
<button type="submit" name="add_quote_copy" class="btn btn-primary text-bold"><i class="fas fa-copy me-2"></i>Copy</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,100 +1,36 @@
<?php
/*
* Edit a quote's details - scope, category, dates and discount. Its lines
* are edited on the quote itself. ?id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$quote_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT client_name, quote_category_id, quote_client_id, quote_created_at, quote_date,
quote_discount_amount, quote_expire, quote_id, quote_number, quote_prefix, quote_scope FROM quotes LEFT JOIN clients ON quote_client_id = client_id WHERE quote_id = $quote_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$quote_id = intval($row['quote_id']);
$quote_prefix = escapeHtml($row['quote_prefix']);
$quote_number = intval($row['quote_number']);
$quote_scope = escapeHtml($row['quote_scope']);
$quote_date = escapeHtml($row['quote_date']);
$quote_expire = escapeHtml($row['quote_expire']);
$quote_discount = floatval($row['quote_discount_amount']);
$quote_created_at = escapeHtml($row['quote_created_at']);
$quote_category_id = intval($row['quote_category_id']);
$client_name = escapeHtml($row['client_name']);
$client_id = intval($row['quote_client_id']);
$form_type = 'quote';
$form_row = billingRow($form_type, intval($_GET['id'] ?? 0));
if (!$form_row) {
exit(json_encode(['error' => 'That quote no longer exists.']));
}
$client_id = intval($form_row['client_id']);
enforceClientAccess();
$form_client_id = $client_id;
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-white"><i class="fas fa-fw fa-comment-dollar me-2"></i>Editing quote: <span class="text-bold"><?= "$quote_prefix$quote_number" ?></span> - <span class="text"><?= $client_name ?></span></h5>
<h5 class="modal-title"><i class="fas fa-fw fa-comment-dollar me-2"></i>Edit Quote <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber($form_type, $form_row)) ?> &middot; <?= escapeHtml($form_row['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="quote_id" value="<?= $quote_id ?>">
<input type="hidden" name="quote_id" value="<?= intval($form_row['quote_id']) ?>">
<div class="modal-body">
<div class="mb-3">
<label>Quote Date</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= $quote_date ?>" required>
</div>
</div>
<div class="mb-3">
<label>Expire <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="expire" max="2999-12-31" value="<?= $quote_expire ?>" required>
</div>
</div>
<div class="mb-3">
<label>Income Category</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="category" required>
<?php
$sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND (category_archived_at > '$quote_created_at' OR category_archived_at IS NULL) ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<option <?php if ($quote_category_id == $category_id) { echo "selected"; } ?> value="<?= $category_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name ?></option>
<?php } ?>
</select>
<button class="btn btn-secondary ajax-modal" title="New category" type="button"
data-modal-url="../admin/modals/category/category_add.php?category=Income">
<i class="fas fa-fw fa-plus"></i>
</button>
</div>
</div>
<div class='mb-3'>
<label>Discount Amount</label>
<div class='input-group'>
<span class='input-group-text'><i class='fa fa-fw fa-dollar-sign'></i></span>
<input type='text' class='form-control' inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}" name='quote_discount' placeholder='0.00' value="<?= number_format($quote_discount, 2, '.', '') ?>">
</div>
</div>
<div class="mb-3">
<label>Scope</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
<input type="text" class="form-control" name="scope" placeholder="Quick description" value="<?= $quote_scope ?>" maxlength="255">
</div>
</div>
<?php require __DIR__ . '/../billing/billing_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="edit_quote" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save</button>
@@ -103,5 +39,4 @@ ob_start();
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -9,6 +9,9 @@ $quote_id = intval($_GET['quote_id']);
$sql = mysqli_query($mysqli, "SELECT quote_client_id, quote_number, quote_prefix, quote_status
FROM quotes WHERE quote_id = $quote_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
exit(json_encode(['error' => 'That quote no longer exists.']));
}
$quote_prefix = escapeHtml($row['quote_prefix']);
$quote_number = intval($row['quote_number']);
$quote_status = escapeHtml($row['quote_status']);
@@ -16,6 +19,8 @@ $client_id = intval($row['quote_client_id']);
enforceClientAccess();
$doc = billingRow('quote', $quote_id);
// Wider than the invoice picker - see documentContactFilterSql(). A quote is
// read by whoever scoped the work as often as by whoever signs it.
$sql_contacts = mysqli_query(
@@ -54,9 +59,7 @@ ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-white">
<i class="fa fa-fw fa-paper-plane me-2"></i>Email Quote <?= "$quote_prefix$quote_number" ?>
</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-paper-plane me-2"></i>Send Quote <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber('quote', $doc)) ?> &middot; <?= escapeHtml($doc['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
@@ -67,7 +70,7 @@ ob_start();
<?php if ($contact_count == 0) { ?>
<p class="text-muted mb-0">
<p class="text-body-secondary mb-0">
This client has no primary, billing, technical or important contact with an email
address, so there is nobody to send a quote to. Flag a contact with one of those
roles, or use Mark Sent to record that the quote went out some other way.
@@ -75,7 +78,20 @@ ob_start();
<?php } else { ?>
<label class="mb-2">Send to <strong class="text-danger">*</strong></label>
<!-- What goes out -->
<div class="d-flex align-items-center gap-3 p-3 mb-3 rounded bg-body-tertiary">
<?= billingTile('quote') ?>
<div class="flex-grow-1 min-w-0">
<div class="fw-semibold"><?= escapeHtml(billingNumber('quote', $doc)) ?><?= trim((string) $doc['quote_scope']) !== '' ? ' - ' . escapeHtml($doc['quote_scope']) : '' ?></div>
<div class="small text-body-secondary">An email with a link to view it, accept or decline it, and download it as a PDF.</div>
</div>
<div class="text-end">
<div class="fw-semibold itflow-money"><?= escapeHtml(billingMoney($doc['quote_amount'], $doc['quote_currency_code'])) ?></div>
<div class="small text-body-secondary">valid until <?= escapeHtml($doc['quote_expire']) ?></div>
</div>
</div>
<label class="form-label">Send to <strong class="text-danger">*</strong></label>
<div class="list-group mb-3">
@@ -115,7 +131,7 @@ ob_start();
</div>
<?php if ($quote_status !== 'Draft') { ?>
<p class="text-muted mb-0">
<p class="text-body-secondary small mb-0">
<i class="fa fa-fw fa-info-circle me-1"></i>This quote is
<strong><?= $quote_status ?></strong>, so sending it will not change its status.
</p>

View File

@@ -1,103 +0,0 @@
<?php
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$item_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT item_created_at, item_description, item_name, item_price, item_product_id, item_quantity,
item_tax_id, quote_client_id FROM quote_items LEFT JOIN quotes ON quote_id = item_quote_id WHERE item_id = $item_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$item_name = escapeHtml($row['item_name']);
$item_description = escapeHtml($row['item_description']);
$item_quantity = floatval($row['item_quantity']);
$item_price = floatval($row['item_price']);
$item_created_at = escapeHtml($row['item_created_at']);
$tax_id = intval($row['item_tax_id']);
$product_id = intval($row['item_product_id']);
$client_id = intval($row['quote_client_id']);
enforceClientAccess();
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-edit me-2"></i>Editing Line Item: <strong><?= $item_name ?></strong></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="item_id" value="<?= $item_id ?>">
<input type="hidden" name="product_id" value="<?= $product_id ?>">
<div class="modal-body">
<div class="mb-3">
<label>Item <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-box"></i></span>
<input type="text" class="form-control" name="name" maxlength="200" value="<?= $item_name ?>" placeholder="Enter item name" required>
</div>
</div>
<div class="row g-2">
<div class="col-sm">
<div class="mb-3">
<label>Quantity <strong class="text-danger">*</strong></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" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" name="qty" value="<?= number_format($item_quantity, 2) ?>" placeholder="0.00" required>
</div>
</div>
</div>
<div class="col-sm">
<div class="mb-3">
<label>Price <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control" inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}" name="price" value="<?= number_format($item_price, 2, '.', '') ?>" placeholder="0.00" required>
</div>
</div>
</div>
</div>
<div class="mb-3">
<label>Description</label>
<div class="input-group">
<textarea class="form-control" rows="5" name="description" placeholder="Enter a description"><?= $item_description ?></textarea>
</div>
</div>
<div class="mb-3">
<label>Tax <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="tax_id" required>
<option value="0">No Tax</option>
<?php
$taxes_sql = mysqli_query($mysqli, "SELECT tax_id, tax_name, tax_percent FROM taxes WHERE (tax_archived_at > '$item_created_at' OR tax_archived_at IS NULL) ORDER BY tax_name ASC");
while ($row = mysqli_fetch_assoc($taxes_sql)) {
$tax_id_select = intval($row['tax_id']);
$tax_name = escapeHtml($row['tax_name']);
$tax_percent = floatval($row['tax_percent']);
?>
<option <?php if ($tax_id_select == $tax_id) { echo "selected"; } ?> value="<?= $tax_id_select ?>"><?= "$tax_name $tax_percent%" ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="edit_quote_item" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,62 +1,61 @@
<?php
/*
* Mark a quote sent - for one that went out some other way than
* ITFlow's email: posted, handed over, sent from your own mail. How, and a
* note, go in its history. ?quote_id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$quote_id = intval($_GET['quote_id']);
$sql = mysqli_query($mysqli, "SELECT quote_client_id, quote_number, quote_prefix
FROM quotes WHERE quote_id = $quote_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$quote_prefix = escapeHtml($row['quote_prefix']);
$quote_number = intval($row['quote_number']);
$client_id = intval($row['quote_client_id']);
$doc_type = 'quote';
$doc = billingRow($doc_type, intval($_GET['quote_id'] ?? 0));
if (!$doc) {
exit(json_encode(['error' => 'That quote no longer exists.']));
}
$client_id = intval($doc['client_id']);
enforceClientAccess();
$doc_number = billingNumber($doc_type, $doc);
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-white">
<i class="fa fa-fw fa-check me-2"></i>Mark Quote <?= "$quote_prefix$quote_number" ?> Sent
</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-check me-2"></i>Mark Sent <span class="fw-normal text-white-50 ms-1"><?= escapeHtml($doc_number) ?> &middot; <?= escapeHtml($doc['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="quote_id" value="<?= $quote_id ?>">
<input type="hidden" name="quote_id" value="<?= intval($doc['quote_id']) ?>">
<div class="modal-body">
<div class="mb-3">
<label>How was it sent? <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-paper-plane"></i></span>
<select class="form-select" name="sent_method" required>
<?php foreach (getSentMethods() as $sent_method) { ?>
<option value="<?= escapeHtml($sent_method) ?>"><?= escapeHtml($sent_method) ?></option>
<?php } ?>
</select>
<p class="text-body-secondary small">For a quote that went out some other way than ITFlow's email. It stops being a draft, and the client can open it from its link.</p>
<div class="row g-3">
<div class="col-12">
<label class="form-label">How was it sent? <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-paper-plane"></i></span>
<select class="form-select" name="sent_method" required>
<?php foreach (getSentMethods() as $sent_method) { ?>
<option value="<?= escapeHtml($sent_method) ?>"><?= escapeHtml($sent_method) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-12">
<label class="form-label">Note</label>
<div class="input-group">
<span class="input-group-text align-items-start pt-2"><i class="fa fa-fw fa-sticky-note"></i></span>
<textarea class="form-control" name="note" rows="3" maxlength="500" placeholder="Tracking number, who it went to, anything worth keeping"></textarea>
</div>
</div>
</div>
<div class="mb-3">
<label>Note</label>
<textarea class="form-control" name="note" rows="3" maxlength="500"
placeholder="Optional - tracking number, who it went to, anything worth keeping"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="mark_quote_sent" class="btn btn-primary text-bold">
<i class="fa fa-fw fa-check me-2"></i>Mark Sent
</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal">
<i class="fa fa-fw fa-times me-2"></i>Cancel
</button>
<button type="submit" name="mark_quote_sent" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Mark Sent</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -1,54 +1,54 @@
<?php
/*
* Invoice an accepted quote - a draft invoice with the quote's lines,
* scope, category, discount and notes, dated as given and due on the
* client's terms. The quote is marked invoiced. ?quote_id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$quote_id = intval($_GET['quote_id']);
$sql = mysqli_query($mysqli, "SELECT quote_client_id, quote_number, quote_prefix FROM quotes WHERE quote_id = $quote_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$quote_prefix = escapeHtml($row['quote_prefix']);
$quote_number = intval($row['quote_number']);
$client_id = intval($row['quote_client_id']);
$doc_type = 'quote';
$doc = billingRow($doc_type, intval($_GET['quote_id'] ?? 0));
if (!$doc) {
exit(json_encode(['error' => 'That quote no longer exists.']));
}
$client_id = intval($doc['client_id']);
enforceClientAccess();
$doc_number = billingNumber($doc_type, $doc);
$lines = count(billingItems('quote', intval($doc['quote_id'])));
$terms = intval($doc['client_net_terms']) ?: intval($config_default_net_terms);
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title">
<i class="fas fa-fw fa-file me-2"></i>
Quote <?= "$quote_prefix$quote_number" ?>
<i class="fas fa-arrow-right me-2"></i>Invoice
</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-file-invoice-dollar me-2"></i>Make Invoice <span class="fw-normal text-white-50 ms-1"><?= escapeHtml($doc_number) ?> &middot; <?= escapeHtml($doc['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="quote_id" value="<?= $quote_id ?>">
<input type="hidden" name="quote_id" value="<?= intval($doc['quote_id']) ?>">
<div class="modal-body">
<div class="mb-3">
<label>Invoice Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date("Y-m-d"); ?>" required>
</div>
<div class="d-flex align-items-center gap-3 mb-3 p-3 rounded bg-body-tertiary">
<?= billingTile('quote') ?>
<i class="fas fa-arrow-right text-body-secondary"></i>
<?= billingTile('invoice') ?>
<div class="small text-body-secondary">A draft invoice with the quote's <?= $lines ?> line<?= $lines === 1 ? '' : 's' ?>, discount and notes - <?= escapeHtml(billingMoney($doc['quote_amount'], $doc['quote_currency_code'])) ?>. <?= escapeHtml($doc_number) ?> is marked invoiced.</div>
</div>
<label class="form-label">Invoice date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date('Y-m-d') ?>" required>
</div>
<div class="form-text">Due <?= $terms ?> days after it - the client's terms.</div>
</div>
<div class="modal-footer">
<button type="submit" name="add_quote_to_invoice" class="btn btn-primary text-bold">
<strong><i class="fas fa-check me-2"></i>Create Invoice</strong>
</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal">
<i class="fas fa-times me-2"></i>Cancel
</button>
<button type="submit" name="add_quote_to_invoice" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Make Invoice</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -1,103 +1,37 @@
<?php
/*
* New recurring invoice - an agreement billed every month or year: who it
* is for, what it is for, how often, the first date it bills, any discount
* and whether the invoices it makes go out by themselves. The lines go on
* the recurring invoice page.
* ?client_id= starts it for that client; without one, pick the client here.
*/
require_once '../../../includes/modal_header.php';
$client_id = intval($_GET['client_id'] ?? 0);
enforceUserPermission('module_sales', 2);
$form_type = 'recurring';
$form_row = null;
$form_client_id = intval($_GET['client_id'] ?? 0);
if ($form_client_id) {
$client_id = $form_client_id;
enforceClientAccess();
}
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-redo-alt me-2"></i>New Recurring Invoice</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-redo-alt me-2"></i>New Recurring Invoice<?php if ($form_client_id) { ?> <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(getFieldById('clients', $form_client_id, 'client_name')) ?></span><?php } ?></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<div class="modal-body">
<?php if ($client_id) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } else { ?>
<div class="mb-3">
<label>Client <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<select class="form-select select2" name="client_id" required>
<option value="">- Select a Client -</option>
<?php
//select unarchived clients
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
?>
<option value="<?= $client_id ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= "$client_name" ?></option>
<?php
}
?>
</select>
</div>
</div>
<?php } ?>
<div class="mb-3">
<label>Scope</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
<input type="text" class="form-control" name="scope" placeholder="Quick description" maxlength="255">
</div>
</div>
<div class="mb-3">
<label>Start Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="start_date" max="2999-12-31" value="<?= date("Y-m-d") ?>" required>
</div>
</div>
<div class="mb-3">
<label>Frequency <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-clock"></i></span>
<select class="form-select select2" name="frequency" required>
<option value="">- Frequency -</option>
<option value="month">Monthly</option>
<option value="year">Yearly</option>
</select>
</div>
</div>
<div class="mb-3">
<label>Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="category" required>
<option value="">- Category -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND category_archived_at IS NULL ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<option value="<?= $category_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name ?></option>
<?php
}
?>
</select>
<button class="btn btn-secondary ajax-modal" title="New category" type="button"
data-modal-url="../admin/modals/category/category_add.php?category=Income">
<i class="fas fa-fw fa-plus"></i>
</button>
</div>
</div>
<?php require __DIR__ . '/../billing/billing_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_recurring_invoice" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Create</button>

View File

@@ -1,134 +1,37 @@
<?php
/*
* Edit a recurring invoice's details - scope, category, how often, its next
* date, discount, whether its invoices go out by themselves, and whether it
* is running. Its lines are edited on the recurring invoice itself. ?id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$recurring_invoice_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT recurring_invoice_category_id, recurring_invoice_client_id, recurring_invoice_created_at,
recurring_invoice_discount_amount, recurring_invoice_frequency,
recurring_invoice_next_date, recurring_invoice_number, recurring_invoice_prefix,
recurring_invoice_auto_send, recurring_invoice_scope, recurring_invoice_status
FROM recurring_invoices WHERE recurring_invoice_id = $recurring_invoice_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$recurring_invoice_prefix = escapeHtml($row['recurring_invoice_prefix']);
$recurring_invoice_number = intval($row['recurring_invoice_number']);
$recurring_invoice_scope = escapeHtml($row['recurring_invoice_scope']);
$recurring_invoice_frequency = escapeHtml($row['recurring_invoice_frequency']);
$recurring_invoice_status = escapeHtml($row['recurring_invoice_status']);
$recurring_invoice_created_at = date('Y-m-d', strtotime($row['recurring_invoice_created_at']));
$recurring_invoice_next_date = escapeHtml($row['recurring_invoice_next_date']);
$recurring_invoice_auto_send = intval($row['recurring_invoice_auto_send']);
$recurring_invoice_discount = floatval($row['recurring_invoice_discount_amount']);
$category_id = intval($row['recurring_invoice_category_id']);
$client_id = intval($row['recurring_invoice_client_id']);
$form_type = 'recurring';
$form_row = billingRow($form_type, intval($_GET['id'] ?? 0));
if (!$form_row) {
exit(json_encode(['error' => 'That recurring invoice no longer exists.']));
}
$client_id = intval($form_row['client_id']);
enforceClientAccess();
$form_client_id = $client_id;
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-redo-alt me-2"></i>Editing Recur Invoice: <strong><?= "$recurring_invoice_prefix$recurring_invoice_number" ?></strong></h5>
<h5 class="modal-title"><i class="fas fa-fw fa-redo-alt me-2"></i>Edit Recurring Invoice <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber($form_type, $form_row)) ?> &middot; <?= escapeHtml($form_row['client_name']) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="recurring_invoice_id" value="<?= $recurring_invoice_id ?>">
<input type="hidden" name="recurring_invoice_id" value="<?= intval($form_row['recurring_invoice_id']) ?>">
<div class="modal-body">
<div class="mb-3">
<label>Scope</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
<input type="text" class="form-control" name="scope" placeholder="Quick description" maxlength="255" value="<?= $recurring_invoice_scope ?>">
</div>
</div>
<div class="mb-3">
<label>Frequency <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-clock"></i></span>
<select class="form-select select2" name="frequency" required>
<option value="">- Frequency -</option>
<option <?php if ($recurring_invoice_frequency == 'month') { echo "selected"; } ?> value="month">Monthly</option>
<option <?php if ($recurring_invoice_frequency == 'year') { echo "selected"; } ?> value="year">Yearly</option>
</select>
</div>
</div>
<div class="mb-3">
<label>Next Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="next_date" max="2999-12-31" value="<?= $recurring_invoice_next_date ?>" required>
</div>
</div>
<div class="mb-3">
<label>Income Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="category" required>
<option value="">- Category -</option>
<?php
$sql_income_category = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND (category_archived_at > '$recurring_invoice_created_at' OR category_archived_at IS NULL) ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql_income_category)) {
$category_id_select = intval($row['category_id']);
$category_name_select = escapeHtml($row['category_name']);
?>
<option <?php if ($category_id == $category_id_select) { ?> selected <?php } ?> value="<?= $category_id_select ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name_select ?></option>
<?php
}
?>
</select>
<button class="btn btn-secondary ajax-modal" title="New category" type="button"
data-modal-url="../admin/modals/category/category_add.php?category=Income">
<i class="fas fa-fw fa-plus"></i>
</button>
</div>
</div>
<div class='mb-3'>
<label>Discount Amount</label>
<div class='input-group'>
<span class='input-group-text'><i class='fa fa-fw fa-dollar-sign'></i></span>
<input type='text' class='form-control' inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}" name='recurring_invoice_discount' placeholder='0.00' value="<?= number_format($recurring_invoice_discount, 2, '.', '') ?>">
</div>
</div>
<div class="mb-3">
<label>Action <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-paper-plane"></i></span>
<select class="form-select select" name="auto_send" required>
<option <?php if ($recurring_invoice_auto_send == 1) { echo "selected"; } ?> value="1">Send Automatically</option>
<option <?php if ($recurring_invoice_auto_send == 0) { echo "selected"; } ?> value="0">Generate Draft for Review</option>
</select>
</div>
</div>
<div class="mb-3">
<label>Status <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-clock"></i></span>
<select class="form-select select" name="status" required>
<option <?php if ($recurring_invoice_status == 1) {
echo "selected";
} ?> value="1">Active</option>
<option <?php if ($recurring_invoice_status == 0) {
echo "selected";
} ?> value="0">InActive</option>
</select>
</div>
</div>
<?php require __DIR__ . '/../billing/billing_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="edit_recurring_invoice" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save</button>
@@ -137,5 +40,4 @@ ob_start();
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,103 +0,0 @@
<?php
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$item_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT item_created_at, item_description, item_name, item_price, item_product_id, item_quantity,
item_tax_id, recurring_invoice_client_id FROM recurring_invoice_items LEFT JOIN recurring_invoices ON recurring_invoice_id = item_recurring_invoice_id WHERE item_id = $item_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$item_name = escapeHtml($row['item_name']);
$item_description = escapeHtml($row['item_description']);
$item_quantity = floatval($row['item_quantity']);
$item_price = floatval($row['item_price']);
$item_created_at = escapeHtml($row['item_created_at']);
$tax_id = intval($row['item_tax_id']);
$product_id = intval($row['item_product_id']);
$client_id = intval($row['recurring_invoice_client_id']);
enforceClientAccess();
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-edit me-2"></i>Editing Line Item: <strong><?= $item_name ?></strong></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="item_id" value="<?= $item_id ?>">
<input type="hidden" name="product_id" value="<?= $product_id ?>">
<div class="modal-body">
<div class="mb-3">
<label>Item <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-box"></i></span>
<input type="text" class="form-control" name="name" maxlength="200" value="<?= $item_name ?>" placeholder="Enter item name" required>
</div>
</div>
<div class="row g-2">
<div class="col-sm">
<div class="mb-3">
<label>Quantity <strong class="text-danger">*</strong></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" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" name="qty" value="<?= number_format($item_quantity, 2) ?>" placeholder="0.00" required>
</div>
</div>
</div>
<div class="col-sm">
<div class="mb-3">
<label>Price <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control" inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}" name="price" value="<?= number_format($item_price, 2, '.', '') ?>" placeholder="0.00" required>
</div>
</div>
</div>
</div>
<div class="mb-3">
<label>Description</label>
<div class="input-group">
<textarea class="form-control" rows="5" name="description" placeholder="Enter a description"><?= $item_description ?></textarea>
</div>
</div>
<div class="mb-3">
<label>Tax <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="tax_id" required>
<option value="0">No Tax</option>
<?php
$taxes_sql = mysqli_query($mysqli, "SELECT tax_id, tax_name, tax_percent FROM taxes WHERE (tax_archived_at > '$item_created_at' OR tax_archived_at IS NULL) ORDER BY tax_name ASC");
while ($row = mysqli_fetch_assoc($taxes_sql)) {
$tax_id_select = intval($row['tax_id']);
$tax_name = escapeHtml($row['tax_name']);
$tax_percent = floatval($row['tax_percent']);
?>
<option <?php if ($tax_id_select == $tax_id) { echo "selected"; } ?> value="<?= $tax_id_select ?>"><?= "$tax_name $tax_percent%" ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="edit_recurring_invoice_item" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

172
agent/post/billing.php Normal file
View File

@@ -0,0 +1,172 @@
<?php
/*
* ITFlow - line items on invoices, quotes and recurring invoices, and the
* small things the billing pages do in place.
*
* One handler for the lines on all three - which kind is in the form's
* "type" (invoice, quote, recurring); functions/billing.php does the work.
* A line can only change while the document is open for it: not once an
* invoice is paid, cancelled or non-billable, nor once a quote has been
* answered or invoiced.
*/
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
/**
* The document a line request is for, checked: the kind, the row (scoped to
* the clients this agent may open) and that its lines may change. Flashes
* and goes back when not.
*/
function billingPostDocument($type, $id) {
global $client_id;
$t = billingType($type);
$row = $t ? billingRow($type, $id) : null;
if (!$row) {
flashAlert('That document no longer exists, or is not one you can open.', 'error');
redirect();
}
$client_id = intval($row['client_id']);
enforceClientAccess();
if (!billingCanEditItems($type, $row)) {
flashAlert(billingNumber($type, $row) . " can't be changed now - " . ($type === 'quote' ? 'it has been answered or invoiced.' : 'it is paid, cancelled or non-billable.'), 'error');
redirect();
}
return $row;
}
/** Back to the document, at the lines. */
function billingPostBack($type, $id, $hash = 'items') {
$t = billingType($type);
$referer = (string) ($_SERVER['HTTP_REFERER'] ?? '');
$path = (string) parse_url($referer, PHP_URL_PATH);
$url = basename($path) === $t['page'] ? strtok($referer, '#') : $t['page'] . '?' . $t['param'] . '=' . intval($id);
redirect($url . ($hash !== '' ? "#$hash" : ''));
}
/** The audit log's name for each kind. */
function billingAuditType($type) {
return ['invoice' => 'Invoice', 'quote' => 'Quote', 'recurring' => 'Recurring Invoice'][$type] ?? 'Invoice';
}
if (isset($_POST['billing_item_save'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$type = (string) ($_POST['type'] ?? '');
$doc_id = intval($_POST['doc_id'] ?? 0);
$item_id = intval($_POST['item_id'] ?? 0);
$row = billingPostDocument($type, $doc_id);
$number = billingNumber($type, $row);
$saved = billingItemSave($type, $doc_id, $_POST, $item_id, $error);
if (!$saved) {
flashAlert(escapeHtml($error), 'error');
billingPostBack($type, $doc_id, $item_id ? 'items' : 'add-line');
}
$name = trim((string) $_POST['name']);
logAudit(billingAuditType($type), 'Edit', escapeSql("$session_name " . ($item_id ? 'edited' : 'added') . " line $name " . ($item_id ? 'on' : 'to') . " $number"), $client_id, $doc_id);
flashAlert('<strong>' . escapeHtml($name) . '</strong> ' . ($item_id ? 'updated' : 'added'));
billingPostBack($type, $doc_id, $item_id ? "line-$saved" : 'add-line');
}
if (isset($_GET['billing_item_delete'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$type = (string) ($_GET['type'] ?? '');
$doc_id = intval($_GET['doc_id'] ?? 0);
$item_id = intval($_GET['billing_item_delete']);
$row = billingPostDocument($type, $doc_id);
$item = billingItemDelete($type, $doc_id, $item_id);
if (!$item) {
flashAlert('That line was already gone.', 'error');
billingPostBack($type, $doc_id);
}
logAudit(billingAuditType($type), 'Edit', escapeSql("$session_name removed line {$item['item_name']} from " . billingNumber($type, $row)), $client_id, $doc_id);
flashAlert('<strong>' . escapeHtml($item['item_name']) . '</strong> removed', 'error');
billingPostBack($type, $doc_id);
}
/*
* Pause or resume a recurring invoice. Resuming one whose next date has
* passed says so - it only runs on its next date, so that has to move first.
*/
if (isset($_GET['recurring_invoice_set_status'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$recurring_invoice_id = intval($_GET['recurring_invoice_set_status']);
$status = intval($_GET['status'] ?? 0) ? 1 : 0;
$row = billingRow('recurring', $recurring_invoice_id);
if (!$row) {
flashAlert('That recurring invoice no longer exists.', 'error');
redirect();
}
$client_id = intval($row['client_id']);
enforceClientAccess();
$number = billingNumber('recurring', $row);
mysqli_query($mysqli, "UPDATE recurring_invoices SET recurring_invoice_status = $status WHERE recurring_invoice_id = $recurring_invoice_id");
billingLog('recurring', $recurring_invoice_id, $status ? 'Active' : 'Paused', ($status ? 'Resumed' : 'Paused') . " by $session_name");
logAudit('Recurring Invoice', 'Edit', escapeSql("$session_name " . ($status ? 'resumed' : 'paused') . " recurring invoice $number"), $client_id, $recurring_invoice_id);
if ($status && $row['recurring_invoice_next_date'] < date('Y-m-d')) {
flashAlert("<strong>" . escapeHtml($number) . "</strong> resumed - its next date has passed, so move it on before it will run again.", 'warning');
} else {
flashAlert("<strong>" . escapeHtml($number) . "</strong> " . ($status ? 'resumed' : 'paused'));
}
redirect();
}
/*
* Move a recurring invoice's next date on to the first one that hasn't
* passed, skipping the runs it missed (nothing is billed for them).
*/
if (isset($_GET['recurring_invoice_catch_up'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$recurring_invoice_id = intval($_GET['recurring_invoice_catch_up']);
$row = billingRow('recurring', $recurring_invoice_id);
if (!$row) {
flashAlert('That recurring invoice no longer exists.', 'error');
redirect();
}
$client_id = intval($row['client_id']);
enforceClientAccess();
$next = recurringInvoiceCatchUp($row);
$number = billingNumber('recurring', $row);
if ($next === $row['recurring_invoice_next_date']) {
flashAlert("<strong>" . escapeHtml($number) . "</strong> is not behind.");
redirect();
}
mysqli_query($mysqli, "UPDATE recurring_invoices SET recurring_invoice_next_date = '" . escapeSql($next) . "' WHERE recurring_invoice_id = $recurring_invoice_id");
billingLog('recurring', $recurring_invoice_id, 'Rescheduled', "Next date moved from {$row['recurring_invoice_next_date']} to $next by $session_name");
logAudit('Recurring Invoice', 'Edit', escapeSql("$session_name moved recurring invoice $number on to $next"), $client_id, $recurring_invoice_id);
flashAlert("<strong>" . escapeHtml($number) . "</strong> next runs on " . escapeHtml($next));
redirect();
}

View File

@@ -73,17 +73,10 @@ if (isset($_POST['edit_invoice'])) {
enforceClientAccess();
// Calculate new total
$sql = mysqli_query($mysqli,"SELECT item_total FROM invoice_items WHERE item_invoice_id = $invoice_id");
$invoice_amount = 0;
while($row = mysqli_fetch_assoc($sql)) {
$item_total = floatval($row['item_total']);
$invoice_amount = $invoice_amount + $item_total;
}
$invoice_amount = $invoice_amount - $invoice_discount;
mysqli_query($mysqli,"UPDATE invoices SET invoice_scope = '$scope', invoice_date = '$date', invoice_due = '$due', invoice_category_id = $category, invoice_discount_amount = $invoice_discount WHERE invoice_id = $invoice_id");
mysqli_query($mysqli,"UPDATE invoices SET invoice_scope = '$scope', invoice_date = '$date', invoice_due = '$due', invoice_category_id = $category, invoice_discount_amount = '$invoice_discount', invoice_amount = '$invoice_amount' WHERE invoice_id = $invoice_id");
// The total from the lines less the new discount - and the status, if it has been paid against
billingRecalc('invoice', $invoice_id);
logAudit("Invoice", "Edit", "$session_name edited Invoice $invoice_prefix$invoice_number - $scope", $client_id, $invoice_id);
@@ -107,7 +100,7 @@ if (isset($_POST['add_invoice_copy'])) {
invoice_currency_code, invoice_discount_amount, invoice_note, invoice_number,
invoice_prefix, invoice_scope FROM clients, invoices WHERE client_id = invoice_client_id AND invoice_id = $invoice_id");
$row = mysqli_fetch_assoc($sql);
$client_net_terms = intval($row['client_net_terms']);
$client_net_terms = intval($row['client_net_terms']) ?: intval($config_default_net_terms);
$invoice_scope = escapeSql($row['invoice_scope']);
$invoice_discount_amount = floatval($row['invoice_discount_amount']);
$invoice_amount = floatval($row['invoice_amount']);
@@ -138,7 +131,7 @@ if (isset($_POST['add_invoice_copy'])) {
$new_invoice_id = mysqli_insert_id($mysqli);
mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Draft', history_description = 'Copied INVOICE!', history_invoice_id = $new_invoice_id");
mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Draft', history_description = 'Copied from $old_invoice_prefix$old_invoice_number by $session_name', history_invoice_id = $new_invoice_id");
$sql_items = mysqli_query($mysqli,"SELECT item_description, item_id, item_name, item_order, item_price, item_quantity, item_subtotal,
item_tax, item_tax_id, item_total FROM invoice_items WHERE item_invoice_id = $invoice_id");
@@ -157,11 +150,11 @@ if (isset($_POST['add_invoice_copy'])) {
mysqli_query($mysqli,"INSERT INTO invoice_items SET item_name = '$item_name', item_description = '$item_description', item_quantity = $item_quantity, item_price = $item_price, item_subtotal = $item_subtotal, item_tax = $item_tax, item_total = $item_total, item_order = $item_order, item_tax_id = $tax_id, item_invoice_id = $new_invoice_id");
}
logAudit("Invoice", "Create", "$session_name created new Invoice $config_invoice_prefix$new_invoice_number from $old_invoice_prefix$old_invoice_prefix", $client_id, $new_invoice_id);
logAudit("Invoice", "Create", "$session_name created new Invoice $config_invoice_prefix$new_invoice_number from $old_invoice_prefix$old_invoice_number", $client_id, $new_invoice_id);
triggerCustomAction('invoice_create', $new_invoice_id);
flashAlert("Created new Invoice <strong>$config_invoice_prefix$new_invoice_number</strong> from <strong>$old_invoice_prefix$old_invoice_prefix</strong>");
flashAlert("Created new Invoice <strong>$config_invoice_prefix$new_invoice_number</strong> from <strong>$old_invoice_prefix$old_invoice_number</strong>");
redirect("invoice.php?invoice_id=$new_invoice_id");
@@ -320,199 +313,6 @@ if (isset($_GET['delete_invoice'])) {
}
if (isset($_POST['add_invoice_item'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$invoice_id = intval($_POST['invoice_id']);
$name = escapeSql($_POST['name']);
$description = escapeSql($_POST['description']);
$qty = floatval($_POST['qty']);
$price = floatval($_POST['price']);
$tax_id = intval($_POST['tax_id']);
$item_order = intval($_POST['item_order']);
$product_id = intval($_POST['product_id']);
$client_id = intval(getFieldById('invoices', $invoice_id, 'invoice_client_id'));
enforceClientAccess();
$subtotal = $price * $qty;
// Update Product Inventory
if ($product_id) {
// Only enforce stock for tangible products
$product_type = escapeSql(getFieldById('products', $product_id, 'product_type'));
if ($product_type === 'product') {
// Current available stock
$sql = mysqli_query(
$mysqli,
"SELECT COALESCE(SUM(stock_qty), 0) AS available_stock
FROM product_stock
WHERE stock_product_id = $product_id"
);
$row = mysqli_fetch_assoc($sql);
$available_stock = floatval($row['available_stock']);
// Enough in stock?
if ($available_stock >= $qty) {
mysqli_query($mysqli,"INSERT INTO product_stock SET stock_qty = -$qty, stock_note = 'QTY $qty - Invoice $invoice_id', stock_product_id = $product_id");
} else {
// Not enough in stock: stop and notify
flashAlert("Not Enough <strong>$name</strong> in stock", 'error');
redirect();
}
}
}
// Tax
if ($tax_id > 0) {
$sql = mysqli_query($mysqli,"SELECT tax_percent FROM taxes WHERE tax_id = $tax_id");
$row = mysqli_fetch_assoc($sql);
$tax_percent = floatval($row['tax_percent']);
$tax_amount = $subtotal * $tax_percent / 100;
} else {
$tax_amount = 0;
}
$total = $subtotal + $tax_amount;
mysqli_query($mysqli,"INSERT INTO invoice_items SET item_name = '$name', item_description = '$description', item_quantity = $qty, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_order = $item_order, item_tax_id = $tax_id, item_product_id = $product_id, item_invoice_id = $invoice_id");
// Get Discount and Invoice Details
$sql = mysqli_query($mysqli,"SELECT invoice_discount_amount, invoice_number, invoice_prefix FROM invoices WHERE invoice_id = $invoice_id");
$row = mysqli_fetch_assoc($sql);
$invoice_prefix = escapeSql($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$invoice_discount = floatval($row['invoice_discount_amount']);
//add up all line items
$sql = mysqli_query($mysqli,"SELECT item_total FROM invoice_items WHERE item_invoice_id = $invoice_id");
$invoice_total = 0;
while($row = mysqli_fetch_assoc($sql)) {
$item_total = floatval($row['item_total']);
$invoice_total = $invoice_total + $item_total;
}
$new_invoice_amount = $invoice_total - $invoice_discount;
mysqli_query($mysqli,"UPDATE invoices SET invoice_amount = $new_invoice_amount WHERE invoice_id = $invoice_id");
logAudit("Invoice", "Edit", "$session_name added item $name to invoice $invoice_prefix$invoice_number", $client_id, $invoice_id);
flashAlert("Item <strong>$name</strong> added to invoice");
redirect();
}
if (isset($_POST['edit_invoice_item'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$item_id = intval($_POST['item_id']);
$name = escapeSql($_POST['name']);
$description = escapeSql($_POST['description']);
$qty = floatval($_POST['qty']);
$price = floatval($_POST['price']);
$tax_id = intval($_POST['tax_id']);
$product_id = intval($_POST['product_id']);
$subtotal = $price * $qty;
if ($tax_id > 0) {
$sql = mysqli_query($mysqli,"SELECT tax_percent FROM taxes WHERE tax_id = $tax_id");
$row = mysqli_fetch_assoc($sql);
$tax_percent = floatval($row['tax_percent']);
$tax_amount = $subtotal * $tax_percent / 100;
} else {
$tax_amount = 0;
}
$total = $subtotal + $tax_amount;
// Determine what type of line item
$sql = mysqli_query($mysqli,"SELECT item_invoice_id FROM invoice_items WHERE item_id = $item_id");
$row = mysqli_fetch_assoc($sql);
$invoice_id = intval($row['item_invoice_id']);
//Get Discount Amount
$sql = mysqli_query($mysqli,"SELECT invoice_client_id, invoice_discount_amount, invoice_number, invoice_prefix FROM invoices WHERE invoice_id = $invoice_id");
$row = mysqli_fetch_assoc($sql);
$invoice_prefix = escapeSql($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$client_id = intval($row['invoice_client_id']);
$invoice_discount = floatval($row['invoice_discount_amount']);
enforceClientAccess();
mysqli_query($mysqli,"UPDATE invoice_items SET item_name = '$name', item_description = '$description', item_quantity = $qty, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_tax_id = $tax_id WHERE item_id = $item_id");
//Update Invoice Balances by tallying up invoice items
$sql_invoice_total = mysqli_query($mysqli,"SELECT SUM(item_total) AS invoice_total FROM invoice_items WHERE item_invoice_id = $invoice_id");
$row = mysqli_fetch_assoc($sql_invoice_total);
$new_invoice_amount = floatval($row['invoice_total']) - $invoice_discount;
mysqli_query($mysqli,"UPDATE invoices SET invoice_amount = $new_invoice_amount WHERE invoice_id = $invoice_id");
logAudit("Invoice", "Edit", "$session_name edited item $name on invoice $invoice_prefix$invoice_number", $client_id, $invoice_id);
flashAlert("Item <strong>$name</strong> updated");
redirect();
}
if (isset($_GET['delete_invoice_item'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$item_id = intval($_GET['delete_invoice_item']);
$sql = mysqli_query($mysqli,"SELECT item_invoice_id, item_name, item_product_id, item_quantity, item_subtotal, item_tax,
item_total FROM invoice_items WHERE item_id = $item_id");
$row = mysqli_fetch_assoc($sql);
$invoice_id = intval($row['item_invoice_id']);
$item_name = escapeSql($row['item_name']);
$item_quantity = floatval($row['item_quantity']);
$item_product_id = intval($row['item_product_id']);
$item_subtotal = floatval($row['item_subtotal']);
$item_tax = floatval($row['item_tax']);
$item_total = floatval($row['item_total']);
$sql = mysqli_query($mysqli,"SELECT invoice_amount, invoice_client_id, invoice_number, invoice_prefix FROM invoices WHERE invoice_id = $invoice_id");
$row = mysqli_fetch_assoc($sql);
$invoice_prefix = escapeSql($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$client_id = intval($row['invoice_client_id']);
enforceClientAccess();
$new_invoice_amount = floatval($row['invoice_amount']) - $item_total;
mysqli_query($mysqli,"UPDATE invoices SET invoice_amount = $new_invoice_amount WHERE invoice_id = $invoice_id");
mysqli_query($mysqli,"DELETE FROM invoice_items WHERE item_id = $item_id");
// Return Product Inventory
if ($item_product_id) {
mysqli_query($mysqli,"INSERT INTO product_stock SET stock_qty = $item_quantity, stock_note = 'Returned QTY $item_quantity back to stock from Invoice $invoice_id', stock_product_id = $item_product_id");
}
logAudit("Invoice", "Delete", "$session_name removed item $item_name from invoice $invoice_prefix$invoice_number", $client_id, $invoice_id);
flashAlert("Item <strong>$item_name</strong> removed from invoice", 'error');
redirect();
}
if (isset($_POST['email_invoice'])) {
validateCSRFToken();
@@ -924,6 +724,12 @@ if (isExportRequest('export_invoices')) {
$status_query = "invoice_status = 'Sent' OR invoice_status = 'Viewed' OR invoice_status = 'Partial'";
$overdue_query = "AND (invoice_due < CURDATE())";
$filter_summary['Status'] = 'Overdue';
} elseif (!empty($_POST['status']) && $_POST['status'] == 'Paid') {
$status_query = "invoice_status = 'Paid'";
$filter_summary['Status'] = 'Paid';
} elseif (!empty($_POST['status']) && $_POST['status'] == 'Cancelled') {
$status_query = "invoice_status IN ('Cancelled', 'Non-Billable')";
$filter_summary['Status'] = 'Cancelled or non-billable';
} else {
// Default - any
$status_query = "invoice_status LIKE '%'";
@@ -1003,28 +809,10 @@ if (isExportRequest('export_invoices')) {
}
// TODO: This should probably be removed as we now allow multiple invoices to be linked to a single ticket
if (isset($_POST['link_invoice_to_ticket'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$invoice_id = intval($_POST['invoice_id']);
$ticket_id = intval($_POST['ticket_id']);
$client_id = intval(getFieldById('invoices', $invoice_id, 'invoice_client_id'));
enforceClientAccess();
mysqli_query($mysqli,"UPDATE invoices SET invoice_ticket_id = $ticket_id WHERE invoice_id = $invoice_id");
flashAlert("Invoice linked to ticket");
redirect();
}
/*
* Put tickets on an invoice - billable ones of the same client that are
* resolved or closed and not on an invoice yet. ticket_ids[] (or ticket_id).
*/
if (isset($_POST['add_ticket_to_invoice'])) {
validateCSRFToken();
@@ -1032,15 +820,34 @@ if (isset($_POST['add_ticket_to_invoice'])) {
enforceUserPermission('module_sales', 2);
$invoice_id = intval($_POST['invoice_id']);
$ticket_id = intval($_POST['ticket_id']);
$client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id'));
$invoice = billingRow('invoice', $invoice_id);
if (!$invoice) {
flashAlert('That invoice no longer exists.', 'error');
redirect();
}
$client_id = intval($invoice['client_id']);
enforceClientAccess();
mysqli_query($mysqli,"UPDATE tickets SET ticket_invoice_id = $invoice_id WHERE ticket_id = $ticket_id");
$ticket_ids = array_filter(array_map('intval', (array) ($_POST['ticket_ids'] ?? [$_POST['ticket_id'] ?? 0])));
$added = [];
foreach (invoiceUnbilledTickets($client_id) as $ticket) {
if (in_array(intval($ticket['ticket_id']), $ticket_ids, true)) {
mysqli_query($mysqli, "UPDATE tickets SET ticket_invoice_id = $invoice_id WHERE ticket_id = " . intval($ticket['ticket_id']) . " AND ticket_invoice_id = 0");
$added[] = $ticket['ticket_prefix'] . $ticket['ticket_number'];
}
}
flashAlert("Ticket linked to invoice");
if (!$added) {
flashAlert('Nothing added - those tickets are already billed, or not billable.', 'error');
redirect("invoice.php?invoice_id=$invoice_id");
}
$number = billingNumber('invoice', $invoice);
billingLog('invoice', $invoice_id, $invoice['invoice_status'], 'Ticket' . (count($added) === 1 ? ' ' : 's ') . implode(', ', $added) . " added by $session_name");
logAudit("Invoice", "Edit", escapeSql("$session_name added ticket" . (count($added) === 1 ? ' ' : 's ') . implode(', ', $added) . " to invoice $number"), $client_id, $invoice_id);
flashAlert(count($added) === 1 ? "Ticket <strong>" . escapeHtml($added[0]) . "</strong> added to the invoice" : count($added) . " tickets added to the invoice");
redirect("invoice.php?invoice_id=$invoice_id");
@@ -1055,13 +862,23 @@ if (isset($_GET['remove_ticket_from_invoice'])) {
$invoice_id = intval($_GET['invoice_id']);
$ticket_id = intval($_GET['ticket_id']);
$client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id'));
$invoice = billingRow('invoice', $invoice_id);
$ticket = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_client_id FROM tickets WHERE ticket_id = $ticket_id AND ticket_invoice_id = $invoice_id"));
if (!$invoice || !$ticket) {
flashAlert('That ticket is not on this invoice.', 'error');
redirect();
}
$client_id = intval($invoice['client_id']);
enforceClientAccess();
mysqli_query($mysqli,"UPDATE tickets SET ticket_invoice_id = 0 WHERE ticket_id = $ticket_id");
flashAlert("Ticket unlinked from invoice");
$ticket_number = $ticket['ticket_prefix'] . $ticket['ticket_number'];
billingLog('invoice', $invoice_id, $invoice['invoice_status'], "Ticket $ticket_number taken off by $session_name");
logAudit("Invoice", "Edit", escapeSql("$session_name took ticket $ticket_number off invoice " . billingNumber('invoice', $invoice)), $client_id, $invoice_id);
flashAlert("Ticket <strong>" . escapeHtml($ticket_number) . "</strong> taken off the invoice - it is unbilled again");
redirect("invoice.php?invoice_id=$invoice_id");
@@ -1073,234 +890,16 @@ if (isset($_GET['export_invoice_pdf'])) {
enforceUserPermission('module_sales');
$invoice_id = intval($_GET['export_invoice_pdf']);
$sql = mysqli_query(
$mysqli,
"SELECT client_currency_code, client_id, client_name, client_net_terms, client_website,
contact_email, contact_extension, contact_mobile, contact_mobile_country_code,
contact_phone, contact_phone_country_code, invoice_amount, invoice_category_id,
invoice_created_at, invoice_currency_code, invoice_date, invoice_discount_amount,
invoice_due, invoice_id, invoice_note, invoice_number, invoice_prefix, invoice_scope,
invoice_status, invoice_url_key, location_address, location_city, location_country,
location_state, location_zip FROM invoices
LEFT JOIN clients ON invoice_client_id = client_id
LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1
LEFT JOIN locations ON clients.client_id = locations.location_client_id AND location_primary = 1
WHERE invoice_id = $invoice_id
" . clientScopeSql('invoice_client_id') . "
LIMIT 1"
);
$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_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;
$invoice = billingRow('invoice', intval($_GET['export_invoice_pdf']));
if (!$invoice) {
flashAlert('That invoice no longer exists.', 'error');
redirect('invoices.php');
}
$client_id = intval($invoice['client_id']);
enforceClientAccess();
$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']);
$sql_payments = mysqli_query($mysqli, "SELECT * FROM payments, accounts WHERE payment_account_id = account_id AND payment_invoice_id = $invoice_id ORDER BY payments.payment_id DESC");
//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;
//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);
require_once("../libs/TCPDF/tcpdf.php");
// Start TCPDF
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetMargins(10, 10, 10);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 10);
// Logo + Right Columns
$html = '<table width="100%" cellspacing="0" cellpadding="3">
<tr>
<td width="40%">';
if (!empty($company_logo) && file_exists("../uploads/settings/$company_logo")) {
$html .= '<img src="/uploads/settings/' . $company_logo . '" width="120">';
}
$html .= '</td>
<td width="60%" align="right">
<span style="font-size:18pt; font-weight:bold;">Invoice</span><br>
<span style="font-size:14pt;">' . $invoice_prefix . $invoice_number . '</span><br>';
if (strtolower($invoice_status) === 'paid') {
$html .= '<span style="color:green; font-weight:bold;">PAID</span><br>';
}
$html .= '</td>
</tr>
</table><br>';
// Billing titles
$html .= '<table width="100%" cellspacing="0" cellpadding="2">
<tr>
<td width="50%" style="font-size:14pt; font-weight:bold;">' . $company_name . '</td>
<td width="50%" align="right" style="font-size:14pt; font-weight:bold;">' . $client_name . '</td>
</tr>
<tr>
<td style="font-size:10pt; line-height:1.4;">' . nl2br(formatAddress($company_address, $company_city, $company_state, $company_zip, $company_country) . "\n$company_phone\n$company_website\n$company_tax_id_display") . '</td>
<td style="font-size:10pt; line-height:1.4;" align="right">' . nl2br(formatAddress($location_address, $location_city, $location_state, $location_zip, $location_country) . "\n$contact_email\n$contact_phone") . '</td>
</tr>
</table><br>';
// Date table
$html .= '<table border="0" cellpadding="2" cellspacing="0" width="100%">
<tr>
<td width="60%"></td>
<td width="20%" style="font-size:10pt;"><strong>Date:</strong></td>
<td width="20%" style="font-size:10pt;" align="right">' . $invoice_date . '</td>
</tr>
<tr>
<td></td>
<td style="font-size:10pt;"><strong>Due:</strong></td>
<td style="font-size:10pt;" align="right">' . $invoice_due . '</td>
</tr>
</table><br><br>';
// Items header
$html .= '
<table border="0" cellpadding="5" cellspacing="0" width="100%">
<tr style="background-color:#f0f0f0;">
<th align="left" width="40%"><strong>Item</strong></th>
<th align="center" width="10%"><strong>Qty</strong></th>
<th align="right" width="15%"><strong>Price</strong></th>
<th align="right" width="15%"><strong>Tax</strong></th>
<th align="right" width="20%"><strong>Amount</strong></th>
</tr>';
// Load items
$sub_total = 0;
$total_tax = 0;
$sql_items = mysqli_query($mysqli, "SELECT item_description, item_name, item_price, item_quantity, item_tax, item_total FROM invoice_items WHERE item_invoice_id = $invoice_id ORDER BY item_order ASC");
while ($item = mysqli_fetch_assoc($sql_items)) {
$name = $item['item_name'];
$desc = $item['item_description'];
$qty = $item['item_quantity'];
$price = $item['item_price'];
$tax = $item['item_tax'];
$total = $item['item_total'];
$sub_total += $price * $qty;
$total_tax += $tax;
$html .= '
<tr>
<td><strong>' . $name . '</strong>
<br><span style="font-style:italic; font-size:9pt;">' . nl2br($desc) . '</span>
</td>
<td align="center">' . number_format($qty, 2) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $price, $invoice_currency_code) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $tax, $invoice_currency_code) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $total, $invoice_currency_code) . '</td>
</tr>';
}
$html .= '</table><br><hr><br><br>';
// Totals
$html .= '<table width="100%" cellspacing="0" cellpadding="4">
<tr>
<td width="60%"><i style="font-size:9pt;">' . nl2br($invoice_note) . '</i></td>
<td width="40%">
<table width="100%" cellpadding="3" cellspacing="0">
<tr><td>Subtotal:</td><td align="right">' . numfmt_format_currency($currency_format, $sub_total, $invoice_currency_code) . '</td></tr>';
if ($invoice_discount > 0) {
$html .= '<tr><td>Discount:</td><td align="right">-' . numfmt_format_currency($currency_format, $invoice_discount, $invoice_currency_code) . '</td></tr>';
}
if ($total_tax > 0) {
$html .= '<tr><td>Tax:</td><td align="right">' . numfmt_format_currency($currency_format, $total_tax, $invoice_currency_code) . '</td></tr>';
}
$html .= '
<tr><td>Total:</td><td align="right">' . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . '</td></tr>';
if ($amount_paid > 0) {
$html .= '<tr><td>Paid:</td><td align="right">' . numfmt_format_currency($currency_format, $amount_paid, $invoice_currency_code) . '</td></tr>';
}
$html .= '
<tr><td><h3><strong>Balance:</strong></h3></td><td align="right"><h3><strong>' . numfmt_format_currency($currency_format, $balance, $invoice_currency_code) . '</strong></h3></td></tr>
</table>
</td>
</tr>
</table><br><br>';
// Footer
$html .= '<div style="text-align:center; font-size:9pt; color:gray;">' . nl2br($config_invoice_footer) . '</div>';
$pdf->writeHTML($html, true, false, true, false, '');
$filename = preg_replace('/[^A-Za-z0-9_\-]/', '_', "{$invoice_date}_{$company_name}_{$client_name}_Invoice_{$invoice_prefix}{$invoice_number}");
$pdf->Output("$filename.pdf", 'I');
exit;
billingPdfSend(billingPdf('invoice', $invoice));
}
@@ -1310,148 +909,16 @@ if (isset($_GET['export_invoice_packing_slip'])) {
enforceUserPermission('module_sales');
$invoice_id = intval($_GET['export_invoice_packing_slip']);
$sql = mysqli_query(
$mysqli,
"SELECT client_id, client_name, contact_email, contact_extension, contact_phone,
contact_phone_country_code, invoice_date, invoice_id, invoice_number, invoice_prefix,
location_address, location_city, location_country, location_state, location_zip FROM invoices
LEFT JOIN clients ON invoice_client_id = client_id
LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1
LEFT JOIN locations ON clients.client_id = locations.location_client_id AND location_primary = 1
WHERE invoice_id = $invoice_id
" . clientScopeSql('invoice_client_id') . "
LIMIT 1"
);
$row = mysqli_fetch_assoc($sql);
$invoice_id = intval($row['invoice_id']);
$invoice_prefix = escapeHtml($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$invoice_date = escapeHtml($row['invoice_date']);
$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']);
$invoice = billingRow('invoice', intval($_GET['export_invoice_packing_slip']));
if (!$invoice) {
flashAlert('That invoice no longer exists.', 'error');
redirect('invoices.php');
}
$client_id = intval($invoice['client_id']);
enforceClientAccess();
$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_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_logo = escapeHtml($row['company_logo']);
require_once("../libs/TCPDF/tcpdf.php");
// Start TCPDF
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetMargins(10, 10, 10);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 10);
// Logo + Right Columns
$html = '<table width="100%" cellspacing="0" cellpadding="3">
<tr>
<td width="40%">';
if (!empty($company_logo) && file_exists("../uploads/settings/$company_logo")) {
$html .= '<img src="/uploads/settings/' . $company_logo . '" width="120">';
}
$html .= '</td>
<td width="60%" align="right">
<span style="font-size:18pt; font-weight:bold;">Packing Slip</span><br>
<span style="font-size:14pt;">' . $invoice_prefix . $invoice_number . '</span><br>';
$html .= '</td>
</tr>
</table><br>';
// Billing titles
$html .= '<table width="100%" cellspacing="0" cellpadding="2">
<tr>
<td width="50%" style="font-size:14pt; font-weight:bold;">' . $company_name . '</td>
<td width="50%" align="right" style="font-size:14pt; font-weight:bold;">' . $client_name . '</td>
</tr>
<tr>
<td style="font-size:10pt; line-height:1.4;">' . nl2br(formatAddress($company_address, $company_city, $company_state, $company_zip, $company_country) . "\n$company_phone\n$company_website") . '</td>
<td style="font-size:10pt; line-height:1.4;" align="right">' . nl2br(formatAddress($location_address, $location_city, $location_state, $location_zip, $location_country) . "\n$contact_email\n$contact_phone") . '</td>
</tr>
</table><br>';
// Items header
$html .= '
<table border="0" cellpadding="5" cellspacing="0" width="100%">
<tr style="background-color:#f0f0f0;">
<th align="left" width="50%"><strong>Item</strong></th>
<th align="center" width="40%"><strong>Qty</strong></th>
<th align="right" width="10%"><strong>Picked?</strong></th>
</tr>';
// Load items
$sub_total = 0;
$total_tax = 0;
$sql_items = mysqli_query($mysqli, "SELECT item_name, item_quantity FROM invoice_items WHERE item_invoice_id = $invoice_id ORDER BY item_order ASC");
while ($item = mysqli_fetch_assoc($sql_items)) {
$name = $item['item_name'];
$qty = $item['item_quantity'];
$html .= '
<tr>
<td><strong>' . $name . '</strong></td>
<td align="center">' . number_format($qty, 2) . '</td>
<td align="right">
<table cellpadding="0" cellspacing="0">
<tr>
<td style="border:0.5px solid #000; width:12px; height:5px; margin-top:2px"></td>
</tr>
</table>
</td>
</tr>';
}
$html .= '</table><br><br><br>';
// Picked/Checked by
$html .= '
<table width="100%" cellspacing="0" cellpadding="8" style="font-size:10pt; margin-top:20px;">
<tr>
<td width="50%" style="border:1px solid #000; height:60px;">
<strong>Picked By:</strong><br><br>
</td>
<td width="50%" style="border:1px solid #000; height:60px;">
<strong>Checked By:</strong><br><br>
</td>
</tr>
</table>
<br><br>';
$pdf->writeHTML($html, true, false, true, false, '');
$filename = preg_replace('/[^A-Za-z0-9_\-]/', '_', "{$invoice_date}_{$company_name}_{$client_name}_Invoice_{$invoice_prefix}{$invoice_number}");
$pdf->Output("$filename.pdf", 'I');
exit;
billingPdfSend(billingPdf('invoice', $invoice, 'packing'));
}

View File

@@ -3,8 +3,8 @@ defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
$date = escapeSql($_POST['date']);
$category = intval($_POST['category']);
$scope = escapeSql($_POST['scope']);
$invoice_discount = floatval($_POST['invoice_discount']);
$recurring_discount = floatval($_POST['recurring_discount']);
$scope = escapeSql($_POST['scope'] ?? '');
$invoice_discount = round(floatval($_POST['invoice_discount'] ?? 0), 2);
$recurring_discount = round(floatval($_POST['recurring_discount'] ?? 0), 2);
$config_invoice_prefix = escapeSql($config_invoice_prefix);

View File

@@ -200,6 +200,9 @@ if (isset($_POST['edit_payment'])) {
mysqli_query($mysqli,"UPDATE payments SET payment_date = '$date', payment_amount = $amount, payment_account_id = $account, payment_method = '$payment_method', payment_reference = '$reference' WHERE payment_id = $payment_id");
// A changed amount can leave the invoice paid, part paid or owing again
updateInvoiceStatusFromPayments(intval(getFieldById('payments', $payment_id, 'payment_invoice_id')));
logAudit("Payment", "Edit", "Payment edited amount of " . numfmt_format_currency($currency_format, $amount, $session_company_currency));
flashAlert("Payment edited to amount <strong>" . numfmt_format_currency($currency_format, $amount, $session_company_currency) . "</strong> added");
@@ -540,10 +543,9 @@ if (isset($_POST['add_bulk_payment'])) {
}
// Get Invoices
// Only invoices still waiting on money - not drafts, not paid, not cancelled or non-billable
$sql_invoices = "SELECT * FROM invoices
WHERE invoice_status != 'Draft'
AND invoice_status != 'Paid'
AND invoice_status != 'Cancelled'
WHERE invoice_status IN ('Sent', 'Viewed', 'Partial')
AND invoice_client_id = $client_id
ORDER BY invoice_number ASC";
$result_invoices = mysqli_query($mysqli, $sql_invoices);
@@ -565,6 +567,11 @@ if (isset($_POST['add_bulk_payment'])) {
break; // Exit the loop if no payment amount is left
}
// Nothing owed on this one - a zero-value invoice, or one paid without its status catching up
if ($invoice_balance <= 0) {
continue;
}
if ($bulk_payment_amount >= $invoice_balance) {
$payment_amount = $invoice_balance;
$invoice_status = "Paid";

View File

@@ -32,7 +32,7 @@ if (isset($_POST['add_quote'])) {
//Generate a unique URL key for clients to access
$quote_url_key = randomString(32);
mysqli_query($mysqli,"INSERT INTO quotes SET quote_prefix = '$config_quote_prefix', quote_number = $quote_number, quote_scope = '$scope', quote_date = '$date', quote_expire = '$expire', quote_currency_code = '$session_company_currency', quote_category_id = $category, quote_status = 'Draft', quote_url_key = '$quote_url_key', quote_client_id = $client_id");
mysqli_query($mysqli,"INSERT INTO quotes SET quote_prefix = '$config_quote_prefix', quote_number = $quote_number, quote_scope = '$scope', quote_date = '$date', quote_expire = '$expire', quote_discount_amount = $quote_discount, quote_amount = " . (0 - $quote_discount) . ", quote_currency_code = '$session_company_currency', quote_category_id = $category, quote_status = 'Draft', quote_url_key = '$quote_url_key', quote_client_id = $client_id");
$quote_id = mysqli_insert_id($mysqli);
@@ -139,7 +139,7 @@ if (isset($_POST['add_quote_to_invoice'])) {
$sql = mysqli_query($mysqli,"SELECT client_net_terms, quote_amount, quote_category_id, quote_client_id, quote_currency_code,
quote_discount_amount, quote_note, quote_number, quote_prefix, quote_scope FROM clients, quotes WHERE client_id = quote_client_id AND quote_id = $quote_id");
$row = mysqli_fetch_assoc($sql);
$client_net_terms = intval($row['client_net_terms']);
$client_net_terms = intval($row['client_net_terms']) ?: intval($config_default_net_terms);
$quote_prefix = escapeSql($row['quote_prefix']);
$quote_number = escapeSql($row['quote_number']);
$quote_discount_amount = floatval($row['quote_discount_amount']);
@@ -169,7 +169,7 @@ if (isset($_POST['add_quote_to_invoice'])) {
//Generate a unique URL key for clients to access
$url_key = randomString(32);
mysqli_query($mysqli,"INSERT INTO invoices SET invoice_prefix = '$config_invoice_prefix', invoice_number = $invoice_number, invoice_scope = '$quote_scope', invoice_date = '$date', invoice_due = DATE_ADD(CURDATE(), INTERVAL $client_net_terms day), invoice_category_id = $category_id, invoice_status = 'Draft', invoice_discount_amount = $quote_discount_amount, invoice_amount = $quote_amount, invoice_currency_code = '$quote_currency_code', invoice_note = '$quote_note', invoice_url_key = '$url_key', invoice_client_id = $client_id");
mysqli_query($mysqli,"INSERT INTO invoices SET invoice_prefix = '$config_invoice_prefix', invoice_number = $invoice_number, invoice_scope = '$quote_scope', invoice_date = '$date', invoice_due = DATE_ADD('$date', INTERVAL $client_net_terms day), invoice_category_id = $category_id, invoice_status = 'Draft', invoice_discount_amount = $quote_discount_amount, invoice_amount = $quote_amount, invoice_currency_code = '$quote_currency_code', invoice_note = '$quote_note', invoice_url_key = '$url_key', invoice_client_id = $client_id");
$new_invoice_id = mysqli_insert_id($mysqli);
@@ -222,125 +222,6 @@ if (isset($_POST['add_quote_to_invoice'])) {
}
if (isset($_POST['add_quote_item'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$quote_id = intval($_POST['quote_id']);
$name = escapeSql($_POST['name']);
$description = escapeSql($_POST['description']);
$qty = floatval($_POST['qty']);
$price = floatval($_POST['price']);
$tax_id = intval($_POST['tax_id']);
$item_order = intval($_POST['item_order']);
$client_id = intval(getFieldById('quotes', $quote_id, 'quote_client_id'));
enforceClientAccess();
$subtotal = $price * $qty;
if ($tax_id > 0) {
$sql = mysqli_query($mysqli,"SELECT tax_percent FROM taxes WHERE tax_id = $tax_id");
$row = mysqli_fetch_assoc($sql);
$tax_percent = floatval($row['tax_percent']);
$tax_amount = $subtotal * $tax_percent / 100;
}else{
$tax_amount = 0;
}
$total = $subtotal + $tax_amount;
mysqli_query($mysqli,"INSERT INTO quote_items SET item_name = '$name', item_description = '$description', item_quantity = $qty, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_tax_id = $tax_id, item_order = $item_order, item_quote_id = $quote_id");
// Get Quote Details
$sql = mysqli_query($mysqli,"SELECT quote_client_id, quote_discount_amount, quote_number, quote_prefix FROM quotes WHERE quote_id = $quote_id");
$row = mysqli_fetch_assoc($sql);
$quote_prefix = escapeSql($row['quote_prefix']);
$quote_number = escapeSql($row['quote_number']);
$quote_discount_amount = floatval($row['quote_discount_amount']);
$client_id = intval($row['quote_client_id']);
//add up the total of all items
$sql = mysqli_query($mysqli,"SELECT item_total FROM quote_items WHERE item_quote_id = $quote_id");
$quote_amount = 0;
while($row = mysqli_fetch_assoc($sql)) {
$item_total = floatval($row['item_total']);
$quote_amount = $quote_amount + $item_total;
}
$new_quote_amount = $quote_amount - $quote_discount_amount;
mysqli_query($mysqli,"UPDATE quotes SET quote_amount = $new_quote_amount WHERE quote_id = $quote_id");
logAudit("Quote", "Edit", "$session_name added item $name to quote $quote_prefix$quote_number", $client_id, $quote_id);
flashAlert("Item <strong>$name</strong> added");
redirect();
}
if (isset($_POST['edit_quote_item'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$item_id = intval($_POST['item_id']);
$name = escapeSql($_POST['name']);
$description = escapeSql($_POST['description']);
$qty = floatval($_POST['qty']);
$price = floatval($_POST['price']);
$tax_id = intval($_POST['tax_id']);
$product_id = intval($_POST['product_id']);
$subtotal = $price * $qty;
if ($tax_id > 0) {
$sql = mysqli_query($mysqli,"SELECT tax_percent FROM taxes WHERE tax_id = $tax_id");
$row = mysqli_fetch_assoc($sql);
$tax_percent = floatval($row['tax_percent']);
$tax_amount = $subtotal * $tax_percent / 100;
} else {
$tax_amount = 0;
}
$total = $subtotal + $tax_amount;
// Get Quote ID from Item ID
$sql = mysqli_query($mysqli,"SELECT item_quote_id FROM quote_items WHERE item_id = $item_id");
$row = mysqli_fetch_assoc($sql);
$quote_id = intval($row['item_quote_id']);
//Get Discount Amount
$sql = mysqli_query($mysqli,"SELECT quote_client_id, quote_discount_amount, quote_number, quote_prefix FROM quotes WHERE quote_id = $quote_id");
$row = mysqli_fetch_assoc($sql);
$quote_prefix = escapeSql($row['quote_prefix']);
$quote_number = intval($row['quote_number']);
$client_id = intval($row['quote_client_id']);
$quote_discount = floatval($row['quote_discount_amount']);
enforceClientAccess();
mysqli_query($mysqli,"UPDATE quote_items SET item_name = '$name', item_description = '$description', item_quantity = $qty, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_tax_id = $tax_id WHERE item_id = $item_id");
//Update Quote Balances by tallying up items
$sql_quote_total = mysqli_query($mysqli,"SELECT SUM(item_total) AS quote_total FROM quote_items WHERE item_quote_id = $quote_id");
$row = mysqli_fetch_assoc($sql_quote_total);
$new_quote_amount = floatval($row['quote_total']) - $quote_discount;
mysqli_query($mysqli,"UPDATE quotes SET quote_amount = $new_quote_amount WHERE quote_id = $quote_id");
logAudit("Quote", "Edit", "$session_name edited item $name on quote $quote_prefix$quote_number", $client_id, $quote_id);
flashAlert("Item <strong>$name</strong> updated");
redirect();
}
if (isset($_POST['edit_quote'])) {
validateCSRFToken();
@@ -360,16 +241,9 @@ if (isset($_POST['edit_quote'])) {
enforceClientAccess();
//Calculate the new quote amount
$sql = mysqli_query($mysqli,"SELECT item_total FROM quote_items WHERE item_quote_id = $quote_id");
$quote_amount = 0;
while($row = mysqli_fetch_assoc($sql)) {
$item_total = floatval($row['item_total']);
$quote_amount = $quote_amount + $item_total;
}
$quote_amount = $quote_amount - $quote_discount;
mysqli_query($mysqli,"UPDATE quotes SET quote_scope = '$scope', quote_date = '$date', quote_expire = '$expire', quote_discount_amount = $quote_discount, quote_category_id = $category WHERE quote_id = $quote_id");
mysqli_query($mysqli,"UPDATE quotes SET quote_scope = '$scope', quote_date = '$date', quote_expire = '$expire', quote_discount_amount = '$quote_discount', quote_amount = '$quote_amount', quote_category_id = $category WHERE quote_id = $quote_id");
billingRecalc('quote', $quote_id);
logAudit("Quote", "Edit", "$session_name edited quote $quote_prefix$quote_number", $client_id, $quote_id);
@@ -425,44 +299,6 @@ if (isset($_GET['delete_quote'])) {
}
if (isset($_GET['delete_quote_item'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$item_id = intval($_GET['delete_quote_item']);
$sql = mysqli_query($mysqli,"SELECT item_name, item_quote_id, item_subtotal, item_tax, item_total FROM quote_items WHERE item_id = $item_id");
$row = mysqli_fetch_assoc($sql);
$item_name = escapeSql($row['item_name']);
$quote_id = intval($row['item_quote_id']);
$item_subtotal = floatval($row['item_subtotal']);
$item_tax = floatval($row['item_tax']);
$item_total = floatval($row['item_total']);
$sql = mysqli_query($mysqli,"SELECT quote_amount, quote_client_id, quote_number, quote_prefix FROM quotes WHERE quote_id = $quote_id");
$row = mysqli_fetch_assoc($sql);
$quote_prefix = escapeSql($row['quote_prefix']);
$quote_number = escapeSql($row['quote_number']);
$client_id = intval($row['quote_client_id']);
enforceClientAccess();
$new_quote_amount = floatval($row['quote_amount']) - $item_total;
mysqli_query($mysqli,"UPDATE quotes SET quote_amount = $new_quote_amount WHERE quote_id = $quote_id");
mysqli_query($mysqli,"DELETE FROM quote_items WHERE item_id = $item_id");
logAudit("Quote", "Edit", "$session_name removed item $item_name from $quote_prefix$quote_number", $client_id, $quote_id);
flashAlert("Item <strong>$item_name</strong> removed", 'error');
redirect();
}
if (isset($_POST['mark_quote_sent'])) {
validateCSRFToken();
@@ -816,220 +652,15 @@ if (isset($_GET['export_quote_pdf'])) {
enforceUserPermission('module_sales');
$quote_id = intval($_GET['export_quote_pdf']);
$sql = mysqli_query(
$mysqli,
"SELECT client_currency_code, client_id, client_name, client_net_terms, client_website,
contact_email, contact_extension, contact_mobile, contact_mobile_country_code,
contact_phone, contact_phone_country_code, location_address, location_city,
location_country, location_state, location_zip, quote_amount, quote_category_id,
quote_created_at, quote_currency_code, quote_date, quote_discount_amount, quote_expire,
quote_id, quote_note, quote_number, quote_prefix, quote_scope, quote_status, quote_url_key FROM quotes
LEFT JOIN clients ON quote_client_id = client_id
LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1
LEFT JOIN locations ON clients.client_id = locations.location_client_id AND location_primary = 1
WHERE quote_id = $quote_id
" . clientScopeSql('quote_client_id') . "
LIMIT 1"
);
$row = mysqli_fetch_assoc($sql);
$quote_id = intval($row['quote_id']);
$quote_prefix = escapeHtml($row['quote_prefix']);
$quote_number = intval($row['quote_number']);
$quote_scope = escapeHtml($row['quote_scope']);
$quote_status = escapeHtml($row['quote_status']);
$quote_date = escapeHtml($row['quote_date']);
$quote_expire = escapeHtml($row['quote_expire']);
$quote_amount = floatval($row['quote_amount']);
$quote_discount = floatval($row['quote_discount_amount']);
$quote_currency_code = escapeHtml($row['quote_currency_code']);
$quote_note = escapeHtml($row['quote_note']);
$quote_url_key = escapeHtml($row['quote_url_key']);
$quote_created_at = escapeHtml($row['quote_created_at']);
$category_id = intval($row['quote_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;
$quote = billingRow('quote', intval($_GET['export_quote_pdf']));
if (!$quote) {
flashAlert('That quote no longer exists.', 'error');
redirect('quotes.php');
}
$client_id = intval($quote['client_id']);
enforceClientAccess();
$sql = mysqli_query($mysqli, "SELECT company_address, company_city, company_country, company_email, settings.company_id,
company_logo, company_name, company_phone, company_phone_country_code, company_state,
company_website, company_zip FROM companies, settings WHERE companies.company_id = settings.company_id AND companies.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_logo = escapeHtml($row['company_logo']);
//Set Badge color based off of quote status
if ($quote_status == "Sent") {
$quote_badge_color = "warning";
} elseif ($quote_status == "Viewed") {
$quote_badge_color = "primary";
} elseif ($quote_status == "Accepted") {
$quote_badge_color = "success";
} elseif ($quote_status == "Declined") {
$quote_badge_color = "danger";
} elseif ($quote_status == "Invoiced") {
$quote_badge_color = "info";
} else {
$quote_badge_color = "secondary";
}
require_once("../libs/TCPDF/tcpdf.php");
// Start TCPDF
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetMargins(10, 10, 10);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 10);
// Logo + Right Columns
$html = '<table width="100%" cellspacing="0" cellpadding="3">
<tr>
<td width="40%">';
if (!empty($company_logo) && file_exists("../uploads/settings/$company_logo")) {
$html .= '<img src="/uploads/settings/' . $company_logo . '" width="120">';
}
$html .= '</td>
<td width="60%" align="right">
<span style="font-size:18pt; font-weight:bold;">QUOTE</span><br>
<span style="font-size:14pt;">' . $quote_prefix . $quote_number . '</span><br>';
if (strtolower($quote_status) === 'accepted') {
$html .= '<span style="color:green; font-weight:bold;">ACCEPTED</span><br>';
}
if (strtolower($quote_status) === 'declined') {
$html .= '<span style="color:red; font-weight:bold;">DECLINED</span><br>';
}
$html .= '</td>
</tr>
</table><br>';
// Billing titles
$html .= '<table width="100%" cellspacing="0" cellpadding="2">
<tr>
<td width="50%" style="font-size:14pt; font-weight:bold;">' . $company_name . '</td>
<td width="50%" align="right" style="font-size:14pt; font-weight:bold;">' . $client_name . '</td>
</tr>
<tr>
<td style="font-size:10pt; line-height:1.4;">' . nl2br(formatAddress($company_address, $company_city, $company_state, $company_zip, $company_country) . "\n$company_phone\n$company_website") . '</td>
<td style="font-size:10pt; line-height:1.4;" align="right">' . nl2br(formatAddress($location_address, $location_city, $location_state, $location_zip, $location_country) . "\n$contact_email\n$contact_phone") . '</td>
</tr>
</table><br>';
// Date table
$html .= '<table border="0" cellpadding="2" cellspacing="0" width="100%">
<tr>
<td width="60%"></td>
<td width="20%" style="font-size:10pt;"><strong>Date:</strong></td>
<td width="20%" style="font-size:10pt;" align="right">' . $quote_date . '</td>
</tr>
<tr>
<td></td>
<td style="font-size:10pt;"><strong>Expires:</strong></td>
<td style="font-size:10pt;" align="right">' . $quote_expire . '</td>
</tr>
</table><br><br>';
// Items header
$html .= '
<table border="0" cellpadding="5" cellspacing="0" width="100%">
<tr style="background-color:#f0f0f0;">
<th align="left" width="40%"><strong>Item</strong></th>
<th align="center" width="10%"><strong>Qty</strong></th>
<th align="right" width="15%"><strong>Price</strong></th>
<th align="right" width="15%"><strong>Tax</strong></th>
<th align="right" width="20%"><strong>Amount</strong></th>
</tr>';
// Load items
$sub_total = 0;
$total_tax = 0;
$sql_items = mysqli_query($mysqli, "SELECT item_description, item_name, item_price, item_quantity, item_tax, item_total FROM quote_items WHERE item_quote_id = $quote_id ORDER BY item_order ASC");
while ($item = mysqli_fetch_assoc($sql_items)) {
$name = $item['item_name'];
$desc = $item['item_description'];
$qty = $item['item_quantity'];
$price = $item['item_price'];
$tax = $item['item_tax'];
$total = $item['item_total'];
$sub_total += $price * $qty;
$total_tax += $tax;
$html .= '
<tr>
<td><strong>' . $name . '</strong>
<br><span style="font-style:italic; font-size:9pt;">' . nl2br($desc) . '</span>
</td>
<td align="center">' . number_format($qty, 2) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $price, $quote_currency_code) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $tax, $quote_currency_code) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $total, $quote_currency_code) . '</td>
</tr>';
}
$html .= '</table><br><hr><br><br>';
// Totals
$html .= '<table width="100%" cellspacing="0" cellpadding="4">
<tr>
<td width="60%"><i style="font-size:9pt;">' . nl2br($quote_note) . '</i></td>
<td width="40%">
<table width="100%" cellpadding="3" cellspacing="0">
<tr><td>Subtotal:</td><td align="right">' . numfmt_format_currency($currency_format, $sub_total, $quote_currency_code) . '</td></tr>';
if ($quote_discount > 0) {
$html .= '<tr><td>Discount:</td><td align="right">-' . numfmt_format_currency($currency_format, $quote_discount, $quote_currency_code) . '</td></tr>';
}
if ($total_tax > 0) {
$html .= '<tr><td>Tax:</td><td align="right">' . numfmt_format_currency($currency_format, $total_tax, $quote_currency_code) . '</td></tr>';
}
$html .= '
<tr><td><h3><strong>Total:</strong></h3></td><td align="right"><h3><strong>' . numfmt_format_currency($currency_format, $quote_amount, $quote_currency_code) . '</strong></h3></td></tr>
</table>
</td>
</tr>
</table><br><br>';
// Footer
$html .= '<div style="text-align:center; font-size:9pt; color:gray;">' . nl2br($config_quote_footer) . '</div>';
$pdf->writeHTML($html, true, false, true, false, '');
$filename = preg_replace('/[^A-Za-z0-9_\-]/', '_', "{$quote_date}_{$company_name}_{$client_name}_Quote_{$quote_prefix}{$quote_number}");
$pdf->Output("$filename.pdf", 'I');
exit;
billingPdfSend(billingPdf('quote', $quote));
}

View File

@@ -4,7 +4,7 @@ defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
$date = escapeSql($_POST['date']);
$expire = escapeSql($_POST['expire']);
$category = intval($_POST['category']);
$scope = escapeSql($_POST['scope']);
$quote_discount = floatval($_POST['quote_discount']);
$scope = escapeSql($_POST['scope'] ?? '');
$quote_discount = round(floatval($_POST['quote_discount'] ?? 0), 2);
$config_quote_prefix = escapeSql($config_quote_prefix);

View File

@@ -83,6 +83,8 @@ if (isset($_POST['add_recurring_invoice'])) {
$start_date = escapeSql($_POST['start_date']);
$category = intval($_POST['category']);
$scope = escapeSql($_POST['scope']);
$recurring_invoice_discount = round(floatval($_POST['recurring_invoice_discount'] ?? 0), 2);
$auto_send = intval($_POST['auto_send'] ?? 1) ? 1 : 0;
enforceClientAccess();
@@ -97,7 +99,7 @@ if (isset($_POST['add_recurring_invoice'])) {
$recurring_invoice_number = mysqli_insert_id($mysqli);
mysqli_query($mysqli,"INSERT INTO recurring_invoices SET recurring_invoice_prefix = '$config_recurring_invoice_prefix', recurring_invoice_number = $recurring_invoice_number, recurring_invoice_scope = '$scope', recurring_invoice_frequency = '$frequency', recurring_invoice_next_date = '$start_date', recurring_invoice_category_id = $category, recurring_invoice_status = 1, recurring_invoice_currency_code = '$session_company_currency', recurring_invoice_client_id = $client_id");
mysqli_query($mysqli,"INSERT INTO recurring_invoices SET recurring_invoice_prefix = '$config_recurring_invoice_prefix', recurring_invoice_number = $recurring_invoice_number, recurring_invoice_scope = '$scope', recurring_invoice_frequency = '$frequency', recurring_invoice_next_date = '$start_date', recurring_invoice_category_id = $category, recurring_invoice_status = 1, recurring_invoice_discount_amount = $recurring_invoice_discount, recurring_invoice_amount = " . (0 - $recurring_invoice_discount) . ", recurring_invoice_auto_send = $auto_send, recurring_invoice_currency_code = '$session_company_currency', recurring_invoice_client_id = $client_id");
$recurring_invoice_id = mysqli_insert_id($mysqli);
@@ -135,18 +137,11 @@ if (isset($_POST['edit_recurring_invoice'])) {
enforceClientAccess();
//Calculate new total
$sql = mysqli_query($mysqli,"SELECT item_total FROM recurring_invoice_items WHERE item_recurring_invoice_id = $recurring_invoice_id");
$recurring_invoice_amount = 0;
while($row = mysqli_fetch_assoc($sql)) {
$item_total = floatval($row['item_total']);
$recurring_invoice_amount = $recurring_invoice_amount + $item_total;
}
$recurring_invoice_amount = $recurring_invoice_amount - $recurring_invoice_discount;
mysqli_query($mysqli,"UPDATE recurring_invoices SET recurring_invoice_scope = '$scope', recurring_invoice_frequency = '$frequency', recurring_invoice_next_date = '$next_date', recurring_invoice_category_id = $category, recurring_invoice_discount_amount = $recurring_invoice_discount, recurring_invoice_auto_send = $auto_send, recurring_invoice_status = $status WHERE recurring_invoice_id = $recurring_invoice_id");
mysqli_query($mysqli,"UPDATE recurring_invoices SET recurring_invoice_scope = '$scope', recurring_invoice_frequency = '$frequency', recurring_invoice_next_date = '$next_date', recurring_invoice_category_id = $category, recurring_invoice_discount_amount = $recurring_invoice_discount, recurring_invoice_amount = $recurring_invoice_amount, recurring_invoice_auto_send = $auto_send, recurring_invoice_status = $status WHERE recurring_invoice_id = $recurring_invoice_id");
billingRecalc('recurring', $recurring_invoice_id);
mysqli_query($mysqli,"INSERT INTO history SET history_status = '$status', history_description = 'Recurring Invoice edited', history_recurring_invoice_id = $recurring_invoice_id");
mysqli_query($mysqli,"INSERT INTO history SET history_status = '" . ($status ? 'Active' : 'Paused') . "', history_description = 'Edited by $session_name', history_recurring_invoice_id = $recurring_invoice_id");
logAudit("Recurring Invoice", "Edit", "$session_name edited recurring invoice $recurring_invoice_prefix$recurring_invoice_number - $scope", $client_id, $recurring_invoice_id);
@@ -176,6 +171,9 @@ if (isset($_GET['delete_recurring_invoice'])) {
mysqli_query($mysqli,"DELETE FROM recurring_invoices WHERE recurring_invoice_id = $recurring_invoice_id");
// Its autopay goes with it - the nightly run would otherwise keep a card set up for nothing
mysqli_query($mysqli,"DELETE FROM recurring_payments WHERE recurring_payment_recurring_invoice_id = $recurring_invoice_id");
//Delete Items Associated with the Recurring
$sql = mysqli_query($mysqli,"SELECT item_id FROM recurring_invoice_items WHERE item_recurring_invoice_id = $recurring_invoice_id");
while($row = mysqli_fetch_assoc($sql)) {
@@ -198,167 +196,6 @@ if (isset($_GET['delete_recurring_invoice'])) {
}
if (isset($_POST['add_recurring_invoice_item'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$recurring_invoice_id = intval($_POST['recurring_invoice_id']);
$name = escapeSql($_POST['name']);
$description = escapeSql($_POST['description']);
$qty = floatval($_POST['qty']);
$price = floatval($_POST['price']);
$tax_id = intval($_POST['tax_id']);
$item_order = intval($_POST['item_order']);
$client_id = intval(getFieldById('recurring_invoices', $recurring_invoice_id, 'recurring_invoice_client_id'));
enforceClientAccess();
$subtotal = $price * $qty;
if ($tax_id > 0) {
$sql = mysqli_query($mysqli,"SELECT tax_percent FROM taxes WHERE tax_id = $tax_id");
$row = mysqli_fetch_assoc($sql);
$tax_percent = floatval($row['tax_percent']);
$tax_amount = $subtotal * $tax_percent / 100;
} else {
$tax_amount = 0;
}
$total = $subtotal + $tax_amount;
mysqli_query($mysqli,"INSERT INTO recurring_invoice_items SET item_name = '$name', item_description = '$description', item_quantity = $qty, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_tax_id = $tax_id, item_order = $item_order, item_recurring_invoice_id = $recurring_invoice_id");
$sql = mysqli_query($mysqli,"SELECT recurring_invoice_client_id, recurring_invoice_discount_amount, recurring_invoice_number,
recurring_invoice_prefix FROM recurring_invoices WHERE recurring_invoice_id = $recurring_invoice_id");
$row = mysqli_fetch_assoc($sql);
$recurring_invoice_discount = floatval($row['recurring_invoice_discount_amount']);
$recurring_invoice_prefix = escapeSql($row['recurring_invoice_prefix']);
$recurring_invoice_number = intval($row['recurring_invoice_number']);
$client_id = intval($row['recurring_invoice_client_id']);
//add up all the items
$sql = mysqli_query($mysqli,"SELECT item_total FROM recurring_invoice_items WHERE item_recurring_invoice_id = $recurring_invoice_id");
$recurring_invoice_amount = 0;
while($row = mysqli_fetch_assoc($sql)) {
$item_total = floatval($row['item_total']);
$recurring_invoice_amount = $recurring_invoice_amount + $item_total;
}
$recurring_invoice_amount = $recurring_invoice_amount - $recurring_invoice_discount;
mysqli_query($mysqli,"UPDATE recurring_invoices SET recurring_invoice_amount = $recurring_invoice_amount WHERE recurring_invoice_id = $recurring_invoice_id");
logAudit("Recurring Invoice", "Edit", "$session_name added item $name to recurring invoice $recurring_invoice_prefix$recurring_invoice_number", $client_id, $recurring_invoice_id);
flashAlert("Item <strong>$name</strong> added to Recurring Invoice");
redirect();
}
if (isset($_POST['edit_recurring_invoice_item'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$item_id = intval($_POST['item_id']);
$name = escapeSql($_POST['name']);
$description = escapeSql($_POST['description']);
$qty = floatval($_POST['qty']);
$price = floatval($_POST['price']);
$tax_id = intval($_POST['tax_id']);
$product_id = intval($_POST['product_id']);
$subtotal = $price * $qty;
if ($tax_id > 0) {
$sql = mysqli_query($mysqli,"SELECT tax_percent FROM taxes WHERE tax_id = $tax_id");
$row = mysqli_fetch_assoc($sql);
$tax_percent = floatval($row['tax_percent']);
$tax_amount = $subtotal * $tax_percent / 100;
} else {
$tax_amount = 0;
}
$total = $subtotal + $tax_amount;
// Get Recurring_invoice_id from item_id
$sql = mysqli_query($mysqli,"SELECT item_recurring_invoice_id FROM recurring_invoice_items WHERE item_id = $item_id");
$row = mysqli_fetch_assoc($sql);
$recurring_invoice_id = intval($row['item_recurring_invoice_id']);
//Get Discount Amount
$sql = mysqli_query($mysqli,"SELECT recurring_invoice_client_id, recurring_invoice_discount_amount, recurring_invoice_number,
recurring_invoice_prefix FROM recurring_invoices WHERE recurring_invoice_id = $recurring_invoice_id");
$row = mysqli_fetch_assoc($sql);
$recurring_invoice_prefix = escapeSql($row['recurring_invoice_prefix']);
$recurring_invoice_number = intval($row['recurring_invoice_number']);
$client_id = intval($row['recurring_invoice_client_id']);
$recurring_invoice_discount = floatval($row['recurring_invoice_discount_amount']);
enforceClientAccess();
mysqli_query($mysqli,"UPDATE recurring_invoice_items SET item_name = '$name', item_description = '$description', item_quantity = $qty, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_tax_id = $tax_id WHERE item_id = $item_id");
//Update Invoice Balances by tallying up invoice items
$sql_recurring_invoice_total = mysqli_query($mysqli,"SELECT SUM(item_total) AS recurring_invoice_total FROM recurring_invoice_items WHERE item_recurring_invoice_id = $recurring_invoice_id");
$row = mysqli_fetch_assoc($sql_recurring_invoice_total);
$new_recurring_invoice_amount = floatval($row['recurring_invoice_total']) - $recurring_invoice_discount;
mysqli_query($mysqli,"UPDATE recurring_invoices SET recurring_invoice_amount = $new_recurring_invoice_amount WHERE recurring_invoice_id = $recurring_invoice_id");
// Logging
logAudit("Recurring Invoice", "Edit", "$session_name edited item $name on recurring invoice $recurring_invoice_prefix$recurring_invoice_number", $client_id, $recurring_invoice_id);
flashAlert("Item <strong>$name</strong> updated");
redirect();
}
if (isset($_GET['delete_recurring_invoice_item'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$item_id = intval($_GET['delete_recurring_invoice_item']);
$sql = mysqli_query($mysqli,"SELECT item_name, item_recurring_invoice_id, item_subtotal, item_tax, item_total FROM recurring_invoice_items WHERE item_id = $item_id");
$row = mysqli_fetch_assoc($sql);
$recurring_invoice_id = intval($row['item_recurring_invoice_id']);
$item_name = escapeSql($row['item_name']);
$item_subtotal = floatval($row['item_subtotal']);
$item_tax = floatval($row['item_tax']);
$item_total = floatval($row['item_total']);
$sql = mysqli_query($mysqli,"SELECT recurring_invoice_amount, recurring_invoice_client_id, recurring_invoice_number,
recurring_invoice_prefix FROM recurring_invoices WHERE recurring_invoice_id = $recurring_invoice_id");
$row = mysqli_fetch_assoc($sql);
$recurring_invoice_prefix = escapeSql($row['recurring_invoice_prefix']);
$recurring_invoice_number = intval($row['recurring_invoice_number']);
$client_id = intval($row['recurring_invoice_client_id']);
enforceClientAccess();
$new_recurring_invoice_amount = floatval($row['recurring_invoice_amount']) - $item_total;
mysqli_query($mysqli,"UPDATE recurring_invoices SET recurring_invoice_amount = $new_recurring_invoice_amount WHERE recurring_invoice_id = $recurring_invoice_id");
mysqli_query($mysqli,"DELETE FROM recurring_invoice_items WHERE item_id = $item_id");
logAudit("Recurring Invoice", "Edit", "$session_name removed item $item_name from recurring invoice $recurring_invoice_prefix$recurring_invoice_number", $client_id);
flashAlert("Item <strong>$item_name</strong> removed", 'error');
redirect();
}
if (isset($_GET['force_recurring'])) {
validateCSRFToken();

View File

@@ -1,670 +1,309 @@
<?php
/*
* Quote - one quote, from draft to answer to invoice.
*
* The header says where it stands - its status, and how long it has left
* (or that it ran out) while it waits for an answer - with the next thing
* to do: send a draft, record the client's answer, turn an accepted quote
* into an invoice. The quote itself is on the left as the client sees it,
* its lines edited in place until it is answered. On the right: what it
* comes to, the ticket it was raised from, files the client sent back with
* their answer, and its history.
*/
// If client_id is in URI then show client Side Bar and client header
if (isset($_GET['client_id'])) {
require_once "includes/inc_all_client.php";
$client_url = "client_id=$client_id&";
} else {
require_once "includes/inc_all.php";
$client_url = '';
}
// Perms
enforceUserPermission('module_sales');
if (isset($_GET['quote_id'])) {
$quote_id = intval($_GET['quote_id'] ?? 0);
$quote = billingRow('quote', $quote_id);
$quote_id = intval($_GET['quote_id']);
$sql = mysqli_query(
$mysqli,
"SELECT client_currency_code, client_id, client_name, client_net_terms, client_website,
contact_email, contact_extension, contact_mobile, contact_mobile_country_code,
contact_phone, contact_phone_country_code, location_address, location_city,
location_country, location_state, location_zip, quote_amount, quote_category_id,
quote_created_at, quote_currency_code, quote_date, quote_discount_amount, quote_expire,
quote_id, quote_note, quote_number, quote_prefix, quote_scope, quote_status, quote_url_key FROM quotes
LEFT JOIN clients ON quote_client_id = client_id
LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1
LEFT JOIN locations ON clients.client_id = locations.location_client_id AND location_primary = 1
WHERE quote_id = $quote_id
" . clientScopeSql('quote_client_id') . "
LIMIT 1"
);
if (mysqli_num_rows($sql) == 0) {
if (isset($_GET['client_id'])) {
$backlink_append = "?client_id=$client_id";
} else {
$backlink_append = '';
}
echo "<h1 class='text-secondary pt-5' style='text-align: center'>There is no Quote here<br><small><a href='quotes.php$backlink_append'><i class='fas fa-arrow-left me-2'></i>Back to Quotes</a></small></h1>";
require_once "../includes/footer.php";
exit();
}
$row = mysqli_fetch_assoc($sql);
$quote_id = intval($row['quote_id']);
$quote_prefix = escapeHtml($row['quote_prefix']);
$quote_number = intval($row['quote_number']);
$quote_scope = escapeHtml($row['quote_scope']);
$quote_status = escapeHtml($row['quote_status']);
$quote_date = escapeHtml($row['quote_date']);
$quote_expire = escapeHtml($row['quote_expire']);
$quote_amount = floatval($row['quote_amount']);
$quote_discount = floatval($row['quote_discount_amount']);
$quote_currency_code = escapeHtml($row['quote_currency_code']);
$quote_note = escapeHtml($row['quote_note']);
$quote_url_key = escapeHtml($row['quote_url_key']);
$quote_created_at = escapeHtml($row['quote_created_at']);
$category_id = intval($row['quote_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 only be used in the tab title
$tab_title = $row['client_name'];
$page_title = "{$row['quote_prefix']}{$row['quote_number']}";
$sql = mysqli_query($mysqli, "SELECT company_address, company_city, company_country, company_email, settings.company_id,
company_logo, company_name, company_phone, company_phone_country_code, company_state,
company_website, company_zip FROM companies, settings WHERE companies.company_id = settings.company_id AND companies.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_logo = escapeHtml($row['company_logo']);
// Must use the same rule as the Send Email picker in
// modals/quote/quote_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('quote')));
$emailable_contacts = intval($row['emailable_contacts']);
$sql_history = mysqli_query($mysqli, "SELECT history_created_at, history_description, history_status FROM history WHERE history_quote_id = $quote_id ORDER BY history_id DESC");
//Set Badge color based off of quote status
if ($quote_status == "Sent") {
$quote_badge_color = "warning";
} elseif ($quote_status == "Viewed") {
$quote_badge_color = "primary";
} elseif ($quote_status == "Accepted") {
$quote_badge_color = "success";
} elseif ($quote_status == "Declined") {
$quote_badge_color = "danger";
} elseif ($quote_status == "Invoiced") {
$quote_badge_color = "info";
} else {
$quote_badge_color = "secondary";
}
//Product autocomplete
$json_products = getProductsForAutocomplete($mysqli);
// Quote File Attachments
$sql_quote_files = mysqli_query(
$mysqli,
"SELECT files.file_id, file_name, file_ext, file_size, file_created_at FROM quote_files JOIN files ON quote_files.file_id = files.file_id WHERE quote_id = $quote_id AND file_archived_at IS NULL ORDER BY file_name ASC"
);
?>
<ol class="breadcrumb d-print-none">
<li class="breadcrumb-item">
<a href="quotes.php">All Quotes</a>
</li>
<li class="breadcrumb-item">
<a href="quotes.php?client_id=<?= $client_id ?>"><?= $client_name ?> Quotes</a>
</li>
<li class="breadcrumb-item active"><?= "$quote_prefix$quote_number" ?></li>
</ol>
<div class="card mb-3">
<div class="card-header d-print-none">
<?php if (lookupUserPermission("module_sales") >= 2) { ?>
<div class="row">
<div class="col-8">
<?php if ($quote_status == 'Draft') { ?>
<button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-paper-plane me-2"></i>Send
</button>
<div class="dropdown-menu">
<?php if (!empty($config_smtp_provider) && $emailable_contacts > 0) { ?>
<button type="submit" class="dropdown-item confirm-link" form="quickSendQuote"
data-confirm-title="Send this quote now?"
data-confirm-text="It goes to the default contacts without opening the picker."
data-confirm-button="Send"
name="quote_id" value="<?= $quote_id ?>">
<i class="fas fa-fw fa-bolt me-2"></i>Quick Send
</button>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/quote/quote_email.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-fw fa-paper-plane me-2"></i>Send Email<span class="text-muted">...</span>
</a>
<div class="dropdown-divider"></div>
<?php } ?>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/quote/quote_mark_sent.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-fw fa-check me-2"></i>Mark Sent
</a>
</div>
<?php } ?>
<?php if ($quote_status == 'Sent' || $quote_status == 'Viewed') { ?>
<a class="btn btn-primary confirm-link" href="post.php?accept_quote=<?= $quote_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-thumbs-up me-2"></i>Accept
</a>
<a class="btn btn-default confirm-link" href="post.php?decline_quote=<?= $quote_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-thumbs-down me-2"></i>Decline
</a>
<?php } ?>
<?php if ($quote_status == 'Accepted') { ?>
<div class="btn-group fix-quote-dropdown">
<button type="button" class="btn btn-primary ajax-modal"
data-modal-url="modals/quote/quote_to_invoice.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-check me-2"></i>Invoice
</button>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-icon" data-bs-toggle="dropdown" aria-expanded="false">
<span class="visually-hidden">Toggle Dropdown</span>
</button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item" href="post.php?mark_quote_invoiced=<?= $quote_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-check me-2"></i>Mark Invoiced
</a>
</div>
</div>
<?php } ?>
</div>
<div class="col-4">
<div class="dropdown dropstart text-center float-end">
<button class="btn btn-secondary" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/quote/quote_edit.php?id=<?= $quote_id ?>">
<i class="fa fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<?php if (lookupUserPermission("module_sales") >= 2) { ?>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/quote/quote_copy.php?id=<?= $quote_id ?>">
<i class="fa fa-fw fa-copy text-secondary me-2"></i>Copy
</a>
<?php } ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#" onclick="window.print();">
<i class="fa fa-fw fa-print text-secondary me-2"></i>Print
</a>
<a class="dropdown-item" href="post.php?export_quote_pdf=<?= $quote_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" target="_blank">
<i class="fa fa-fw fa-download text-secondary me-2"></i>Download PDF
</a>
<?php if (!empty($config_smtp_provider) && $emailable_contacts > 0) { ?>
<button type="submit" class="dropdown-item confirm-link" form="quickSendQuote"
data-confirm-title="Send this quote now?"
data-confirm-text="It goes to the default contacts without opening the picker."
data-confirm-button="Send"
name="quote_id" value="<?= $quote_id ?>">
<i class="fa fa-fw fa-bolt text-secondary me-2"></i>Quick Send
</button>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/quote/quote_email.php?quote_id=<?= $quote_id ?>">
<i class="fa fa-fw fa-paper-plane text-secondary me-2"></i>Send Email<span class="text-muted">...</span>
</a>
<?php } ?>
<a class="dropdown-item clipboardjs" href="#" data-clipboard-text="https://<?= $config_base_url ?>/guest/guest_view_quote.php?quote_id=<?= "$quote_id&url_key=$quote_url_key" ?>">
<i class="fa fa-fw fa-copy text-secondary me-2"></i>Copy Guest URL
</a>
<?php if (lookupUserPermission("module_sales") >= 3) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_quote=<?= $quote_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fa fa-fw fa-times me-2"></i>Delete
</a>
<?php } ?>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
<div class="card-body">
<div class="row mb-3">
<?php if (file_exists("../uploads/settings/$company_logo")) { ?>
<div class="col-sm-2">
<img class="img-fluid" src="<?= "../uploads/settings/$company_logo" ?>" alt="Company logo">
</div>
<?php } ?>
<div class="col-sm-6 <?php if (!file_exists("../uploads/settings/$company_logo")) { echo "col-sm-8"; } ?>">
<ul class="list-unstyled">
<li><h4><strong><?= $company_name ?></strong></h4></li>
<li><?= formatAddress($company_address, $company_city, $company_state, $company_zip, $company_country, '<br>') ?></li>
<li><?= "$company_email | $company_phone" ?></li>
<li><?= $company_website ?></li>
</ul>
</div>
<div class="col-sm-4">
<h3 class="text-end"><strong>QUOTE</strong></h3>
<h5 class="badge text-bg-<?= $quote_badge_color ?> p-2 float-end">
<?= "$quote_status" ?>
</h5>
<table class="table table-sm table-borderless">
<tr>
<th>Quote #:</th>
<td class="text-end"><?= "$quote_prefix$quote_number" ?></td>
</tr>
<tr>
<th>Date:</th>
<td class="text-end"><?= $quote_date ?></td>
</tr>
<tr>
<th>Expires:</th>
<td class="text-end"><?= $quote_expire ?></td>
</tr>
</table>
</div>
</div>
<div class="row mb-3 bg-light p-3">
<div class="col">
<h6><strong>To:</strong></h6>
<ul class="list-unstyled mb-0">
<li><?= $client_name ?></li>
<li><?= formatAddress($location_address, $location_city, $location_state, $location_zip, $location_country, '<br>') ?></li>
<li><?= "$contact_email | $contact_phone $contact_extension" ?></li>
</ul>
</div>
</div>
<?php $sql_items = mysqli_query($mysqli, "SELECT item_created_at, item_description, item_id, item_name, item_price, item_quantity, item_tax,
item_tax_id, item_total FROM quote_items WHERE item_quote_id = $quote_id ORDER BY item_order ASC"); ?>
<div class="row mb-3">
<div class="col-md-12">
<div class="card">
<div class="table-responsive">
<table class="table table-hover mb-0" id="items">
<thead class="bg-light">
<tr>
<th class="d-print-none"></th>
<th>Item</th>
<th>Description</th>
<th class="text-center">Qty</th>
<th class="text-end">Unit Price</th>
<th class="text-end">Tax</th>
<th class="text-end">Amount</th>
</tr>
</thead>
<tbody>
<?php
$total_tax = 0.00;
$sub_total = 0.00;
while ($row = mysqli_fetch_assoc($sql_items)) {
$item_id = intval($row['item_id']);
$item_name = escapeHtml($row['item_name']);
$item_description = escapeHtml($row['item_description']);
$item_quantity = floatval($row['item_quantity']);
$item_price = floatval($row['item_price']);
$item_tax = floatval($row['item_tax']);
$item_total = floatval($row['item_total']);
$item_created_at = escapeHtml($row['item_created_at']);
$tax_id = intval($row['item_tax_id']);
$total_tax = $item_tax + $total_tax;
$sub_total = $item_price * $item_quantity + $sub_total;
?>
<tr data-item-id="<?= $item_id ?>">
<td class="d-print-none">
<?php if ($quote_status !== "Invoiced" && $quote_status !== "Accepted" && $quote_status !== "Declined" && lookupUserPermission("module_sales") >= 2) { ?>
<div class="btn-group">
<button type="button" class="btn btn-sm btn-link drag-handle" title="Drag to reorder">
<i class="fas fa-bars text-muted"></i>
</button>
<div class="dropdown">
<button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/quote/quote_item_edit.php?id=<?= $item_id ?>">
<i class="fa fa-fw fa-edit me-2"></i>Edit
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger confirm-link" href="post.php?delete_quote_item=<?= $item_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fa fa-fw fa-trash me-2"></i>Delete
</a>
</div>
</div>
</div>
<?php } ?>
</td>
<td><?= $item_name ?></td>
<td><?= nl2br($item_description) ?></td>
<td class="text-center"><?= number_format($item_quantity, 2) ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_price, $quote_currency_code) ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_tax, $quote_currency_code) ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_total, $quote_currency_code) ?></td>
</tr>
<?php
}
?>
<tr class="d-print-none" <?php if ($quote_status == "Invoiced" || $quote_status == "Accepted" || $quote_status == "Declined" || lookupUserPermission("module_sales") <= 1) {
echo "hidden";
} ?>>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="quote_id" value="<?= $quote_id ?>">
<input type="hidden" id="product_id" name="product_id" value="0">
<input type="hidden" name="item_order" value="<?php
//find largest order number and add 1
$sql = mysqli_query($mysqli, "SELECT MAX(item_order) AS item_order FROM quote_items WHERE item_quote_id = $quote_id");
$row = mysqli_fetch_assoc($sql);
$item_order = intval($row['item_order']) + 1;
echo $item_order;
?>">
<td></td>
<td>
<input type="text" class="form-control" name="name" id="name" placeholder="Item" maxlength="200" required>
</td>
<td>
<textarea class="form-control" rows="2" name="description" id="desc" placeholder="Enter a Description"></textarea>
</td>
<td>
<input type="text" class="form-control" inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}" id="qty" style="text-align: center;" name="qty" placeholder="Qty">
</td>
<td>
<input type="text" class="form-control" inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}" id="price" style="text-align: right;" name="price" placeholder="Price (<?= $quote_currency_code ?>)">
</td>
<td>
<select class="form-select select2" id="tax" name="tax_id" required>
<option value="0">No Tax</option>
<?php
$taxes_sql = mysqli_query($mysqli, "SELECT tax_id, tax_name, tax_percent FROM taxes WHERE tax_archived_at IS NULL ORDER BY tax_name ASC");
while ($row = mysqli_fetch_assoc($taxes_sql)) {
$tax_id = intval($row['tax_id']);
$tax_name = escapeHtml($row['tax_name']);
$tax_percent = floatval($row['tax_percent']);
?>
<option value="<?= $tax_id ?>"><?= "$tax_name $tax_percent%" ?></option>
<?php
}
?>
</select>
</td>
<td class="text-center">
<button class="btn btn-light text-success" title="Add item" type="submit" name="add_quote_item">
<i class="fa fa-check"></i>
</button>
</td>
</form>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-sm-7">
<div class="card">
<div class="card-header text-bold">
Notes:
<span class="d-print-none" data-note-status-for="quoteNotes"></span>
</div>
<div class="card-body p-2">
<?php if (lookupUserPermission("module_sales") >= 2) { ?>
<textarea class="form-control itflow-inline-note d-print-none" rows="6"
id="quoteNotes"
placeholder="Enter some notes"
data-endpoint="quote_set_notes"
data-id-field="quote_id"
data-id="<?= $quote_id ?>"
data-csrf="<?= $_SESSION['csrf_token'] ?>"><?= $quote_note ?></textarea>
<?php } else { ?>
<div class="d-print-none"><?= nl2br($quote_note) ?></div>
<?php } ?>
<!-- Printed output must be plain text, not a form control -->
<div class="d-none d-print-block"><?= nl2br($quote_note) ?></div>
</div>
</div>
</div>
<div class="col-sm-3 offset-sm-2">
<table class="table table-hover mb-0">
<tbody>
<tr>
<td>Subtotal:</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $sub_total, $quote_currency_code) ?></td>
</tr>
<?php if ($quote_discount > 0) { ?>
<tr>
<td>Discount:</td>
<td class="text-end">-<?= numfmt_format_currency($currency_format, $quote_discount, $quote_currency_code) ?></td>
</tr>
<?php } ?>
<?php if ($total_tax > 0) { ?>
<tr>
<td>Tax:</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $total_tax, $quote_currency_code) ?></td>
</tr>
<?php } ?>
<tr class="h5 text-bold">
<td>Total:</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $quote_amount, $quote_currency_code) ?></td>
</tr>
</tbody>
</table>
</div>
</div>
<hr class="d-none d-print-block mt-5">
<div class="d-none d-print-block text-center"><?= nl2br(escapeHtml($config_quote_footer)) ?></div>
</div>
</div>
<?php if (mysqli_num_rows($sql_quote_files) > 0) { ?>
<div class="row mb-3">
<div class="col-sm d-print-none">
<div class="card">
<div class="card-header text-bold">
<i class="fa fa-paperclip me-2"></i>Attachments
<div class="card-tools">
<button type="button" class="btn btn-tool" title="Show/hide" data-lte-toggle="card-collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" title="Hide" data-lte-toggle="card-remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
<?php /* Through the file quick look and agent/file.php, which check access -
not a link straight into the uploads folder */ ?>
<table class="table table-hover align-middle mb-0">
<thead class="table-light">
<tr>
<th>File</th>
<th>Uploaded</th>
<th></th>
</tr>
</thead>
<tbody>
<?php while ($quote_file = mysqli_fetch_assoc($sql_quote_files)) {
$quote_file_id = intval($quote_file['file_id']); ?>
<tr>
<td>
<div class="d-flex align-items-center gap-2">
<?= fileTypeTile($quote_file['file_ext'], 'sm') ?>
<a class="ajax-modal text-break" href="#" data-modal-size="lg" data-modal-url="modals/file/file.php?id=<?= $quote_file_id ?>"><?= escapeHtml($quote_file['file_name']) ?></a>
<span class="small text-body-secondary text-nowrap"><?= formatBytes(intval($quote_file['file_size'])) ?></span>
</div>
</td>
<td class="small text-nowrap" title="<?= escapeHtml($quote_file['file_created_at']) ?>"><?= timeAgo($quote_file['file_created_at']) ?></td>
<td class="text-end"><a class="btn btn-sm btn-light" href="file.php?file_id=<?= $quote_file_id ?>" title="Download"><i class="fas fa-fw fa-download"></i></a></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php } ?>
<div class="row mb-3">
<div class="col-sm d-print-none">
<div class="card">
<div class="card-header text-bold">
<i class="fa fa-history me-2"></i>History
<div class="card-tools">
<button type="button" class="btn btn-tool" title="Show/hide" data-lte-toggle="card-collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" title="Hide" data-lte-toggle="card-remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Status</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql_history)) {
$history_created_at = escapeHtml($row['history_created_at']);
$history_status = escapeHtml($row['history_status']);
$history_description = nl2br(escapeHtml($row['history_description']));
?>
<tr>
<td><?= $history_created_at ?></td>
<td><?= $history_status ?></td>
<td><?= $history_description ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php if (lookupUserPermission("module_sales") >= 2 && !empty($config_smtp_provider) && $emailable_contacts > 0) { ?>
<?php
/*
* One hidden form for the page, targeted by the Quick Send buttons via
* their form="" attribute, so a button can sit inside a dropdown
* without needing a form of its own. The button carries the id as its
* own name/value, which a submit button contributes to the submission.
*
* Must stay inside this block - $emailable_contacts is only set on the
* path where the document was found.
*/
?>
<form id="quickSendQuote" action="post.php" method="post" class="d-none">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="email_quote" value="1">
<input type="hidden" name="quick_send" value="1">
</form>
<?php } ?>
<?php
if (!$quote || ($client_url && intval($quote['client_id']) !== intval($client_id))) {
billingNotFound('quote', $client_url);
require_once "../includes/footer.php";
exit;
}
$client_id = intval($quote['client_id']);
enforceClientAccess();
$number = billingNumber('quote', $quote);
$status = (string) $quote['quote_status'];
$currency = (string) $quote['quote_currency_code'];
$money = function ($amount) use ($currency) {
return escapeHtml(billingMoney($amount, $currency));
};
$items = billingItems('quote', $quote_id);
$totals = billingTotals('quote', $quote, $items);
$history = billingHistory('quote', $quote_id);
$expired = quoteExpired($quote);
$awaiting = in_array($status, ['Sent', 'Viewed'], true);
$can_edit = lookupUserPermission('module_sales') >= 2;
$can_delete = lookupUserPermission('module_sales') >= 3;
$can_edit_lines = billingCanEditItems('quote', $quote);
$mail_ready = !empty($config_smtp_provider) && billingEmailableContacts('quote', $client_id) > 0;
$guest_url = billingGuestUrl('quote', $quote);
$csrf = $_SESSION['csrf_token'];
// The ticket it was raised from, and what the client sent back with their answer
$ticket = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject FROM tickets WHERE ticket_quote_id = $quote_id LIMIT 1"));
$files = [];
$sql = mysqli_query($mysqli, "SELECT files.file_id, file_name, file_ext, file_size, file_created_at FROM quote_files JOIN files ON quote_files.file_id = files.file_id
WHERE quote_id = $quote_id AND file_archived_at IS NULL ORDER BY file_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$files[] = $row;
}
// Override Tab Title // No Sanitizing needed as this var will only be used in the tab title
$tab_title = $quote['client_name'];
$page_title = $number;
$paper = [
'type' => 'quote',
'row' => $quote,
'items' => $items,
'totals' => $totals,
'edit' => $can_edit_lines,
'notes_edit' => $can_edit,
'taxes' => $can_edit_lines ? billingTaxes($quote['quote_created_at']) : [],
'logo_url' => billingCompany()['logo_url'],
'csrf' => $csrf,
];
?>
<ol class="breadcrumb d-print-none">
<li class="breadcrumb-item"><a href="client_overview.php?client_id=<?= $client_id ?>"><?= escapeHtml($quote['client_name']) ?></a></li>
<li class="breadcrumb-item"><a href="quotes.php?client_id=<?= $client_id ?>">Quotes</a></li>
<li class="breadcrumb-item active"><?= escapeHtml($number) ?></li>
</ol>
<!-- What it is, where it stands, and the next thing to do -->
<div class="card mb-3 d-print-none">
<div class="card-body d-flex flex-wrap align-items-center gap-3">
<?= billingTile('quote', 'lg') ?>
<div class="flex-grow-1 min-w-0">
<h1 class="h4 fw-semibold mb-1 d-flex flex-wrap align-items-center gap-2">
<span>Quote <?= escapeHtml($number) ?></span>
<span class="fs-6"><?= quoteStatusBadge($quote) ?></span>
<?php if (!$expired) { ?><span class="fs-6"><?= quoteExpiryPill($quote) ?></span><?php } ?>
</h1>
<div class="text-body-secondary small d-flex flex-wrap column-gap-3 row-gap-1">
<span><i class="fas fa-fw fa-building me-1"></i><a class="text-reset" href="quotes.php?client_id=<?= $client_id ?>"><?= escapeHtml($quote['client_name']) ?></a></span>
<?php if (trim((string) $quote['quote_scope']) !== '') { ?><span><i class="fas fa-fw fa-comment me-1"></i><?= escapeHtml($quote['quote_scope']) ?></span><?php } ?>
<?php if ($quote['category_name']) { ?><span><i class="fas fa-fw fa-tag me-1"></i><?= escapeHtml($quote['category_name']) ?></span><?php } ?>
<?php if ($ticket) { ?>
<span><i class="fas fa-fw fa-life-ring me-1"></i>For <a class="text-reset" href="ticket.php?ticket_id=<?= intval($ticket['ticket_id']) ?>"><?= escapeHtml($ticket['ticket_prefix'] . $ticket['ticket_number']) ?></a></span>
<?php } ?>
<span title="<?= escapeHtml($quote['quote_created_at']) ?>"><i class="far fa-fw fa-clock me-1"></i>Created <?= escapeHtml(timeAgo($quote['quote_created_at'])) ?></span>
</div>
</div>
<div class="d-flex flex-wrap gap-2">
<?php if ($can_edit && $status === 'Draft') { ?>
<div class="btn-group">
<?php if ($mail_ready) { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/quote/quote_email.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-paper-plane me-2"></i>Send
</button>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-label="More ways to send"></button>
<div class="dropdown-menu dropdown-menu-end">
<button type="submit" class="dropdown-item confirm-link" form="quickSendQuote" name="quote_id" value="<?= $quote_id ?>"
data-confirm-title="Send <?= escapeHtml($number) ?> now?" data-confirm-text="It goes to the client's primary contact." data-confirm-button="Send">
<i class="fas fa-fw fa-bolt text-secondary me-2"></i>Quick Send
</button>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/quote/quote_mark_sent.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-fw fa-check text-secondary me-2"></i>Mark Sent<span class="text-body-secondary">...</span>
</a>
</div>
<?php } else { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/quote/quote_mark_sent.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-check me-2"></i>Mark Sent
</button>
<?php } ?>
</div>
<?php } ?>
<?php if ($can_edit && $awaiting) { ?>
<a class="btn btn-success confirm-link" href="post.php?accept_quote=<?= $quote_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-title="Mark <?= escapeHtml($number) ?> accepted?" data-confirm-text="For when the client said yes by phone or email - its lines are locked and it can be invoiced." data-confirm-button="Accepted">
<i class="fas fa-thumbs-up me-2"></i>Accepted
</a>
<a class="btn btn-outline-danger confirm-link" href="post.php?decline_quote=<?= $quote_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-title="Mark <?= escapeHtml($number) ?> declined?" data-confirm-text="The client said no - its lines are locked." data-confirm-button="Declined">
<i class="fas fa-thumbs-down me-2"></i>Declined
</a>
<?php } ?>
<?php if ($can_edit && $status === 'Accepted') { ?>
<div class="btn-group">
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/quote/quote_to_invoice.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-file-invoice-dollar me-2"></i>Make Invoice
</button>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-label="More"></button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item confirm-link" href="post.php?mark_quote_invoiced=<?= $quote_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-text="For a quote billed some other way - it is marked invoiced without making an invoice.">
<i class="fas fa-fw fa-check-double text-secondary me-2"></i>Mark Invoiced
</a>
</div>
</div>
<?php } ?>
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-outline-secondary ajax-modal" data-modal-url="modals/quote/quote_edit.php?id=<?= $quote_id ?>">
<i class="fas fa-edit me-2"></i>Edit
</button>
<?php } ?>
<div class="dropdown dropstart">
<button class="btn btn-outline-secondary" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="post.php?export_quote_pdf=<?= $quote_id ?>&csrf_token=<?= $csrf ?>" target="_blank">
<i class="fas fa-fw fa-file-pdf text-secondary me-2"></i>Download PDF
</a>
<a class="dropdown-item" href="#" onclick="window.print(); return false;">
<i class="fas fa-fw fa-print text-secondary me-2"></i>Print
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item clipboardjs" href="#" data-clipboard-text="<?= escapeHtml($guest_url) ?>">
<i class="fas fa-fw fa-link text-secondary me-2"></i>Copy Client Link
</a>
<a class="dropdown-item" href="<?= escapeHtml($guest_url) ?>" target="_blank" rel="noopener">
<i class="fas fa-fw fa-external-link-alt text-secondary me-2"></i>View as Client
</a>
<?php if ($can_edit) { ?>
<?php if ($status !== 'Draft' && $mail_ready) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/quote/quote_email.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-fw fa-paper-plane text-secondary me-2"></i>Send Again<span class="text-body-secondary">...</span>
</a>
<?php } ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/quote/quote_copy.php?id=<?= $quote_id ?>">
<i class="fas fa-fw fa-copy text-secondary me-2"></i>Copy
</a>
<?php } ?>
<?php if ($can_delete) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_quote=<?= $quote_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-text="<?= escapeHtml($number) ?> goes for good, with its lines and history.">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
<?php if ($expired && $can_edit) { ?>
<div class="alert alert-warning d-flex flex-wrap align-items-center gap-2 d-print-none">
<i class="fas fa-hourglass-end"></i>
<span class="me-auto">It ran out on <?= escapeHtml($quote['quote_expire']) ?> without an answer - the client can still see it but can't accept it.</span>
<button type="button" class="btn btn-sm btn-warning ajax-modal" data-modal-url="modals/quote/quote_edit.php?id=<?= $quote_id ?>"><i class="fas fa-calendar-plus me-1"></i>Extend</button>
</div>
<?php } ?>
<div class="row g-3">
<!-- The quote, as the client sees it -->
<div class="col-xl-8 itflow-paper-col">
<?php require "../includes/billing_paper.php"; ?>
</div>
<div class="col-xl-4 d-print-none">
<div class="card mb-3">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-comment-dollar text-secondary me-2"></i>Quote</h3>
</div>
<div class="card-body">
<div class="itflow-billing-stat-label">Total</div>
<div class="itflow-billing-stat-value mb-3"><?= $money($totals['total']) ?></div>
<dl class="itflow-asset-dl mb-0">
<dt>Status</dt><dd><?= quoteStatusBadge($quote) ?></dd>
<dt>Dated</dt><dd><?= escapeHtml($quote['quote_date']) ?></dd>
<dt>Valid until</dt>
<dd>
<?= escapeHtml($quote['quote_expire']) ?>
<?php if ($awaiting || $status === 'Draft') { ?><div class="mt-1"><?= quoteExpiryPill($quote) ?></div><?php } ?>
</dd>
<?php if ($status === 'Draft') { ?>
<dt>Client</dt><dd class="text-body-secondary">Not sent yet - the client can't see it</dd>
<?php } elseif ($awaiting) { ?>
<dt>Client</dt><dd class="text-body-secondary"><?= $status === 'Viewed' ? 'Has opened it' : "Hasn't opened it yet" ?> - they can accept or decline it from the link</dd>
<?php } ?>
</dl>
</div>
</div>
<?php if ($files) { ?>
<div class="card mb-3">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-paperclip text-secondary me-2"></i>From the client <span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal ms-1"><?= count($files) ?></span></h3>
</div>
<div class="list-group list-group-flush">
<?php /* Through the file quick look and agent/file.php, which check access - not a link straight into the uploads folder */ ?>
<?php foreach ($files as $file) {
$file_id = intval($file['file_id']); ?>
<div class="list-group-item d-flex align-items-center gap-2">
<?= fileTypeTile($file['file_ext'], 'sm') ?>
<div class="flex-grow-1 min-w-0">
<a class="ajax-modal text-break" href="#" data-modal-size="lg" data-modal-url="modals/file/file.php?id=<?= $file_id ?>"><?= escapeHtml($file['file_name']) ?></a>
<div class="small text-body-secondary"><?= formatBytes(intval($file['file_size'])) ?> &middot; <span title="<?= escapeHtml($file['file_created_at']) ?>"><?= escapeHtml(timeAgo($file['file_created_at'])) ?></span></div>
</div>
<a class="btn btn-sm btn-link text-body-secondary" href="file.php?file_id=<?= $file_id ?>" title="Download"><i class="fas fa-fw fa-download"></i></a>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
<div class="card mb-3">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-history text-secondary me-2"></i>History</h3>
</div>
<?= billingHistoryHtml($history) ?>
</div>
</div>
</div>
<?php if ($can_edit && $mail_ready) { ?>
<!-- Quick Send posts this, the button carrying the quote id as its own name/value -->
<form id="quickSendQuote" action="post.php" method="post" class="d-none">
<input type="hidden" name="csrf_token" value="<?= $csrf ?>">
<input type="hidden" name="email_quote" value="1">
<input type="hidden" name="quick_send" value="1">
</form>
<?php } ?>
<script src="/js/inline_notes.js"></script>
<?php
require_once "../includes/footer.php";
?>
<!-- Product autocomplete for the add-item row -->
<script src="/js/product_autocomplete.js"></script>
<script src="/libs/SortableJS/Sortable.min.js"></script>
<script src="/js/billing_items.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
initProductAutocomplete(<?= $json_products ?? '[]' ?>);
itflowBillingItems({
products: <?= $can_edit_lines ? getProductsForAutocomplete($mysqli) : '[]' ?>,
csrf: <?= json_encode($csrf) ?>,
currency: <?= json_encode($currency) ?>,
locale: <?= json_encode(str_replace('_', '-', (string) $session_company_locale)) ?>
});
});
</script>
<script src="../libs/SortableJS/Sortable.min.js"></script>
<script>
new Sortable(document.querySelector('table#items tbody'), {
handle: '.drag-handle',
animation: 150,
onEnd: function (evt) {
const rows = document.querySelectorAll('table#items tbody tr');
const positions = Array.from(rows).map((row, index) => ({
id: row.dataset.itemId,
order: index
}));
itflowPostForm('ajax.php', {
update_quote_items_order: true,
csrf_token: '<?= $_SESSION['csrf_token'] ?>',
quote_id: <?= $quote_id ?>,
positions: positions
});
}
});
</script>
<link rel="stylesheet" href="css/quote_dropdowns_fix.css">
<?php require_once "../includes/footer.php";

View File

@@ -1,5 +1,15 @@
<?php
/*
* Quotes - one client's, or every quote the agent can see.
*
* Along the top, the pipeline: what is out waiting for an answer, what has
* been accepted and not invoiced yet, and what was won over the last 90
* days with the share of answers that were a yes. The pills filter by where
* a quote stands - Expired picks out the ones that ran out unanswered. Each
* row has how long a quote has left while it waits.
*/
// Default Column Sortby/Order Filter
$sort = "quote_number";
$order = "DESC";
@@ -18,42 +28,137 @@ if (isset($_GET['client_id'])) {
// Perms
enforceUserPermission('module_sales');
$sql = mysqli_query(
$mysqli,
"SELECT SQL_CALC_FOUND_ROWS category_id, category_name, client_currency_code, client_id, client_name, client_net_terms,
quote_amount, quote_created_at, quote_currency_code, quote_date, quote_discount_amount,
quote_expire, quote_id, 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
WHERE (CONCAT(quote_prefix,quote_number) LIKE '%$q%' OR quote_scope LIKE '%$q%' OR category_name LIKE '%$q%' OR quote_status LIKE '%$q%' OR quote_amount LIKE '%$q%' OR client_name LIKE '%$q%')
AND DATE(quote_date) BETWEEN '$dtf' AND '$dtt'
" . clientScopeSql('quote_client_id') . "
$client_query
ORDER BY $sort $order LIMIT $record_from, $record_to"
);
$can_edit = lookupUserPermission('module_sales') >= 2;
$can_delete = lookupUserPermission('module_sales') >= 3;
$mail_ready = !empty($config_smtp_provider);
// Client Filter (all clients)
$client = '';
if (!$client_url && !empty($_GET['client'])) {
$client = intval($_GET['client']);
$client_query = "AND quote_client_id = $client";
}
$unanswered_sql = "quote_status IN ('Draft', 'Sent', 'Viewed')";
$statuses = [
'' => ['label' => 'All', 'where' => ''],
'Draft' => ['label' => 'Draft', 'icon' => 'fa-pencil-ruler', 'where' => "quote_status = 'Draft'", 'title' => 'Not sent yet - the client can\'t see them'],
'Awaiting' => ['label' => 'Awaiting answer', 'icon' => 'fa-hourglass-half', 'where' => "quote_status IN ('Sent', 'Viewed') AND quote_expire >= CURDATE()", 'title' => 'Sent, not answered, and not run out'],
'Expired' => ['label' => 'Expired', 'icon' => 'fa-hourglass-end', 'where' => "$unanswered_sql AND quote_expire < CURDATE()", 'title' => 'Ran out without an answer'],
'Accepted' => ['label' => 'Accepted', 'icon' => 'fa-thumbs-up', 'where' => "quote_status = 'Accepted'", 'title' => 'Accepted and not invoiced yet'],
'Invoiced' => ['label' => 'Invoiced', 'icon' => 'fa-file-invoice-dollar', 'where' => "quote_status = 'Invoiced'"],
'Declined' => ['label' => 'Declined', 'icon' => 'fa-thumbs-down', 'where' => "quote_status = 'Declined'"],
];
$status = isset($statuses[$_GET['status'] ?? '']) ? ($_GET['status'] ?? '') : '';
$status_query = $statuses[$status]['where'] ? 'AND ' . $statuses[$status]['where'] : '';
$sortable_columns = ['quote_number' => 'quote_number', 'quote_scope' => 'quote_scope', 'client_name' => 'client_name', 'quote_date' => 'quote_date',
'quote_expire' => 'quote_expire', 'quote_amount' => 'quote_amount', 'quote_status' => 'quote_status', 'category_name' => 'category_name'];
if (!isset($sortable_columns[$sort])) {
$sort = 'quote_number';
}
$scope_query = clientScopeSql('quote_client_id');
$search_query = "AND (CONCAT(quote_prefix, quote_number) LIKE '%$q%' OR quote_scope LIKE '%$q%' OR category_name LIKE '%$q%' OR quote_status LIKE '%$q%' OR quote_amount LIKE '%$q%' OR client_name LIKE '%$q%')";
$date_query = "AND DATE(quote_date) BETWEEN '$dtf' AND '$dtt'";
$filters = "$scope_query $client_query $date_query $search_query";
$joins = "LEFT JOIN clients ON quote_client_id = client_id LEFT JOIN categories ON quote_category_id = category_id";
$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS quotes.*, client_name, category_name
FROM quotes $joins
WHERE 1 $filters $status_query
ORDER BY {$sortable_columns[$sort]} $order, quote_id DESC LIMIT $record_from, $record_to");
$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$quotes = [];
while ($row = mysqli_fetch_assoc($sql)) {
$quotes[] = $row;
}
$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 quotes $joins WHERE 1 $filters"));
$counts = [];
foreach (array_keys($statuses) as $i => $key) {
$counts[$key] = intval($row[$i]);
}
// The pipeline along the top - everything in this scope
$pipeline = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT
COALESCE(SUM(CASE WHEN {$statuses['Awaiting']['where']} THEN quote_amount END), 0) AS awaiting,
COALESCE(SUM(CASE WHEN {$statuses['Awaiting']['where']} THEN 1 END), 0) AS awaiting_count,
COALESCE(SUM(CASE WHEN quote_status = 'Accepted' THEN quote_amount END), 0) AS accepted,
COALESCE(SUM(CASE WHEN quote_status = 'Accepted' THEN 1 END), 0) AS accepted_count,
COALESCE(SUM(CASE WHEN quote_status IN ('Accepted', 'Invoiced') AND quote_date >= CURDATE() - INTERVAL 90 DAY THEN quote_amount END), 0) AS won,
COALESCE(SUM(CASE WHEN quote_status IN ('Accepted', 'Invoiced') AND quote_date >= CURDATE() - INTERVAL 90 DAY THEN 1 END), 0) AS won_count,
COALESCE(SUM(CASE WHEN quote_status IN ('Accepted', 'Invoiced', 'Declined') AND quote_date >= CURDATE() - INTERVAL 90 DAY THEN 1 END), 0) AS answered_count
FROM quotes WHERE 1 $scope_query $client_query"));
$win_rate = intval($pipeline['answered_count']) ? round(intval($pipeline['won_count']) / intval($pipeline['answered_count']) * 100) : null;
$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; }));
};
$stat_money = function ($amount) use ($session_company_currency) {
return escapeHtml(billingMoney($amount, $session_company_currency));
};
?>
<!-- The pipeline -->
<div class="row g-3 mb-3">
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $status === 'Awaiting' ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['status' => 'Awaiting'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-hourglass-half me-1"></i>Awaiting answer</div>
<div class="itflow-billing-stat-value"><?= $stat_money($pipeline['awaiting']) ?></div>
<div class="itflow-billing-stat-note"><?= intval($pipeline['awaiting_count']) ?> out with clients</div>
</a>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $status === 'Accepted' ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['status' => 'Accepted'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-thumbs-up me-1"></i>Accepted, to invoice</div>
<div class="itflow-billing-stat-value <?= $pipeline['accepted'] > 0 ? 'text-primary-emphasis' : '' ?>"><?= $stat_money($pipeline['accepted']) ?></div>
<div class="itflow-billing-stat-note"><?= intval($pipeline['accepted_count']) ?> ready to bill</div>
</a>
</div>
<div class="col-sm-6 col-xl-3">
<div class="itflow-billing-stat">
<div class="itflow-billing-stat-label"><i class="fas fa-trophy me-1"></i>Won, 90 days</div>
<div class="itflow-billing-stat-value text-success-emphasis"><?= $stat_money($pipeline['won']) ?></div>
<div class="itflow-billing-stat-note"><?= intval($pipeline['won_count']) ?> quote<?= intval($pipeline['won_count']) === 1 ? '' : 's' ?> accepted</div>
</div>
</div>
<div class="col-sm-6 col-xl-3">
<div class="itflow-billing-stat" title="Of the quotes dated in the last 90 days that have been answered, the share accepted">
<div class="itflow-billing-stat-label"><i class="fas fa-percentage me-1"></i>Win rate, 90 days</div>
<div class="itflow-billing-stat-value"><?= $win_rate === null ? '-' : $win_rate . '%' ?></div>
<div class="itflow-billing-stat-note"><?= intval($pipeline['answered_count']) ?> answered</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header bg-dark py-2">
<h3 class="card-title mt-2"><i class="fa fa-comment-dollar me-2"></i>Quotes</h3>
<h3 class="card-title mt-2"><i class="fa fa-fw fa-comment-dollar me-2"></i>Quotes</h3>
<div class="card-tools">
<?php if (lookupUserPermission("module_sales") >= 2) { ?>
<div class="btn-group">
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/quote/quote_add.php?<?= $client_url ?>"><i class="fas fa-plus me-2"></i>New Quote</button>
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/quote/quote_add.php?<?= $client_url ?>"><i class="fas fa-plus me-2"></i>New Quote</button>
<?php } ?>
<?php if ($num_rows[0] > 0) { ?>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown"></button>
<div class="dropdown-menu">
<a class="dropdown-item text-dark ajax-modal" href="#"
data-modal-url="<?= buildExportModalUrl('modals/quote/quote_export.php', ['client_id', 'q'], ['dtf' => $dtf, 'dtt' => $dtt]) ?>">
<i class="fa fa-fw fa-download me-2"></i>Export
<button type="button" class="btn btn-primary dropdown-toggle <?= $can_edit ? 'dropdown-toggle-split' : '' ?>" data-bs-toggle="dropdown"><?= $can_edit ? '' : '<i class="fas fa-ellipsis-h"></i>' ?></button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item ajax-modal" href="#" data-modal-url="<?= buildExportModalUrl('modals/quote/quote_export.php', ['client_id', 'q'], ['dtf' => $dtf, 'dtt' => $dtt, 'client_id' => $client ?: '']) ?>">
<i class="fa fa-fw fa-download text-secondary me-2"></i>Export
</a>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
</div>
@@ -62,216 +167,144 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
<?php if ($client_url) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } ?>
<div class="row g-2 align-items-end">
<div class="col-sm-4">
<input type="hidden" name="status" value="<?= escapeHtml($status) ?>">
<div class="row g-2 align-items-center">
<div class="<?= $client_url ? 'col-lg-5' : 'col-lg-4' ?> col-md-6">
<div class="input-group">
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search Quotes">
<button class="btn btn-secondary" title="More filters" type="button" data-bs-toggle="collapse" data-bs-target="#advancedFilter"><i class="fas fa-filter"></i></button>
<button class="btn btn-primary" title="Search"><i class="fa fa-search"></i></button>
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search number, scope, client, amount...">
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
</div>
</div>
<div class="col-sm-8">
<div class="float-end">
</div>
<div class="col-lg-3 col-md-6">
<input type="text" id="dateFilter" class="form-control" autocomplete="off" title="Quote date" aria-label="Quote date">
<input type="hidden" name="canned_date" id="canned_date" value="<?= escapeHtml($_GET['canned_date'] ?? '') ?>">
<input type="hidden" name="dtf" id="dtf" value="<?= escapeHtml($dtf ?? '') ?>">
<input type="hidden" name="dtt" id="dtt" value="<?= escapeHtml($dtt ?? '') ?>">
</div>
</div>
<div class="collapse mt-3 <?php if (isset($_GET['dtf']) && $_GET['dtf'] !== '1970-01-01') { echo"show"; } ?>" id="advancedFilter">
<div class="row g-3">
<div class="col-md-3">
<div>
<label class="form-label">Date range</label>
<input type="text" id="dateFilter" class="form-control" autocomplete="off">
<input type="hidden" name="canned_date" id="canned_date" value="<?= escapeHtml($_GET['canned_date']) ?? '' ?>">
<input type="hidden" name="dtf" id="dtf" value="<?= escapeHtml($dtf ?? '') ?>">
<input type="hidden" name="dtt" id="dtt" value="<?= escapeHtml($dtt ?? '') ?>">
</div>
<?php if (!$client_url) { ?>
<div class="col-lg-3 col-md-6">
<select class="form-select select2" name="client" onchange="this.form.submit()">
<option value="">- All Clients -</option>
<?php
$sql_clients_filter = mysqli_query($mysqli, "SELECT DISTINCT client_id, client_name, client_abbreviation FROM clients
JOIN quotes ON quote_client_id = client_id WHERE 1 " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql_clients_filter)) {
$client_option_id = intval($row['client_id']); ?>
<option <?= $client === $client_option_id ? 'selected' : '' ?> value="<?= $client_option_id ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= escapeHtml($row['client_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<?php } ?>
</div>
</form>
<nav class="nav nav-pills itflow-asset-tabs mt-2 flex-nowrap overflow-auto">
<?php foreach ($statuses as $key => $s) {
$alarm = $key === 'Accepted' && $counts[$key]; ?>
<a class="nav-link text-nowrap <?= $status === $key ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['status' => $key])) ?>"<?= !empty($s['title']) ? ' title="' . escapeHtml($s['title']) . '"' : '' ?>>
<?php if (!empty($s['icon'])) { ?><i class="fas fa-fw <?= $s['icon'] ?> me-1"></i><?php } ?><?= $s['label'] ?>
<span class="badge rounded-pill ms-1 <?= $alarm ? 'text-bg-primary' : '' ?>"><?= $counts[$key] ?></span>
</a>
<?php } ?>
</nav>
</div>
<div class="table-responsive">
<table class="table table-striped table-borderless table-hover mb-0">
<thead class="text-dark <?php if ($num_rows[0] == 0) { echo "d-none"; } ?> text-nowrap">
<table class="table table-hover align-middle mb-0 itflow-billing-table">
<thead class="<?= $num_rows[0] ? '' : 'd-none' ?> text-nowrap table-light">
<tr>
<th class="ps-3">
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=quote_number&order=<?= $disp ?>">
Number <?php if ($sort == 'quote_number') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=quote_scope&order=<?= $disp ?>">
Scope <?php if ($sort == 'quote_scope') { echo $order_icon; } ?>
</a>
</th>
<th class="ps-3"><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=quote_number&order=<?= $disp ?>">Quote <?php if ($sort == 'quote_number') { echo $order_icon; } ?></a></th>
<?php if (!$client_url) { ?>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=client_name&order=<?= $disp ?>">
Client <?php if ($sort == 'client_name') { echo $order_icon; } ?>
</a>
</th>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=client_name&order=<?= $disp ?>">Client <?php if ($sort == 'client_name') { echo $order_icon; } ?></a></th>
<?php } ?>
<th class="text-end">
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=quote_amount&order=<?= $disp ?>">
Amount <?php if ($sort == 'quote_amount') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=quote_date&order=<?= $disp ?>">
Date <?php if ($sort == 'quote_number') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=quote_expire&order=<?= $disp ?>">
Expire <?php if ($sort == 'quote_number') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=category_name&order=<?= $disp ?>">
Category <?php if ($sort == 'category_name') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=quote_status&order=<?= $disp ?>">
Status <?php if ($sort == 'quote_status') { echo $order_icon; } ?>
</a>
</th>
<th class="text-center">Action</th>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=quote_date&order=<?= $disp ?>">Date <?php if ($sort == 'quote_date') { echo $order_icon; } ?></a></th>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=quote_expire&order=<?= $disp ?>">Valid until <?php if ($sort == 'quote_expire') { echo $order_icon; } ?></a></th>
<th class="text-end"><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=quote_amount&order=<?= $disp ?>">Total <?php if ($sort == 'quote_amount') { echo $order_icon; } ?></a></th>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=quote_status&order=<?= $disp ?>">Status <?php if ($sort == 'quote_status') { echo $order_icon; } ?></a></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql)) {
<?php foreach ($quotes as $row) {
$quote_id = intval($row['quote_id']);
$quote_prefix = escapeHtml($row['quote_prefix']);
$quote_number = intval($row['quote_number']);
$quote_scope = escapeHtml($row['quote_scope']);
if (empty($quote_scope)) {
$quote_scope_display = "-";
} else {
$quote_scope_display = $quote_scope;
}
$quote_status = escapeHtml($row['quote_status']);
$quote_date = escapeHtml($row['quote_date']);
$quote_expire = escapeHtml($row['quote_expire']);
$quote_amount = floatval($row['quote_amount']);
$quote_discount = floatval($row['quote_discount_amount']);
$quote_currency_code = escapeHtml($row['quote_currency_code']);
$quote_created_at = escapeHtml($row['quote_created_at']);
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$client_currency_code = escapeHtml($row['client_currency_code']);
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
$client_net_terms = intval($row['client_net_terms']);
if ($client_net_terms == 0) {
$client_net_terms = $config_default_net_terms;
}
if ($quote_status == "Sent") {
$quote_badge_color = "warning";
} elseif ($quote_status == "Viewed") {
$quote_badge_color = "primary";
} elseif ($quote_status == "Accepted") {
$quote_badge_color = "success";
} elseif ($quote_status == "Declined") {
$quote_badge_color = "danger";
} elseif ($quote_status == "Invoiced") {
$quote_badge_color = "info";
} else {
$quote_badge_color = "secondary";
}
$row_client_id = intval($row['quote_client_id']);
$row_number = billingNumber('quote', $row);
$row_status = (string) $row['quote_status'];
$row_url = "quote.php?{$client_url}quote_id=$quote_id";
?>
<tr>
<td class="text-bold ps-3">
<a href="quote.php?client_id=<?= $client_id ?>&quote_id=<?= $quote_id ?>">
<?= "$quote_prefix$quote_number" ?>
</a>
<td class="ps-3 itflow-billing-number">
<a class="fw-semibold" href="<?= $row_url ?>"><?= escapeHtml($row_number) ?></a>
<div class="small text-body-secondary text-truncate" style="max-width: 24rem;"><?= escapeHtml(implode(' · ', array_filter([$row['quote_scope'], $row['category_name']]))) ?: '&nbsp;' ?></div>
</td>
<td><?= $quote_scope_display ?></td>
<?php if (!$client_url) { ?>
<td class="text-bold">
<a href="quotes.php?client_id=<?= $client_id ?>"><?= $client_name ?></a>
</td>
<td><a class="text-reset" href="quotes.php?client_id=<?= $row_client_id ?>"><?= escapeHtml($row['client_name']) ?></a></td>
<?php } ?>
<td class="text-end font-monospace"><?= numfmt_format_currency($currency_format, $quote_amount, $quote_currency_code) ?></td>
<td><?= $quote_date ?></td>
<td><?= $quote_expire ?></td>
<td><?= $category_name ?></td>
<td>
<span class="p-2 badge text-bg-<?= $quote_badge_color ?>">
<?= $quote_status ?>
</span>
<td class="text-nowrap"><?= escapeHtml($row['quote_date']) ?></td>
<td class="text-nowrap">
<?= escapeHtml($row['quote_expire']) ?>
<?php $expiry_pill = quoteExpiryPill($row); if ($expiry_pill) { ?><div><?= $expiry_pill ?></div><?php } ?>
</td>
<td>
<div class="dropdown dropstart text-center">
<button class="btn btn-secondary btn-sm" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-ellipsis-h"></i>
</button>
<td class="text-end itflow-money fw-semibold"><?= escapeHtml(billingMoney($row['quote_amount'], $row['quote_currency_code'])) ?></td>
<td class="text-nowrap"><?= quoteStatusBadge($row) ?></td>
<td class="text-end">
<div class="dropdown dropstart">
<button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown"><i class="fas fa-fw fa-ellipsis-v"></i></button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/quote/quote_edit.php?id=<?= $quote_id ?>">
<i class="fas fa-fw fa-edit me-2"></i>Edit
</a>
<?php if (lookupUserPermission("module_sales") >= 2) { ?>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/quote/quote_copy.php?id=<?= $quote_id ?>">
<i class="fas fa-fw fa-copy me-2"></i>Copy
</a>
<?php if (!empty($config_smtp_provider)) { ?>
<div class="dropdown-divider"></div>
<button type="submit" class="dropdown-item confirm-link" form="quickSendQuote"
data-confirm-title="Send this quote now?"
data-confirm-text="It goes to the default contacts without opening the picker."
data-confirm-button="Send"
name="quote_id" value="<?= $quote_id ?>">
<i class="fas fa-fw fa-bolt me-2"></i>Quick Send
<a class="dropdown-item" href="<?= $row_url ?>"><i class="fas fa-fw fa-eye text-secondary me-2"></i>Open</a>
<a class="dropdown-item" href="post.php?export_quote_pdf=<?= $quote_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" target="_blank"><i class="fas fa-fw fa-file-pdf text-secondary me-2"></i>Download PDF</a>
<?php if ($can_edit) { ?>
<div class="dropdown-divider"></div>
<?php if ($mail_ready && in_array($row_status, ['Draft', 'Sent', 'Viewed'], true)) { ?>
<button type="submit" class="dropdown-item confirm-link" form="quickSendQuote" name="quote_id" value="<?= $quote_id ?>"
data-confirm-title="Send <?= escapeHtml($row_number) ?> now?" data-confirm-text="It goes to the client's primary contact." data-confirm-button="Send">
<i class="fas fa-fw fa-bolt text-secondary me-2"></i>Quick Send
</button>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/quote/quote_email.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-fw fa-paper-plane me-2"></i>Email<span class="text-muted">...</span>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/quote/quote_email.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-fw fa-paper-plane text-secondary me-2"></i>Send Email<span class="text-body-secondary">...</span>
</a>
<?php } ?>
<?php if (lookupUserPermission("module_sales") >= 3) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_quote=<?= $quote_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-trash me-2"></i>Delete
<?php if ($row_status === 'Draft') { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/quote/quote_mark_sent.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-fw fa-check text-secondary me-2"></i>Mark Sent<span class="text-body-secondary">...</span>
</a>
<?php } ?>
<?php if ($row_status === 'Accepted') { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/quote/quote_to_invoice.php?quote_id=<?= $quote_id ?>">
<i class="fas fa-fw fa-file-invoice-dollar text-secondary me-2"></i>Make Invoice<span class="text-body-secondary">...</span>
</a>
<?php } ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/quote/quote_edit.php?id=<?= $quote_id ?>">
<i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/quote/quote_copy.php?id=<?= $quote_id ?>">
<i class="fas fa-fw fa-copy text-secondary me-2"></i>Copy
</a>
<?php } ?>
<?php if ($can_delete) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_quote=<?= $quote_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-text="<?= escapeHtml($row_number) ?> goes for good, with its lines and history.">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
</div>
</div>
</td>
</tr>
<?php
}
?>
<?php } ?>
</tbody>
</table>
</div>
<?php require_once "../includes/filter_footer.php";
?>
<?php if (!$num_rows[0]) { ?>
<div class="itflow-asset-empty">
<i class="fas fa-comment-dollar fa-2x mb-2 opacity-50"></i>
<div><?= $q || $status || $dtf !== '1970-01-01' ? 'No quotes match.' : 'No quotes yet.' ?></div>
</div>
<?php } ?>
<?php require_once "../includes/filter_footer.php"; ?>
</div>
<?php if (lookupUserPermission("module_sales") >= 2 && !empty($config_smtp_provider)) { ?>
<?php
/*
* One hidden form for the whole page, targeted by the Quick Send buttons via
* their form="" attribute. It cannot be a form per button: agent/invoices.php
* wraps its table in a bulkActions form, and a nested form is invalid
* HTML - the browser drops the inner one and the click silently submits the
* bulk action instead. The button carries the id as its own name/value, which
* a submit button contributes to the submission.
*/
?>
<?php if ($can_edit && $mail_ready) { ?>
<form id="quickSendQuote" action="post.php" method="post" class="d-none">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="email_quote" value="1">
@@ -279,5 +312,4 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
</form>
<?php } ?>
<?php
require_once "../includes/footer.php";
<?php require_once "../includes/footer.php";

View File

@@ -1,534 +1,310 @@
<?php
/*
* Recurring Invoice - an agreement billed every month or year.
*
* The header says whether it is running and when it next bills - and,
* when its next date has passed, that it won't bill again until the date
* moves on (with the button that moves it). The template is on the left as
* the invoices it makes will look, its lines edited in place. On the
* right: the schedule (what it brings in a month, the next few dates,
* whether invoices go out by themselves), the card it charges, the
* invoices it has made and whether they were paid, and its history.
*/
// If client_id is in URI then show client Side Bar and client header
if (isset($_GET['client_id'])) {
require_once "includes/inc_all_client.php";
$client_url = "client_id=$client_id&";
} else {
require_once "includes/inc_all.php";
$client_url = '';
}
// Perms
enforceUserPermission('module_sales');
if (isset($_GET['recurring_invoice_id'])) {
$recurring_invoice_id = intval($_GET['recurring_invoice_id']);
$sql = mysqli_query(
$mysqli,
"SELECT client_currency_code, client_id, client_name, client_net_terms, client_website,
contact_email, contact_extension, contact_mobile, contact_mobile_country_code,
contact_phone, contact_phone_country_code, location_address, location_city,
location_country, location_state, location_zip, recurring_invoice_amount,
recurring_invoice_category_id, recurring_invoice_created_at,
recurring_invoice_currency_code, recurring_invoice_discount_amount,
recurring_invoice_email_notify, recurring_invoice_frequency, recurring_invoice_last_sent,
recurring_invoice_next_date, recurring_invoice_note, recurring_invoice_auto_send, recurring_invoice_number,
recurring_invoice_prefix, recurring_invoice_scope, recurring_invoice_status,
recurring_payment_id, recurring_payment_method, recurring_payment_recurring_invoice_id,
recurring_payment_saved_payment_id FROM recurring_invoices
LEFT JOIN clients ON recurring_invoice_client_id = client_id
LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1
LEFT JOIN locations ON clients.client_id = locations.location_client_id AND location_primary = 1
LEFT JOIN recurring_payments ON recurring_payment_recurring_invoice_id = recurring_invoice_id
WHERE recurring_invoice_id = $recurring_invoice_id LIMIT 1"
);
if (mysqli_num_rows($sql) == 0) {
if (isset($_GET['client_id'])) {
$backlink_append = "?client_id=$client_id";
} else {
$backlink_append = '';
}
echo "<h1 class='text-secondary pt-5' style='text-align: center'>There is no Recurring Invoice here<br><small><a href='recurring_invoices.php$backlink_append'><i class='fas fa-arrow-left me-2'></i>Back to Recurring Invoices</a></small></h1>";
require_once "../includes/footer.php";
exit();
}
$row = mysqli_fetch_assoc($sql);
$recurring_invoice_prefix = escapeHtml($row['recurring_invoice_prefix']);
$recurring_invoice_number = intval($row['recurring_invoice_number']);
$recurring_invoice_scope = escapeHtml($row['recurring_invoice_scope']);
$recurring_invoice_frequency = escapeHtml($row['recurring_invoice_frequency']);
$recurring_invoice_status = escapeHtml($row['recurring_invoice_status']);
$recurring_invoice_created_at = date('Y-m-d', strtotime($row['recurring_invoice_created_at']));
$recurring_invoice_last_sent = escapeHtml($row['recurring_invoice_last_sent']);
if ($recurring_invoice_last_sent == 0) {
$recurring_invoice_last_sent = '-';
}
$recurring_invoice_next_date = escapeHtml($row['recurring_invoice_next_date']);
$recurring_invoice_amount = floatval($row['recurring_invoice_amount']);
$recurring_invoice_discount = floatval($row['recurring_invoice_discount_amount']);
$recurring_invoice_currency_code = escapeHtml($row['recurring_invoice_currency_code']);
$recurring_invoice_note = escapeHtml($row['recurring_invoice_note']);
$recurring_invoice_auto_send = intval($row['recurring_invoice_auto_send']);
$recurring_invoice_email_notify = intval($row['recurring_invoice_email_notify']);
$category_id = intval($row['recurring_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 ($recurring_invoice_status == 1) {
$status = "Active";
$status_badge_color = "success";
} else {
$status = "Inactive";
$status_badge_color = "secondary";
}
$recurring_payment_id = intval($row['recurring_payment_id']);
$recurring_payment_recurring_invoice_id = intval($row['recurring_payment_recurring_invoice_id']);
$recurring_payment_method = escapeHtml($row['recurring_payment_method']);
$recurring_payment_saved_payment_id = intval($row['recurring_payment_saved_payment_id']);
// Override Tab Title // No Sanitizing needed as this var will only be used in the tab title
$tab_title = $row['client_name'];
$page_title = "{$row['recurring_invoice_prefix']}{$row['recurring_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_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_logo = escapeHtml($row['company_logo']);
$sql_history = mysqli_query($mysqli, "SELECT history_created_at, history_description, history_status FROM history WHERE history_recurring_invoice_id = $recurring_invoice_id ORDER BY history_id DESC");
//Product autocomplete
$json_products = getProductsForAutocomplete($mysqli);
enforceClientAccess();
?>
<ol class="breadcrumb d-print-none">
<?php if (isset($_GET['client_id'])) { ?>
<li class="breadcrumb-item">
<a href="client_overview.php?client_id=<?= $client_id ?>"><?= $client_name ?></a>
</li>
<li class="breadcrumb-item">
<a href="recurring_invoices.php?client_id=<?= $client_id ?>">Recurring Invoices</a>
</li>
<?php } else { ?>
<li class="breadcrumb-item">
<a href="recurring_invoices.php">Recurring Invoices</a>
</li>
<li class="breadcrumb-item">
<a href="recurring_invoices.php?client_id=<?= $client_id ?>"><?= $client_name ?></a>
</li>
<?php } ?>
<li class="breadcrumb-item active"><?= "$recurring_invoice_prefix$recurring_invoice_number" ?></li>
</ol>
<div class="card mb-3">
<div class="card-header d-print-none">
<div class="row">
<div class="col-2">
<?php if ($recurring_invoice_auto_send) { ?>
<?php if ($recurring_invoice_email_notify) { ?>
<a href="post.php?recurring_invoice_email_notify=0&recurring_invoice_id=<?= $recurring_invoice_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" class="btn btn-primary"><i class="fas fa-fw fa-bell me-2"></i>Email Notify</a>
<?php } else { ?>
<a href="post.php?recurring_invoice_email_notify=1&recurring_invoice_id=<?= $recurring_invoice_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" class="btn btn-outline-danger"><i class="fas fa-fw fa-bell-slash me-2"></i>Email Notify</a>
<?php } ?>
<?php } ?>
</div>
<div class="col-3">
<?php $sql_saved_payments = mysqli_query($mysqli, "SELECT saved_payment_description, saved_payment_id FROM client_saved_payment_methods WHERE saved_payment_client_id = $client_id");
if (mysqli_num_rows($sql_saved_payments) > 0) { ?>
<form class="form" action="post.php" method="post">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="set_recurring_payment" value="1">
<input type="hidden" name="recurring_invoice_id" value="<?= $recurring_invoice_id ?>">
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-redo-alt"></i></span>
<select class="form-select select2" name="saved_payment_id" onchange="this.form.submit()">
<option value="0">Disabled</option>
<?php
while ($row = mysqli_fetch_assoc($sql_saved_payments)) {
$saved_payment_id = intval($row['saved_payment_id']);
$saved_payment_description = escapeHtml($row['saved_payment_description']);
?>
<option <?php if ($recurring_payment_saved_payment_id == $saved_payment_id) { echo "selected"; } ?> value="<?= $saved_payment_id ?>"><?= $saved_payment_description ?></option>
<?php } ?>
</select>
</div>
</form>
<?php } ?>
</div>
<div class="col-7">
<div class="dropdown dropstart text-center float-end">
<button class="btn btn-secondary" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/recurring_invoice/recurring_invoice_edit.php?id=<?= $recurring_invoice_id ?>">
<i class="fa fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="post.php?force_recurring=<?= $recurring_invoice_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fa fa-fw fa-paper-plane text-secondary me-2"></i>Force Send
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger confirm-link" href="post.php?delete_recurring_invoice=<?= $recurring_invoice_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fa fa-fw fa-trash me-2"></i>Delete
</a>
</div>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="row mb-3">
<div class="col-sm-2">
<img class="img-fluid" src="<?= "../uploads/settings/$company_logo" ?>" alt="Company logo">
</div>
<div class="col-sm-6">
<ul class="list-unstyled">
<li><h4><strong><?= $company_name ?></strong></h4></li>
<li><?= formatAddress($company_address, $company_city, $company_state, $company_zip, $company_country, '<br>') ?></li>
<li><?= "$company_email | $company_phone" ?></li>
<li><?= $company_website ?></li>
</ul>
</div>
<div class="col-sm-4">
<h3 class="text-end"><strong>RECURRING INVOICE</strong></h3>
<h5 class="badge text-bg-<?= $status_badge_color ?> p-2 float-end">
<?= $status ?>
</h5>
<table class="table table-sm table-borderless">
<tr>
<th>Frequency:</th>
<th class="text-end"><?= ucwords($recurring_invoice_frequency) ?>ly</th>
</tr>
<tr>
<th>Next Date:</th>
<td class="text-end"><?= $recurring_invoice_next_date ?></td>
</tr>
<tr>
<th>Last Sent:</th>
<td class="text-end"><?= $recurring_invoice_last_sent ?></td>
</tr>
<tr>
<th>Created:</th>
<td class="text-end"><?= $recurring_invoice_created_at ?></td>
</tr>
</table>
</div>
</div>
<div class="row mb-3 bg-light p-3">
<div class="col">
<h6><strong>Bill To:</strong></h6>
<ul class="list-unstyled mb-0">
<li><?= $client_name ?></li>
<li><?= formatAddress($location_address, $location_city, $location_state, $location_zip, $location_country, '<br>') ?></li>
<li><?= "$contact_email | $contact_phone $contact_extension" ?></li>
</ul>
</div>
</div>
<?php $sql_items = mysqli_query($mysqli, "SELECT item_created_at, item_description, item_id, item_name, item_price, item_quantity, item_tax,
item_tax_id, item_total FROM recurring_invoice_items WHERE item_recurring_invoice_id = $recurring_invoice_id ORDER BY item_order ASC"); ?>
<div class="row mb-3">
<div class="col-md-12">
<div class="card">
<div class="table-responsive">
<table class="table table-hover mb-0" id="items">
<thead class="bg-light">
<tr>
<th class="d-print-none"></th>
<th>Item</th>
<th>Description</th>
<th class="text-center">Qty</th>
<th class="text-end">Price</th>
<th class="text-end">Tax</th>
<th class="text-end">Amount</th>
</tr>
</thead>
<tbody>
<?php
$total_tax = 0.00;
$sub_total = 0.00;
while ($row = mysqli_fetch_assoc($sql_items)) {
$item_id = intval($row['item_id']);
$item_name = escapeHtml($row['item_name']);
$item_description = escapeHtml($row['item_description']);
$item_quantity = number_format(floatval($row['item_quantity']),2);
$item_price = floatval($row['item_price']);
$item_tax = floatval($row['item_tax']);
$item_total = floatval($row['item_total']);
$item_created_at = escapeHtml($row['item_created_at']);
$tax_id = intval($row['item_tax_id']);
$total_tax = $item_tax + $total_tax;
$sub_total = $item_price * $item_quantity + $sub_total;
?>
<tr data-item-id="<?= $item_id ?>">
<td class="d-print-none">
<div class="btn-group">
<button type="button" class="btn btn-sm btn-link drag-handle" title="Drag to reorder">
<i class="fas fa-bars text-muted"></i>
</button>
<div class="dropdown">
<button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/recurring_invoice/recurring_invoice_item_edit.php?id=<?= $item_id ?>">
<i class="fa fa-fw fa-edit me-2"></i>Edit
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger confirm-link" href="post.php?delete_recurring_invoice_item=<?= $item_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"><i class="fa fa-fw fa-trash me-2"></i>Delete</a>
</div>
</div>
</div>
</td>
<td><?= $item_name ?></td>
<td><?= nl2br($item_description) ?></td>
<td class="text-center"><?= $item_quantity ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_price, $recurring_invoice_currency_code) ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_tax, $recurring_invoice_currency_code) ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_total, $recurring_invoice_currency_code) ?></td>
</tr>
<?php
}
?>
<tr class="d-print-none">
<form action="post.php" method="post">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="recurring_invoice_id" value="<?= $recurring_invoice_id ?>">
<input type="hidden" id="product_id" name="product_id" value="0">
<input type="hidden" name="item_order" value="<?php
//find largest order number and add 1
$sql = mysqli_query($mysqli, "SELECT MAX(item_order) AS item_order FROM recurring_invoice_items WHERE item_recurring_invoice_id = $recurring_invoice_id");
$row = mysqli_fetch_assoc($sql);
$item_order = intval($row['item_order']) + 1;
echo $item_order;
?>">
<td></td>
<td>
<input type="text" class="form-control" id="name" name="name" placeholder="Item" maxlength="200" required>
</td>
<td>
<textarea class="form-control" rows="2" id="desc" name="description" placeholder="Enter a Description"></textarea>
</td>
<td>
<input type="text" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" class="form-control" style="text-align: center;" id="qty" name="qty" placeholder="Qty">
</td>
<td>
<input type="text" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" class="form-control" style="text-align: right;" id="price" name="price" placeholder="Price (<?= $recurring_invoice_currency_code ?>)">
</td>
<td>
<select class="form-select select2" name="tax_id" id="tax" required>
<option value="0">No Tax</option>
<?php
$taxes_sql = mysqli_query($mysqli, "SELECT tax_id, tax_name, tax_percent FROM taxes WHERE tax_archived_at IS NULL ORDER BY tax_name ASC");
while ($row = mysqli_fetch_assoc($taxes_sql)) {
$tax_id = intval($row['tax_id']);
$tax_name = escapeHtml($row['tax_name']);
$tax_percent = floatval($row['tax_percent']);
?>
<option value="<?= $tax_id ?>"><?= "$tax_name $tax_percent%" ?></option>
<?php
}
?>
</select>
</td>
<td class="text-center">
<button class="btn btn-light text-success" title="Add item" type="submit" name="add_recurring_invoice_item">
<i class="fa fa-fw fa-check"></i>
</button>
</td>
</form>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-sm-7">
<div class="card">
<div class="card-header text-bold">
Notes:
<span class="d-print-none" data-note-status-for="recurringInvoiceNotes"></span>
</div>
<div class="card-body p-2">
<?php if (lookupUserPermission("module_sales") >= 2) { ?>
<textarea class="form-control itflow-inline-note d-print-none" rows="6"
id="recurringInvoiceNotes"
placeholder="Enter some notes"
data-endpoint="recurring_invoice_set_notes"
data-id-field="recurring_invoice_id"
data-id="<?= $recurring_invoice_id ?>"
data-csrf="<?= $_SESSION['csrf_token'] ?>"><?= $recurring_invoice_note ?></textarea>
<?php } else { ?>
<div class="d-print-none"><?= nl2br($recurring_invoice_note) ?></div>
<?php } ?>
<!-- Printed output must be plain text, not a form control -->
<div class="d-none d-print-block"><?= nl2br($recurring_invoice_note) ?></div>
</div>
</div>
</div>
<div class="col-sm-3 offset-sm-2">
<table class="table table-hover mb-0">
<tbody>
<tr>
<td>Subtotal</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $sub_total, $recurring_invoice_currency_code) ?></td>
</tr>
<?php if ($recurring_invoice_discount > 0) { ?>
<tr>
<td>Discount</td>
<td class="text-end">-<?= numfmt_format_currency($currency_format, $recurring_invoice_discount, $recurring_invoice_currency_code) ?></td>
</tr>
<?php } ?>
<?php if ($total_tax > 0) { ?>
<tr>
<td>Tax</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $total_tax, $recurring_invoice_currency_code) ?></td>
</tr>
<?php } ?>
<tr class="h5 text-bold">
<td>Total</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $recurring_invoice_amount, $recurring_invoice_currency_code) ?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-sm d-print-none">
<div class="card">
<div class="card-header text-bold">
<i class="fas fa-fw fa-history me-2"></i>History
<div class="card-tools">
<button type="button" class="btn btn-tool" title="Show/hide" data-lte-toggle="card-collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" title="Hide" data-lte-toggle="card-remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Event</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql_history)) {
$history_created_at = escapeHtml($row['history_created_at']);
$history_status = escapeHtml($row['history_status']);
$history_description = escapeHtml($row['history_description']);
?>
<tr>
<td><?= $history_created_at ?></td>
<td><?= $history_description ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php
$recurring_invoice_id = intval($_GET['recurring_invoice_id'] ?? 0);
$recurring = billingRow('recurring', $recurring_invoice_id);
if (!$recurring || ($client_url && intval($recurring['client_id']) !== intval($client_id))) {
billingNotFound('recurring', $client_url);
require_once "../includes/footer.php";
exit;
}
$client_id = intval($recurring['client_id']);
enforceClientAccess();
$number = billingNumber('recurring', $recurring);
$active = intval($recurring['recurring_invoice_status']) === 1;
$frequency = (string) $recurring['recurring_invoice_frequency'];
$frequency_label = recurringInvoiceFrequencies()[$frequency] ?? ucfirst($frequency);
$currency = (string) $recurring['recurring_invoice_currency_code'];
$money = function ($amount) use ($currency) {
return escapeHtml(billingMoney($amount, $currency));
};
$items = billingItems('recurring', $recurring_invoice_id);
$totals = billingTotals('recurring', $recurring, $items);
$history = billingHistory('recurring', $recurring_invoice_id);
$generated = recurringInvoiceGenerated($recurring_invoice_id, 8);
$generated_count = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM invoices WHERE invoice_recurring_invoice_id = $recurring_invoice_id"))[0]);
$upcoming = $active ? recurringInvoiceUpcoming($recurring, 4) : [];
$late = $active && $recurring['recurring_invoice_next_date'] < date('Y-m-d');
$auto_send = intval($recurring['recurring_invoice_auto_send']) === 1;
$email_notify = intval($recurring['recurring_invoice_email_notify']) === 1;
$can_edit = lookupUserPermission('module_sales') >= 2;
$can_delete = lookupUserPermission('module_sales') >= 3;
$csrf = $_SESSION['csrf_token'];
// Cards on file the client could be charged on
$saved_methods = [];
$sql = mysqli_query($mysqli, "SELECT saved_payment_id, saved_payment_description, payment_provider_name, payment_provider_active FROM client_saved_payment_methods
LEFT JOIN payment_providers ON payment_provider_id = saved_payment_provider_id
WHERE saved_payment_client_id = $client_id ORDER BY saved_payment_description ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$saved_methods[intval($row['saved_payment_id'])] = $row;
}
$autopay_id = intval($recurring['recurring_payment_saved_payment_id'] ?? 0);
// Override Tab Title // No Sanitizing needed as this var will only be used in the tab title
$tab_title = $recurring['client_name'];
$page_title = $number;
$paper = [
'type' => 'recurring',
'row' => $recurring,
'items' => $items,
'totals' => $totals,
'edit' => $can_edit,
'notes_edit' => $can_edit,
'taxes' => $can_edit ? billingTaxes($recurring['recurring_invoice_created_at']) : [],
'logo_url' => billingCompany()['logo_url'],
'csrf' => $csrf,
];
?>
<ol class="breadcrumb d-print-none">
<li class="breadcrumb-item"><a href="client_overview.php?client_id=<?= $client_id ?>"><?= escapeHtml($recurring['client_name']) ?></a></li>
<li class="breadcrumb-item"><a href="recurring_invoices.php?client_id=<?= $client_id ?>">Recurring Invoices</a></li>
<li class="breadcrumb-item active"><?= escapeHtml($number) ?></li>
</ol>
<!-- What it is, whether it is running, and when it bills next -->
<div class="card mb-3 d-print-none">
<div class="card-body d-flex flex-wrap align-items-center gap-3">
<?= billingTile('recurring', 'lg') ?>
<div class="flex-grow-1 min-w-0">
<h1 class="h4 fw-semibold mb-1 d-flex flex-wrap align-items-center gap-2">
<span>Recurring Invoice <?= escapeHtml($number) ?></span>
<span class="fs-6"><span class="badge rounded-pill text-bg-<?= $active ? 'success' : 'secondary' ?>"><?= $active ? 'Active' : 'Paused' ?></span></span>
<?php if ($active) { ?><span class="fs-6"><?= recurringInvoiceNextPill($recurring) ?></span><?php } ?>
</h1>
<div class="text-body-secondary small d-flex flex-wrap column-gap-3 row-gap-1">
<span><i class="fas fa-fw fa-building me-1"></i><a class="text-reset" href="recurring_invoices.php?client_id=<?= $client_id ?>"><?= escapeHtml($recurring['client_name']) ?></a></span>
<?php if (trim((string) $recurring['recurring_invoice_scope']) !== '') { ?><span><i class="fas fa-fw fa-comment me-1"></i><?= escapeHtml($recurring['recurring_invoice_scope']) ?></span><?php } ?>
<?php if ($recurring['category_name']) { ?><span><i class="fas fa-fw fa-tag me-1"></i><?= escapeHtml($recurring['category_name']) ?></span><?php } ?>
<span><i class="fas fa-fw fa-sync-alt me-1"></i><?= escapeHtml($frequency_label) ?></span>
<?php if ($autopay_id && isset($saved_methods[$autopay_id])) { ?><span><i class="fas fa-fw fa-wallet me-1"></i>Autopay</span><?php } ?>
</div>
</div>
<div class="d-flex flex-wrap gap-2">
<?php if ($can_edit) { ?>
<a class="btn btn-primary confirm-link" href="post.php?force_recurring=<?= $recurring_invoice_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-title="Make an invoice from <?= escapeHtml($number) ?> now?"
data-confirm-text="<?= $auto_send ? 'An invoice is made, dated today, and sent - the next one moves on a period from today.' : 'A draft invoice is made, dated today, for you to check and send. The schedule does not change.' ?>"
data-confirm-button="Invoice Now">
<i class="fas fa-bolt me-2"></i>Invoice Now
</a>
<?php if ($active) { ?>
<a class="btn btn-outline-secondary confirm-link" href="post.php?recurring_invoice_set_status=<?= $recurring_invoice_id ?>&status=0&csrf_token=<?= $csrf ?>"
data-confirm-title="Pause <?= escapeHtml($number) ?>?" data-confirm-text="No invoices are made from it until it is resumed." data-confirm-button="Pause">
<i class="fas fa-pause me-2"></i>Pause
</a>
<?php } else { ?>
<a class="btn btn-outline-success" href="post.php?recurring_invoice_set_status=<?= $recurring_invoice_id ?>&status=1&csrf_token=<?= $csrf ?>">
<i class="fas fa-play me-2"></i>Resume
</a>
<?php } ?>
<button type="button" class="btn btn-outline-secondary ajax-modal" data-modal-url="modals/recurring_invoice/recurring_invoice_edit.php?id=<?= $recurring_invoice_id ?>">
<i class="fas fa-edit me-2"></i>Edit
</button>
<?php } ?>
<div class="dropdown dropstart">
<button class="btn btn-outline-secondary" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#" onclick="window.print(); return false;">
<i class="fas fa-fw fa-print text-secondary me-2"></i>Print
</a>
<a class="dropdown-item" href="invoices.php?client_id=<?= $client_id ?>&recurring_invoice_id=<?= $recurring_invoice_id ?>">
<i class="fas fa-fw fa-file-invoice-dollar text-secondary me-2"></i>Invoices Made <span class="text-body-secondary">(<?= $generated_count ?>)</span>
</a>
<?php if ($can_edit && $auto_send) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="post.php?recurring_invoice_email_notify=<?= $email_notify ? 0 : 1 ?>&recurring_invoice_id=<?= $recurring_invoice_id ?>&csrf_token=<?= $csrf ?>">
<i class="fas fa-fw <?= $email_notify ? 'fa-bell-slash' : 'fa-bell' ?> text-secondary me-2"></i><?= $email_notify ? "Don't email the invoices" : 'Email the invoices' ?>
</a>
<?php } ?>
<?php if ($can_delete) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_recurring_invoice=<?= $recurring_invoice_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-text="<?= escapeHtml($number) ?> goes for good, with its lines, autopay and history. The invoices it made stay.">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
<?php if ($late) { ?>
<div class="alert alert-danger d-flex flex-wrap align-items-center gap-2 d-print-none">
<i class="fas fa-exclamation-triangle"></i>
<span class="me-auto">Its next date, <?= escapeHtml($recurring['recurring_invoice_next_date']) ?>, has passed - it only bills on its next date, so nothing more will be made until that moves on.</span>
<?php if ($can_edit) { ?>
<a class="btn btn-sm btn-danger confirm-link" href="post.php?recurring_invoice_catch_up=<?= $recurring_invoice_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-title="Skip the missed runs?" data-confirm-text="The next date moves on to <?= escapeHtml(recurringInvoiceCatchUp($recurring)) ?>. Nothing is billed for the runs it missed - use Invoice Now for those." data-confirm-button="Move on">
<i class="fas fa-forward me-1"></i>Move on to <?= escapeHtml(recurringInvoiceCatchUp($recurring)) ?>
</a>
<?php } ?>
</div>
<?php } ?>
<div class="row g-3">
<!-- The invoice it makes -->
<div class="col-xl-8 itflow-paper-col">
<?php require "../includes/billing_paper.php"; ?>
</div>
<div class="col-xl-4 d-print-none">
<div class="card mb-3">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-calendar-alt text-secondary me-2"></i>Schedule</h3>
</div>
<div class="card-body">
<div class="d-flex justify-content-between align-items-end mb-3">
<div>
<div class="itflow-billing-stat-label">Each <?= $frequency === 'year' ? 'year' : 'month' ?></div>
<div class="itflow-billing-stat-value"><?= $money($totals['total']) ?></div>
</div>
<?php if ($frequency === 'year') { ?>
<div class="text-end small text-body-secondary"><?= $money(recurringInvoiceMonthly($totals['total'], $frequency)) ?> a month</div>
<?php } ?>
</div>
<dl class="itflow-asset-dl mb-0">
<dt>Next</dt>
<dd>
<?php if ($active) { ?>
<?= escapeHtml($recurring['recurring_invoice_next_date']) ?>
<?php if (count($upcoming) > 1 && !$late) { ?>
<div class="small text-body-secondary">then <?= escapeHtml(implode(', ', array_slice($upcoming, 1))) ?></div>
<?php } ?>
<?php } else { ?>
<span class="text-body-secondary">Paused - nothing until it is resumed</span>
<?php } ?>
</dd>
<dt>Last</dt><dd><?= $recurring['recurring_invoice_last_sent'] ? escapeHtml($recurring['recurring_invoice_last_sent']) : '<span class="text-body-secondary">Not yet</span>' ?></dd>
<dt>Sending</dt>
<dd>
<?php if (!$auto_send) { ?>
Made as a draft for you to check and send
<?php } elseif (empty($config_recurring_auto_send_invoice)) { ?>
Made as a draft<div class="small text-body-secondary">Sending recurring invoices is off in the billing settings</div>
<?php } elseif ($email_notify) { ?>
Emailed to the primary and billing contacts as it is made
<?php } else { ?>
Made as a draft<div class="small text-body-secondary">Emailing is off for this one</div>
<?php } ?>
</dd>
<dt>Since</dt><dd title="<?= escapeHtml($recurring['recurring_invoice_created_at']) ?>"><?= escapeHtml(date('Y-m-d', strtotime($recurring['recurring_invoice_created_at']))) ?></dd>
</dl>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-wallet text-secondary me-2"></i>Autopay</h3>
</div>
<div class="card-body">
<?php if ($saved_methods) { ?>
<form action="post.php" method="post">
<input type="hidden" name="csrf_token" value="<?= $csrf ?>">
<input type="hidden" name="set_recurring_payment" value="1">
<input type="hidden" name="recurring_invoice_id" value="<?= $recurring_invoice_id ?>">
<div class="input-group">
<span class="input-group-text"><i class="fas fa-fw fa-credit-card"></i></span>
<select class="form-select" name="saved_payment_id" onchange="this.form.submit()" <?= $can_edit ? '' : 'disabled' ?> aria-label="Card to charge">
<option value="0">Off - the client pays each invoice</option>
<?php foreach ($saved_methods as $saved_id => $method) { ?>
<option value="<?= $saved_id ?>" <?= $autopay_id === $saved_id ? 'selected' : '' ?>><?= escapeHtml($method['saved_payment_description']) ?><?= $method['payment_provider_name'] ? ' (' . escapeHtml($method['payment_provider_name']) . (intval($method['payment_provider_active']) ? '' : ', turned off') . ')' : '' ?></option>
<?php } ?>
</select>
</div>
</form>
<div class="form-text"><?= $autopay_id ? 'Charged on the due date of each invoice it makes.' : 'Charge a card on file on the due date of each invoice it makes.' ?></div>
<?php } else { ?>
<div class="small text-body-secondary">No card on file for <?= escapeHtml($recurring['client_name']) ?>. Once they save one paying an invoice online, it can be charged here automatically.</div>
<?php } ?>
</div>
</div>
<div class="card mb-3">
<div class="card-header d-flex align-items-center">
<h3 class="card-title mb-0 me-auto"><i class="fas fa-fw fa-file-invoice-dollar text-secondary me-2"></i>Invoices Made <span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal ms-1"><?= $generated_count ?></span></h3>
<?php if ($generated_count > count($generated)) { ?>
<a class="small" href="invoices.php?client_id=<?= $client_id ?>&recurring_invoice_id=<?= $recurring_invoice_id ?>">All</a>
<?php } ?>
</div>
<?php if ($generated) { ?>
<div class="list-group list-group-flush">
<?php foreach ($generated as $made) {
$made_state = invoiceState($made, $made['paid']); ?>
<a class="list-group-item list-group-item-action d-flex align-items-center gap-2" href="invoice.php?invoice_id=<?= intval($made['invoice_id']) ?>">
<div class="flex-grow-1 min-w-0">
<div class="fw-semibold"><?= escapeHtml($made['invoice_prefix'] . $made['invoice_number']) ?> <span class="fw-normal text-body-secondary small ms-1"><?= escapeHtml($made['invoice_date']) ?></span></div>
<div class="small"><?= invoiceStatusBadge($made['invoice_status'], $made_state['state'] === 'overdue') ?></div>
</div>
<span class="itflow-money small"><?= escapeHtml(billingMoney($made['invoice_amount'], $made['invoice_currency_code'])) ?></span>
</a>
<?php } ?>
</div>
<?php } else { ?>
<div class="card-body small text-body-secondary">None yet<?= $active ? ' - the first is made on ' . escapeHtml($recurring['recurring_invoice_next_date']) : '' ?>.</div>
<?php } ?>
</div>
<div class="card mb-3">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-history text-secondary me-2"></i>History</h3>
</div>
<?= billingHistoryHtml($history) ?>
</div>
</div>
</div>
<script src="/js/inline_notes.js"></script>
<?php
require_once "../includes/footer.php";
?>
<!-- Product autocomplete for the add-item row -->
<script src="/js/product_autocomplete.js"></script>
<script src="/libs/SortableJS/Sortable.min.js"></script>
<script src="/js/billing_items.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
initProductAutocomplete(<?= $json_products ?? '[]' ?>);
itflowBillingItems({
products: <?= $can_edit ? getProductsForAutocomplete($mysqli) : '[]' ?>,
csrf: <?= json_encode($csrf) ?>,
currency: <?= json_encode($currency) ?>,
locale: <?= json_encode(str_replace('_', '-', (string) $session_company_locale)) ?>
});
});
</script>
<script src="../libs/SortableJS/Sortable.min.js"></script>
<script>
new Sortable(document.querySelector('table#items tbody'), {
handle: '.drag-handle',
animation: 150,
onEnd: function (evt) {
const rows = document.querySelectorAll('table#items tbody tr');
const positions = Array.from(rows).map((row, index) => ({
id: row.dataset.itemId,
order: index
}));
itflowPostForm('ajax.php', {
update_recurring_invoice_items_order: true,
csrf_token: '<?= $_SESSION['csrf_token'] ?>',
recurring_invoice_id: <?= $recurring_invoice_id ?>,
positions: positions
});
}
});
</script>
<?php require_once "../includes/footer.php";

View File

@@ -1,5 +1,17 @@
<?php
/*
* Recurring Invoices - one client's agreements, or every one the agent can
* see.
*
* Along the top, the recurring revenue: what the running ones bring in a
* month (yearly ones counted as a twelfth), what bills over the next 30
* days, how many are running, and how many need looking at - running, but
* with a next date that has passed, so they won't bill until it moves on.
* Pills: Active (the default - ?status=active), Next 7 days, Late, Paused
* (?status=inactive, as before) and All.
*/
// Default Column Sortby/Order Filter
$sort = "recurring_invoice_next_date";
$order = "ASC";
@@ -18,252 +30,254 @@ if (isset($_GET['client_id'])) {
// Perms
enforceUserPermission('module_sales');
// Status Filter
if (isset($_GET['status']) && $_GET['status'] == "inactive") {
$status_filter = "inactive";
$status_query = "AND recurring_invoice_status = 0";
} else {
$status_filter = "active";
$status_query = "AND recurring_invoice_status = 1";
$can_edit = lookupUserPermission('module_sales') >= 2;
$can_delete = lookupUserPermission('module_sales') >= 3;
// Client Filter (all clients)
$client = '';
if (!$client_url && !empty($_GET['client'])) {
$client = intval($_GET['client']);
$client_query = "AND recurring_invoice_client_id = $client";
}
$sql = mysqli_query(
$mysqli,
"SELECT SQL_CALC_FOUND_ROWS category_id, category_name, client_currency_code, client_id, client_name,
recurring_invoice_amount, recurring_invoice_created_at, recurring_invoice_currency_code,
recurring_invoice_discount_amount, recurring_invoice_frequency, recurring_invoice_id,
recurring_invoice_last_sent, recurring_invoice_next_date, recurring_invoice_number,
recurring_invoice_prefix, recurring_invoice_scope, recurring_invoice_status,
recurring_payment_id, recurring_payment_recurring_invoice_id,
recurring_payment_saved_payment_id FROM recurring_invoices
LEFT JOIN clients ON recurring_invoice_client_id = client_id
LEFT JOIN categories ON recurring_invoice_category_id = category_id
LEFT JOIN recurring_payments ON recurring_payment_recurring_invoice_id = recurring_invoice_id
WHERE (CONCAT(recurring_invoice_prefix,recurring_invoice_number) LIKE '%$q%' OR recurring_invoice_frequency LIKE '%$q%' OR recurring_invoice_scope LIKE '%$q%' OR client_name LIKE '%$q%' OR category_name LIKE '%$q%')
AND DATE(recurring_invoice_created_at) BETWEEN '$dtf' AND '$dtt'
$status_query
$client_query
" . clientScopeSql('recurring_invoice_client_id') . "
$statuses = [
'active' => ['label' => 'Active', 'icon' => 'fa-play', 'where' => 'recurring_invoice_status = 1'],
'soon' => ['label' => 'Next 7 days', 'icon' => 'fa-calendar-day', 'where' => 'recurring_invoice_status = 1 AND recurring_invoice_next_date BETWEEN CURDATE() AND CURDATE() + INTERVAL 7 DAY',
'title' => 'Running, and billing in the next week'],
'late' => ['label' => 'Late', 'icon' => 'fa-exclamation-triangle', 'where' => 'recurring_invoice_status = 1 AND recurring_invoice_next_date < CURDATE()',
'title' => "Running, but the next date has passed - they won't bill until it moves on"],
'inactive' => ['label' => 'Paused', 'icon' => 'fa-pause', 'where' => 'recurring_invoice_status = 0'],
'all' => ['label' => 'All', 'where' => ''],
];
$status = isset($statuses[$_GET['status'] ?? '']) ? ($_GET['status'] ?? '') : 'active';
$status_query = $statuses[$status]['where'] ? 'AND ' . $statuses[$status]['where'] : '';
ORDER BY $sort $order LIMIT $record_from, $record_to");
$sortable_columns = ['recurring_invoice_number' => 'recurring_invoice_number', 'recurring_invoice_scope' => 'recurring_invoice_scope', 'client_name' => 'client_name',
'recurring_invoice_frequency' => 'recurring_invoice_frequency', 'recurring_invoice_amount' => 'recurring_invoice_amount', 'monthly' => 'monthly',
'recurring_invoice_next_date' => 'recurring_invoice_next_date', 'recurring_invoice_last_sent' => 'recurring_invoice_last_sent', 'category_name' => 'category_name'];
if (!isset($sortable_columns[$sort])) {
$sort = 'recurring_invoice_next_date';
}
$monthly_sql = "CASE WHEN recurring_invoice_frequency = 'year' THEN recurring_invoice_amount / 12 ELSE recurring_invoice_amount END";
$scope_query = clientScopeSql('recurring_invoice_client_id');
$search_query = "AND (CONCAT(recurring_invoice_prefix, recurring_invoice_number) LIKE '%$q%' OR recurring_invoice_frequency LIKE '%$q%' OR recurring_invoice_scope LIKE '%$q%' OR client_name LIKE '%$q%' OR category_name LIKE '%$q%')";
$filters = "AND recurring_invoice_archived_at IS NULL $scope_query $client_query $search_query";
$joins = "LEFT JOIN clients ON recurring_invoice_client_id = client_id LEFT JOIN categories ON recurring_invoice_category_id = category_id";
$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS recurring_invoices.*, client_name, category_name, recurring_payment_id, $monthly_sql AS monthly
FROM recurring_invoices $joins
LEFT JOIN recurring_payments ON recurring_payment_recurring_invoice_id = recurring_invoice_id
WHERE 1 $filters $status_query
ORDER BY {$sortable_columns[$sort]} $order, recurring_invoice_id ASC LIMIT $record_from, $record_to");
$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$recurring_invoices = [];
while ($row = mysqli_fetch_assoc($sql)) {
$recurring_invoices[] = $row;
}
$count_sql = [];
foreach ($statuses as $key => $s) {
$count_sql[] = $s['where'] === '' ? 'COUNT(*)' : "COALESCE(SUM({$s['where']}), 0)";
}
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT " . implode(', ', $count_sql) . " FROM recurring_invoices $joins WHERE 1 $filters"));
$counts = [];
foreach (array_keys($statuses) as $i => $key) {
$counts[$key] = intval($row[$i]);
}
// The recurring revenue along the top - everything in this scope
$revenue = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT
COALESCE(SUM(CASE WHEN recurring_invoice_status = 1 THEN $monthly_sql END), 0) AS mrr,
COALESCE(SUM(CASE WHEN recurring_invoice_status = 1 AND recurring_invoice_next_date BETWEEN CURDATE() AND CURDATE() + INTERVAL 30 DAY THEN recurring_invoice_amount END), 0) AS next30,
COALESCE(SUM(CASE WHEN recurring_invoice_status = 1 AND recurring_invoice_next_date BETWEEN CURDATE() AND CURDATE() + INTERVAL 30 DAY THEN 1 END), 0) AS next30_count,
COALESCE(SUM(recurring_invoice_status = 1), 0) AS active_count,
COALESCE(SUM(recurring_invoice_status = 0), 0) AS paused_count,
COALESCE(SUM(recurring_invoice_status = 1 AND recurring_invoice_next_date < CURDATE()), 0) AS late_count
FROM recurring_invoices WHERE recurring_invoice_archived_at IS NULL $scope_query $client_query"));
$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; }));
};
$stat_money = function ($amount) use ($session_company_currency) {
return escapeHtml(billingMoney($amount, $session_company_currency));
};
?>
<!-- The recurring revenue -->
<div class="row g-3 mb-3">
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat" href="<?= escapeHtml($filter_url(['status' => 'active'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-sync-alt me-1"></i>Monthly recurring</div>
<div class="itflow-billing-stat-value text-success-emphasis"><?= $stat_money($revenue['mrr']) ?></div>
<div class="itflow-billing-stat-note"><?= $stat_money($revenue['mrr'] * 12) ?> a year</div>
</a>
</div>
<div class="col-sm-6 col-xl-3">
<div class="itflow-billing-stat">
<div class="itflow-billing-stat-label"><i class="fas fa-calendar-alt me-1"></i>Bills in 30 days</div>
<div class="itflow-billing-stat-value"><?= $stat_money($revenue['next30']) ?></div>
<div class="itflow-billing-stat-note"><?= intval($revenue['next30_count']) ?> invoice<?= intval($revenue['next30_count']) === 1 ? '' : 's' ?> to be made</div>
</div>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $status === 'active' ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['status' => 'active'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-play me-1"></i>Running</div>
<div class="itflow-billing-stat-value"><?= intval($revenue['active_count']) ?></div>
<div class="itflow-billing-stat-note"><?= intval($revenue['paused_count']) ?> paused</div>
</a>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $status === 'late' ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['status' => 'late'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-exclamation-triangle me-1"></i>Need a look</div>
<div class="itflow-billing-stat-value <?= $revenue['late_count'] ? 'text-danger-emphasis' : '' ?>"><?= intval($revenue['late_count']) ?></div>
<div class="itflow-billing-stat-note"><?= $revenue['late_count'] ? "Next date passed - won't bill" : 'All on schedule' ?></div>
</a>
</div>
</div>
<div class="card">
<div class="card-header bg-dark py-2">
<h3 class="card-title mt-2"><i class="fa fa-redo-alt me-2"></i>Recurring Invoices</h3>
<?php if (lookupUserPermission("module_sales") >= 2) { ?>
<h3 class="card-title mt-2"><i class="fa fa-fw fa-redo-alt me-2"></i>Recurring Invoices</h3>
<div class="card-tools">
<div class="btn-group">
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/recurring_invoice/recurring_invoice_add.php?<?= $client_url ?>"><i class="fas fa-plus"></i><span class="d-none d-lg-inline ms-2">New Recurring Invoice</span></button>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown"></button>
<div class="dropdown-menu">
<?php if ($num_rows[0] > 0) { ?>
<a class="dropdown-item text-dark ajax-modal" href="#"
data-modal-url="<?= buildExportModalUrl('modals/recurring_invoice/recurring_invoice_export.php', ['client_id', 'status', 'q'], ['dtf' => $dtf, 'dtt' => $dtt]) ?>">
<i class="fa fa-fw fa-download me-2"></i>Export
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/recurring_invoice/recurring_invoice_add.php?<?= $client_url ?>"><i class="fas fa-plus me-2"></i>New Recurring Invoice</button>
<?php } ?>
<?php if ($num_rows[0] > 0) { ?>
<button type="button" class="btn btn-primary dropdown-toggle <?= $can_edit ? 'dropdown-toggle-split' : '' ?>" data-bs-toggle="dropdown"><?= $can_edit ? '' : '<i class="fas fa-ellipsis-h"></i>' ?></button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item ajax-modal" href="#" data-modal-url="<?= buildExportModalUrl('modals/recurring_invoice/recurring_invoice_export.php', ['client_id', 'q'], ['status' => in_array($status, ['active', 'inactive'], true) ? $status : '', 'client_id' => $client ?: '']) ?>">
<i class="fa fa-fw fa-download text-secondary me-2"></i>Export
</a>
<?php } ?>
</div>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
</div>
<div class="card-header py-3">
<form autocomplete="off">
<form autocomplete="off">
<?php if ($client_url) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } ?>
<input type="hidden" name="status" value="<?= $status_filter ?>">
<div class="row g-2 align-items-end">
<div class="col-sm-4">
<input type="hidden" name="status" value="<?= escapeHtml($status) ?>">
<div class="row g-2 align-items-center">
<div class="<?= $client_url ? 'col-lg-6' : 'col-lg-5' ?> col-md-6">
<div class="input-group">
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) {echo strip_tags(escapeHtml($q));} ?>" placeholder="Search Recurring Invoices">
<button class="btn btn-secondary" title="More filters" type="button" data-bs-toggle="collapse" data-bs-target="#advancedFilter"><i class="fas fa-filter"></i></button>
<button class="btn btn-primary" title="Search"><i class="fa fa-search"></i></button>
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search number, scope, client, category...">
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
</div>
</div>
<div class="col-sm-8">
<div class="btn-toolbar float-end">
<div class="btn-group">
<a href="?<?= $client_url ?>status=active" class="btn btn-<?php if ($status_filter == "active"){ echo "primary"; } else { echo "default"; } ?>"><i class="fa fa-fw fa-check me-2"></i>Active</a>
<a href="?<?= $client_url ?>status=inactive" class="btn btn-<?php if ($status_filter == "inactive"){ echo "primary"; } else { echo "default"; } ?>"><i class="fa fa-fw fa-ban me-2"></i>Inactive</a>
</div>
<?php if (!$client_url) { ?>
<div class="col-lg-3 col-md-6">
<select class="form-select select2" name="client" onchange="this.form.submit()">
<option value="">- All Clients -</option>
<?php
$sql_clients_filter = mysqli_query($mysqli, "SELECT DISTINCT client_id, client_name, client_abbreviation FROM clients
JOIN recurring_invoices ON recurring_invoice_client_id = client_id WHERE 1 " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql_clients_filter)) {
$client_option_id = intval($row['client_id']); ?>
<option <?= $client === $client_option_id ? 'selected' : '' ?> value="<?= $client_option_id ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= escapeHtml($row['client_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="collapse mt-3 <?php if (isset($_GET['dtf']) && $_GET['dtf'] !== '1970-01-01') { echo "show"; } ?>" id="advancedFilter">
<div class="row g-3">
<div class="col-md-3">
<div>
<label>Date range</label>
<input type="text" id="dateFilter" class="form-control" autocomplete="off">
<input type="hidden" name="canned_date" id="canned_date" value="<?= escapeHtml($_GET['canned_date']) ?? '' ?>">
<input type="hidden" name="dtf" id="dtf" value="<?= escapeHtml($dtf ?? '') ?>">
<input type="hidden" name="dtt" id="dtt" value="<?= escapeHtml($dtt ?? '') ?>">
</div>
</div>
</div>
<?php } ?>
</div>
</form>
<nav class="nav nav-pills itflow-asset-tabs mt-2 flex-nowrap overflow-auto">
<?php foreach ($statuses as $key => $s) {
$alarm = $key === 'late' && $counts[$key]; ?>
<a class="nav-link text-nowrap <?= $status === $key ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['status' => $key])) ?>"<?= !empty($s['title']) ? ' title="' . escapeHtml($s['title']) . '"' : '' ?>>
<?php if (!empty($s['icon'])) { ?><i class="fas fa-fw <?= $s['icon'] ?> me-1"></i><?php } ?><?= $s['label'] ?>
<span class="badge rounded-pill ms-1 <?= $alarm ? 'text-bg-danger' : '' ?>"><?= $counts[$key] ?></span>
</a>
<?php } ?>
</nav>
</div>
<div class="table-responsive">
<table class="table table-striped table-borderless table-hover mb-0">
<thead class="text-dark <?php if ($num_rows[0] == 0) { echo "d-none"; } ?> text-nowrap">
<table class="table table-hover align-middle mb-0 itflow-billing-table">
<thead class="<?= $num_rows[0] ? '' : 'd-none' ?> text-nowrap table-light">
<tr>
<th class="ps-3">
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_number&order=<?= $disp ?>">
Number <?php if ($sort == 'recurring_invoice_number') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_next_date&order=<?= $disp ?>">
Next Date <?php if ($sort == 'recurring_invoice_next_date') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_scope&order=<?= $disp ?>">
Scope <?php if ($sort == 'recurring_invoice_scope') { echo $order_icon; } ?>
</a>
</th>
<th class="ps-3"><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_number&order=<?= $disp ?>">Recurring invoice <?php if ($sort == 'recurring_invoice_number') { echo $order_icon; } ?></a></th>
<?php if (!$client_url) { ?>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=client_name&order=<?= $disp ?>">
Client <?php if ($sort == 'client_name') { echo $order_icon; } ?>
</a>
</th>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=client_name&order=<?= $disp ?>">Client <?php if ($sort == 'client_name') { echo $order_icon; } ?></a></th>
<?php } ?>
<th class="text-end">
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_amount&order=<?= $disp ?>">
Amount <?php if ($sort == 'recurring_invoice_amount') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_frequency&order=<?= $disp ?>">
Frequency <?php if ($sort == 'recurring_invoice_frequency') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_last_sent&order=<?= $disp ?>">
Last Sent <?php if ($sort == 'recurring_invoice_last_sent') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=category_name&order=<?= $disp ?>">
Category <?php if ($sort == 'category_name') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_payment_recurring_invoice_id&order=<?= $disp ?>">
Auto Pay <?php if ($sort == 'recurring_payment_recurring_invoice_id') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_status&order=<?= $disp ?>">
Status <?php if ($sort == 'recurring_invoice_status') { echo $order_icon; } ?>
</a>
</th>
<th class="text-center">Action</th>
<th class="text-end"><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_amount&order=<?= $disp ?>">Amount <?php if ($sort == 'recurring_invoice_amount') { echo $order_icon; } ?></a></th>
<th class="text-end"><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=monthly&order=<?= $disp ?>">A month <?php if ($sort == 'monthly') { echo $order_icon; } ?></a></th>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_next_date&order=<?= $disp ?>">Next <?php if ($sort == 'recurring_invoice_next_date') { echo $order_icon; } ?></a></th>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=recurring_invoice_last_sent&order=<?= $disp ?>">Last <?php if ($sort == 'recurring_invoice_last_sent') { echo $order_icon; } ?></a></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql)) {
<?php foreach ($recurring_invoices as $row) {
$recurring_invoice_id = intval($row['recurring_invoice_id']);
$recurring_invoice_prefix = escapeHtml($row['recurring_invoice_prefix']);
$recurring_invoice_number = intval($row['recurring_invoice_number']);
$recurring_invoice_scope = escapeHtml($row['recurring_invoice_scope']);
$recurring_invoice_frequency = escapeHtml($row['recurring_invoice_frequency']);
$recurring_invoice_status = escapeHtml($row['recurring_invoice_status']);
$recurring_invoice_discount = floatval($row['recurring_invoice_discount_amount']);
$recurring_invoice_last_sent = $row['recurring_invoice_last_sent'];
if ($recurring_invoice_last_sent == 0) {
$recurring_invoice_last_sent = "-";
}
$recurring_invoice_next_date = escapeHtml($row['recurring_invoice_next_date']);
$recurring_invoice_amount = floatval($row['recurring_invoice_amount']);
$recurring_invoice_currency_code = escapeHtml($row['recurring_invoice_currency_code']);
$recurring_invoice_created_at = escapeHtml($row['recurring_invoice_created_at']);
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$client_currency_code = escapeHtml($row['client_currency_code']);
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
if ($recurring_invoice_status == 1) {
$status = "Active";
$status_badge_color = "success";
} else {
$status = "Inactive";
$status_badge_color = "secondary";
}
$recurring_payment_id = intval($row['recurring_payment_id']);
$recurring_payment_recurring_invoice_id = intval($row['recurring_payment_recurring_invoice_id']);
$recurring_payment_saved_payment_id = intval($row['recurring_payment_saved_payment_id']);
$row_client_id = intval($row['recurring_invoice_client_id']);
$row_number = billingNumber('recurring', $row);
$row_active = intval($row['recurring_invoice_status']) === 1;
$row_currency = (string) $row['recurring_invoice_currency_code'];
$row_url = "recurring_invoice.php?{$client_url}recurring_invoice_id=$recurring_invoice_id";
$row_frequency = recurringInvoiceFrequencies()[$row['recurring_invoice_frequency']] ?? ucfirst((string) $row['recurring_invoice_frequency']);
?>
<tr>
<td class="text-bold ps-3">
<a href="recurring_invoice.php?client_id=<?= $client_id ?>&recurring_invoice_id=<?= $recurring_invoice_id ?>">
<?= "$recurring_invoice_prefix$recurring_invoice_number" ?>
</a>
<tr class="<?= $row_active ? '' : 'text-body-secondary' ?>">
<td class="ps-3 itflow-billing-number">
<a class="fw-semibold" href="<?= $row_url ?>"><?= escapeHtml($row_number) ?></a>
<?php if (intval($row['recurring_payment_id'])) { ?><i class="fas fa-wallet text-success small ms-1" title="Autopay - charged to a card on file"></i><?php } ?>
<div class="small text-body-secondary text-truncate" style="max-width: 24rem;"><?= escapeHtml(implode(' · ', array_filter([$row['recurring_invoice_scope'], $row['category_name']]))) ?: '&nbsp;' ?></div>
</td>
<td class="text-bold"><?= $recurring_invoice_next_date ?></td>
<td><?= $recurring_invoice_scope ?></td>
<?php if (!$client_url) { ?>
<td class="text-bold"><a href="recurring_invoices.php?client_id=<?= $client_id ?>"><?= $client_name ?></a></td>
<td><a class="text-reset" href="recurring_invoices.php?client_id=<?= $row_client_id ?>"><?= escapeHtml($row['client_name']) ?></a></td>
<?php } ?>
<td class="text-end font-monospace"><?= numfmt_format_currency($currency_format, $recurring_invoice_amount, $recurring_invoice_currency_code) ?></td>
<td><?= ucwords($recurring_invoice_frequency) ?>ly</td>
<td><?= $recurring_invoice_last_sent ?></td>
<td><?= $category_name ?></td>
<td>
<?php $sql_saved_payments = mysqli_query($mysqli, "SELECT saved_payment_description, saved_payment_id FROM client_saved_payment_methods WHERE saved_payment_client_id = $client_id");
if (mysqli_num_rows($sql_saved_payments) > 0) { ?>
<form class="form" action="post.php" method="post">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="set_recurring_payment" value="1">
<input type="hidden" name="recurring_invoice_id" value="<?= $recurring_invoice_id ?>">
<select class="form-select select2" name="saved_payment_id" onchange="this.form.submit()">
<option value="0">Disabled</option>
<?php
while ($row = mysqli_fetch_assoc($sql_saved_payments)) {
$saved_payment_id = intval($row['saved_payment_id']);
$saved_payment_description = escapeHtml($row['saved_payment_description']);
?>
<option <?php if ($recurring_payment_saved_payment_id == $saved_payment_id) { echo "selected"; } ?> value="<?= $saved_payment_id ?>"><?= $saved_payment_description ?></option>
<?php } ?>
</select>
</form>
<?php } else { ?>
No Cards on File
<?php } ?>
<td class="text-end itflow-money">
<span class="fw-semibold"><?= escapeHtml(billingMoney($row['recurring_invoice_amount'], $row_currency)) ?></span>
<div class="small text-body-secondary"><?= escapeHtml($row_frequency) ?></div>
</td>
<td>
<span class="p-2 badge text-bg-<?= $status_badge_color ?>">
<?= $status ?>
</span>
<td class="text-end itflow-money"><?= escapeHtml(billingMoney($row['monthly'], $row_currency)) ?></td>
<td class="text-nowrap">
<?= $row_active ? escapeHtml($row['recurring_invoice_next_date']) : '' ?>
<div><?= recurringInvoiceNextPill($row) ?></div>
</td>
<td>
<div class="dropdown dropstart text-center">
<button class="btn btn-secondary btn-sm" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-ellipsis-h"></i>
</button>
<td class="text-nowrap small"><?= $row['recurring_invoice_last_sent'] ? escapeHtml($row['recurring_invoice_last_sent']) : '<span class="text-body-secondary">Not yet</span>' ?></td>
<td class="text-end">
<div class="dropdown dropstart">
<button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown"><i class="fas fa-fw fa-ellipsis-v"></i></button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/recurring_invoice/recurring_invoice_edit.php?id=<?= $recurring_invoice_id ?>">
<i class="fas fa-fw fa-edit me-2"></i>Edit
</a>
<?php if ($status !== 'Active') { ?>
<a class="dropdown-item" href="<?= $row_url ?>"><i class="fas fa-fw fa-eye text-secondary me-2"></i>Open</a>
<a class="dropdown-item" href="invoices.php?client_id=<?= $row_client_id ?>&recurring_invoice_id=<?= $recurring_invoice_id ?>"><i class="fas fa-fw fa-file-invoice-dollar text-secondary me-2"></i>Invoices Made</a>
<?php if ($can_edit) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_recurring_invoice=<?= $recurring_invoice_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<?php if ($row_active && $row['recurring_invoice_next_date'] < date('Y-m-d')) { ?>
<a class="dropdown-item confirm-link" href="post.php?recurring_invoice_catch_up=<?= $recurring_invoice_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-title="Skip the missed runs?" data-confirm-text="The next date moves on to <?= escapeHtml(recurringInvoiceCatchUp($row)) ?>. Nothing is billed for the runs it missed." data-confirm-button="Move on">
<i class="fas fa-fw fa-forward text-secondary me-2"></i>Move On to <?= escapeHtml(recurringInvoiceCatchUp($row)) ?>
</a>
<?php } ?>
<?php if ($row_active) { ?>
<a class="dropdown-item confirm-link" href="post.php?recurring_invoice_set_status=<?= $recurring_invoice_id ?>&status=0&csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-title="Pause <?= escapeHtml($row_number) ?>?" data-confirm-text="No invoices are made from it until it is resumed." data-confirm-button="Pause">
<i class="fas fa-fw fa-pause text-secondary me-2"></i>Pause
</a>
<?php } else { ?>
<a class="dropdown-item" href="post.php?recurring_invoice_set_status=<?= $recurring_invoice_id ?>&status=1&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-play text-secondary me-2"></i>Resume
</a>
<?php } ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/recurring_invoice/recurring_invoice_edit.php?id=<?= $recurring_invoice_id ?>">
<i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<?php } ?>
<?php if ($can_delete) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_recurring_invoice=<?= $recurring_invoice_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-text="<?= escapeHtml($row_number) ?> goes for good, with its lines, autopay and history. The invoices it made stay.">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
@@ -271,17 +285,17 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
</div>
</td>
</tr>
<?php
}
?>
<?php } ?>
</tbody>
</table>
</div>
<?php require_once "../includes/filter_footer.php";
?>
<?php if (!$num_rows[0]) { ?>
<div class="itflow-asset-empty">
<i class="fas fa-redo-alt fa-2x mb-2 opacity-50"></i>
<div><?= $q || $status !== 'active' ? 'No recurring invoices match.' : 'No recurring invoices running.' ?></div>
</div>
<?php } ?>
<?php require_once "../includes/filter_footer.php"; ?>
</div>
<?php
require_once "../includes/footer.php";
<?php require_once "../includes/footer.php";

View File

@@ -5850,3 +5850,358 @@ a.itflow-report-stat:focus-visible {
box-shadow: none !important;
}
}
/* Billing - invoices, quotes and recurring invoices (includes/billing_paper.php,
the agent billing pages and the guest invoice and quote pages) */
.itflow-paper {
position: relative;
padding: 2rem 2.25rem;
background-color: var(--bs-body-bg);
border: 1px solid var(--bs-border-color-translucent);
border-radius: var(--bs-border-radius-lg);
box-shadow: 0 1px 3px rgba(0, 0, 0, .06);
overflow: hidden;
}
.itflow-paper::before {
content: "";
position: absolute;
inset: 0 0 auto 0;
height: 4px;
background-color: var(--bs-primary);
}
.itflow-paper-head,
.itflow-paper-parties,
.itflow-paper-bottom {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 1.25rem 2rem;
}
.itflow-paper-head {
padding-bottom: 1.5rem;
border-bottom: 1px solid var(--bs-border-color-translucent);
}
.itflow-paper-from {
max-width: 24rem;
}
.itflow-paper-logo {
display: block;
max-width: 11rem;
max-height: 4.5rem;
margin-bottom: .75rem;
object-fit: contain;
}
.itflow-paper-title {
font-size: .8rem;
font-weight: 600;
letter-spacing: .14em;
text-transform: uppercase;
color: var(--bs-primary-text-emphasis);
}
.itflow-paper-dates {
display: grid;
grid-template-columns: auto auto;
justify-content: end;
gap: .15rem 1rem;
margin: .5rem 0 0;
font-size: .875rem;
}
.itflow-paper-dates dt {
font-weight: 500;
color: var(--bs-secondary-color);
}
.itflow-paper-dates dd {
margin: 0;
}
.itflow-paper-parties {
padding: 1.25rem 0;
}
.itflow-paper-label {
margin-bottom: .2rem;
font-size: .72rem;
font-weight: 600;
letter-spacing: .08em;
text-transform: uppercase;
color: var(--bs-secondary-color);
}
.itflow-paper-label .text-transform-none {
text-transform: none;
letter-spacing: normal;
}
.itflow-paper-amount {
font-size: 1.6rem;
font-weight: 600;
line-height: 1.2;
font-variant-numeric: tabular-nums;
}
.itflow-paper-scope {
margin-bottom: 1rem;
padding: .55rem .85rem;
border-radius: var(--bs-border-radius);
background-color: var(--bs-tertiary-bg);
}
.itflow-paper-items {
--bs-table-bg: transparent;
font-variant-numeric: tabular-nums;
}
.itflow-paper-items thead th {
font-size: .72rem;
font-weight: 600;
letter-spacing: .06em;
text-transform: uppercase;
color: var(--bs-secondary-color);
border-bottom-width: 2px;
}
.itflow-paper-items td {
padding-top: .7rem;
padding-bottom: .7rem;
}
.itflow-paper-item {
min-width: 12rem;
width: 55%;
}
.itflow-paper-handle {
width: 1.5rem;
padding-left: 0 !important;
padding-right: 0 !important;
}
.itflow-paper-handle .drag-handle {
display: inline-block;
padding: .1rem .25rem;
color: var(--bs-secondary-color);
cursor: grab;
opacity: .5;
}
.itflow-paper-items tbody tr:hover .drag-handle {
opacity: 1;
}
.itflow-paper-actions {
width: 2.5rem;
}
.itflow-paper-actions .btn {
padding-top: 0;
padding-bottom: 0;
}
.itflow-paper-items tr.sortable-ghost {
background-color: var(--bs-primary-bg-subtle);
}
.itflow-paper-items tr.itflow-paper-flash {
animation: itflow-paper-flash 2s ease-out;
}
@keyframes itflow-paper-flash {
from { background-color: var(--bs-warning-bg-subtle); }
to { background-color: transparent; }
}
.itflow-paper-add > td {
padding: .75rem !important;
border-bottom: 0;
background-color: var(--bs-tertiary-bg);
border-radius: var(--bs-border-radius);
}
.itflow-paper-add-grid {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: .5rem;
}
.itflow-paper-add-item {
flex: 1 1 15rem;
}
.itflow-paper-add-qty {
flex: 0 0 4.5rem;
}
.itflow-paper-add-price {
flex: 0 0 7rem;
}
.itflow-paper-add-tax {
flex: 0 1 9rem;
}
.itflow-paper-add-go {
display: flex;
align-items: center;
gap: .5rem;
margin-left: auto;
}
.itflow-paper-bottom {
align-items: flex-start;
padding-top: 1.25rem;
}
.itflow-paper-notes {
flex: 1 1 18rem;
max-width: 32rem;
}
.itflow-paper-totals {
flex: 0 1 19rem;
margin-left: auto;
font-size: .9rem;
font-variant-numeric: tabular-nums;
}
.itflow-paper-totals th {
padding: .25rem 1.5rem .25rem 0;
font-weight: 500;
color: var(--bs-secondary-color);
}
.itflow-paper-totals td {
padding: .25rem 0;
text-align: right;
white-space: nowrap;
}
.itflow-paper-totals tr.text-success th,
.itflow-paper-totals tr.text-success td {
color: var(--bs-success-text-emphasis);
}
.itflow-paper-totals .itflow-paper-total th,
.itflow-paper-totals .itflow-paper-total td {
padding-top: .5rem;
border-top: 1px solid var(--bs-border-color);
font-size: 1.05rem;
font-weight: 600;
color: var(--bs-emphasis-color);
}
.itflow-paper-footer {
margin-top: 2rem;
padding-top: 1rem;
border-top: 1px solid var(--bs-border-color-translucent);
font-size: .8rem;
text-align: center;
color: var(--bs-secondary-color);
}
.itflow-paper-stamp {
position: absolute;
top: 2.75rem;
left: 50%;
margin-left: -4rem;
padding: .2rem .9rem;
border: 3px solid currentColor;
border-radius: var(--bs-border-radius);
font-size: 1.35rem;
font-weight: 700;
letter-spacing: .14em;
text-transform: uppercase;
opacity: .3;
transform: rotate(-12deg);
pointer-events: none;
}
@media (max-width: 767.98px) {
.itflow-paper {
padding: 1.25rem 1rem;
}
.itflow-paper-dates {
justify-content: start;
}
.itflow-paper-totals {
flex-basis: 100%;
}
.itflow-paper-stamp {
display: none;
}
}
/* Header tile and money on the billing pages and lists */
.itflow-billing-tile {
--itflow-asset-tone: var(--bs-primary);
}
.itflow-billing-tile-invoice { --itflow-asset-tone: #2f6fd8; }
.itflow-billing-tile-quote { --itflow-asset-tone: #8a55d6; }
.itflow-billing-tile-recurring { --itflow-asset-tone: #1f9d83; }
[data-bs-theme="dark"] .itflow-billing-tile-invoice { --itflow-asset-tone: #6f9fe0; }
[data-bs-theme="dark"] .itflow-billing-tile-quote { --itflow-asset-tone: #b08ae8; }
[data-bs-theme="dark"] .itflow-billing-tile-recurring { --itflow-asset-tone: #4fc4b0; }
.itflow-money {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.itflow-billing-stat {
display: block;
height: 100%;
padding: .9rem 1.1rem;
border: 1px solid var(--bs-border-color-translucent);
border-radius: var(--bs-border-radius-lg);
background-color: var(--bs-body-bg);
color: inherit;
text-decoration: none;
transition: border-color .12s ease-in-out, box-shadow .12s ease-in-out;
}
a.itflow-billing-stat:hover {
border-color: var(--bs-primary-border-subtle);
box-shadow: 0 1px 4px rgba(0, 0, 0, .06);
color: inherit;
}
.itflow-billing-stat.active {
border-color: var(--bs-primary);
box-shadow: inset 0 0 0 1px var(--bs-primary);
}
.itflow-billing-stat-label {
font-size: .75rem;
font-weight: 600;
letter-spacing: .06em;
text-transform: uppercase;
color: var(--bs-secondary-color);
}
.itflow-billing-stat-value {
margin-top: .15rem;
font-size: 1.45rem;
font-weight: 600;
line-height: 1.25;
font-variant-numeric: tabular-nums;
}
.itflow-billing-stat-note {
font-size: .8rem;
color: var(--bs-secondary-color);
}
.itflow-billing-progress {
height: .45rem;
}
.itflow-billing-table td {
padding-top: .65rem;
padding-bottom: .65rem;
}
.itflow-billing-number {
min-width: 13rem;
}
.itflow-billing-history {
max-height: 26rem;
overflow-y: auto;
}
.itflow-billing-history li {
position: relative;
padding: 0 0 .85rem 1.35rem;
font-size: .875rem;
}
.itflow-billing-history li::before {
content: "";
position: absolute;
left: .3rem;
top: .45rem;
width: .5rem;
height: .5rem;
border-radius: 50%;
background-color: var(--bs-secondary-color);
}
.itflow-billing-history li::after {
content: "";
position: absolute;
left: .52rem;
top: 1.1rem;
bottom: .1rem;
width: 1px;
background-color: var(--bs-border-color);
}
.itflow-billing-history li:last-child::after {
display: none;
}
@media print {
.itflow-paper-col {
flex: 0 0 100% !important;
width: 100% !important;
max-width: 100% !important;
}
.itflow-paper {
border: 0;
box-shadow: none;
padding: 0;
}
.itflow-paper::before {
display: none;
}
}

View File

@@ -50,3 +50,4 @@ require_once __DIR__ . '/functions/project.php';
require_once __DIR__ . '/functions/service.php';
require_once __DIR__ . '/functions/client_export.php';
require_once __DIR__ . '/functions/share.php';
require_once __DIR__ . '/functions/billing.php';

View File

@@ -873,8 +873,8 @@ function getSentMethods() {
* Products for the line-item autocomplete on invoices, quotes and recurring
* invoices.
*
* All three pages share js/product_autocomplete.js, so they must all be handed
* the same shape. They used to carry a SELECT each and they drifted: quote and
* All three pages share js/billing_items.js, so they must all be handed the
* same shape. They used to carry a SELECT each and they drifted: quote and
* recurring invoice only selected label/description/price/tax, so the shared
* onSelect wrote item.product_name - undefined - into the item name field.
*

839
functions/billing.php Normal file
View File

@@ -0,0 +1,839 @@
<?php
/*
* Billing documents - invoices, quotes and recurring invoices.
*
* The three share their shape: a numbered document for a client, with a
* scope, an income category, line items (a name, a description, a quantity,
* a price and a tax), a discount and a total. Each keeps its items in its own
* table - invoice_items, quote_items, recurring_invoice_items - with the same
* columns, and its history in the history table under its own id column.
* billingTypes() says where each keeps what, so one set of functions serves
* all three: the line items (billingItemSave(), billingItemDelete(),
* billingRecalc()), the totals, the numbers, and the statuses and pills the
* lists and pages show.
*
* Amounts are rounded to the cent where they are made - a line's tax and
* total, a document's total - so what is stored is what is shown, printed
* and paid.
*/
/** Where each kind of billing document keeps its parts. */
function billingTypes() {
return [
'invoice' => [
'label' => 'Invoice', 'plural' => 'Invoices', 'icon' => 'fa-file-invoice-dollar',
'table' => 'invoices', 'col' => 'invoice', 'items' => 'invoice_items', 'item_fk' => 'item_invoice_id',
'history_fk' => 'history_invoice_id', 'page' => 'invoice.php', 'list' => 'invoices.php', 'param' => 'invoice_id',
'number_setting' => 'config_invoice_next_number',
],
'quote' => [
'label' => 'Quote', 'plural' => 'Quotes', 'icon' => 'fa-comment-dollar',
'table' => 'quotes', 'col' => 'quote', 'items' => 'quote_items', 'item_fk' => 'item_quote_id',
'history_fk' => 'history_quote_id', 'page' => 'quote.php', 'list' => 'quotes.php', 'param' => 'quote_id',
'number_setting' => 'config_quote_next_number',
],
'recurring' => [
'label' => 'Recurring invoice', 'plural' => 'Recurring invoices', 'icon' => 'fa-redo-alt',
'table' => 'recurring_invoices', 'col' => 'recurring_invoice', 'items' => 'recurring_invoice_items', 'item_fk' => 'item_recurring_invoice_id',
'history_fk' => 'history_recurring_invoice_id', 'page' => 'recurring_invoice.php', 'list' => 'recurring_invoices.php', 'param' => 'recurring_invoice_id',
'number_setting' => 'config_recurring_invoice_next_number',
],
];
}
/** One kind's map, or null. */
function billingType($type) {
return billingTypes()[$type] ?? null;
}
/**
* An amount in a currency, the way the rest of the app shows money - in the
* company's locale, also on the guest pages and in PDFs where the agent
* session's formatter isn't set up.
*/
function billingMoney($amount, $currency_code = '') {
global $currency_format, $session_company_currency;
static $formatter = null;
if ($currency_format instanceof NumberFormatter) {
$format = $currency_format;
} else {
$formatter = $formatter ?: numfmt_create((string) (billingCompany()['company_locale'] ?? '') ?: 'en_US', NumberFormatter::CURRENCY);
$format = $formatter;
}
$currency_code = (string) $currency_code !== '' ? (string) $currency_code : (string) (($session_company_currency ?? '') ?: (billingCompany()['company_currency'] ?? '') ?: 'USD');
return numfmt_format_currency($format, floatval($amount), $currency_code);
}
/** A quantity without trailing zeros - 1, 2.5, 0.25. */
function billingQuantity($quantity) {
$text = rtrim(rtrim(number_format(floatval($quantity), 2, '.', ''), '0'), '.');
return $text === '' || $text === '-0' ? '0' : $text;
}
/** A document's number as shown - INV-123. */
function billingNumber($type, $row) {
$t = billingType($type);
return (string) ($row["{$t['col']}_prefix"] ?? '') . (string) ($row["{$t['col']}_number"] ?? '');
}
/**
* One document by id, with its client - raw, or null. $scoped limits it to
* the clients this agent may open; the guest pages pass false and check the
* document's own url key instead.
*/
function billingRow($type, $id, $scoped = true) {
global $mysqli;
$t = billingType($type);
$id = intval($id);
if (!$t || !$id) {
return null;
}
$c = $t['col'];
$scope = $scoped ? clientScopeSql("{$c}_client_id") : '';
$extra = $type === 'recurring' ? ', recurring_payment_id, recurring_payment_saved_payment_id, recurring_payment_method' : '';
$join = $type === 'recurring' ? 'LEFT JOIN recurring_payments ON recurring_payment_recurring_invoice_id = recurring_invoice_id' : '';
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT {$t['table']}.*, client_id, client_name, client_abbreviation, client_currency_code, client_net_terms,
client_tax_id_number, category_name $extra
FROM {$t['table']}
LEFT JOIN clients ON client_id = {$c}_client_id
LEFT JOIN categories ON category_id = {$c}_category_id
$join
WHERE {$c}_id = $id $scope
LIMIT 1"));
return $row ?: null;
}
/** A document's line items, in order. */
function billingItems($type, $id) {
global $mysqli;
$t = billingType($type);
$id = intval($id);
$items = [];
if (!$t || !$id) {
return $items;
}
$sql = mysqli_query($mysqli, "SELECT item_id, item_name, item_description, item_quantity, item_price, item_subtotal, item_tax, item_total,
item_order, item_tax_id, item_product_id, item_created_at, tax_name, tax_percent
FROM {$t['items']}
LEFT JOIN taxes ON tax_id = item_tax_id
WHERE {$t['item_fk']} = $id
ORDER BY item_order ASC, item_id ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$items[] = $row;
}
return $items;
}
/**
* The taxes to offer - those not archived, and those archived after $since
* (a document's or line's date), so an old line keeps the tax it was given.
*/
function billingTaxes($since = null) {
global $mysqli;
$since_sql = $since ? "OR tax_archived_at > '" . escapeSql($since) . "'" : '';
$taxes = [];
$sql = mysqli_query($mysqli, "SELECT tax_id, tax_name, tax_percent FROM taxes WHERE tax_archived_at IS NULL $since_sql ORDER BY tax_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$taxes[intval($row['tax_id'])] = $row;
}
return $taxes;
}
/** The income categories to offer - the same rule as billingTaxes(). */
function billingCategories($since = null) {
global $mysqli;
$since_sql = $since ? "OR category_archived_at > '" . escapeSql($since) . "'" : '';
$categories = [];
$sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories
WHERE category_type = 'Income' AND (category_archived_at IS NULL $since_sql) ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$categories[intval($row['category_id'])] = $row;
}
return $categories;
}
/** A line's subtotal, tax and total, each to the cent. */
function billingLineAmounts($quantity, $price, $tax_percent) {
$subtotal = round(floatval($quantity) * floatval($price), 2);
$tax = round($subtotal * floatval($tax_percent) / 100, 2);
return [$subtotal, $tax, round($subtotal + $tax, 2)];
}
/** A number from a form - "1,250.50", "$99", "-15" - or null when it is not one. */
function billingNumberInput($value) {
$value = trim(str_replace([',', ' ', '$', '€', '£'], '', (string) $value));
if ($value === '') {
return 0.0;
}
return is_numeric($value) ? round(floatval($value), 2) : null;
}
/**
* May a document's lines change? Not once an invoice is paid, cancelled or
* non-billable, nor once a quote has been answered or invoiced.
*/
function billingCanEditItems($type, $row) {
if (!$row || lookupUserPermission('module_sales') < 2) {
return false;
}
if ($type === 'invoice') {
return !in_array($row['invoice_status'], ['Paid', 'Cancelled', 'Non-Billable'], true);
}
if ($type === 'quote') {
return !in_array($row['quote_status'], ['Accepted', 'Declined', 'Invoiced'], true);
}
return true;
}
/**
* Add a line to a document, or change one. $in: name, description, qty,
* price, tax_id, product_id. For an invoice, a stocked product's stock goes
* down by what the line takes (and back up if the quantity drops). The
* document's total follows. The line's id, or null with $error.
*/
function billingItemSave($type, $doc_id, array $in, $item_id = 0, &$error = '') {
global $mysqli;
$error = '';
$t = billingType($type);
$doc_id = intval($doc_id);
$item_id = intval($item_id);
if (!$t || !$doc_id) {
$error = 'That document no longer exists.';
return null;
}
$name = trim((string) ($in['name'] ?? ''));
$description = trim((string) ($in['description'] ?? ''));
$quantity = billingNumberInput($in['qty'] ?? '1');
$price = billingNumberInput($in['price'] ?? '0');
$tax_id = intval($in['tax_id'] ?? 0);
$product_id = intval($in['product_id'] ?? 0);
if ($name === '') {
$error = 'A line needs a name.';
return null;
}
if (mb_strlen($name) > 200) {
$error = 'That name is too long - keep it under 200 characters, and put the rest in the description.';
return null;
}
if ($quantity === null || $price === null) {
$error = 'The quantity and price have to be numbers.';
return null;
}
if (abs($quantity) >= 1e9 || abs($price) >= 1e11) {
$error = 'That amount is too large.';
return null;
}
$tax_percent = 0;
if ($tax_id) {
$tax = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT tax_percent FROM taxes WHERE tax_id = $tax_id"));
if (!$tax) {
$error = 'That tax no longer exists.';
return null;
}
$tax_percent = floatval($tax['tax_percent']);
}
[$subtotal, $tax_amount, $total] = billingLineAmounts($quantity, $price, $tax_percent);
$old = null;
if ($item_id) {
$old = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT item_quantity, item_product_id FROM {$t['items']} WHERE item_id = $item_id AND {$t['item_fk']} = $doc_id"));
if (!$old) {
$error = 'That line no longer exists.';
return null;
}
$product_id = intval($old['item_product_id']);
} elseif ($product_id && !getFieldById('products', $product_id, 'product_name')) {
$product_id = 0;
}
// Stock moves only with invoices, and only for things on a shelf
if ($type === 'invoice' && $product_id && getFieldById('products', $product_id, 'product_type') === 'product') {
$change = round($quantity - ($old ? floatval($old['item_quantity']) : 0), 2);
if ($change > 0) {
$available = floatval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(SUM(stock_qty), 0) FROM product_stock WHERE stock_product_id = $product_id"))[0]);
if ($available < $change) {
$error = 'Not enough ' . $name . ' in stock - ' . billingQuantity($available) . ' left.';
return null;
}
}
if ($change != 0) {
$note = escapeSql(($change > 0 ? 'QTY ' . billingQuantity($change) . ' to' : 'Returned QTY ' . billingQuantity(-$change) . ' from') . " Invoice $doc_id");
mysqli_query($mysqli, "INSERT INTO product_stock SET stock_qty = " . (-$change) . ", stock_note = '$note', stock_product_id = $product_id");
}
}
$set = "item_name = '" . escapeSql($name) . "', item_description = '" . escapeSql($description) . "',
item_quantity = $quantity, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_tax_id = $tax_id";
if ($item_id) {
mysqli_query($mysqli, "UPDATE {$t['items']} SET $set WHERE item_id = $item_id");
} else {
$order = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(MAX(item_order), 0) + 1 FROM {$t['items']} WHERE {$t['item_fk']} = $doc_id"))[0]);
mysqli_query($mysqli, "INSERT INTO {$t['items']} SET $set, item_order = $order, item_product_id = $product_id, {$t['item_fk']} = $doc_id");
$item_id = mysqli_insert_id($mysqli);
}
billingRecalc($type, $doc_id);
return $item_id;
}
/** Take a line off a document - a stocked product goes back on the shelf. The line, or null. */
function billingItemDelete($type, $doc_id, $item_id) {
global $mysqli;
$t = billingType($type);
$doc_id = intval($doc_id);
$item_id = intval($item_id);
$item = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT item_name, item_quantity, item_product_id FROM {$t['items']} WHERE item_id = $item_id AND {$t['item_fk']} = $doc_id"));
if (!$item) {
return null;
}
mysqli_query($mysqli, "DELETE FROM {$t['items']} WHERE item_id = $item_id");
$product_id = intval($item['item_product_id']);
if ($type === 'invoice' && $product_id && getFieldById('products', $product_id, 'product_type') === 'product' && floatval($item['item_quantity']) > 0) {
$quantity = floatval($item['item_quantity']);
mysqli_query($mysqli, "INSERT INTO product_stock SET stock_qty = $quantity, stock_note = 'Returned QTY " . billingQuantity($quantity) . " back to stock from Invoice $doc_id', stock_product_id = $product_id");
}
billingRecalc($type, $doc_id);
return $item;
}
/** Put a document's lines in this order - item ids, first to last. */
function billingItemsOrder($type, $doc_id, array $item_ids) {
global $mysqli;
$t = billingType($type);
$doc_id = intval($doc_id);
foreach (array_values($item_ids) as $order => $item_id) {
$item_id = intval($item_id);
mysqli_query($mysqli, "UPDATE {$t['items']} SET item_order = " . ($order + 1) . " WHERE item_id = $item_id AND {$t['item_fk']} = $doc_id");
}
}
/**
* A document's total from its lines, less its discount - stored, and for an
* invoice the status follows what has been paid against the new total.
*/
function billingRecalc($type, $doc_id) {
global $mysqli;
$t = billingType($type);
$doc_id = intval($doc_id);
$c = $t['col'];
$lines = floatval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(SUM(item_total), 0) FROM {$t['items']} WHERE {$t['item_fk']} = $doc_id"))[0]);
$discount = floatval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT {$c}_discount_amount FROM {$t['table']} WHERE {$c}_id = $doc_id"))[0] ?? 0);
$amount = round($lines - $discount, 2);
mysqli_query($mysqli, "UPDATE {$t['table']} SET {$c}_amount = $amount WHERE {$c}_id = $doc_id");
if ($type === 'invoice') {
$status = getFieldById('invoices', $doc_id, 'invoice_status');
if (in_array($status, ['Sent', 'Viewed', 'Partial', 'Paid'], true) && invoicePaid($doc_id) > 0) {
updateInvoiceStatusFromPayments($doc_id);
}
}
return $amount;
}
/** Subtotal, discount, tax and total for showing - from the lines, and the stored total. */
function billingTotals($type, $row, array $items) {
$c = billingType($type)['col'];
$subtotal = 0;
$tax = 0;
$taxes = [];
foreach ($items as $item) {
$subtotal += floatval($item['item_subtotal']);
$tax += floatval($item['item_tax']);
if (floatval($item['item_tax']) != 0) {
$label = trim(($item['tax_name'] ?? 'Tax') . ' ' . billingQuantity($item['tax_percent'] ?? 0) . '%');
$taxes[$label] = ($taxes[$label] ?? 0) + floatval($item['item_tax']);
}
}
return [
'subtotal' => round($subtotal, 2),
'discount' => floatval($row["{$c}_discount_amount"] ?? 0),
'credit' => floatval($row["{$c}_credit_amount"] ?? 0),
'tax' => round($tax, 2),
'taxes' => $taxes,
'total' => floatval($row["{$c}_amount"] ?? 0),
];
}
/** The next number for a new invoice, quote or recurring invoice - taken atomically. */
function billingNextNumber($type) {
global $mysqli;
$setting = billingType($type)['number_setting'];
mysqli_query($mysqli, "UPDATE settings SET $setting = LAST_INSERT_ID($setting), $setting = $setting + 1 WHERE company_id = 1");
return intval(mysqli_insert_id($mysqli));
}
/** A document's history, newest first. */
function billingHistory($type, $id) {
global $mysqli;
$t = billingType($type);
$id = intval($id);
$rows = [];
$sql = mysqli_query($mysqli, "SELECT history_status, history_description, history_created_at FROM history WHERE {$t['history_fk']} = $id ORDER BY history_id DESC LIMIT 200");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
}
return $rows;
}
/** Add to a document's history. $description raw. */
function billingLog($type, $id, $status, $description) {
$id = intval($id);
logHistory(escapeSql($status), escapeSql($description), $type === 'invoice' ? $id : 0, $type === 'quote' ? $id : 0, $type === 'recurring' ? $id : 0);
}
/** The company the documents come from - its name, address and how to reach it, raw. */
function billingCompany() {
global $mysqli;
static $company = null;
if ($company === null) {
$company = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT company_name, company_address, company_city, company_state, company_zip, company_country,
company_phone, company_phone_country_code, company_email, company_website, company_logo, company_tax_id, company_locale, company_currency FROM companies WHERE company_id = 1")) ?: [];
$company['phone_display'] = !empty($company['company_phone']) ? formatPhoneNumber($company['company_phone'], $company['company_phone_country_code']) : '';
$logo = basename((string) ($company['company_logo'] ?? ''));
$company['logo_path'] = $logo !== '' && is_file(dirname(__DIR__) . "/uploads/settings/$logo") ? dirname(__DIR__) . "/uploads/settings/$logo" : '';
$company['logo_url'] = $company['logo_path'] !== '' ? '/uploads/settings/' . rawurlencode($logo) : '';
}
return $company;
}
/**
* Who a document is for - the client, its primary location and its billing
* contact (or primary contact), raw.
*/
function billingBillTo($client_id) {
global $mysqli;
$client_id = intval($client_id);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT client_name, client_tax_id_number, location_address, location_city, location_state, location_zip, location_country
FROM clients
LEFT JOIN locations ON location_client_id = client_id AND location_primary = 1 AND location_archived_at IS NULL
WHERE client_id = $client_id LIMIT 1")) ?: [];
$contact = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_name, contact_email, contact_phone, contact_phone_country_code, contact_extension
FROM contacts WHERE contact_client_id = $client_id AND contact_archived_at IS NULL AND (contact_billing = 1 OR contact_primary = 1)
ORDER BY contact_billing DESC, contact_primary DESC LIMIT 1")) ?: [];
$row['contact_name'] = $contact['contact_name'] ?? '';
$row['contact_email'] = $contact['contact_email'] ?? '';
$row['contact_phone'] = !empty($contact['contact_phone']) ? formatPhoneNumber($contact['contact_phone'], $contact['contact_phone_country_code']) . (!empty($contact['contact_extension']) ? ' x' . $contact['contact_extension'] : '') : '';
return $row;
}
/** The guest link for an invoice or a quote. */
function billingGuestUrl($type, $row) {
global $config_base_url;
if ($type === 'invoice') {
return "https://$config_base_url/guest/guest_view_invoice.php?invoice_id=" . intval($row['invoice_id']) . '&url_key=' . rawurlencode((string) $row['invoice_url_key']);
}
return "https://$config_base_url/guest/guest_view_quote.php?quote_id=" . intval($row['quote_id']) . '&url_key=' . rawurlencode((string) $row['quote_url_key']);
}
/** How many of a client's contacts the Send window would offer - none means no Send. */
function billingEmailableContacts($type, $client_id) {
global $mysqli;
$client_id = intval($client_id);
return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_client_id = $client_id AND contact_archived_at IS NULL
AND contact_email IS NOT NULL AND contact_email != '' " . documentContactFilterSql($type)))[0]);
}
/* ---------------------------------------------------------------- Invoices */
/** What has been paid against an invoice. */
function invoicePaid($invoice_id) {
global $mysqli;
$invoice_id = intval($invoice_id);
return round(floatval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(SUM(payment_amount), 0) FROM payments WHERE payment_invoice_id = $invoice_id"))[0]), 2);
}
/** Invoice statuses still waiting on money. */
function invoiceOpenStatuses() {
return ['Sent', 'Viewed', 'Partial'];
}
/**
* Where an invoice stands for payment: open (owed and not late), overdue,
* draft, paid, cancelled or non-billable - with the balance, and how many
* days until it is due or since it was.
*/
function invoiceState($row, $paid) {
$status = (string) $row['invoice_status'];
$balance = round(floatval($row['invoice_amount']) - floatval($paid), 2);
$due = strtotime((string) $row['invoice_due']);
$today = strtotime(date('Y-m-d'));
$days = $due ? intval(round(($due - $today) / 86400)) : 0;
$state = [
'Draft' => 'draft', 'Paid' => 'paid', 'Cancelled' => 'cancelled', 'Non-Billable' => 'nonbillable',
][$status] ?? 'open';
if ($state === 'open' && $balance <= 0) {
$state = 'paid';
}
if ($state === 'open' && $days < 0) {
$state = 'overdue';
}
return ['state' => $state, 'balance' => $balance, 'paid' => round(floatval($paid), 2), 'days' => $days];
}
/** An invoice's status as a badge - its stored status, and Overdue when it is late. */
function invoiceStatusBadge($status, $overdue = false) {
$status = (string) $status;
$html = '<span class="badge rounded-pill text-bg-' . getInvoiceBadgeColor($status) . '">' . escapeHtml($status) . '</span>';
if ($overdue) {
$html .= ' <span class="badge rounded-pill text-bg-danger">Overdue</span>';
}
return $html;
}
/** "Due in 5 days", "Due today", "12 days overdue" - for an invoice still owed. */
function invoiceDuePill($state) {
if (!in_array($state['state'], ['open', 'overdue'], true)) {
return '';
}
$days = $state['days'];
if ($days < 0) {
$late = -$days;
return '<span class="badge rounded-pill text-bg-danger fw-normal" title="Past its due date"><i class="fas fa-exclamation-circle me-1"></i>' . $late . ' ' . ($late === 1 ? 'day' : 'days') . ' overdue</span>';
}
if ($days === 0) {
return '<span class="badge rounded-pill text-bg-warning fw-normal"><i class="fas fa-clock me-1"></i>Due today</span>';
}
$class = $days <= 7 ? 'bg-warning-subtle text-warning-emphasis' : 'bg-secondary-subtle text-secondary-emphasis';
return '<span class="badge rounded-pill ' . $class . ' fw-normal"><i class="far fa-clock me-1"></i>Due in ' . $days . ' ' . ($days === 1 ? 'day' : 'days') . '</span>';
}
/** May a payment be recorded against this invoice? */
function invoiceCanPay($row, $state) {
return in_array($row['invoice_status'], invoiceOpenStatuses(), true) && $state['balance'] > 0;
}
/** Does the client have a card on file with an active provider, to charge from the invoice? */
function invoiceHasSavedCard($client_id) {
global $mysqli;
$client_id = intval($client_id);
return (bool) mysqli_fetch_row(mysqli_query($mysqli, "SELECT 1 FROM client_saved_payment_methods
JOIN payment_providers ON saved_payment_provider_id = payment_provider_id
WHERE saved_payment_client_id = $client_id AND payment_provider_active = 1 LIMIT 1"));
}
/** An invoice's payments, newest first, with the account they went to. */
function invoicePayments($invoice_id) {
global $mysqli;
$invoice_id = intval($invoice_id);
$rows = [];
$sql = mysqli_query($mysqli, "SELECT payment_id, payment_date, payment_amount, payment_currency_code, payment_method, payment_reference, account_name
FROM payments LEFT JOIN accounts ON account_id = payment_account_id
WHERE payment_invoice_id = $invoice_id ORDER BY payment_date DESC, payment_id DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
}
return $rows;
}
/** The tickets billed on an invoice, with the time worked on each. */
function invoiceTickets($invoice_id) {
global $mysqli;
$invoice_id = intval($invoice_id);
$rows = [];
$sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_created_at, ticket_closed_at,
COALESCE(SUM(TIME_TO_SEC(ticket_reply_time_worked)), 0) AS seconds
FROM tickets LEFT JOIN ticket_replies ON ticket_reply_ticket_id = ticket_id
WHERE ticket_invoice_id = $invoice_id
GROUP BY ticket_id ORDER BY ticket_id DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
}
return $rows;
}
/** A client's billable tickets, resolved or closed, not on an invoice yet. */
function invoiceUnbilledTickets($client_id) {
global $mysqli;
$client_id = intval($client_id);
$rows = [];
$sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_created_at,
COALESCE(SUM(TIME_TO_SEC(ticket_reply_time_worked)), 0) AS seconds
FROM tickets LEFT JOIN ticket_replies ON ticket_reply_ticket_id = ticket_id
WHERE ticket_client_id = $client_id AND ticket_billable = 1 AND ticket_invoice_id = 0 AND ticket_status IN (4, 5)
GROUP BY ticket_id ORDER BY ticket_id DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
}
return $rows;
}
/** Seconds as "1h 30m". */
function billingDuration($seconds) {
$seconds = intval($seconds);
$hours = intdiv($seconds, 3600);
$minutes = intdiv($seconds % 3600, 60);
if (!$hours && !$minutes) {
return $seconds ? '<1m' : '-';
}
return trim(($hours ? "{$hours}h " : '') . ($minutes ? "{$minutes}m" : ''));
}
/* ------------------------------------------------------------------ Quotes */
/** A quote's badge colour by status. */
function getQuoteBadgeColor($status) {
return ['Sent' => 'warning', 'Viewed' => 'primary', 'Accepted' => 'success', 'Declined' => 'danger', 'Invoiced' => 'info'][(string) $status] ?? 'secondary';
}
/** Has a quote passed its expiry without an answer? */
function quoteExpired($row) {
return in_array($row['quote_status'], ['Draft', 'Sent', 'Viewed'], true)
&& !empty($row['quote_expire']) && strtotime((string) $row['quote_expire']) < strtotime(date('Y-m-d'));
}
/** A quote's status as a badge, and Expired when it ran out unanswered. */
function quoteStatusBadge($row) {
$html = '<span class="badge rounded-pill text-bg-' . getQuoteBadgeColor($row['quote_status']) . '">' . escapeHtml($row['quote_status']) . '</span>';
if (quoteExpired($row)) {
$html .= ' <span class="badge rounded-pill text-bg-dark">Expired</span>';
}
return $html;
}
/** "Expires in 5 days", "Expired 3 days ago" - for a quote not answered yet. */
function quoteExpiryPill($row) {
if (!in_array($row['quote_status'], ['Draft', 'Sent', 'Viewed'], true) || empty($row['quote_expire'])) {
return '';
}
$days = intval(round((strtotime((string) $row['quote_expire']) - strtotime(date('Y-m-d'))) / 86400));
if ($days < 0) {
return '<span class="badge rounded-pill bg-dark-subtle text-dark-emphasis fw-normal">Expired ' . (-$days) . ' ' . (-$days === 1 ? 'day' : 'days') . ' ago</span>';
}
if ($days === 0) {
return '<span class="badge rounded-pill text-bg-warning fw-normal">Expires today</span>';
}
$class = $days <= 7 ? 'bg-warning-subtle text-warning-emphasis' : 'bg-secondary-subtle text-secondary-emphasis';
return '<span class="badge rounded-pill ' . $class . ' fw-normal">Expires in ' . $days . ' ' . ($days === 1 ? 'day' : 'days') . '</span>';
}
/* ------------------------------------------------------- Recurring invoices */
/** How often a recurring invoice runs => label. */
function recurringInvoiceFrequencies() {
return ['month' => 'Monthly', 'year' => 'Yearly'];
}
/** What a recurring invoice brings in a month. */
function recurringInvoiceMonthly($amount, $frequency) {
return $frequency === 'year' ? floatval($amount) / 12 : floatval($amount);
}
/** "In 5 days", "Today", "3 days late" - for an active recurring invoice's next run. */
function recurringInvoiceNextPill($row) {
if (intval($row['recurring_invoice_status']) !== 1) {
return '<span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal"><i class="fas fa-pause me-1"></i>Paused</span>';
}
$days = intval(round((strtotime((string) $row['recurring_invoice_next_date']) - strtotime(date('Y-m-d'))) / 86400));
if ($days < 0) {
return '<span class="badge rounded-pill text-bg-danger fw-normal" title="The next run date is in the past - it will not run until it is moved forward"><i class="fas fa-exclamation-triangle me-1"></i>' . (-$days) . ' ' . (-$days === 1 ? 'day' : 'days') . ' late</span>';
}
if ($days === 0) {
return '<span class="badge rounded-pill text-bg-info fw-normal">Today</span>';
}
return '<span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal">In ' . $days . ' ' . ($days === 1 ? 'day' : 'days') . '</span>';
}
/**
* A run date one period on - the way MySQL's DATE_ADD (and so the nightly
* run) does it: the 31st of January plus a month is the 28th of February.
*/
function recurringInvoiceStep($date, $frequency) {
$d = new DateTime((string) $date);
$day = intval($d->format('j'));
$d->modify('first day of this month')->modify($frequency === 'year' ? '+12 months' : '+1 month');
$d->setDate(intval($d->format('Y')), intval($d->format('n')), min($day, intval($d->format('t'))));
return $d->format('Y-m-d');
}
/** The next few dates a recurring invoice will run on. */
function recurringInvoiceUpcoming($row, $count = 3) {
$dates = [];
$date = (string) $row['recurring_invoice_next_date'];
for ($i = 0; $i < $count && $date; $i++) {
$dates[] = $date;
$date = recurringInvoiceStep($date, $row['recurring_invoice_frequency']);
}
return $dates;
}
/** The first run date from a recurring invoice's next date on that hasn't passed - the missed runs skipped. */
function recurringInvoiceCatchUp($row) {
$date = (string) $row['recurring_invoice_next_date'];
$today = date('Y-m-d');
for ($guard = 0; $date < $today && $guard < 1200; $guard++) {
$date = recurringInvoiceStep($date, $row['recurring_invoice_frequency']);
}
return $date;
}
/** The invoices a recurring invoice has made, newest first, with what has been paid on each. */
function recurringInvoiceGenerated($recurring_invoice_id, $limit = 12) {
global $mysqli;
$recurring_invoice_id = intval($recurring_invoice_id);
$limit = max(1, intval($limit));
$rows = [];
$sql = mysqli_query($mysqli, "SELECT invoice_id, invoice_prefix, invoice_number, invoice_date, invoice_due, invoice_amount, invoice_status, invoice_currency_code,
(SELECT COALESCE(SUM(payment_amount), 0) FROM payments WHERE payment_invoice_id = invoice_id) AS paid
FROM invoices WHERE invoice_recurring_invoice_id = $recurring_invoice_id
ORDER BY invoice_date DESC, invoice_id DESC LIMIT $limit");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
}
return $rows;
}
/* ---------------------------------------------------------------- Showing */
/** A document's history as a timeline, newest first. */
function billingHistoryHtml(array $rows) {
if (!$rows) {
return '<div class="itflow-asset-empty py-4">Nothing has happened to it yet.</div>';
}
$html = '<ul class="list-unstyled mb-0 p-3 itflow-billing-history">';
foreach ($rows as $row) {
// Older guest views put the browser's HTML into the description
$description = trim(preg_replace('/[ \t]+/', ' ', strip_tags((string) $row['history_description'])));
$html .= '<li><div>' . nl2br(escapeHtml($description)) . '</div>'
. '<div class="small text-body-secondary">' . escapeHtml($row['history_status'])
. ' &middot; <span title="' . escapeHtml($row['history_created_at']) . '">' . escapeHtml(timeAgo($row['history_created_at'])) . '</span></div></li>';
}
return $html . '</ul>';
}
/** The square tile for a kind of billing document. */
function billingTile($type, $size = '') {
$t = billingType($type);
return '<span class="itflow-asset-icon itflow-billing-tile itflow-billing-tile-' . $type . ($size ? " itflow-asset-icon-$size" : '') . '" aria-hidden="true"><i class="fas fa-fw ' . $t['icon'] . '"></i></span>';
}
/** The "not found" page for a billing document that isn't there or can't be opened. */
function billingNotFound($type, $client_url = '') {
$t = billingType($type);
echo '<div class="itflow-asset-empty mt-5"><i class="fas ' . $t['icon'] . ' fa-3x mb-3 opacity-50"></i>'
. '<h1 class="h4">That ' . strtolower($t['label']) . " isn't here</h1>"
. '<p>It may have been deleted, or it belongs to a client you can\'t open.</p>'
. '<a class="btn btn-outline-secondary" href="' . $t['list'] . ($client_url ? '?' . rtrim($client_url, '&') : '') . '"><i class="fas fa-arrow-left me-2"></i>Back to ' . $t['plural'] . '</a></div>';
}
/* ---------------------------------------------------------------- Payments */
/**
* The accounts a payment can go to, with each one's balance - one query.
* $keep_id keeps an archived account in the list (the one a payment is in).
*/
function paymentAccounts($keep_id = 0) {
global $mysqli;
$keep_id = intval($keep_id);
$accounts = [];
$sql = mysqli_query($mysqli, "SELECT account_id, account_name, account_currency_code, account_archived_at,
opening_balance + COALESCE(payments_in.total, 0) + COALESCE(revenues_in.total, 0) - COALESCE(expenses_out.total, 0) AS balance
FROM accounts
LEFT JOIN (SELECT payment_account_id, SUM(payment_amount) AS total FROM payments GROUP BY payment_account_id) AS payments_in ON payments_in.payment_account_id = account_id
LEFT JOIN (SELECT revenue_account_id, SUM(revenue_amount) AS total FROM revenues GROUP BY revenue_account_id) AS revenues_in ON revenues_in.revenue_account_id = account_id
LEFT JOIN (SELECT expense_account_id, SUM(expense_amount) AS total FROM expenses GROUP BY expense_account_id) AS expenses_out ON expenses_out.expense_account_id = account_id
WHERE account_archived_at IS NULL OR account_id = $keep_id
ORDER BY account_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$accounts[intval($row['account_id'])] = $row;
}
return $accounts;
}
/** The ways a payment can be made - Cash, Check, ACH and whatever else is set up. */
function paymentMethods() {
global $mysqli;
$methods = [];
$sql = mysqli_query($mysqli, "SELECT payment_method_name FROM payment_methods ORDER BY payment_method_name ASC");
while ($row = mysqli_fetch_row($sql)) {
$methods[] = $row[0];
}
return $methods;
}
/** Can clients pay invoices online - is a payment provider turned on? */
function billingOnlinePayments() {
global $mysqli;
static $online = null;
if ($online === null) {
$online = (bool) mysqli_fetch_row(mysqli_query($mysqli, "SELECT 1 FROM payment_providers WHERE payment_provider_active = 1 LIMIT 1"));
}
return $online;
}
/* -------------------------------------------------------------------- PDFs */
/**
* An invoice, quote or recurring invoice as a PDF - or an invoice's packing
* slip ($variant 'packing'): ['name' => file name, 'data' => the PDF].
* $row is billingRow(). See functions/billing_pdf.php.
*/
function billingPdf($type, array $row, $variant = 'document') {
require_once __DIR__ . '/../libs/TCPDF/tcpdf.php';
require_once __DIR__ . '/billing_pdf.php';
return billingPdfRender($type, $row, $variant);
}
/** Hand a billingPdf() to the browser - opened in a tab, or saved with $download. */
function billingPdfSend(array $pdf, $download = false) {
header('Content-Type: application/pdf');
header('Content-Disposition: ' . ($download ? 'attachment' : 'inline') . '; filename="' . $pdf['name'] . '"');
header('Content-Length: ' . strlen($pdf['data']));
header('Cache-Control: private, no-store');
header('X-Content-Type-Options: nosniff');
echo $pdf['data'];
exit;
}
/* ------------------------------------------------------------- Guest pages */
/**
* A client has opened an invoice or quote from its link: a sent one becomes
* viewed, the view goes in its history (where from, in plain text), and the
* agents hear about it while it still matters - an invoice not yet paid, a
* quote not yet answered.
*/
function billingGuestViewed($type, array $row) {
global $mysqli;
$t = billingType($type);
$c = $t['col'];
$id = intval($row["{$c}_id"]);
$status = (string) $row["{$c}_status"];
$number = billingNumber($type, $row);
if ($status === 'Sent') {
mysqli_query($mysqli, "UPDATE {$t['table']} SET {$c}_status = 'Viewed' WHERE {$c}_id = $id AND {$c}_status = 'Sent'");
}
$agent = (string) ($_SERVER['HTTP_USER_AGENT'] ?? '');
$where = implode(' - ', array_filter([getIP(), trim(strip_tags(getOS($agent))), trim(strip_tags(getWebBrowser($agent)))], function ($part) {
return $part !== '' && $part !== '-';
}));
billingLog($type, $id, $status === 'Sent' ? 'Viewed' : $status, 'Viewed by the client' . ($where !== '' ? " - $where" : ''));
$matters = $type === 'invoice' ? !in_array($status, ['Paid', 'Cancelled', 'Non-Billable'], true) : in_array($status, ['Draft', 'Sent', 'Viewed'], true);
if ($matters) {
appNotify($t['label'] . ' Viewed', escapeSql("$number has been viewed by {$row['client_name']}" . ($where !== '' ? " - $where" : '')), "/agent/{$t['page']}?{$t['param']}=$id", intval($row['client_id']));
}
}
/** A client's invoices still owed, oldest first, with what is left on each - their statement. */
function billingClientOpenInvoices($client_id) {
global $mysqli;
$client_id = intval($client_id);
$rows = [];
$sql = mysqli_query($mysqli, "SELECT invoice_id, invoice_prefix, invoice_number, invoice_scope, invoice_date, invoice_due, invoice_status,
invoice_amount, invoice_currency_code, invoice_url_key,
COALESCE((SELECT SUM(payment_amount) FROM payments WHERE payment_invoice_id = invoice_id), 0) AS paid
FROM invoices
WHERE invoice_client_id = $client_id AND invoice_status IN ('Sent', 'Viewed', 'Partial')
ORDER BY invoice_date ASC, invoice_number ASC");
while ($row = mysqli_fetch_assoc($sql)) {
if (round(floatval($row['invoice_amount']) - floatval($row['paid']), 2) > 0) {
$rows[] = $row;
}
}
return $rows;
}

305
functions/billing_pdf.php Normal file
View File

@@ -0,0 +1,305 @@
<?php
/*
* Invoice, quote and packing slip PDFs - loaded by billingPdf() once TCPDF
* itself is, as a class has to follow the one it extends.
*
* One look for all of them, the same as the document on screen: a band of
* the accent colour, the logo and who it is from, what it is and its
* number and dates, who it is for and what it comes to, the lines, the
* totals and notes, and the footer from the billing settings with the page
* number. An invoice still owed carries a code to scan to open it online
* (and pay, when online payments are on); a quote, one to answer it. Paid,
* cancelled, accepted and declined ones are stamped.
*/
class BillingPdf extends TCPDF {
public $footer_text = '';
public $footer_label = '';
public function Header() {
// The accent band across the top of every page
$this->SetFillColor(13, 110, 253);
$this->Rect(0, 0, $this->getPageWidth(), 2.5, 'F');
}
public function Footer() {
$margins = $this->getMargins();
$width = $this->getPageWidth() - $margins['left'] - $margins['right'];
$this->SetY(-14);
$this->SetDrawColor(222, 226, 230);
$this->SetLineWidth(0.2);
$this->Line($margins['left'], $this->GetY() - 1.5, $this->getPageWidth() - $margins['right'], $this->GetY() - 1.5);
$this->SetFont('dejavusans', '', 7);
$this->SetTextColor(108, 117, 125);
$this->Cell($width * 0.75, 4, $this->footer_label, 0, 0, 'L');
$this->Cell($width * 0.25, 4, 'Page ' . $this->getAliasNumPage() . ' of ' . $this->getAliasNbPages(), 0, 0, 'R');
}
}
/**
* Draw an invoice, quote or recurring invoice - or an invoice's packing slip
* ($variant 'packing') - and return ['name' => file name, 'data' => the PDF].
*/
function billingPdfRender($type, array $row, $variant = 'document') {
global $config_invoice_footer, $config_quote_footer, $config_invoice_show_tax_id;
$t = billingType($type);
$c = $t['col'];
$id = intval($row["{$c}_id"]);
$company = billingCompany();
$bill_to = billingBillTo($row['client_id']);
$items = billingItems($type, $id);
$totals = billingTotals($type, $row, $items);
$currency = (string) $row["{$c}_currency_code"];
$number = billingNumber($type, $row);
$packing = $variant === 'packing';
$e = function ($value) {
return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
};
$money = function ($amount) use ($currency, $e) {
return $e(billingMoney($amount, $currency));
};
$status = $type === 'recurring' ? '' : (string) $row["{$c}_status"];
$paid = $type === 'invoice' ? invoicePaid($id) : 0;
$state = $type === 'invoice' ? invoiceState($row, $paid) : null;
// Letter for North America, A4 everywhere else
$format = in_array($company['company_country'] ?? '', ['United States', 'USA', 'US', 'Canada'], true) ? 'LETTER' : 'A4';
$pdf = new BillingPdf('P', 'mm', $format, true, 'UTF-8', false);
$title = $packing ? 'Packing Slip' : ['invoice' => 'Invoice', 'quote' => 'Quote', 'recurring' => 'Recurring Invoice'][$type];
$pdf->SetCreator('ITFlow');
$pdf->SetAuthor((string) ($company['company_name'] ?? ''));
$pdf->SetTitle("$title $number");
$pdf->SetMargins(16, 14, 16);
$pdf->SetHeaderMargin(0);
$pdf->SetFooterMargin(12);
$pdf->SetAutoPageBreak(true, 20);
$pdf->setFontSubsetting(true);
$pdf->setImageScale(1.5);
$pdf->footer_label = trim(($company['company_name'] ?? '') . ' · ' . "$title $number", ' ·');
$pdf->AddPage();
$margins = $pdf->getMargins();
$width = $pdf->getPageWidth() - $margins['left'] - $margins['right'];
$grey = '#6c757d';
$line = '#dee2e6';
$label = function ($text) use ($grey, $e) {
return '<span style="font-size:6.5pt; color:' . $grey . '; font-weight:bold;">' . $e(strtoupper($text)) . '</span>';
};
// Who it is from, and what it is
$from_lines = array_filter([
formatAddress($company['company_address'] ?? '', $company['company_city'] ?? '', $company['company_state'] ?? '', $company['company_zip'] ?? '', $company['company_country'] ?? '', "\n"),
implode(' · ', array_filter([$company['company_email'] ?? '', $company['phone_display'] ?? ''])),
$company['company_website'] ?? '',
!empty($config_invoice_show_tax_id) && !empty($company['company_tax_id']) ? 'Tax ID: ' . $company['company_tax_id'] : '',
]);
$logo = !empty($company['logo_path']) ? '<img src="' . $e($company['logo_path']) . '" height="42"><br>' : '';
if ($packing) {
$dates = ['Invoice' => $number, 'Date' => $row['invoice_date']];
} elseif ($type === 'invoice') {
$dates = ['Invoice date' => $row['invoice_date'], 'Due' => $row['invoice_due']];
} elseif ($type === 'quote') {
$dates = ['Quote date' => $row['quote_date'], 'Valid until' => $row['quote_expire']];
} else {
$dates = ['Billed' => recurringInvoiceFrequencies()[$row['recurring_invoice_frequency']] ?? $row['recurring_invoice_frequency'], 'Next invoice' => $row['recurring_invoice_next_date']];
}
$dates_html = '';
foreach ($dates as $date_label => $value) {
$dates_html .= '<tr><td align="right" style="color:' . $grey . ';">' . $e($date_label) . '</td><td align="right" width="30mm">' . $e($value) . '</td></tr>';
}
$html = '<table cellpadding="0" cellspacing="0" width="100%"><tr>
<td width="58%">' . $logo . '<span style="font-size:12pt; font-weight:bold;">' . $e($company['company_name'] ?? '') . '</span><br><span style="font-size:7.5pt; color:' . $grey . '; line-height:1.4;">' . nl2br($e(implode("\n", $from_lines))) . '</span></td>
<td width="42%" align="right"><span style="font-size:8pt; color:#0a58ca; font-weight:bold; letter-spacing:2px;">' . $e(strtoupper($title)) . '</span><br><span style="font-size:15pt; font-weight:bold;">' . $e($number) . '</span><br>
<table cellpadding="1.2" cellspacing="0" width="100%" style="font-size:8pt;">' . $dates_html . '</table></td>
</tr></table>';
$pdf->SetFont('dejavusans', '', 8.5);
$pdf->SetTextColor(33, 37, 41);
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->SetDrawColor(222, 226, 230);
$pdf->SetLineWidth(0.2);
$pdf->Ln(1);
$pdf->Line($margins['left'], $pdf->GetY(), $margins['left'] + $width, $pdf->GetY());
$pdf->Ln(4);
// Who it is for, and what it comes to
$to_lines = array_filter([
formatAddress($bill_to['location_address'] ?? '', $bill_to['location_city'] ?? '', $bill_to['location_state'] ?? '', $bill_to['location_zip'] ?? '', $bill_to['location_country'] ?? '', "\n"),
$bill_to['contact_name'] ?? '',
implode(' · ', array_filter([$bill_to['contact_email'] ?? '', $bill_to['contact_phone'] ?? ''])),
!empty($bill_to['client_tax_id_number']) ? 'Tax ID: ' . $bill_to['client_tax_id_number'] : '',
]);
$to_label = $packing ? 'Ship to' : ($type === 'quote' ? 'Prepared for' : 'Bill to');
if ($packing) {
$amount_html = '';
} elseif ($type === 'invoice') {
$done = in_array($status, ['Paid', 'Cancelled', 'Non-Billable'], true);
$amount_html = $label($done ? 'Balance' : 'Amount due') . '<br><span style="font-size:17pt; font-weight:bold;">' . $money($state['balance']) . '</span>'
. (!$done && $status !== 'Draft' && $state['balance'] > 0 ? '<br><span style="font-size:7.5pt; color:' . $grey . ';">by ' . $e($row['invoice_due']) . '</span>' : '');
} elseif ($type === 'quote') {
$amount_html = $label('Quote total') . '<br><span style="font-size:17pt; font-weight:bold;">' . $money($totals['total']) . '</span>';
} else {
$amount_html = $label($row['recurring_invoice_frequency'] === 'year' ? 'Each year' : 'Each month') . '<br><span style="font-size:17pt; font-weight:bold;">' . $money($totals['total']) . '</span>';
}
$html = '<table cellpadding="0" cellspacing="0" width="100%"><tr>
<td width="60%">' . $label($to_label) . '<br><span style="font-size:10pt; font-weight:bold;">' . $e($bill_to['client_name'] ?? $row['client_name']) . '</span><br><span style="font-size:7.5pt; color:' . $grey . '; line-height:1.4;">' . nl2br($e(implode("\n", $to_lines))) . '</span></td>
<td width="40%" align="right">' . $amount_html . '</td>
</tr></table>';
$pdf->writeHTML($html, true, false, true, false, '');
// A stamp across a document that is done with
$stamp = null;
if (!$packing) {
if ($type === 'invoice' && $status === 'Paid') {
$stamp = ['PAID', [25, 135, 84]];
} elseif ($type === 'invoice' && $status === 'Cancelled') {
$stamp = ['CANCELLED', [220, 53, 69]];
} elseif ($type === 'quote' && in_array($status, ['Accepted', 'Invoiced'], true)) {
$stamp = ['ACCEPTED', [25, 135, 84]];
} elseif ($type === 'quote' && $status === 'Declined') {
$stamp = ['DECLINED', [220, 53, 69]];
}
}
if ($stamp) {
$y = $pdf->GetY();
$pdf->SetAlpha(0.28);
$pdf->StartTransform();
$pdf->Rotate(12, $margins['left'] + $width / 2, 21);
$pdf->SetFont('dejavusans', 'B', 20);
$pdf->SetTextColor(...$stamp[1]);
$pdf->SetDrawColor(...$stamp[1]);
$pdf->SetLineWidth(0.8);
$stamp_width = $pdf->GetStringWidth($stamp[0]) + 8;
$pdf->SetXY($margins['left'] + $width / 2 - $stamp_width / 2, 15.5);
$pdf->Cell($stamp_width, 11, $stamp[0], 1, 0, 'C');
$pdf->StopTransform();
$pdf->SetAlpha(1);
$pdf->SetDrawColor(222, 226, 230);
$pdf->SetLineWidth(0.2);
$pdf->SetTextColor(33, 37, 41);
$pdf->SetXY($margins['left'], $y);
}
$pdf->SetFont('dejavusans', '', 8.5);
if (trim((string) $row["{$c}_scope"]) !== '') {
$pdf->Ln(1);
$pdf->writeHTML('<table cellpadding="5" cellspacing="0" width="100%"><tr><td style="background-color:#f1f3f5;">'
. $label('For') . '&nbsp;&nbsp;' . $e($row["{$c}_scope"]) . '</td></tr></table>', true, false, true, false, '');
}
$pdf->Ln(2);
// The lines
$th = 'font-size:6.5pt; color:' . $grey . '; font-weight:bold; border-bottom:0.6px solid #adb5bd;';
$td = 'border-bottom:0.3px solid ' . $line . ';';
if ($packing) {
$html = '<table cellpadding="4" cellspacing="0" width="100%"><thead><tr>
<td width="74%" style="' . $th . '">ITEM</td><td width="13%" align="right" style="' . $th . '">QTY</td><td width="13%" align="center" style="' . $th . '">PACKED</td></tr></thead>';
foreach ($items as $item) {
$html .= '<tr nobr="true"><td width="74%" style="' . $td . '"><b>' . $e($item['item_name']) . '</b>'
. (trim((string) $item['item_description']) !== '' ? '<br><span style="font-size:7.5pt; color:' . $grey . ';">' . nl2br($e($item['item_description'])) . '</span>' : '') . '</td>
<td width="13%" align="right" style="' . $td . '">' . $e(billingQuantity($item['item_quantity'])) . '</td>
<td width="13%" align="center" style="' . $td . '"><span style="font-size:11pt;">☐</span></td></tr>';
}
$html .= '</table>';
} else {
$html = '<table cellpadding="4" cellspacing="0" width="100%"><thead><tr>
<td width="49%" style="' . $th . '">ITEM</td><td width="9%" align="right" style="' . $th . '">QTY</td>
<td width="14%" align="right" style="' . $th . '">PRICE</td><td width="13%" align="right" style="' . $th . '">TAX</td>
<td width="15%" align="right" style="' . $th . '">AMOUNT</td></tr></thead>';
foreach ($items as $item) {
$tax_label = floatval($item['item_tax']) != 0 || intval($item['item_tax_id'])
? '<br><span style="font-size:6.5pt; color:' . $grey . ';">' . $e(trim(($item['tax_name'] ?? '') . ' ' . ($item['tax_percent'] !== null ? billingQuantity($item['tax_percent']) . '%' : ''))) . '</span>'
: '';
$html .= '<tr nobr="true"><td width="49%" style="' . $td . '"><b>' . $e($item['item_name']) . '</b>'
. (trim((string) $item['item_description']) !== '' ? '<br><span style="font-size:7.5pt; color:' . $grey . ';">' . nl2br($e($item['item_description'])) . '</span>' : '') . '</td>
<td width="9%" align="right" style="' . $td . '">' . $e(billingQuantity($item['item_quantity'])) . '</td>
<td width="14%" align="right" style="' . $td . '">' . $money($item['item_price']) . '</td>
<td width="13%" align="right" style="' . $td . '">' . ($tax_label !== '' ? $money($item['item_tax']) . $tax_label : '<span style="color:' . $grey . ';">-</span>') . '</td>
<td width="15%" align="right" style="' . $td . '"><b>' . $money($item['item_total']) . '</b></td></tr>';
}
if (!$items) {
$html .= '<tr><td colspan="5" align="center" style="color:' . $grey . ';">Nothing on it yet.</td></tr>';
}
$html .= '</table>';
}
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Ln(3);
if ($packing) {
// Who packed it, and who took it
$sign = '<table cellpadding="5" cellspacing="0" width="100%"><tr nobr="true">
<td width="48%" style="border:0.4px solid #adb5bd; height:22mm;">' . $label('Packed by') . '<br><br><br><span style="font-size:7pt; color:' . $grey . ';">Name, signature and date</span></td>
<td width="4%"></td>
<td width="48%" style="border:0.4px solid #adb5bd; height:22mm;">' . $label('Received by') . '<br><br><br><span style="font-size:7pt; color:' . $grey . ';">Name, signature and date</span></td>
</tr></table>';
$pdf->writeHTML($sign, true, false, true, false, '');
} else {
// Notes, and what it all comes to
$rows = '<tr><td style="color:' . $grey . ';">Subtotal</td><td align="right">' . $money($totals['subtotal']) . '</td></tr>';
if ($totals['discount'] != 0) {
$rows .= '<tr><td style="color:' . $grey . ';">Discount</td><td align="right">-' . $money($totals['discount']) . '</td></tr>';
}
foreach ($totals['taxes'] as $tax_label => $tax_amount) {
$rows .= '<tr><td style="color:' . $grey . ';">' . $e($tax_label) . '</td><td align="right">' . $money($tax_amount) . '</td></tr>';
}
if ($totals['credit'] > 0) {
$rows .= '<tr><td style="color:' . $grey . ';">Credit</td><td align="right">-' . $money($totals['credit']) . '</td></tr>';
}
$rows .= '<tr><td style="border-top:0.6px solid #adb5bd; font-size:10pt;"><b>Total</b></td><td align="right" style="border-top:0.6px solid #adb5bd; font-size:10pt;"><b>' . $money($totals['total']) . '</b></td></tr>';
if ($type === 'invoice' && $state['paid'] > 0) {
$rows .= '<tr><td style="color:#198754;">Paid</td><td align="right" style="color:#198754;">-' . $money($state['paid']) . '</td></tr>';
$rows .= '<tr><td style="border-top:0.6px solid #adb5bd; font-size:10pt;"><b>Balance due</b></td><td align="right" style="border-top:0.6px solid #adb5bd; font-size:10pt;"><b>' . $money($state['balance']) . '</b></td></tr>';
}
$note = trim((string) $row["{$c}_note"]);
$html = '<table cellpadding="0" cellspacing="0" width="100%"><tr nobr="true">
<td width="54%">' . ($note !== '' ? $label('Notes') . '<br><span style="font-size:8pt;">' . nl2br($e($note)) . '</span>' : '') . '</td>
<td width="6%"></td>
<td width="40%"><table cellpadding="2.5" cellspacing="0" width="100%" style="font-size:8.5pt;">' . $rows . '</table></td>
</tr></table>';
$pdf->writeHTML($html, true, false, true, false, '');
// Open it online - pay an invoice still owed, answer a quote still waiting
$online = null;
if ($type === 'invoice' && in_array($status, invoiceOpenStatuses(), true) && $state['balance'] > 0) {
$online = [billingOnlinePayments() ? 'Pay online' : 'View online', billingOnlinePayments() ? 'Scan to open this invoice and pay it by card.' : 'Scan to open this invoice online.'];
} elseif ($type === 'quote' && in_array($status, ['Sent', 'Viewed'], true) && !quoteExpired($row)) {
$online = ['Answer online', 'Scan to open this quote and accept or decline it.'];
}
if ($online) {
$url = billingGuestUrl($type, $row);
if ($pdf->GetY() > $pdf->getPageHeight() - 60) {
$pdf->AddPage();
}
$pdf->Ln(4);
$y = $pdf->GetY();
$pdf->SetFillColor(241, 243, 245);
$pdf->RoundedRect($margins['left'], $y, $width, 28, 2, '1111', 'F');
$pdf->write2DBarcode($url, 'QRCODE,M', $margins['left'] + 3, $y + 3, 22, 22, ['border' => false, 'padding' => 0, 'fgcolor' => [33, 37, 41], 'bgcolor' => false], 'N');
$pdf->SetXY($margins['left'] + 30, $y + 6);
$pdf->SetFont('dejavusans', 'B', 10);
$pdf->Cell($width - 34, 5, $online[0], 0, 2, 'L');
$pdf->SetFont('dejavusans', '', 7.5);
$pdf->SetTextColor(108, 117, 125);
$pdf->MultiCell($width - 34, 4, $online[1] . "\n" . $url, 0, 'L', false, 1, $margins['left'] + 30);
$pdf->SetTextColor(33, 37, 41);
$pdf->SetY($y + 30);
}
$footer = trim((string) ($type === 'quote' ? $config_quote_footer : $config_invoice_footer));
if ($footer !== '') {
$pdf->Ln(4);
$pdf->SetFont('dejavusans', '', 7.5);
$pdf->SetTextColor(108, 117, 125);
$pdf->MultiCell($width, 4, $footer, 0, 'C', false, 1);
}
}
$date = $type === 'recurring' ? date('Y-m-d') : (string) $row["{$c}_date"];
$name = preg_replace('/[^A-Za-z0-9_\-]+/', '_', trim("{$date}_{$row['client_name']}_" . str_replace(' ', '_', $title) . "_$number", '_')) . '.pdf';
return ['name' => $name, 'data' => $pdf->Output($name, 'S')];
}

View File

@@ -29,14 +29,16 @@ if (isset($_GET['accept_quote'], $_GET['url_key'])) {
// Claim the response - only a quote still awaiting one can be accepted,
// and only the first request through wins
mysqli_query($mysqli, "UPDATE quotes SET quote_status = 'Accepted' WHERE quote_id = $quote_id AND quote_status IN ('Sent', 'Viewed')");
// ...and not once it has run out - a price that has expired is asked for again
mysqli_query($mysqli, "UPDATE quotes SET quote_status = 'Accepted' WHERE quote_id = $quote_id AND quote_status IN ('Sent', 'Viewed') AND quote_expire >= CURDATE()");
if (mysqli_affected_rows($mysqli) !== 1) {
flashAlert("This quote is no longer awaiting a response", 'error');
$expired = mysqli_fetch_row(mysqli_query($mysqli, "SELECT quote_expire FROM quotes WHERE quote_id = $quote_id AND quote_status IN ('Sent', 'Viewed') AND quote_expire < CURDATE()"));
flashAlert($expired ? "This quote ran out on " . escapeHtml($expired[0]) . " - ask for an updated one" : "This quote is no longer awaiting a response", 'error');
redirect();
}
mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Accepted', history_description = 'Client accepted Quote!', history_quote_id = $quote_id");
mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Accepted', history_description = 'Accepted by the client', history_quote_id = $quote_id");
// Notification
appNotify("Quote Accepted", "Quote $quote_prefix$quote_number has been accepted by $client_name", "/agent/quote.php?quote_id=$quote_id", $client_id);
@@ -111,7 +113,7 @@ if (isset($_GET['decline_quote'], $_GET['url_key'])) {
redirect();
}
mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Declined', history_description = 'Client declined Quote!', history_quote_id = $quote_id");
mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Declined', history_description = 'Declined by the client', history_quote_id = $quote_id");
// Notification
appNotify("Quote Declined", "Quote $quote_prefix$quote_number has been declined by $client_name", "/agent/quote.php?quote_id=$quote_id", $client_id);
@@ -287,446 +289,27 @@ if (isset($_GET['approve_ticket_task'])) {
if (isset($_GET['export_quote_pdf'])) {
$quote_id = intval($_GET['export_quote_pdf']);
$url_key = escapeSql($_GET['url_key']);
$sql = mysqli_query(
$mysqli,
"SELECT client_currency_code, client_id, client_name, client_net_terms, client_website,
contact_email, contact_extension, contact_mobile, contact_mobile_country_code,
contact_phone, contact_phone_country_code, location_address, location_city,
location_country, location_state, location_zip, quote_amount, quote_category_id,
quote_created_at, quote_currency_code, quote_date, quote_discount_amount, quote_expire,
quote_id, quote_note, quote_number, quote_prefix, quote_scope, quote_status, quote_url_key FROM quotes
LEFT JOIN clients ON quote_client_id = client_id
LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1
LEFT JOIN locations ON clients.client_id = locations.location_client_id AND location_primary = 1
WHERE quote_id = $quote_id AND quote_url_key = '$url_key'
LIMIT 1"
);
if (mysqli_num_rows($sql) == 1) {
$row = mysqli_fetch_assoc($sql);
$quote_id = intval($row['quote_id']);
$quote_prefix = escapeHtml($row['quote_prefix']);
$quote_number = intval($row['quote_number']);
$quote_scope = escapeHtml($row['quote_scope']);
$quote_status = escapeHtml($row['quote_status']);
$quote_date = escapeHtml($row['quote_date']);
$quote_expire = escapeHtml($row['quote_expire']);
$quote_amount = floatval($row['quote_amount']);
$quote_discount = floatval($row['quote_discount_amount']);
$quote_currency_code = escapeHtml($row['quote_currency_code']);
$quote_note = escapeHtml($row['quote_note']);
$quote_url_key = escapeHtml($row['quote_url_key']);
$quote_created_at = escapeHtml($row['quote_created_at']);
$category_id = intval($row['quote_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;
}
$sql = mysqli_query($mysqli, "SELECT company_address, company_city, company_country, company_email, settings.company_id,
company_locale, company_logo, company_name, company_phone, company_phone_country_code,
company_state, company_website, company_zip FROM companies, settings WHERE companies.company_id = settings.company_id AND companies.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_logo = escapeHtml($row['company_logo']);
$company_locale = escapeHtml($row['company_locale']);
//Set Currency Format
$currency_format = numfmt_create($company_locale, NumberFormatter::CURRENCY);
require_once("../libs/TCPDF/tcpdf.php");
// Start TCPDF
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetMargins(10, 10, 10);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 10);
// Logo + Right Columns
$html = '<table width="100%" cellspacing="0" cellpadding="3">
<tr>
<td width="40%">';
if (!empty($company_logo) && file_exists("../uploads/settings/$company_logo")) {
$html .= '<img src="/uploads/settings/' . $company_logo . '" width="120">';
}
$html .= '</td>
<td width="60%" align="right">
<span style="font-size:18pt; font-weight:bold;">QUOTE</span><br>
<span style="font-size:14pt;">' . $quote_prefix . $quote_number . '</span><br>';
if (strtolower($quote_status) === 'accepted') {
$html .= '<span style="color:green; font-weight:bold;">ACCEPTED</span><br>';
}
if (strtolower($quote_status) === 'declined') {
$html .= '<span style="color:red; font-weight:bold;">DECLINED</span><br>';
}
$html .= '</td>
</tr>
</table><br>';
// Billing titles
$html .= '<table width="100%" cellspacing="0" cellpadding="2">
<tr>
<td width="50%" style="font-size:14pt; font-weight:bold;">' . $company_name . '</td>
<td width="50%" align="right" style="font-size:14pt; font-weight:bold;">' . $client_name . '</td>
</tr>
<tr>
<td style="font-size:10pt; line-height:1.4;">' . nl2br(formatAddress($company_address, $company_city, $company_state, $company_zip, $company_country) . "\n$company_phone\n$company_website") . '</td>
<td style="font-size:10pt; line-height:1.4;" align="right">' . nl2br(formatAddress($location_address, $location_city, $location_state, $location_zip, $location_country) . "\n$contact_email\n$contact_phone") . '</td>
</tr>
</table><br>';
// Date table
$html .= '<table border="0" cellpadding="2" cellspacing="0" width="100%">
<tr>
<td width="60%"></td>
<td width="20%" style="font-size:10pt;"><strong>Date:</strong></td>
<td width="20%" style="font-size:10pt;" align="right">' . $quote_date . '</td>
</tr>
<tr>
<td></td>
<td style="font-size:10pt;"><strong>Expires:</strong></td>
<td style="font-size:10pt;" align="right">' . $quote_expire . '</td>
</tr>
</table><br><br>';
// Items header
$html .= '
<table border="0" cellpadding="5" cellspacing="0" width="100%">
<tr style="background-color:#f0f0f0;">
<th align="left" width="40%"><strong>Item</strong></th>
<th align="center" width="10%"><strong>Qty</strong></th>
<th align="right" width="15%"><strong>Price</strong></th>
<th align="right" width="15%"><strong>Tax</strong></th>
<th align="right" width="20%"><strong>Amount</strong></th>
</tr>';
// Load items
$sub_total = 0;
$total_tax = 0;
$sql_items = mysqli_query($mysqli, "SELECT item_description, item_name, item_price, item_quantity, item_tax, item_total FROM quote_items WHERE item_quote_id = $quote_id ORDER BY item_order ASC");
while ($item = mysqli_fetch_assoc($sql_items)) {
$name = $item['item_name'];
$desc = $item['item_description'];
$qty = $item['item_quantity'];
$price = $item['item_price'];
$tax = $item['item_tax'];
$total = $item['item_total'];
$sub_total += $price * $qty;
$total_tax += $tax;
$html .= '
<tr>
<td><strong>' . $name . '</strong>
<br><span style="font-style:italic; font-size:9pt;">' . nl2br($desc) . '</span>
</td>
<td align="center">' . number_format($qty, 2) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $price, $quote_currency_code) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $tax, $quote_currency_code) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $total, $quote_currency_code) . '</td>
</tr>';
}
$html .= '</table><br><hr><br><br>';
// Totals
$html .= '<table width="100%" cellspacing="0" cellpadding="4">
<tr>
<td width="60%"><i style="font-size:9pt;">' . nl2br($quote_note) . '</i></td>
<td width="40%">
<table width="100%" cellpadding="3" cellspacing="0">
<tr><td>Subtotal:</td><td align="right">' . numfmt_format_currency($currency_format, $sub_total, $quote_currency_code) . '</td></tr>';
if ($quote_discount > 0) {
$html .= '<tr><td>Discount:</td><td align="right">-' . numfmt_format_currency($currency_format, $quote_discount, $quote_currency_code) . '</td></tr>';
}
if ($total_tax > 0) {
$html .= '<tr><td>Tax:</td><td align="right">' . numfmt_format_currency($currency_format, $total_tax, $quote_currency_code) . '</td></tr>';
}
$html .= '
<tr><td><h3><strong>Total:</strong></h3></td><td align="right"><h3><strong>' . numfmt_format_currency($currency_format, $quote_amount, $quote_currency_code) . '</strong></h3></td></tr>
</table>
</td>
</tr>
</table><br><br>';
// Footer
$html .= '<div style="text-align:center; font-size:9pt; color:gray;">' . nl2br($config_quote_footer) . '</div>';
$pdf->writeHTML($html, true, false, true, false, '');
$filename = preg_replace('/[^A-Za-z0-9_\-]/', '_', "{$quote_date}_{$company_name}_{$client_name}_Quote_{$quote_prefix}{$quote_number}");
$pdf->Output("$filename.pdf", 'I');
// The quote's own link key is the only way in - the same one its guest page checks
$quote = billingRow('quote', intval($_GET['export_quote_pdf']), false);
if (!$quote || (string) $quote['quote_url_key'] === '' || !hash_equals((string) $quote['quote_url_key'], (string) ($_GET['url_key'] ?? ''))) {
http_response_code(404);
exit('That quote is not available.');
}
exit;
billingPdfSend(billingPdf('quote', $quote));
}
if (isset($_GET['export_invoice_pdf'])) {
$invoice_id = intval($_GET['export_invoice_pdf']);
$url_key = escapeSql($_GET['url_key']);
$sql = mysqli_query(
$mysqli,
"SELECT client_currency_code, client_id, client_name, client_net_terms, client_website,
contact_email, contact_extension, contact_mobile, contact_mobile_country_code,
contact_phone, contact_phone_country_code, invoice_amount, invoice_category_id,
invoice_created_at, invoice_currency_code, invoice_date, invoice_discount_amount,
invoice_due, invoice_id, invoice_note, invoice_number, invoice_prefix, invoice_scope,
invoice_status, invoice_url_key, location_address, location_city, location_country,
location_state, location_zip FROM invoices
LEFT JOIN clients ON invoice_client_id = client_id
LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1
LEFT JOIN locations ON clients.client_id = locations.location_client_id AND location_primary = 1
WHERE invoice_id = $invoice_id AND invoice_url_key = '$url_key'
LIMIT 1"
);
if (mysqli_num_rows($sql) == 1) {
$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_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;
}
$sql = mysqli_query($mysqli, "SELECT company_address, company_city, company_country, company_email, company_id, company_locale,
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']);
$company_locale = escapeHtml($row['company_locale']);
//Set Currency Format
$currency_format = numfmt_create($company_locale, NumberFormatter::CURRENCY);
$sql_payments = mysqli_query($mysqli, "SELECT * FROM payments, accounts WHERE payment_account_id = account_id AND payment_invoice_id = $invoice_id ORDER BY payments.payment_id DESC");
//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;
//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);
require_once("../libs/TCPDF/tcpdf.php");
// Start TCPDF
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetMargins(10, 10, 10);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 10);
// Logo + Right Columns
$html = '<table width="100%" cellspacing="0" cellpadding="3">
<tr>
<td width="40%">';
if (!empty($company_logo) && file_exists("../uploads/settings/$company_logo")) {
$html .= '<img src="/uploads/settings/' . $company_logo . '" width="120">';
}
$html .= '</td>
<td width="60%" align="right">
<span style="font-size:18pt; font-weight:bold;">Invoice</span><br>
<span style="font-size:14pt;">' . $invoice_prefix . $invoice_number . '</span><br>';
if (strtolower($invoice_status) === 'paid') {
$html .= '<span style="color:green; font-weight:bold;">PAID</span><br>';
}
$html .= '</td>
</tr>
</table><br>';
// Billing titles
$html .= '<table width="100%" cellspacing="0" cellpadding="2">
<tr>
<td width="50%" style="font-size:14pt; font-weight:bold;">' . $company_name . '</td>
<td width="50%" align="right" style="font-size:14pt; font-weight:bold;">' . $client_name . '</td>
</tr>
<tr>
<td style="font-size:10pt; line-height:1.4;">' . nl2br(formatAddress($company_address, $company_city, $company_state, $company_zip, $company_country) . "\n$company_phone\n$company_website\n$company_tax_id_display") . '</td>
<td style="font-size:10pt; line-height:1.4;" align="right">' . nl2br(formatAddress($location_address, $location_city, $location_state, $location_zip, $location_country) . "\n$contact_email\n$contact_phone") . '</td>
</tr>
</table><br>';
// Date table
$html .= '<table border="0" cellpadding="2" cellspacing="0" width="100%">
<tr>
<td width="60%"></td>
<td width="20%" style="font-size:10pt;"><strong>Date:</strong></td>
<td width="20%" style="font-size:10pt;" align="right">' . $invoice_date . '</td>
</tr>
<tr>
<td></td>
<td style="font-size:10pt;"><strong>Due:</strong></td>
<td style="font-size:10pt;" align="right">' . $invoice_due . '</td>
</tr>
</table><br><br>';
// Items header
$html .= '
<table border="0" cellpadding="5" cellspacing="0" width="100%">
<tr style="background-color:#f0f0f0;">
<th align="left" width="40%"><strong>Item</strong></th>
<th align="center" width="10%"><strong>Qty</strong></th>
<th align="right" width="15%"><strong>Price</strong></th>
<th align="right" width="15%"><strong>Tax</strong></th>
<th align="right" width="20%"><strong>Amount</strong></th>
</tr>';
// Load items
$sub_total = 0;
$total_tax = 0;
$sql_items = mysqli_query($mysqli, "SELECT item_description, item_name, item_price, item_quantity, item_tax, item_total FROM invoice_items WHERE item_invoice_id = $invoice_id ORDER BY item_order ASC");
while ($item = mysqli_fetch_assoc($sql_items)) {
$name = $item['item_name'];
$desc = $item['item_description'];
$qty = $item['item_quantity'];
$price = $item['item_price'];
$tax = $item['item_tax'];
$total = $item['item_total'];
$sub_total += $price * $qty;
$total_tax += $tax;
$html .= '
<tr>
<td><strong>' . $name . '</strong>
<br><span style="font-style:italic; font-size:9pt;">' . nl2br($desc) . '</span>
</td>
<td align="center">' . number_format($qty, 2) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $price, $invoice_currency_code) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $tax, $invoice_currency_code) . '</td>
<td align="right">' . numfmt_format_currency($currency_format, $total, $invoice_currency_code) . '</td>
</tr>';
}
$html .= '</table><br><hr><br><br>';
// Totals
$html .= '<table width="100%" cellspacing="0" cellpadding="4">
<tr>
<td width="60%"><i style="font-size:9pt;">' . nl2br($invoice_note) . '</i></td>
<td width="40%">
<table width="100%" cellpadding="3" cellspacing="0">
<tr><td>Subtotal:</td><td align="right">' . numfmt_format_currency($currency_format, $sub_total, $invoice_currency_code) . '</td></tr>';
if ($invoice_discount > 0) {
$html .= '<tr><td>Discount:</td><td align="right">-' . numfmt_format_currency($currency_format, $invoice_discount, $invoice_currency_code) . '</td></tr>';
}
if ($total_tax > 0) {
$html .= '<tr><td>Tax:</td><td align="right">' . numfmt_format_currency($currency_format, $total_tax, $invoice_currency_code) . '</td></tr>';
}
$html .= '
<tr><td>Total:</td><td align="right">' . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . '</td></tr>';
if ($amount_paid > 0) {
$html .= '<tr><td>Paid:</td><td align="right">' . numfmt_format_currency($currency_format, $amount_paid, $invoice_currency_code) . '</td></tr>';
}
$html .= '
<tr><td><h3><strong>Balance:</strong></h3></td><td align="right"><h3><strong>' . numfmt_format_currency($currency_format, $balance, $invoice_currency_code) . '</strong></h3></td></tr>
</table>
</td>
</tr>
</table><br><br>';
// Footer
$html .= '<div style="text-align:center; font-size:9pt; color:gray;">' . nl2br($config_invoice_footer) . '</div>';
$pdf->writeHTML($html, true, false, true, false, '');
$filename = preg_replace('/[^A-Za-z0-9_\-]/', '_', "{$invoice_date}_{$company_name}_{$client_name}_Invoice_{$invoice_prefix}{$invoice_number}");
$pdf->Output("$filename.pdf", 'I');
// The invoice's own link key is the only way in - the same one its guest page checks
$invoice = billingRow('invoice', intval($_GET['export_invoice_pdf']), false);
if (!$invoice || (string) $invoice['invoice_url_key'] === '' || !hash_equals((string) $invoice['invoice_url_key'], (string) ($_GET['url_key'] ?? ''))) {
http_response_code(404);
exit('That invoice is not available.');
}
exit;
billingPdfSend(billingPdf('invoice', $invoice));
}

View File

@@ -1,25 +0,0 @@
<div class="modal" id="uploadFileModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content bg-dark">
<div class="modal-header">
<h5 class="modal-title"><i class="fa fa-fw fa-cloud-upload-alt me-2"></i>Upload File</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="guest_post.php" method="post" enctype="multipart/form-data" autocomplete="off">
<input type="hidden" name="quote_id" value="<?= $quote_id ?>">
<input type="hidden" name="url_key" value="<?= $url_key ?>">
<div class="modal-body bg-white">
<div class="mb-3">
<input type="file" class="form-control" name="file[]" id="fileInput" accept=".pdf">
</div>
</div>
<div class="modal-footer bg-white">
<button type="submit" name="guest_quote_upload_file" class="btn btn-primary text-bold"><i class="fa fa-upload me-2"></i>Upload</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
</div>
</div>
</div>

View File

@@ -1,512 +1,163 @@
<?php
require_once "includes/inc_all_guest.php";
if (!isset($_GET['invoice_id'], $_GET['url_key'])) {
echo "<br><h2>Oops, something went wrong! Please raise a ticket if you believe this is an error.</h2>";
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php';
exit();
}
$url_key = escapeSql($_GET['url_key']);
$invoice_id = intval($_GET['invoice_id']);
$sql = mysqli_query(
$mysqli,
"SELECT client_currency_code, client_id, client_name, client_net_terms, client_website,
contact_email, contact_extension, contact_mobile, contact_mobile_country_code,
contact_phone, contact_phone_country_code, invoice_amount, invoice_category_id,
invoice_currency_code, invoice_date, invoice_discount_amount, invoice_due, invoice_id,
invoice_note, invoice_number, invoice_prefix, invoice_status, location_address,
location_city, location_country, location_state, location_zip FROM invoices
LEFT JOIN clients ON invoice_client_id = client_id
LEFT JOIN locations ON clients.client_id = locations.location_client_id AND location_primary = 1
LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1
WHERE invoice_id = $invoice_id
AND invoice_url_key = '$url_key'"
);
if (mysqli_num_rows($sql) !== 1) {
// Invalid invoice/key
echo "<br><h2>Oops, something went wrong! Please raise a ticket if you believe this is an error.</h2>";
require_once $_SERVER['DOCUMENT_ROOT'] . '/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_status = escapeHtml($row['invoice_status']);
$invoice_date = escapeHtml($row['invoice_date']);
$invoice_due = escapeHtml($row['invoice_due']);
$invoice_discount = floatval($row['invoice_discount_amount']);
$invoice_amount = floatval($row['invoice_amount']);
$invoice_currency_code = escapeHtml($row['invoice_currency_code']);
$invoice_note = escapeHtml($row['invoice_note']);
$invoice_category_id = intval($row['invoice_category_id']);
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$client_name_escaped = escapeSql($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']);
$sql = mysqli_query($mysqli, "SELECT company_address, company_city, company_country, company_email, company_locale,
company_logo, company_name, company_phone, company_phone_country_code, company_state,
company_tax_id, company_website, company_zip, config_invoice_footer FROM companies, settings WHERE companies.company_id = settings.company_id AND companies.company_id = 1");
$row = mysqli_fetch_assoc($sql);
$company_name = escapeHtml($row['company_name']);
$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_country = escapeHtml($row['company_country']);
$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']);
if (!empty($company_logo)) {
$company_logo_base64 = base64_encode(file_get_contents("../uploads/settings/$company_logo"));
}
$company_locale = escapeHtml($row['company_locale']);
$config_invoice_footer = escapeHtml($row['config_invoice_footer']);
// Get Payment Provide Details
$sql = mysqli_query($mysqli, "SELECT payment_provider_id, payment_provider_name, payment_provider_threshold FROM payment_providers WHERE payment_provider_active = 1 AND payment_provider_name = 'Stripe' LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$payment_provider_id = $stripe_provider_id = intval($row['payment_provider_id']);
$payment_provider_name = escapeHtml($row['payment_provider_name']);
$payment_provider_threshold = floatval($row['payment_provider_threshold']);
// Get client's Stripe customer ID
$stripe_customer_query = mysqli_query($mysqli, "
SELECT payment_provider_client FROM client_payment_provider
WHERE client_id = $client_id AND payment_provider_id = $stripe_provider_id
LIMIT 1
");
$stripe_customer = mysqli_fetch_assoc($stripe_customer_query);
$stripe_customer_id = $stripe_customer ? escapeSql($stripe_customer['payment_provider_client']) : null;
//Set Currency Format
$currency_format = numfmt_create($company_locale, NumberFormatter::CURRENCY);
$invoice_tally_total = 0; // Default
//Set Badge color based off of invoice status
$invoice_badge_color = getInvoiceBadgeColor($invoice_status);
//Update status to Viewed only if invoice_status = "Sent"
if ($invoice_status == 'Sent') {
mysqli_query($mysqli, "UPDATE invoices SET invoice_status = 'Viewed' WHERE invoice_id = $invoice_id");
}
//Mark viewed in history
mysqli_query($mysqli, "INSERT INTO history SET history_status = '$invoice_status', history_description = 'Invoice viewed - $ip - $os - $browser', history_invoice_id = $invoice_id");
if ($invoice_status !== 'Paid') {
appNotify("Invoice Viewed", "Invoice $invoice_prefix$invoice_number has been viewed by $client_name_escaped - $ip - $os - $browser", "/agent/invoice.php?invoice_id=$invoice_id", $client_id);
}
$sql_payments = mysqli_query($mysqli, "SELECT * FROM payments, accounts WHERE payment_account_id = account_id AND payment_invoice_id = $invoice_id ORDER BY payments.payment_id DESC");
//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']);
// Calculate the balance owed
$balance = $invoice_amount - $amount_paid;
//check to see if overdue
$invoice_color = $invoice_badge_color; // Default
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_color = "text-danger";
}
}
// Invoice individual items
$sql_invoice_items = mysqli_query($mysqli, "SELECT item_description, item_id, item_name, item_price, item_quantity, item_tax, item_total FROM invoice_items WHERE item_invoice_id = $invoice_id ORDER BY item_order ASC");
// Get Total Account Balance
//Add up all the payments for the invoice and get the total amount paid to the invoice
$sql_invoice_amounts = mysqli_query($mysqli, "SELECT SUM(invoice_amount) AS invoice_amounts FROM invoices WHERE invoice_client_id = $client_id AND invoice_status != 'Draft' AND invoice_status != 'Cancelled' AND invoice_status != 'Non-Billable'");
$row = mysqli_fetch_assoc($sql_invoice_amounts);
$account_balance = floatval($row['invoice_amounts']);
$sql_amount_paid = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS amount_paid FROM payments, invoices WHERE payment_invoice_id = invoice_id AND invoice_client_id = $client_id");
$row = mysqli_fetch_assoc($sql_amount_paid);
$account_amount_paid = floatval($row['amount_paid']);
$account_balance = $account_balance - $account_amount_paid;
//set Text color on balance
if ($balance > 0) {
$balance_text_color = "text-danger fw-bold";
} else {
$balance_text_color = "";
}
?>
<div class="card my-3">
<div class="card-header bg-light d-print-none">
<div class="row">
<div class="col-6">
<h4 class="mt-1">Account Balance: <b><?= numfmt_format_currency($currency_format, $account_balance, $invoice_currency_code) ?></b></h4>
</div>
<div class="col-6">
<div class="float-end">
<a class="btn btn-default" href="#" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</a>
<a class="btn btn-default" href="guest_post.php?export_invoice_pdf=<?= $invoice_id ?>&url_key=<?= $url_key ?>">
<i class="fa fa-fw fa-download me-2"></i>Download
</a>
<?php if (
$invoice_status !== "Paid" &&
$invoice_status !== "Cancelled" &&
$invoice_status !== "Draft" &&
$payment_provider_id &&
(
$payment_provider_threshold == 0 ||
$payment_provider_threshold > $invoice_amount
)
)
{
// Stripe - Online payment (either setup a customer record, or pay directly if customer record already exists)
// Needs adjusting if we do ever add more payment providers but fine for now.
if ($stripe_customer_id) { ?>
<a class="btn btn-success" href="guest_pay_invoice_stripe.php?invoice_id=<?= $invoice_id ?>&url_key=<?= $url_key ?>"><i class="fa fa-fw fa-credit-card me-2"></i>Pay Now </a>
<?php }
else { ?>
<a class="btn btn-success" href="guest_pay_setup_stripe_customer.php?invoice_id=<?= $invoice_id ?>&url_key=<?= $url_key ?>"><i class="fa fa-fw fa-credit-card me-2"></i>Pay Now </a>
<?php }
} ?>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="row mb-3">
<?php if (file_exists("../uploads/settings/$company_logo")) { ?>
<div class="col-sm-2">
<img class="img-fluid" src="<?= "../uploads/settings/$company_logo" ?>" alt="Company logo">
</div>
<?php } ?>
<div class="col-sm-6 <?php if (!file_exists("../uploads/settings/$company_logo")) { echo "col-sm-8"; } ?>">
<ul class="list-unstyled">
<li><h4><strong><?= $company_name ?></strong></h4></li>
<li><?= formatAddress($company_address, $company_city, $company_state, $company_zip, $company_country, '<br>') ?></li>
<li><?= "$company_email | $company_phone" ?></li>
<li><?= $company_website ?></li>
<?php if ($company_tax_id_display) { ?>
<li><?= $company_tax_id_display ?></li>
<?php } ?>
</ul>
</div>
<div class="col-sm-4">
<h3 class="text-end"><strong>INVOICE</strong></h3>
<h5 class="badge text-bg-<?= $invoice_badge_color ?> p-2 float-end">
<?= "$invoice_status" ?>
</h5>
<table class="table table-sm table-borderless">
<tr>
<th>Invoice #:</th>
<td class="text-end"><?= "$invoice_prefix$invoice_number" ?></td>
</tr>
<tr>
<th>Date:</th>
<td class="text-end"><?= $invoice_date ?></td>
</tr>
<tr>
<th>Due:</th>
<td class="text-end"><?= $invoice_due ?></td>
</tr>
</table>
</div>
</div>
<div class="row mb-3 bg-light p-3">
<div class="col">
<h6><strong>Bill To:</strong></h6>
<ul class="list-unstyled mb-0">
<li><?= $client_name ?></li>
<li><?= formatAddress($location_address, $location_city, $location_state, $location_zip, $location_country, '<br>') ?></li>
<li><?= "$contact_email | $contact_phone $contact_extension" ?></li>
</ul>
</div>
</div>
<div class="row mb-3">
<div class="col-md-12">
<div class="card">
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="bg-light">
<tr>
<th>Item</th>
<th>Description</th>
<th class="text-center">Qty</th>
<th class="text-end">Unit Price</th>
<th class="text-end">Tax</th>
<th class="text-end">Amount</th>
</tr>
</thead>
<tbody>
<?php
$total_tax = 0.00;
$sub_total = 0.00 - $invoice_discount;
while ($row = mysqli_fetch_assoc($sql_invoice_items)) {
$item_id = intval($row['item_id']);
$item_name = escapeHtml($row['item_name']);
$item_description = escapeHtml($row['item_description']);
$item_quantity = floatval($row['item_quantity']);
$item_price = floatval($row['item_price']);
$item_tax = floatval($row['item_tax']);
$item_total = floatval($row['item_total']);
$total_tax = $item_tax + $total_tax;
$sub_total = $item_price * $item_quantity + $sub_total;
?>
<tr>
<td><?= $item_name ?></td>
<td><?= nl2br($item_description) ?></td>
<td class="text-center"><?= $item_quantity ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_price, $invoice_currency_code) ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_tax, $invoice_currency_code) ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_total, $invoice_currency_code) ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-sm-7">
<?php if (!empty($invoice_note)) { ?>
<div class="card">
<div class="card-body">
<?= nl2br($invoice_note) ?>
</div>
</div>
<?php } ?>
</div>
<div class="col-sm-3 offset-sm-2">
<table class="table table-hover mb-0">
<tbody>
<tr>
<td>Subtotal:</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $sub_total, $invoice_currency_code) ?></td>
</tr>
<?php
if ($invoice_discount > 0) {
?>
<tr>
<td>Discount:</td>
<td class="text-end">-<?= numfmt_format_currency($currency_format, $invoice_discount, $invoice_currency_code) ?></td>
</tr>
<?php
}
?>
<?php if ($total_tax > 0) { ?>
<tr>
<td>Tax:</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $total_tax, $invoice_currency_code) ?></td>
</tr>
<?php } ?>
<tr>
<td>Total:</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) ?></td>
</tr>
<?php if ($amount_paid > 0) { ?>
<tr>
<td><div class="text-success">Paid:</div></td>
<td class="text-end text-success"><?= numfmt_format_currency($currency_format, $amount_paid, $invoice_currency_code) ?></td>
</tr>
<?php
}
?>
<tr class="h5 text-bold">
<td>Balance:</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $balance, $invoice_currency_code) ?></td>
</tr>
</tbody>
</table>
</div>
</div>
<hr class="mt-5">
<div class="text-center text-secondary"><?= nl2br($config_invoice_footer) ?></div>
</div>
</div>
<?php
/*
* ACCOUNT STATEMENT
*
* Replaces the old Current Invoices / Outstanding Invoices pair. Those split
* the same list on due date and both showed invoice_amount, which is the
* ORIGINAL total - a $1,000 invoice with $900 paid appeared here as $1,000
* owing. This shows amount, paid and balance, and the running total both cards
* were accumulating into $invoice_tally_total but never printing.
*
* Payments are summed in a derived table rather than joined directly, or an
* invoice with two payments against it would be counted twice.
*
* Draft / Cancelled / Non-Billable are not money owed, and the balance test
* drops anything fully paid, so Paid invoices fall out without naming them.
* An invoice as the client opens it from its link - the invoice on the
* left, as it prints; on the right what is owed and by when, Pay Now when
* it can be paid online, the PDF, the payments made, and everything else
* they owe with a link to each. Opening it marks a sent invoice viewed and
* tells the agents.
*/
$sql_statement = mysqli_query(
$mysqli,
"SELECT invoice_amount, invoice_currency_code, invoice_date, invoice_due, invoice_id,
invoice_number, invoice_prefix, invoice_scope, invoice_url_key,
IFNULL(amount_paid, 0) AS amount_paid
FROM invoices
LEFT JOIN (
SELECT payment_invoice_id, SUM(payment_amount) AS amount_paid FROM payments
WHERE payment_archived_at IS NULL
GROUP BY payment_invoice_id
) AS invoice_payments ON payment_invoice_id = invoice_id
WHERE invoice_client_id = $client_id
AND invoice_status NOT IN ('Draft', 'Cancelled', 'Non-Billable')
AND invoice_amount - IFNULL(invoice_payments.amount_paid, 0) > 0
ORDER BY invoice_date ASC, invoice_number ASC"
);
require_once "includes/inc_all_guest.php";
$statement_count = mysqli_num_rows($sql_statement);
$invoice = billingRow('invoice', intval($_GET['invoice_id'] ?? 0), false);
$url_key = (string) ($_GET['url_key'] ?? '');
if ($statement_count > 0) { ?>
if (!$invoice || (string) $invoice['invoice_url_key'] === '' || !hash_equals((string) $invoice['invoice_url_key'], $url_key)) {
echo '<div class="itflow-asset-empty mt-5"><i class="fas fa-file-invoice-dollar fa-3x mb-3 opacity-50"></i><h1 class="h4">This invoice link isn\'t working</h1><p>It may have been mistyped or replaced. Ask whoever sent it for a new link.</p></div>';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php';
exit();
}
<div class="card d-print-none">
<div class="card-header bg-dark">
<strong class="text-white">
<i class="fa fa-fw fa-file-alt me-2"></i>Account Statement
</strong>
$invoice_id = intval($invoice['invoice_id']);
$client_id = intval($invoice['client_id']);
$number = billingNumber('invoice', $invoice);
$status = (string) $invoice['invoice_status'];
$currency = (string) $invoice['invoice_currency_code'];
$money = function ($amount) use ($currency) {
return escapeHtml(billingMoney($amount, $currency));
};
billingGuestViewed('invoice', $invoice);
$items = billingItems('invoice', $invoice_id);
$totals = billingTotals('invoice', $invoice, $items);
$payments = invoicePayments($invoice_id);
$state = invoiceState($invoice, invoicePaid($invoice_id));
$company = billingCompany();
$open_invoices = billingClientOpenInvoices($client_id);
$open_total = 0;
foreach ($open_invoices as $open) {
$open_total += floatval($open['invoice_amount']) - floatval($open['paid']);
}
$query_key = rawurlencode($url_key);
// Paying online - through Stripe, under its limit, when there is something to pay
$stripe = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT payment_provider_id, payment_provider_threshold FROM payment_providers WHERE payment_provider_active = 1 AND payment_provider_name = 'Stripe' LIMIT 1"));
$pay_url = '';
if ($stripe && invoiceCanPay($invoice, $state) && (floatval($stripe['payment_provider_threshold']) == 0 || floatval($stripe['payment_provider_threshold']) > floatval($invoice['invoice_amount']))) {
$stripe_customer = mysqli_fetch_row(mysqli_query($mysqli, "SELECT payment_provider_client FROM client_payment_provider WHERE client_id = $client_id AND payment_provider_id = " . intval($stripe['payment_provider_id']) . " LIMIT 1"));
$pay_url = ($stripe_customer ? 'guest_pay_invoice_stripe.php' : 'guest_pay_setup_stripe_customer.php') . "?invoice_id=$invoice_id&url_key=$query_key";
}
$paper = [
'type' => 'invoice',
'row' => $invoice,
'items' => $items,
'totals' => $totals,
'paid' => $state['paid'],
'balance' => $state['balance'],
'logo_url' => $company['logo_url'],
];
?>
<div class="row g-3 my-1">
<div class="col-lg-8 itflow-paper-col">
<?php require $_SERVER['DOCUMENT_ROOT'] . '/includes/billing_paper.php'; ?>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-sm mb-0">
<thead>
<tr>
<th class="text-center">Invoice</th>
<th class="d-none d-md-table-cell">Scope</th>
<th>Date</th>
<th>Due</th>
<th class="text-end">Amount</th>
<th class="text-end">Paid</th>
<th class="text-end">Balance</th>
</tr>
</thead>
<tbody>
<?php
/*
* Distinct variable names on purpose. The two cards this
* replaces reused $invoice_id / $invoice_prefix / $invoice_due
* for their loop rows, which clobbered the page's own invoice -
* that is why the old highlight test had to read $_GET instead
* of comparing against $invoice_id.
*/
while ($row = mysqli_fetch_assoc($sql_statement)) {
$statement_invoice_id = intval($row['invoice_id']);
$statement_invoice_prefix = escapeHtml($row['invoice_prefix']);
$statement_invoice_number = intval($row['invoice_number']);
$statement_invoice_scope = escapeHtml($row['invoice_scope']);
$statement_invoice_date = escapeHtml($row['invoice_date']);
$statement_invoice_due = escapeHtml($row['invoice_due']);
$statement_invoice_url_key = escapeHtml($row['invoice_url_key']);
$statement_invoice_amount = floatval($row['invoice_amount']);
$statement_invoice_currency_code = escapeHtml($row['invoice_currency_code']);
$statement_amount_paid = floatval($row['amount_paid']);
$statement_invoice_balance = $statement_invoice_amount - $statement_amount_paid;
<div class="col-lg-4 d-print-none">
$invoice_tally_total = $invoice_tally_total + $statement_invoice_balance;
$statement_days = floor((time() - strtotime($statement_invoice_due)) / (60 * 60 * 24));
if ($statement_days > 0) {
$statement_due_class = 'text-danger';
$statement_due_note = "(overdue by $statement_days days)";
} else {
$statement_due_class = '';
$statement_due_note = '(due in ' . abs($statement_days) . ' days)';
}
?>
<tr <?php if ($statement_invoice_id === $invoice_id) { echo "class='table-primary'"; } ?>>
<th class="text-center">
<a href="guest_view_invoice.php?invoice_id=<?= $statement_invoice_id ?>&url_key=<?= $statement_invoice_url_key ?>">
<?= "$statement_invoice_prefix$statement_invoice_number" ?>
</a>
</th>
<td class="d-none d-md-table-cell"><?= $statement_invoice_scope ?></td>
<td><?= $statement_invoice_date ?></td>
<td class="<?= $statement_due_class ?>"><?= "$statement_invoice_due $statement_due_note" ?></td>
<td class="text-end font-monospace"><?= numfmt_format_currency($currency_format, $statement_invoice_amount, $statement_invoice_currency_code) ?></td>
<td class="text-end font-monospace"><?= numfmt_format_currency($currency_format, $statement_amount_paid, $statement_invoice_currency_code) ?></td>
<td class="text-end font-monospace text-bold"><?= numfmt_format_currency($currency_format, $statement_invoice_balance, $statement_invoice_currency_code) ?></td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
<tr>
<th colspan="6" class="text-end">Total Balance Due</th>
<th class="text-end font-monospace"><?= numfmt_format_currency($currency_format, $invoice_tally_total, $client_currency_code) ?></th>
</tr>
</tfoot>
</table>
<!-- What is owed, and paying it -->
<div class="card mb-3">
<div class="card-body">
<?php if ($state['state'] === 'paid') { ?>
<div class="d-flex align-items-center gap-3">
<span class="itflow-asset-icon bg-success-subtle text-success-emphasis" aria-hidden="true"><i class="fas fa-check"></i></span>
<div>
<div class="fw-semibold">Paid in full</div>
<div class="small text-body-secondary"><?= $payments ? 'On ' . escapeHtml($payments[0]['payment_date']) . ' - thank you.' : 'Thank you.' ?></div>
</div>
</div>
<?php } elseif (in_array($state['state'], ['cancelled', 'nonbillable'], true)) { ?>
<div class="d-flex align-items-center gap-3">
<span class="itflow-asset-icon bg-secondary-subtle text-secondary-emphasis" aria-hidden="true"><i class="fas fa-ban"></i></span>
<div>
<div class="fw-semibold"><?= $state['state'] === 'cancelled' ? 'Cancelled' : 'Nothing to pay' ?></div>
<div class="small text-body-secondary">Nothing is owed on this invoice.</div>
</div>
</div>
<?php } else { ?>
<div class="itflow-billing-stat-label">Amount due</div>
<div class="itflow-billing-stat-value mb-1 <?= $state['state'] === 'overdue' ? 'text-danger-emphasis' : '' ?>"><?= $money($state['balance']) ?></div>
<div class="mb-3"><?= invoiceDuePill($state) ?: '<span class="small text-body-secondary">Due ' . escapeHtml($invoice['invoice_due']) . '</span>' ?></div>
<?php if ($pay_url) { ?>
<a class="btn btn-success btn-lg w-100 mb-2" href="<?= escapeHtml($pay_url) ?>"><i class="fas fa-credit-card me-2"></i>Pay Now</a>
<div class="small text-body-secondary text-center mb-3"><i class="fas fa-lock me-1"></i>Securely, by card</div>
<?php } ?>
<?php } ?>
<div class="d-flex gap-2 <?= $state['state'] === 'paid' || in_array($state['state'], ['cancelled', 'nonbillable'], true) ? 'mt-3' : '' ?>">
<a class="btn btn-outline-primary flex-fill" href="guest_post.php?export_invoice_pdf=<?= $invoice_id ?>&url_key=<?= $query_key ?>"><i class="fas fa-file-pdf me-2"></i>Download PDF</a>
<button type="button" class="btn btn-outline-secondary" onclick="window.print();" title="Print"><i class="fas fa-print"></i></button>
</div>
</div>
</div>
<?php if ($payments) { ?>
<div class="card mb-3">
<div class="card-header"><h3 class="card-title mb-0"><i class="fas fa-fw fa-receipt text-secondary me-2"></i>Payments</h3></div>
<div class="list-group list-group-flush">
<?php foreach ($payments as $payment) { ?>
<div class="list-group-item d-flex justify-content-between align-items-center">
<div>
<div class="fw-semibold itflow-money"><?= escapeHtml(billingMoney($payment['payment_amount'], $payment['payment_currency_code'])) ?></div>
<div class="small text-body-secondary"><?= escapeHtml(implode(' · ', array_filter([$payment['payment_method'], $payment['payment_reference']]))) ?></div>
</div>
<span class="small text-body-secondary"><?= escapeHtml($payment['payment_date']) ?></span>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
<?php if ($open_invoices && !(count($open_invoices) === 1 && intval($open_invoices[0]['invoice_id']) === $invoice_id)) { ?>
<!-- Everything else they owe -->
<div class="card mb-3">
<div class="card-header d-flex align-items-center">
<h3 class="card-title mb-0 me-auto"><i class="fas fa-fw fa-file-alt text-secondary me-2"></i>Your account</h3>
<span class="fw-semibold itflow-money"><?= escapeHtml(billingMoney($open_total, $currency)) ?></span>
</div>
<div class="list-group list-group-flush">
<?php foreach ($open_invoices as $open) {
$open_id = intval($open['invoice_id']);
$open_state = invoiceState($open, $open['paid']); ?>
<a class="list-group-item list-group-item-action d-flex align-items-center gap-2 <?= $open_id === $invoice_id ? 'active' : '' ?>"
href="guest_view_invoice.php?invoice_id=<?= $open_id ?>&url_key=<?= rawurlencode((string) $open['invoice_url_key']) ?>">
<div class="flex-grow-1 min-w-0">
<div class="fw-semibold"><?= escapeHtml($open['invoice_prefix'] . $open['invoice_number']) ?></div>
<div class="small text-truncate <?= $open_id === $invoice_id ? '' : 'text-body-secondary' ?>"><?= escapeHtml($open['invoice_scope']) ?: 'Dated ' . escapeHtml($open['invoice_date']) ?></div>
</div>
<div class="text-end">
<div class="itflow-money small fw-semibold"><?= escapeHtml(billingMoney($open_state['balance'], $open['invoice_currency_code'])) ?></div>
<?php if ($open_id !== $invoice_id) { ?><?= invoiceDuePill($open_state) ?><?php } ?>
</div>
</a>
<?php } ?>
</div>
</div>
<?php } ?>
<?php if (!empty($company['company_email']) || !empty($company['phone_display'])) { ?>
<div class="small text-body-secondary px-1">
Questions about this invoice? Contact <?= escapeHtml($company['company_name']) ?>
<?php if (!empty($company['company_email'])) { ?> at <a href="mailto:<?= escapeHtml($company['company_email']) ?>?subject=<?= rawurlencode("Invoice $number") ?>"><?= escapeHtml($company['company_email']) ?></a><?php } ?>
<?php if (!empty($company['phone_display'])) { ?> or <?= escapeHtml($company['phone_display']) ?><?php } ?>.
</div>
<?php } ?>
</div>
</div>
<?php } // End account statement
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php';
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php';

View File

@@ -1,305 +1,156 @@
<?php
/*
* A quote as the client opens it from its link - the quote on the left, as
* it prints; on the right what it comes to, how long it is good for, and
* Accept and Decline while it waits for an answer. Once accepted, the
* client can send back a signed copy or a purchase order. Opening it marks
* a sent quote viewed and tells the agents.
*/
require_once $_SERVER['DOCUMENT_ROOT'] . '/guest/includes/inc_all_guest.php';
$quote = billingRow('quote', intval($_GET['quote_id'] ?? 0), false);
$url_key = (string) ($_GET['url_key'] ?? '');
if (!isset($_GET['quote_id'], $_GET['url_key'])) {
echo "<br><h2>Oops, something went wrong! Please raise a ticket if you believe this is an error.</h2>";
if (!$quote || (string) $quote['quote_url_key'] === '' || !hash_equals((string) $quote['quote_url_key'], $url_key)) {
echo '<div class="itflow-asset-empty mt-5"><i class="fas fa-comment-dollar fa-3x mb-3 opacity-50"></i><h1 class="h4">This quote link isn\'t working</h1><p>It may have been mistyped or replaced. Ask whoever sent it for a new link.</p></div>';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php';
exit();
}
$quote_id = intval($quote['quote_id']);
$number = billingNumber('quote', $quote);
$status = (string) $quote['quote_status'];
$currency = (string) $quote['quote_currency_code'];
$url_key = escapeSql($_GET['url_key']);
$quote_id = intval($_GET['quote_id']);
billingGuestViewed('quote', $quote);
$sql = mysqli_query(
$mysqli,
"SELECT client_currency_code, client_id, client_name, client_website, contact_email,
contact_extension, contact_mobile, contact_mobile_country_code, contact_phone,
contact_phone_country_code, location_address, location_city, location_country,
location_state, location_zip, quote_amount, quote_currency_code, quote_date,
quote_discount_amount, quote_expire, quote_id, quote_note, quote_number, quote_prefix,
quote_status FROM quotes
LEFT JOIN clients ON quote_client_id = client_id
LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1
LEFT JOIN locations ON clients.client_id = locations.location_client_id AND location_primary = 1
WHERE quote_id = $quote_id
AND quote_url_key = '$url_key'"
);
$items = billingItems('quote', $quote_id);
$totals = billingTotals('quote', $quote, $items);
$company = billingCompany();
$expired = quoteExpired($quote);
$awaiting = in_array($status, ['Sent', 'Viewed'], true) && !$expired;
$query_key = rawurlencode($url_key);
$days_left = intval(round((strtotime((string) $quote['quote_expire']) - strtotime(date('Y-m-d'))) / 86400));
if (mysqli_num_rows($sql) !== 1) {
// Invalid quote/key
echo "<br><h2>Oops, something went wrong! Please raise a ticket if you believe this is an error.</h2>";
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php';
exit();
}
$row = mysqli_fetch_assoc($sql);
$quote_id = intval($row['quote_id']);
$quote_prefix = escapeHtml($row['quote_prefix']);
$quote_number = intval($row['quote_number']);
$quote_status = escapeHtml($row['quote_status']);
$quote_date = escapeHtml($row['quote_date']);
$quote_expire = escapeHtml($row['quote_expire']);
$quote_discount = floatval($row['quote_discount_amount']);
$quote_amount = floatval($row['quote_amount']);
$quote_currency_code = escapeHtml($row['quote_currency_code']);
$quote_note = escapeHtml($row['quote_note']);
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$client_name_escaped = escapeSql($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']);
$sql = mysqli_query($mysqli, "SELECT company_address, company_city, company_country, company_email, company_locale,
company_logo, company_name, company_phone, company_phone_country_code, company_state,
company_website, company_zip, config_quote_footer FROM companies, settings WHERE companies.company_id = settings.company_id AND companies.company_id = 1");
$row = mysqli_fetch_assoc($sql);
$company_name = escapeHtml($row['company_name']);
$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_country = escapeHtml($row['company_country']);
$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_logo = escapeHtml($row['company_logo']);
if (!empty($company_logo)) {
$company_logo_base64 = base64_encode(file_get_contents("../uploads/settings/$company_logo"));
}
$company_locale = escapeHtml($row['company_locale']);
$config_quote_footer = escapeHtml($row['config_quote_footer']);
//Set Currency Format
$currency_format = numfmt_create($company_locale, NumberFormatter::CURRENCY);
//Set Badge color based off of quote status
if ($quote_status == "Sent") {
$quote_badge_color = "warning";
} elseif ($quote_status == "Viewed") {
$quote_badge_color = "primary";
} elseif ($quote_status == "Accepted") {
$quote_badge_color = "success";
} elseif ($quote_status == "Declined") {
$quote_badge_color = "danger";
} elseif ($quote_status == "Invoiced") {
$quote_badge_color = "info";
} else {
$quote_badge_color = "secondary";
}
//Update status to Viewed only if invoice_status = "Sent"
if ($quote_status == 'Sent') {
mysqli_query($mysqli, "UPDATE quotes SET quote_status = 'Viewed' WHERE quote_id = $quote_id");
}
//Mark viewed in history
mysqli_query($mysqli, "INSERT INTO history SET history_status = '$quote_status', history_description = 'Quote viewed - $ip - $os - $browser', history_quote_id = $quote_id");
if ($quote_status == "Draft" || $quote_status == "Sent" || $quote_status == "Viewed") {
appNotify("Quote Viewed", "Quote $quote_prefix$quote_number has been viewed by $client_name_escaped - $ip - $os - $browser", "/agent/quote.php?quote_id=$quote_id", $client_id);
}
$paper = [
'type' => 'quote',
'row' => $quote,
'items' => $items,
'totals' => $totals,
'logo_url' => $company['logo_url'],
];
?>
<div class="card my-3">
<div class="row g-3 my-1">
<div class="card-header d-print-none">
<div class="float-end">
<a class="btn btn-primary" href="#" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</a>
<a class="btn btn-primary" href="guest_post.php?export_quote_pdf=<?= $quote_id ?>&url_key=<?= $url_key ?>">
<i class="fa fa-fw fa-download me-2"></i>Download
</a>
</div>
<div class="col-lg-8 itflow-paper-col">
<?php require $_SERVER['DOCUMENT_ROOT'] . '/includes/billing_paper.php'; ?>
</div>
<div class="card-body">
<div class="row mb-3">
<?php if (file_exists("../uploads/settings/$company_logo")) { ?>
<div class="col-sm-2">
<img class="img-fluid" src="<?= "/uploads/settings/$company_logo" ?>" alt="Company logo">
</div>
<?php } ?>
<div class="col-sm-6 <?php if (!file_exists("../uploads/settings/$company_logo")) { echo "col-sm-8"; } ?>">
<ul class="list-unstyled">
<li><h4><strong><?= $company_name ?></strong></h4></li>
<li><?= formatAddress($company_address, $company_city, $company_state, $company_zip, $company_country, '<br>') ?></li>
<li><?= "$company_email | $company_phone" ?></li>
<li><?= $company_website ?></li>
</ul>
</div>
<div class="col-lg-4 d-print-none">
<div class="col-sm-4">
<h3 class="text-end"><strong>QUOTE</strong></h3>
<h5 class="badge text-bg-<?= $quote_badge_color ?> p-2 float-end">
<?= "$quote_status" ?>
</h5>
<table class="table table-sm table-borderless">
<tr>
<th>Quote #:</th>
<td class="text-end"><?= "$quote_prefix$quote_number" ?></td>
</tr>
<tr>
<th>Date:</th>
<td class="text-end"><?= $quote_date ?></td>
</tr>
<tr>
<th>Expires:</th>
<td class="text-end"><?= $quote_expire ?></td>
</tr>
</table>
</div>
<div class="card mb-3">
<div class="card-body">
<div class="itflow-billing-stat-label">Quote total</div>
<div class="itflow-billing-stat-value mb-3"><?= escapeHtml(billingMoney($totals['total'], $currency)) ?></div>
</div>
<div class="row mb-3 bg-light p-3">
<div class="col">
<h6><strong>To:</strong></h6>
<ul class="list-unstyled mb-0">
<li><?= $client_name ?></li>
<li><?= formatAddress($location_address, $location_city, $location_state, $location_zip, $location_country, '<br>') ?></li>
<li><?= "$contact_email | $contact_phone $contact_extension" ?></li>
</ul>
</div>
</div>
<?php $sql_items = mysqli_query($mysqli, "SELECT item_description, item_id, item_name, item_price, item_quantity, item_tax, item_total FROM quote_items WHERE item_quote_id = $quote_id ORDER BY item_order ASC"); ?>
<div class="row mb-3">
<div class="col-md-12">
<div class="card">
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="bg-light">
<tr>
<th>Item</th>
<th>Description</th>
<th class="text-center">Qty</th>
<th class="text-end">Unit Price</th>
<th class="text-end">Tax</th>
<th class="text-end">Amount</th>
</tr>
</thead>
<tbody>
<?php
$total_tax = $sub_total = 0; // Default 0
while ($row = mysqli_fetch_assoc($sql_items)) {
$item_id = intval($row['item_id']);
$item_name = escapeHtml($row['item_name']);
$item_description = escapeHtml($row['item_description']);
$item_quantity = floatval($row['item_quantity']);
$item_price = floatval($row['item_price']);
$item_tax = floatval($row['item_tax']);
$item_total = floatval($row['item_total']);
$total_tax = $item_tax + $total_tax;
$sub_total = $item_price * $item_quantity + $sub_total;
?>
<tr>
<td><?= $item_name ?></td>
<td><?= nl2br($item_description) ?></td>
<td class="text-center"><?= $item_quantity ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_price, $quote_currency_code) ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_tax, $quote_currency_code) ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $item_total, $quote_currency_code) ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php if ($awaiting) { ?>
<p class="small text-body-secondary mb-3">
Good until <?= escapeHtml($quote['quote_expire']) ?><?= $days_left === 0 ? ' - today is the last day' : ' - ' . $days_left . ' day' . ($days_left === 1 ? '' : 's') . ' left' ?>.
Let us know whether to go ahead.
</p>
<div class="d-grid gap-2 mb-3">
<a class="btn btn-success btn-lg confirm-link" href="guest_post.php?accept_quote=<?= $quote_id ?>&url_key=<?= $query_key ?>"
data-confirm-title="Accept <?= escapeHtml($number) ?>?" data-confirm-text="We'll be told straight away and be in touch to get started." data-confirm-button="Accept">
<i class="fas fa-thumbs-up me-2"></i>Accept
</a>
<a class="btn btn-outline-danger confirm-link" href="guest_post.php?decline_quote=<?= $quote_id ?>&url_key=<?= $query_key ?>"
data-confirm-title="Decline <?= escapeHtml($number) ?>?" data-confirm-text="We'll be told. If something needs changing, a reply to our email gets you a new quote." data-confirm-button="Decline">
<i class="fas fa-thumbs-down me-2"></i>Decline
</a>
</div>
<?php } elseif ($expired) { ?>
<div class="d-flex align-items-center gap-3 mb-3">
<span class="itflow-asset-icon bg-warning-subtle text-warning-emphasis" aria-hidden="true"><i class="fas fa-hourglass-end"></i></span>
<div>
<div class="fw-semibold">This quote has run out</div>
<div class="small text-body-secondary">It was good until <?= escapeHtml($quote['quote_expire']) ?> - ask us for an updated one.</div>
</div>
</div>
<?php } elseif (in_array($status, ['Accepted', 'Invoiced'], true)) { ?>
<div class="d-flex align-items-center gap-3 mb-3">
<span class="itflow-asset-icon bg-success-subtle text-success-emphasis" aria-hidden="true"><i class="fas fa-check"></i></span>
<div>
<div class="fw-semibold">Accepted - thank you</div>
<div class="small text-body-secondary">We'll be in touch to get started.</div>
</div>
</div>
<?php if ($status === 'Accepted') { ?>
<button type="button" class="btn btn-outline-success w-100 mb-3" data-bs-toggle="modal" data-bs-target="#uploadFileModal">
<i class="fas fa-file-upload me-2"></i>Send a Signed Copy or PO
</button>
<?php } ?>
<?php } elseif ($status === 'Declined') { ?>
<div class="d-flex align-items-center gap-3 mb-3">
<span class="itflow-asset-icon bg-secondary-subtle text-secondary-emphasis" aria-hidden="true"><i class="fas fa-times"></i></span>
<div>
<div class="fw-semibold">Declined</div>
<div class="small text-body-secondary">If something needs changing, let us know and we'll send a new one.</div>
</div>
</div>
<?php } else { ?>
<p class="small text-body-secondary mb-3">This quote is still being put together and may change.</p>
<?php } ?>
<div class="d-flex gap-2">
<a class="btn btn-outline-primary flex-fill" href="guest_post.php?export_quote_pdf=<?= $quote_id ?>&url_key=<?= $query_key ?>"><i class="fas fa-file-pdf me-2"></i>Download PDF</a>
<button type="button" class="btn btn-outline-secondary" onclick="window.print();" title="Print"><i class="fas fa-print"></i></button>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-sm-7">
<?php if (!empty($quote_note)) { ?>
<div class="card">
<div class="card-body">
<?= nl2br($quote_note) ?>
</div>
</div>
<?php } ?>
<?php if (!empty($company['company_email']) || !empty($company['phone_display'])) { ?>
<div class="small text-body-secondary px-1">
Questions about this quote? Contact <?= escapeHtml($company['company_name']) ?>
<?php if (!empty($company['company_email'])) { ?> at <a href="mailto:<?= escapeHtml($company['company_email']) ?>?subject=<?= rawurlencode("Quote $number") ?>"><?= escapeHtml($company['company_email']) ?></a><?php } ?>
<?php if (!empty($company['phone_display'])) { ?> or <?= escapeHtml($company['phone_display']) ?><?php } ?>.
</div>
<div class="col-sm-3 offset-sm-2">
<table class="table table-hover mb-0">
<tbody>
<tr>
<td>Subtotal:</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $sub_total, $quote_currency_code) ?></td>
</tr>
<?php if ($quote_discount > 0) { ?>
<tr>
<td>Discount:</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, -$quote_discount, $quote_currency_code) ?></td>
</tr>
<?php } ?>
<?php if ($total_tax > 0) { ?>
<tr>
<td>Tax:</td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $total_tax, $quote_currency_code) ?></td>
</tr>
<?php } ?>
<tr class="border-top h5 text-bold">
<td><strong>Total:</strong></td>
<td class="text-end"><strong><?= numfmt_format_currency($currency_format, $quote_amount, $quote_currency_code) ?></strong></td>
</tr>
</tbody>
</table>
</div>
</div>
<hr class="mt-5">
<div class="text-center"><?= nl2br($config_quote_footer) ?></div>
<div class="">
<?php
if ($quote_status == "Sent" || $quote_status == "Viewed" && strtotime($quote_expire) > strtotime("now")) { ?>
<a class="btn btn-success confirm-link" href="guest_post.php?accept_quote=<?= $quote_id ?>&url_key=<?= $url_key ?>">
<i class="fas fa-fw fa-thumbs-up me-2"></i>Accept
</a>
<a class="btn btn-danger confirm-link" href="guest_post.php?decline_quote=<?= $quote_id ?>&url_key=<?= $url_key ?>">
<i class="fas fa-fw fa-thumbs-down me-2"></i>Decline
</a>
<?php } ?>
<?php if ($quote_status == "Accepted") { ?>
<button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#uploadFileModal">
<i class="fas fa-fw fa-cloud-upload-alt me-2"></i>Upload File
</button>
<?php } ?>
</div>
<?php } ?>
</div>
</div>
<?php
require_once "guest_quote_upload_file_modal.php";
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php';
<?php if ($status === 'Accepted') { ?>
<!-- A signed copy or purchase order, back to us -->
<div class="modal fade" id="uploadFileModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-file-upload me-2"></i>Send a Signed Copy or PO</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="guest_post.php" method="post" enctype="multipart/form-data" autocomplete="off">
<input type="hidden" name="quote_id" value="<?= $quote_id ?>">
<input type="hidden" name="url_key" value="<?= escapeHtml($url_key) ?>">
<div class="modal-body">
<label class="form-label" for="quoteUploadFile">PDF file</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-fw fa-file-pdf"></i></span>
<input type="file" class="form-control" name="file[]" id="quoteUploadFile" accept=".pdf" required>
</div>
<div class="form-text">The signed quote, a purchase order - goes straight to us with <?= escapeHtml($number) ?>.</div>
</div>
<div class="modal-footer">
<button type="submit" name="guest_quote_upload_file" class="btn btn-primary text-bold"><i class="fas fa-upload me-2"></i>Send</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
</div>
</div>
</div>
<?php } ?>
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php';

286
includes/billing_paper.php Normal file
View File

@@ -0,0 +1,286 @@
<?php
/*
* The document itself - an invoice, quote or recurring invoice as the
* client sees it, on the agent pages and the guest pages alike, and as it
* prints. Set $paper before including:
*
* type invoice | quote | recurring
* row billingRow()
* items billingItems()
* totals billingTotals()
* paid what has been paid (invoices)
* balance what is still owed (invoices)
* edit the lines can be changed here (agent pages): drag handles,
* a menu on each line and the add-a-line row
* notes_edit the notes save in place (agent pages)
* taxes billingTaxes(), for the add-a-line row
* logo_url the company logo, relative to the page
* csrf the agent's token, for the edit controls
*
* Everything in it is escaped here.
*/
isset($paper) || die("Direct file access is not allowed");
$paper_type = $paper['type'];
$paper_t = billingType($paper_type);
$paper_c = $paper_t['col'];
$paper_row = $paper['row'];
$paper_items = $paper['items'];
$paper_totals = $paper['totals'];
$paper_edit = !empty($paper['edit']);
$paper_currency = (string) ($paper_row["{$paper_c}_currency_code"] ?? '');
$paper_id = intval($paper_row["{$paper_c}_id"]);
$paper_company = billingCompany();
$paper_bill_to = billingBillTo($paper_row['client_id']);
$paper_status = $paper_type === 'recurring' ? (intval($paper_row['recurring_invoice_status']) ? 'Active' : 'Paused') : (string) $paper_row["{$paper_c}_status"];
$paper_money = function ($amount) use ($paper_currency) {
return escapeHtml(billingMoney($amount, $paper_currency));
};
$paper_title = ['invoice' => 'Invoice', 'quote' => 'Quote', 'recurring' => 'Recurring Invoice'][$paper_type];
$paper_footer = $paper_type === 'quote' ? ($GLOBALS['config_quote_footer'] ?? '') : ($GLOBALS['config_invoice_footer'] ?? '');
// A stamp across a document that is done with
$paper_stamp = '';
if ($paper_type === 'invoice' && $paper_status === 'Paid') {
$paper_stamp = ['Paid', 'success'];
} elseif ($paper_type === 'invoice' && $paper_status === 'Cancelled') {
$paper_stamp = ['Cancelled', 'danger'];
} elseif ($paper_type === 'quote' && in_array($paper_status, ['Accepted', 'Invoiced'], true)) {
$paper_stamp = ['Accepted', 'success'];
} elseif ($paper_type === 'quote' && $paper_status === 'Declined') {
$paper_stamp = ['Declined', 'danger'];
}
$paper_dates = [];
if ($paper_type === 'invoice') {
$paper_dates = ['Invoice date' => $paper_row['invoice_date'], 'Due' => $paper_row['invoice_due']];
} elseif ($paper_type === 'quote') {
$paper_dates = ['Quote date' => $paper_row['quote_date'], 'Valid until' => $paper_row['quote_expire']];
} else {
$paper_dates = ['Billed' => recurringInvoiceFrequencies()[$paper_row['recurring_invoice_frequency']] ?? ucfirst((string) $paper_row['recurring_invoice_frequency']),
'Next invoice' => $paper_row['recurring_invoice_next_date']];
}
$paper_post = function ($params) use ($paper_type, $paper_id, $paper) {
return 'post.php?' . http_build_query(array_merge($params, ['type' => $paper_type, 'doc_id' => $paper_id, 'csrf_token' => $paper['csrf'] ?? '']));
};
$paper_company_lines = array_filter([
formatAddress($paper_company['company_address'] ?? '', $paper_company['company_city'] ?? '', $paper_company['company_state'] ?? '', $paper_company['company_zip'] ?? '', $paper_company['company_country'] ?? '', "\n"),
implode(' · ', array_filter([$paper_company['company_email'] ?? '', $paper_company['phone_display'] ?? ''])),
$paper_company['company_website'] ?? '',
!empty($GLOBALS['config_invoice_show_tax_id']) && !empty($paper_company['company_tax_id']) ? 'Tax ID: ' . $paper_company['company_tax_id'] : '',
]);
$paper_bill_lines = array_filter([
formatAddress($paper_bill_to['location_address'] ?? '', $paper_bill_to['location_city'] ?? '', $paper_bill_to['location_state'] ?? '', $paper_bill_to['location_zip'] ?? '', $paper_bill_to['location_country'] ?? '', "\n"),
$paper_bill_to['contact_name'] ?? '',
implode(' · ', array_filter([$paper_bill_to['contact_email'] ?? '', $paper_bill_to['contact_phone'] ?? ''])),
!empty($paper_bill_to['client_tax_id_number']) ? 'Tax ID: ' . $paper_bill_to['client_tax_id_number'] : '',
]);
?>
<div class="itflow-paper" id="items" data-billing-type="<?= $paper_type ?>" data-billing-id="<?= $paper_id ?>">
<?php if ($paper_stamp) { ?>
<div class="itflow-paper-stamp text-<?= $paper_stamp[1] ?>" aria-hidden="true"><?= $paper_stamp[0] ?></div>
<?php } ?>
<!-- Who it is from, and what it is -->
<div class="itflow-paper-head">
<div class="itflow-paper-from">
<?php if (!empty($paper['logo_url']) && !empty($paper_company['logo_url'])) { ?>
<img class="itflow-paper-logo" src="<?= escapeHtml($paper['logo_url']) ?>" alt="<?= escapeHtml($paper_company['company_name'] ?? '') ?>">
<?php } ?>
<div class="fw-semibold fs-5"><?= escapeHtml($paper_company['company_name'] ?? '') ?></div>
<div class="small text-body-secondary"><?= nl2br(escapeHtml(implode("\n", $paper_company_lines))) ?></div>
</div>
<div class="itflow-paper-what text-md-end">
<div class="itflow-paper-title"><?= $paper_title ?></div>
<div class="fs-5 fw-semibold font-monospace"><?= escapeHtml(billingNumber($paper_type, $paper_row)) ?></div>
<dl class="itflow-paper-dates">
<?php foreach ($paper_dates as $label => $value) { ?>
<dt><?= $label ?></dt><dd><?= escapeHtml($value) ?></dd>
<?php } ?>
</dl>
</div>
</div>
<!-- Who it is for, and what it comes to -->
<div class="itflow-paper-parties">
<div>
<div class="itflow-paper-label"><?= $paper_type === 'quote' ? 'Prepared for' : 'Bill to' ?></div>
<div class="fw-semibold"><?= escapeHtml($paper_bill_to['client_name'] ?? $paper_row['client_name']) ?></div>
<div class="small text-body-secondary"><?= nl2br(escapeHtml(implode("\n", $paper_bill_lines))) ?></div>
</div>
<div class="itflow-paper-due text-md-end">
<?php if ($paper_type === 'invoice') { ?>
<div class="itflow-paper-label"><?= in_array($paper_status, ['Paid', 'Cancelled', 'Non-Billable'], true) ? 'Balance' : 'Amount due' ?></div>
<div class="itflow-paper-amount"><?= $paper_money($paper['balance'] ?? $paper_totals['total']) ?></div>
<?php if (!in_array($paper_status, ['Paid', 'Cancelled', 'Non-Billable', 'Draft'], true) && ($paper['balance'] ?? 0) > 0) { ?>
<div class="small text-body-secondary">by <?= escapeHtml($paper_row['invoice_due']) ?></div>
<?php } ?>
<?php } elseif ($paper_type === 'quote') { ?>
<div class="itflow-paper-label">Quote total</div>
<div class="itflow-paper-amount"><?= $paper_money($paper_totals['total']) ?></div>
<?php } else { ?>
<div class="itflow-paper-label">Each <?= $paper_row['recurring_invoice_frequency'] === 'year' ? 'year' : 'month' ?></div>
<div class="itflow-paper-amount"><?= $paper_money($paper_totals['total']) ?></div>
<?php } ?>
</div>
</div>
<?php if (trim((string) $paper_row["{$paper_c}_scope"]) !== '') { ?>
<div class="itflow-paper-scope"><span class="itflow-paper-label me-2">For</span><?= escapeHtml($paper_row["{$paper_c}_scope"]) ?></div>
<?php } ?>
<!-- The lines -->
<?php if ($paper_edit) { ?>
<form id="billingAddLine" action="post.php" method="post" autocomplete="off" class="d-none">
<input type="hidden" name="csrf_token" value="<?= escapeHtml($paper['csrf'] ?? '') ?>">
<input type="hidden" name="billing_item_save" value="1">
<input type="hidden" name="type" value="<?= $paper_type ?>">
<input type="hidden" name="doc_id" value="<?= $paper_id ?>">
<input type="hidden" name="product_id" value="0" data-line-product>
</form>
<?php } ?>
<div class="table-responsive">
<table class="table itflow-paper-items align-top mb-0" data-billing-items>
<thead>
<tr>
<?php if ($paper_edit) { ?><th class="itflow-paper-handle d-print-none"></th><?php } ?>
<th>Item</th>
<th class="text-end">Qty</th>
<th class="text-end">Price</th>
<th class="text-end">Tax</th>
<th class="text-end">Amount</th>
<?php if ($paper_edit) { ?><th class="d-print-none"></th><?php } ?>
</tr>
</thead>
<tbody>
<?php foreach ($paper_items as $item) {
$item_id = intval($item['item_id']);
$item_tax_label = floatval($item['item_tax']) != 0 || intval($item['item_tax_id'])
? trim(($item['tax_name'] ?? '') . ' ' . ($item['tax_percent'] !== null ? billingQuantity($item['tax_percent']) . '%' : ''))
: ''; ?>
<tr id="line-<?= $item_id ?>" data-item-id="<?= $item_id ?>">
<?php if ($paper_edit) { ?>
<td class="itflow-paper-handle d-print-none"><span class="drag-handle" title="Drag to reorder"><i class="fas fa-grip-vertical"></i></span></td>
<?php } ?>
<td class="itflow-paper-item">
<div class="fw-semibold"><?= escapeHtml($item['item_name']) ?></div>
<?php if (trim((string) $item['item_description']) !== '') { ?>
<div class="small text-body-secondary"><?= nl2br(escapeHtml($item['item_description'])) ?></div>
<?php } ?>
</td>
<td class="text-end text-nowrap"><?= billingQuantity($item['item_quantity']) ?></td>
<td class="text-end text-nowrap"><?= $paper_money($item['item_price']) ?></td>
<td class="text-end text-nowrap">
<?php if ($item_tax_label !== '') { ?>
<?= $paper_money($item['item_tax']) ?>
<div class="small text-body-secondary"><?= escapeHtml($item_tax_label) ?></div>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>
</td>
<td class="text-end text-nowrap fw-semibold"><?= $paper_money($item['item_total']) ?></td>
<?php if ($paper_edit) { ?>
<td class="text-end d-print-none itflow-paper-actions">
<div class="dropdown dropstart">
<button class="btn btn-sm btn-link text-body-secondary" title="Line actions" type="button" data-bs-toggle="dropdown"><i class="fas fa-fw fa-ellipsis-v"></i></button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/billing/billing_item.php?type=<?= $paper_type ?>&doc_id=<?= $paper_id ?>&item_id=<?= $item_id ?>">
<i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger confirm-link" href="<?= escapeHtml($paper_post(['billing_item_delete' => $item_id])) ?>"
data-confirm-text="<?= escapeHtml($item['item_name']) ?> comes off <?= escapeHtml(billingNumber($paper_type, $paper_row)) ?><?= $paper_type === 'invoice' && intval($item['item_product_id']) ? ' - anything taken from stock goes back' : '' ?>.">
<i class="fas fa-fw fa-trash me-2"></i>Remove
</a>
</div>
</div>
</td>
<?php } ?>
</tr>
<?php } ?>
<?php if (!$paper_items && !$paper_edit) { ?>
<tr><td colspan="5" class="text-center text-body-secondary py-4">Nothing on it yet.</td></tr>
<?php } ?>
</tbody>
<?php if ($paper_edit) { ?>
<tfoot class="d-print-none">
<tr class="itflow-paper-add" id="add-line">
<td colspan="7">
<div class="itflow-paper-add-grid" data-billing-add>
<div class="itflow-paper-add-item">
<input type="text" class="form-control form-control-sm mb-1" name="name" form="billingAddLine" placeholder="<?= $paper_items ? 'Add a line - type a product, or anything' : 'First line - type a product, or anything' ?>" maxlength="200" required data-line-name aria-label="Item">
<textarea class="form-control form-control-sm" name="description" form="billingAddLine" rows="1" placeholder="Description (optional)" data-line-description aria-label="Description"></textarea>
</div>
<div class="itflow-paper-add-qty">
<label class="form-label small text-body-secondary mb-0">Qty</label>
<input type="text" class="form-control form-control-sm text-end" name="qty" form="billingAddLine" inputmode="decimal" placeholder="1" value="1" data-line-qty>
</div>
<div class="itflow-paper-add-price">
<label class="form-label small text-body-secondary mb-0">Price</label>
<input type="text" class="form-control form-control-sm text-end" name="price" form="billingAddLine" inputmode="decimal" placeholder="0.00" data-line-price>
</div>
<div class="itflow-paper-add-tax">
<label class="form-label small text-body-secondary mb-0">Tax</label>
<select class="form-select form-select-sm" name="tax_id" form="billingAddLine" data-line-tax>
<option value="0" data-percent="0">No tax</option>
<?php foreach ($paper['taxes'] ?? [] as $tax_id => $tax) { ?>
<option value="<?= intval($tax_id) ?>" data-percent="<?= floatval($tax['tax_percent']) ?>"><?= escapeHtml($tax['tax_name'] . ' ' . billingQuantity($tax['tax_percent']) . '%') ?></option>
<?php } ?>
</select>
</div>
<div class="itflow-paper-add-go">
<span class="small text-body-secondary text-nowrap" data-line-preview></span>
<button type="submit" form="billingAddLine" class="btn btn-sm btn-primary text-nowrap" title="Add the line"><i class="fas fa-plus me-1"></i>Add</button>
</div>
</div>
</td>
</tr>
</tfoot>
<?php } ?>
</table>
</div>
<!-- Notes, and what it all comes to -->
<div class="itflow-paper-bottom">
<div class="itflow-paper-notes">
<?php if (!empty($paper['notes_edit'])) { ?>
<div class="itflow-paper-label d-flex align-items-center">Notes <span class="ms-2 d-print-none fw-normal text-transform-none" data-note-status-for="billingNotes"></span></div>
<textarea class="form-control form-control-sm itflow-inline-note d-print-none" rows="3" id="billingNotes"
placeholder="Payment details, terms, a thank you - shown on the <?= strtolower($paper_title) ?>"
data-endpoint="<?= $paper_c ?>_set_notes" data-id-field="<?= $paper_t['param'] ?>" data-id="<?= $paper_id ?>"
data-csrf="<?= escapeHtml($paper['csrf'] ?? '') ?>"><?= escapeHtml($paper_row["{$paper_c}_note"]) ?></textarea>
<div class="d-none d-print-block small"><?= nl2br(escapeHtml($paper_row["{$paper_c}_note"])) ?></div>
<?php } elseif (trim((string) $paper_row["{$paper_c}_note"]) !== '') { ?>
<div class="itflow-paper-label">Notes</div>
<div class="small"><?= nl2br(escapeHtml($paper_row["{$paper_c}_note"])) ?></div>
<?php } ?>
</div>
<table class="itflow-paper-totals">
<tr><th>Subtotal</th><td><?= $paper_money($paper_totals['subtotal']) ?></td></tr>
<?php if ($paper_totals['discount'] != 0) { ?>
<tr><th>Discount</th><td>-<?= $paper_money($paper_totals['discount']) ?></td></tr>
<?php } ?>
<?php foreach ($paper_totals['taxes'] as $tax_label => $tax_amount) { ?>
<tr><th><?= escapeHtml($tax_label) ?></th><td><?= $paper_money($tax_amount) ?></td></tr>
<?php } ?>
<?php if ($paper_totals['credit'] > 0) { ?>
<tr><th>Credit</th><td>-<?= $paper_money($paper_totals['credit']) ?></td></tr>
<?php } ?>
<tr class="itflow-paper-total"><th>Total</th><td><?= $paper_money($paper_totals['total']) ?></td></tr>
<?php if ($paper_type === 'invoice' && ($paper['paid'] ?? 0) > 0) { ?>
<tr class="text-success"><th>Paid</th><td>-<?= $paper_money($paper['paid']) ?></td></tr>
<tr class="itflow-paper-total"><th>Balance due</th><td><?= $paper_money($paper['balance']) ?></td></tr>
<?php } ?>
</table>
</div>
<?php if (trim((string) $paper_footer) !== '') { ?>
<div class="itflow-paper-footer"><?= nl2br(escapeHtml($paper_footer)) ?></div>
<?php } ?>
</div>

233
js/billing_items.js Normal file
View File

@@ -0,0 +1,233 @@
/*
* The lines on an invoice, quote or recurring invoice page
* (includes/billing_paper.php):
*
* - the add-a-line row: type a product's name or code and pick it to fill
* in its description, price and tax; the amount it comes to shows as you
* type; after adding, the page comes back here ready for the next
* - drag a line by its handle to move it - saved as it drops
* - the line just edited is picked out when the page comes back
*
* Call once the page has loaded:
*
* itflowBillingItems({ products: [...], csrf: '...', currency: 'USD', locale: 'en-US' });
*
* products is what getProductsForAutocomplete() gives.
*
* itflowBillingLineForm(form, options) does the product pick and the amount
* for any other line form - the Edit Line window uses it.
*/
function itflowBillingMoney(amount, currency, locale) {
try {
return new Intl.NumberFormat(locale || undefined, { style: 'currency', currency: currency || 'USD' }).format(amount);
} catch (e) {
return (Math.round(amount * 100) / 100).toFixed(2);
}
}
/* A number from a form field - "1,250.50", "$99" - or NaN */
function itflowBillingNumber(value) {
var text = String(value == null ? '' : value).replace(/[\s,$€£]/g, '');
return text === '' ? NaN : Number(text);
}
function itflowBillingLineForm(root, options) {
if (!root) {
return;
}
var opts = options || {};
var name = root.querySelector('[data-line-name]');
var description = root.querySelector('[data-line-description]');
var qty = root.querySelector('[data-line-qty]');
var price = root.querySelector('[data-line-price]');
var tax = root.querySelector('[data-line-tax]');
var preview = root.querySelector('[data-line-preview]');
// The hidden product id can sit in a separate form (the add row's inputs use form="")
var product = root.querySelector('[data-line-product]') || (opts.productInput || null);
function update() {
if (!preview) {
return;
}
var q = itflowBillingNumber(qty && qty.value !== '' ? qty.value : '1');
var p = itflowBillingNumber(price ? price.value : '');
if (isNaN(q) || isNaN(p)) {
preview.textContent = price && price.value !== '' ? 'Not a number' : '';
return;
}
var option = tax && tax.options[tax.selectedIndex];
var percent = option ? Number(option.getAttribute('data-percent') || 0) : 0;
var subtotal = Math.round(q * p * 100) / 100;
var total = subtotal + Math.round(subtotal * percent) / 100;
preview.textContent = itflowBillingMoney(total, opts.currency, opts.locale);
}
[qty, price, tax].forEach(function (el) {
if (el) {
el.addEventListener('input', update);
el.addEventListener('change', update);
}
});
update();
// The description grows with what is typed into it
if (description && description.tagName === 'TEXTAREA') {
var grow = function () {
description.style.height = 'auto';
description.style.height = Math.min(description.scrollHeight + 2, 240) + 'px';
};
description.addEventListener('input', grow);
if (description.value) {
grow();
}
}
if (!name || !opts.products || !opts.products.length || typeof itflowAutocomplete !== 'function') {
return;
}
itflowAutocomplete(name, {
minLength: 1,
source: opts.products,
match: function (item, term) {
return String(item.label || '').toLowerCase().indexOf(term) !== -1
|| String(item.product_name || '').toLowerCase().indexOf(term) !== -1
|| String(item.product_code || '').toLowerCase().indexOf(term) !== -1;
},
render: function (item) {
var esc = itflowEscapeHtml;
var isService = String(item.type || '').toLowerCase() === 'service';
var stock = Number(item.available_stock || 0);
return "<div class='d-flex justify-content-between align-items-start gap-3'>" +
"<div class='min-w-0'>" +
"<div class='fw-semibold'>" + esc(item.label) + "</div>" +
(item.description ? "<div class='small text-body-secondary text-truncate'>" + esc(item.description) + "</div>" : "") +
"<div class='small mt-1'>" +
"<span class='badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal me-1'>" + (isService ? 'Service' : 'Product') + "</span>" +
(item.tax_percent != null ? "<span class='badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal me-1'>Tax " + esc(parseFloat(item.tax_percent)) + "%</span>" : "") +
(!isService ? "<span class='badge rounded-pill fw-normal " + (stock > 0 ? "bg-success-subtle text-success-emphasis" : "bg-danger-subtle text-danger-emphasis") + "'>" + esc(stock) + " in stock</span>" : "") +
"</div>" +
"</div>" +
"<div class='fw-semibold text-nowrap'>" + esc(item.price != null && item.price !== '' ? itflowBillingMoney(Number(item.price), opts.currency, opts.locale) : '') + "</div>" +
"</div>";
},
onSelect: function (item) {
name.value = item.product_name;
if (description) {
description.value = item.description || '';
description.dispatchEvent(new Event('input', { bubbles: true }));
}
if (qty && (qty.value === '' || qty.value === '0')) {
qty.value = 1;
}
if (price) {
price.value = item.price;
}
if (tax) {
tax.value = item.tax || 0;
if (tax.selectedIndex < 0) {
tax.value = 0;
}
tax.dispatchEvent(new Event('change', { bubbles: true }));
}
if (product) {
product.value = item.prod_id;
}
update();
if (price) {
price.focus();
price.select();
}
}
});
// Typing over the name by hand breaks the link to the product
if (product) {
name.addEventListener('input', function () {
product.value = 0;
});
}
}
function itflowBillingItems(options) {
var opts = options || {};
var paper = document.querySelector('.itflow-paper[data-billing-type]');
if (!paper) {
return;
}
var type = paper.getAttribute('data-billing-type');
var docId = paper.getAttribute('data-billing-id');
var addRow = paper.querySelector('[data-billing-add]');
var addForm = document.getElementById('billingAddLine');
if (addRow) {
itflowBillingLineForm(addRow, {
products: opts.products,
currency: opts.currency,
locale: opts.locale,
productInput: addForm ? addForm.querySelector('[data-line-product]') : null
});
// Enter in the name, quantity or price adds the line
addRow.querySelectorAll('input').forEach(function (input) {
input.addEventListener('keydown', function (e) {
if (e.key === 'Enter' && !e.defaultPrevented && !document.querySelector('.itflow-ac-menu.show')) {
e.preventDefault();
if (addForm && addForm.reportValidity()) {
addForm.requestSubmit ? addForm.requestSubmit() : addForm.submit();
}
}
});
});
}
// Back from adding a line - ready for the next; back from editing one - show which
var hash = window.location.hash;
if (hash === '#add-line' && addRow) {
var nameInput = addRow.querySelector('[data-line-name]');
addRow.scrollIntoView({ block: 'center' });
if (nameInput) {
nameInput.focus();
}
} else if (/^#line-\d+$/.test(hash)) {
var line = document.querySelector(hash);
if (line) {
line.scrollIntoView({ block: 'center' });
line.classList.add('itflow-paper-flash');
}
}
// Drag to reorder
var body = paper.querySelector('[data-billing-items] tbody');
if (body && typeof Sortable !== 'undefined' && paper.querySelector('.drag-handle')) {
new Sortable(body, {
handle: '.drag-handle',
animation: 150,
onEnd: function (evt) {
if (evt.oldIndex === evt.newIndex) {
return;
}
var ids = Array.prototype.map.call(body.querySelectorAll('tr[data-item-id]'), function (row) {
return row.getAttribute('data-item-id');
});
itflowPost('ajax.php', {
billing_items_order: 1,
type: type,
doc_id: docId,
items: ids.join(','),
csrf_token: opts.csrf
}, function () {
if (typeof itflowToast === 'function') {
itflowToast('Order saved', 'success');
}
}, function () {
if (typeof itflowToast === 'function') {
itflowToast("The new order didn't save - reloading", 'error');
}
setTimeout(function () { window.location.reload(); }, 1200);
});
}
});
}
}

View File

@@ -1,80 +0,0 @@
/*
* Product autocomplete for the add-item row on invoices, quotes and recurring
* invoices.
*
* The three pages used to carry a copy of this each, and they drifted - the
* quote and recurring invoice copies were fed a four column product query, so
* item.product_name was undefined and selecting a product wrote the literal
* string "undefined" into the item name.
*
* Call with the array emitted by getProductsForAutocomplete():
*
* initProductAutocomplete(<?= $json_products ?? '[]' ?>);
*/
function initProductAutocomplete(availableProducts) {
var nameInput = document.getElementById('name');
if (!nameInput) {
return;
}
// Quote and recurring invoice do not store the product link yet, so treat
// the hidden input as optional rather than throwing on every keystroke.
var productIdInput = document.getElementById('product_id');
itflowAutocomplete(nameInput, {
minLength: 1,
source: availableProducts || [],
match: function (item, term) {
return String(item.label || '').toLowerCase().indexOf(term) !== -1
|| String(item.product_name || '').toLowerCase().indexOf(term) !== -1
|| String(item.product_code || '').toLowerCase().indexOf(term) !== -1;
},
render: function (item) {
var esc = itflowEscapeHtml;
var typeText = item.type ? item.type.charAt(0).toUpperCase() + item.type.slice(1).toLowerCase() : "";
var showStock = (typeText.toLowerCase() !== "service");
var taxText = (item.tax_percent != null) ? (parseFloat(item.tax_percent) + "%") : "No tax";
var priceText = (item.price != null && item.price !== "") ? String(item.price) : "";
var stockText = (item.available_stock ?? 0);
return "<div class='d-flex justify-content-between align-items-start'>" +
"<div class='flex-fill pe-2'>" +
"<div class='fw-bold'>" + esc(item.label) +
(typeText ? " <small class='text-muted'>(" + esc(typeText) + ")</small>" : "") +
"</div>" +
"<div class='small text-muted'>" + esc(item.description) + "</div>" +
"<div class='mt-1'>" +
"<span class='badge bg-secondary me-1'>Tax: " + esc(taxText) + "</span>" +
(showStock ? "<span class='badge " + (stockText > 0 ? "bg-success" : "bg-danger") + "'>Stock: " + esc(stockText) + "</span>" : "") +
"</div>" +
"</div>" +
"<div class='text-end'>" +
"<div class='fw-bold'>" + esc(priceText) + "</div>" +
"</div>" +
"</div>";
},
onSelect: function (item) {
nameInput.value = item.product_name;
document.getElementById('desc').value = item.description;
document.getElementById('qty').value = 1;
document.getElementById('price').value = item.price;
const tax = document.getElementById('tax');
if (tax) {
tax.value = item.tax;
tax.dispatchEvent(new Event('change', { bubbles: true }));
}
if (productIdInput) {
productIdInput.value = item.prod_id;
}
}
});
// Typing over the name by hand breaks the link to the product
if (productIdInput) {
nameInput.addEventListener('input', function () {
productIdInput.value = 0;
});
}
}