diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a63ba5fe..abbb82b03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.11 -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 3.4.1) in the same pass. Nothing else is required. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 3.4.2) in the same pass. Nothing else is required. This is a big release, with sixty database steps in one go, so take a backup before you update. @@ -33,6 +33,10 @@ Ticket statuses keep their names, colours, order and SLA settings, and every one Payment methods are all offered for money in and out, as before, until you say one is only for one of them (see New Features, Payment Methods). Methods that payments, income or expenses were recorded with but that aren't in Admin > Payment Methods - ACH from a bank import, say - are listed there to add with one click. +Contracts and contract templates keep their names, dates, rates, support hours and terms. Their response and resolution hours become an SLA from Admin > SLAs for each ticket priority - one you already have with the same hours, or a new one named for the template or contract and the priority, such as "Gold - High" - and Urgent takes High's, as there were no urgent hours. A renewal frequency becomes a term: Annually is 1 year, 2 Year is 2 years and so on, each renewing itself, and Manual is 1 year that is only renewed by hand. Net terms become a number of days, so "Net 30" is 30, and ones without a number are left empty, which means the client's own apply. Fully Managed and Partially Managed become Fully managed and Co-managed, Break/Fix stays, and any other type is Other. A contract's status becomes Active, Draft, Ended or Cancelled: Pending is a draft, Expired is ended, and anything that isn't one of those is active. Each has 30 days' notice, and no owner, contact or template until you give it one. + +The first nightly run after the update deals with active contracts whose end date has passed (see New Features, Contracts). One that renews itself is renewed term by term until it is current, and one that doesn't is marked ended. Agents are notified in ITFlow about the ones due soon, and the owner is emailed once a contract has one. Look over Contracts once after the update if end dates weren't kept up to date. + Every account is given a kind - checking, savings, credit card, cash or payment processor - guessed from its name: Visa, Amex or card is a credit card, savings or reserve is savings, cash or petty cash is cash, and Stripe, PayPal, Square or merchant is a payment processor. An account given a liability type back when accounts had types (2023) is a credit card, so what is on it reads as owed. Anything else is checking. Change any that came out wrong with Edit on the Accounts page. An account's balance now leaves out archived payments, income and expenses everywhere, so the Accounts page can show less or more than before (see Bug Fixes). No account is reconciled after the update. The first statement you reconcile on each can start from the bank's balance on the day it starts, bringing everything before it forward as reconciled, or from the account's opening balance (see New Features, Accounts and transactions). Transfers already made out of a cash account count as having taken everything in it up to then to the bank, so the first deposit you make after the update only offers the checks and cash taken in since the last one. Taxes keep their names and rates, now kept to four decimal places. No client has a rate of its own or is tax exempt, and there is no default rate, so new lines start untaxed as before until you pick one in Admin > Taxes. Billed time, trips and expenses stay untaxed until you switch them on there. Discounts now come off before tax on invoices and quotes that are still open, the next time they are edited (see Breaking Changes, Taxes). No expense has tax recorded on it until you add it, so Tax Collected shows no tax paid on purchases for the months before. @@ -1133,6 +1137,19 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Delete a method nothing used; one that was used is merged into another instead - its records change to the method you pick, which takes its place as a default too. For two names for one thing, "Card" and "Credit Card". - Methods records were paid by but that aren't in the list - from a bank import, an older version or demo data - are named at the top with how much they are used, to add with one click. - New and Edit are one window, with an icon in front of every field. +- **Contracts** (new) + - Contracts, under Billing in the menu and in each client's menu, keeps every agreement with a client: its type (Fully managed, Co-managed, Block hours, Time and materials, Break/fix, Project or Other), its term, start and end, whether it renews itself and the notice needed to end it, support hours, rates, net terms and an SLA for each ticket priority from Admin > SLAs. Leave a rate, the net terms or an SLA empty and the client's own apply. + - Along the top of the list: how many are in force, ending soon without renewing, renewing soon (a good time to review them with the client) and drafts. Tabs for Active, Due soon, Drafts, Ended and All, with search, filters for type and client, and sorting by name, client, type, start, end or owner. Each row says when it renews or ends, and when notice is due. The menu shows how many are due soon. + - New Contract can start from a template, which fills in the type, term, renewal, notice, cover and terms, and any of them can be changed after. Pick the client, a contact there and the agent who looks after it. The end date follows the start and the term until you change it, and the window says when notice is due. Save it as active, or as a draft to make active when it is signed. Copy starts a new contract from an existing one. + - A contract's page shows where it stands (draft, starts soon, active, renews soon, ends soon, ended or cancelled) and how far through its term it is. It also shows what the contract covers, with the SLA for each priority, the terms and internal notes, the client, contact and owner, and its history. + - Renew sets a new last day, a term on by default. Cancel takes the last day it is in force and why, and it doesn't renew after that. Make active takes the day a draft starts and sets its end a term later. + - Every night, a contract that renews itself is renewed for another term once it ends, and one that doesn't is marked ended. A month before its notice date, its owner is emailed what it is, when notice is due and a link to it, and agents are notified in ITFlow. This happens once a term. + - The client overview lists contracts ending or renewing soon under Needs attention, and shows the contract in force in the Financial row. + - Deleting a client deletes its contracts. It used to fail while the client had one (see Bug Fixes). +- **Contract Templates** (rebuilt) + - Admin > Contract Templates shows each template with its type, its term and renewal, the notice, its cover (support hours, rate and net terms), the SLA for each priority and how many contracts were started from it. Tabs for the ones in use and the archived ones; search; sort by name, term or contracts. + - New and Edit are one window with Template, Cover and Terms tabs and an icon in front of every field. A template has the same terms as a contract, without the client and dates. + - Copy makes "Name (copy)". Archive takes a template off New Contract and keeps it, and Restore brings it back. Delete leaves the contracts started from it as they are. ### Bug Fixes @@ -1333,6 +1350,9 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Payment methods: renaming one left every record that used it under the old name, so lists, filters and reports split it in two, and deleting one left its records with a name that couldn't be picked again. - Payments: editing a payment made online (recorded as Stripe), or one with a method no longer in the list, showed no method and couldn't be saved without picking another. - Payment methods: the same name could be added twice, and the description had no label. +- Clients: a client with a contract couldn't be deleted, because the database refused it. +- Contract templates: the after-hours rate of a new template was never saved, rates were cut to whole amounts, and net terms written as "Net 30", as the field suggested, were saved as 0. +- Contract templates: Edit showed the rates empty, so saving a template set them to 0. ### Developer Updates @@ -1929,6 +1949,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Debug: new `functions/system_health.php`. `healthChecks()` returns the sections in order (`key`, `title`, `icon`, `items`), each item from `healthItem($label, $level, $value, $fix, $url, $action, $private)` - level `ok`, `info`, `warning` or `danger`, `fix` as HTML, `private` leaving the value out of the report. `healthSummary($sections)` counts them by level and lists the warnings and problems, problems first. `healthDatabaseTables($exact)` reads sizes and InnoDB's row estimates from `information_schema.TABLES` in one query, or counts each table with `$exact` (`debug.php?exact=1`); `healthStructureDifferences()` compares `information_schema.COLUMNS` with `db.sql`, ignoring integer display widths (`healthColumnType()`); `healthUploads($seconds)` counts uploads by top-level folder and stops at the time given, marked `partial`. `healthReport()` is the plain-text report. Every read goes through `healthQuery()` / `healthRow()`, which answer null instead of throwing, so a column the database doesn't have yet costs a line, not the page. The certificate is read from `$config_base_url`'s host (`healthBaseHost()`, `healthCertificate()`), never `HTTP_HOST`; HTTPS counts `X-Forwarded-Proto`; the required extensions come from `setupRequiredExtensions()` in `setup/setup_checks.php` so setup and Debug agree; mail uses `mailQueueHealth()` and `mailQueueSummary()`; updates use `shellCommandsAvailable()` and `commandPath('git')`. `admin/debug.php` no longer closes the database before the footer, uses `reportStats()` for the figures along the top, and the copy button is the shared `.clipboardjs` one, targeting the report's textarea. New CSS: `.itflow-debug-section-icon`, `.itflow-debug-item`, `.itflow-debug-fix`, `.itflow-debug-attention`, `.itflow-debug-bar`, `.itflow-debug-stats`. No database change. - Ticket statuses: database 3.4.0 adds `ticket_statuses.ticket_status_description` varchar(255) and `ticket_status_client_reply` tinyint(1) (1, the default, sends the ticket back to Open when the client replies; 0 leaves it), gives the five built-in statuses their descriptions where they have none, and numbers `ticket_status_order` 1, 2, 3... in the order they already showed in. New `functions/ticket_status.php`: `ticketStatusBuiltIns()` (ids 1-5 with icon, meaning and what sets them), `ticketStatusIsBuiltIn()`, `ticketStatusRow()`, `ticketStatusesAll()` (once a page, in order), `ticketStatusAbout()`, `ticketStatusColor()`, `ticketStatusBadgeHtml()` (text colour from `tagTextColor()`, the description as its title), `ticketStatusOptions($keep)`, `ticketStatusTicketCounts()`, `ticketStatusMoveTargets()`, `ticketStatusFromInput()` (a built-in keeps its name, stays on and takes `getTicketStatusSlaLock()` and client reply 1 whatever is posted), `ticketStatusProblem()` (a name, not taken), `ticketStatusCreate()`, `ticketStatusUpdate()` (returns the from-to changes, syncs its tickets' SLA clocks when pausing changes), `ticketStatusMoveTickets()`, `ticketStatusSetActive()`, `ticketStatusDelete()`, `ticketStatusReorder()` and `ticketStatusAfterClientReply($status_id)`, which `cron/ticket_email_parser.php` and `client/post.php` now use instead of setting status 2. `ticketStatusColumnsReady()` keeps all of it working before 3.4.0 has run. `ticketStatusHtml()` draws through `ticketStatusBadgeHtml()`, and the dashboard, client overview, ticket page, Ticket Aging and Client Review reports use it instead of their own badges. `admin/post/ticket_status.php` adds `move_ticket_status`, `reorder_ticket_statuses` (POST, JSON), `switch_on_ticket_status`, `switch_off_ticket_status` (POST, `move_to`) and `delete_ticket_status` as POST with `move_to` - the GET delete is gone. The add and edit windows share `admin/modals/ticket_status/ticket_status_form.php` with `js/ticket_status_form.js`; `ticket_status_remove.php` is the switch-off and delete window. Quick picker options take a `title` (`js/quick_pick.js`), which the status picker sets to the description. New CSS: `.itflow-ticket-status`. - Payment methods: database 3.4.1 adds `payment_methods.payment_method_use` tinyint(1) (0 money in and out - every method so far, 1 money in, 2 money out) and `payment_method_archived_at`. New `functions/payment_method.php`: `PAYMENT_METHOD_USES`, `PAYMENT_METHOD_ONLINE` ('Stripe', what online card payments are recorded as - its name can't be changed), `paymentMethodUsageColumns()` (every column a method is kept in by name: `payment_method`, `revenue_payment_method`, `expense_payment_method`, `recurring_expense_payment_method`, `reimbursement_payment_method`, `transfer_method`, `recurring_payment_method`), `paymentMethodRow()`, `paymentMethodsAll()`, `paymentMethodUsage()` (one UNION ALL, counts and the last date per name), `paymentMethodUsageText()`, `paymentMethodsNotSetUp()`, `paymentMethodDefaults()`, `paymentMethodDefaultFor()`, `paymentMethodSetDefault()`, `paymentMethodFromInput()`, `paymentMethodProblem()` (a name, not taken), `paymentMethodCreate()`, `paymentMethodRename()` (every column above and both defaults, case-insensitively), `paymentMethodUpdate()` (returns the from-to changes and how many records were renamed; drops a default the new use rules out), `paymentMethodSetArchived()`, `paymentMethodDelete()` (refuses a used method without another to merge into) and `paymentMethodAddNames()`. `paymentMethods($way = '', $with_archived = false)` moves here from `functions/billing.php` - `'in'` for payments and income, `'out'` for expenses, `''` for transfers; archived ones only for filters - and every picker and check passes its way: the payment, income, expense, recurring expense, reimbursement, mileage claim, bulk edit and import windows, `incomeImportMethod()`, the expense and income save functions, and Settings > Defaults. `paymentMethodColumnsReady()` keeps it working before 3.4.1 has run. The payment window keeps a payment's own method among the choices. `admin/post/payment_method.php` adds `default_payment_method` (GET, `way` in or out), `archive_payment_method`, `restore_payment_method`, `delete_payment_method` as POST with `move_to` (the GET delete is gone) and `add_payment_method_names`. The add and edit windows share `admin/modals/payment_method/payment_method_form.php`; `payment_method_delete.php` is the delete and merge window. +- Contracts: database 3.4.2 adds to `contract_templates` and `contracts` `{prefix}_term_months` int (12), `_auto_renew` tinyint(1) (1), `_notice_days` int (30) and `_sla_low_id`, `_sla_medium_id`, `_sla_high_id`, `_sla_urgent_id` int (0, the client's own), and to `contracts` `contract_template_id`, `contract_contact_id`, `contract_owner_id`, `contract_created_by` int, `contract_notes` text, `contract_renewed_at`, `contract_reminded_at`, `contract_cancelled_at` datetime and `contract_cancel_reason` varchar(255). It turns the `_sla_{low,medium,high}_{response,resolution}_time` hours into SLA ids - an unarchived `slas` row with the same minutes, or a new one - and `_renewal_frequency` into the term and auto-renew, then drops those seven columns from both tables. It makes `_net_terms` int (the digits of the old text, or NULL), sets `_type` to a key of `CONTRACT_TYPES` and `contract_status` to Draft, Active, Ended or Cancelled, and re-adds `contracts_ibfk_1` with ON DELETE CASCADE. New `functions/contract.php`: `CONTRACT_TYPES` (key => label, icon, about), `CONTRACT_TERMS`, `CONTRACT_REMINDER_DAYS` (30), `CONTRACT_SLA_PRIORITIES`, `contractsReady()` (keeps every page and the nightly job working before 3.4.2 has run), `contractRow()` (with the client, contact, owner and template names), `contractTemplateRow()`, `contractTemplates()`, `contractTypeLabel()`, `contractTermLabel()`, `contractTermEnd($start, $months)` (a term less a day - `termEnd()` in `js/contract_form.js` matches it), `contractNextEnd()`, `contractNoticeDate()`, `contractReminderDate()`, `contractState()` and `contractStateHtml()`, `contractViews()`, `contractSlaChoices($keep)`, `contractSlaTargets()`, `contractFromInput($in, 'contract'|'template')` (returns the fields and an error; checks the client in scope, the contact at that client, an active agent as owner and listed SLAs, and purifies the terms), `contractTermsSetSql($f, $prefix)` (shared by contracts and templates), `contractSetSql()`, `contractCreate()`, `contractUpdate()` (returns the changes; a new end date clears `contract_reminded_at`), `contractActivate()`, `contractRenew()`, `contractCancel()`, `contractsNightly($today)` (returns renewed, ended and reminded counts; `cron/nightly_tasks.php` runs it and logs them), `contractRemind()`, `contractClientCount()` and `contractClientActive()`. New `agent/contracts.php`, `agent/contract.php`, `agent/post/contract.php` (`add_contract`, `edit_contract`, `activate_contract`, `renew_contract`, `cancel_contract` POST with Sales Modify, and `delete_contract` GET with Sales Delete), and `agent/modals/contract/` (the add, copy and edit windows share `contract_form.php` with `js/contract_form.js`, plus `contract_activate.php`, `contract_renew.php` and `contract_cancel.php`). `admin/post/contract_template.php` is rewritten on `contractFromInput()` and adds `copy_contract_template`; deleting a template sets its contracts' `contract_template_id` to 0. The template add and edit windows share `admin/modals/contract_template/contract_template_form.php`. `auditLogKinds()` has a Contract kind, the client overview has Contracts ending and Contracts renewing attention items and a contract in the Financial row, and `agent/post/client.php` deletes a client's contracts with it. ### Library Updates diff --git a/admin/contract_templates.php b/admin/contract_templates.php index 2bceb7e62..c9fbc93b3 100644 --- a/admin/contract_templates.php +++ b/admin/contract_templates.php @@ -1,21 +1,66 @@ Contract Templates - the agreements you offer, to start a client's + * contract from: its type, term, renewal and notice, support hours, rates, + * net terms, an SLA for each ticket priority, and the terms themselves. + * Each row says what it sets and how many contracts were started from it. + * Tabs for the ones in use and the archived ones. The work is in + * functions/contract.php; the handlers are admin/post/contract_template.php. + */ + // Default Column Sort by Filter $sort = "contract_template_name"; $order = "ASC"; require_once "includes/inc_all_admin.php"; -// Search query -$sql = mysqli_query( - $mysqli, - "SELECT SQL_CALC_FOUND_ROWS * FROM contract_templates - WHERE contract_template_name LIKE '%$q%' OR contract_template_type LIKE '%$q%' - OR contract_template_description LIKE '%$q%' - ORDER BY $sort $order LIMIT $record_from, $record_to" -); +$views = [ + '' => ['label' => 'In use', 'icon' => 'fa-file-contract', 'where' => 'contract_template_archived_at IS NULL', 'title' => 'Offered on a new contract'], + 'archived' => ['label' => 'Archived', 'icon' => 'fa-archive', 'where' => 'contract_template_archived_at IS NOT NULL', 'title' => 'Kept, but not offered'], +]; +$show = (string) ($_GET['show'] ?? ''); +$show = isset($views[$show]) ? $show : ''; -$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); +$sortable_columns = [ + 'contract_template_name' => "contract_template_name $order", + 'contract_template_type' => "contract_template_type $order, contract_template_name ASC", + 'contract_template_term_months' => "contract_template_term_months $order, contract_template_name ASC", + 'contracts' => "n_contracts $order, contract_template_name ASC", +]; +if (!isset($sortable_columns[$sort])) { + $sort = 'contract_template_name'; +} + +$rows = []; +$num_rows = [0]; +$view_counts = ['' => 0, 'archived' => 0]; +if (contractsReady()) { + $filters = "(contract_template_name LIKE '%$q%' OR contract_template_description LIKE '%$q%' OR contract_template_support_hours LIKE '%$q%')"; + $sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS contract_templates.*, + (SELECT COUNT(*) FROM contracts WHERE contracts.contract_template_id = contract_templates.contract_template_id) AS n_contracts + FROM contract_templates + WHERE $filters AND {$views[$show]['where']} + ORDER BY {$sortable_columns[$sort]} LIMIT $record_from, $record_to"); + $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); + while ($row = mysqli_fetch_assoc($sql)) { + $rows[] = $row; + } + $counts = mysqli_fetch_row(mysqli_query($mysqli, "SELECT " . implode(', ', array_map(function ($v) { + return "COALESCE(SUM({$v['where']}), 0)"; + }, $views)) . " FROM contract_templates WHERE $filters")); + $view_counts = array_combine(array_keys($views), array_map('intval', $counts)); +} +$slas = contractSlaChoices(); + +$sort_link = function ($column, $label) use ($url_query_strings_sort, $sort, $disp, $order_icon) { + return '' + . $label . ($sort === $column ? " $order_icon" : '') . ''; +}; +$pill_url = function ($view) { + return '?' . http_build_query(array_filter(['q' => $_GET['q'] ?? '', 'show' => $view])); +}; +$csrf = $_SESSION['csrf_token']; ?> @@ -24,133 +69,110 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));

Contract Templates

-
-
- - + +
+
+
+ + +
+
+
- -
- - "> - - - - - - - - - - - - - - +
+
- - Template Name - - - - Type - - - - Update Frequency - - SLA (L/M/H Response)SLA (L/M/H Resolution) - - Hourly Rate - - - - After Hours Rate - - - - Support Hours - - - - Net Terms - - - - Created - - - - Updated - - Action
+ "> + + + + + + + - $part) { + $sla = $slas[intval($row["contract_template_sla_{$part}_id"])] ?? null; + if ($sla) { + $sla_names[$sla['sla_name']][] = $priority; + } + } + $cover = array_filter([ + $row['contract_template_support_hours'], + $row['contract_template_rate_standard'] !== null ? number_format((float) $row['contract_template_rate_standard'], 2) . '/hr' : '', + $row['contract_template_net_terms'] !== null ? 'Net ' . intval($row['contract_template_net_terms']) : '', + ]); ?> - + - - - - - - - - - - - + + + - +
Cover
- - - -
+
+ +
+ +
+ +
Archived
+ +
+
- + +
, days notice
+
+ The client\'s rate and terms' ?> +
+ + The client's usual SLAs + +
+
0' ?> +
@@ -158,10 +180,15 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); $empty_state = [ 'thing' => 'contract templates', 'icon' => 'fa-file-contract', + 'filtered' => $q !== '', + 'archived' => $show === 'archived', + 'views' => ['show'], + 'text' => 'The agreements you offer - Fully managed, Block hours, Break/fix - to start a client\'s contract from.', 'actions' => [['label' => 'New Template', 'modal' => 'modals/contract_template/contract_template_add.php', 'size' => 'lg']], ]; + require_once "../includes/filter_footer.php"; ?> -
- + SLAs - an SLA for each ticket + * priority - instead of hours of their own; a template's hours become the + * SLA with the same targets, or a new one named for the template. The + * renewal frequency becomes a term in months with auto-renew on or off, and + * a notice period; net terms become a number of days; the types become keys + * (functions/contract.php). A contract also has a contact at the client, an + * owner who is reminded before it ends, internal notes, and when it was + * renewed, reminded about and cancelled; its status is Draft, Active, Ended + * or Cancelled. Deleting a client deletes its contracts - the foreign key + * used to stop the client being deleted. + */ + +defined('FROM_DB_UPDATER') || die("Direct file access is not allowed"); + + $itflow_column = function ($table, $column) use ($mysqli) { + $result = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$table' AND COLUMN_NAME = '$column' LIMIT 1"); + return $result && mysqli_num_rows($result) > 0; + }; + + // The new columns - on both tables, the contract's after its template's + foreach (['contract_templates' => 'contract_template', 'contracts' => 'contract'] as $itflow_table => $itflow_prefix) { + $itflow_adds = [ + "{$itflow_prefix}_term_months" => "int(11) NOT NULL DEFAULT 12", + "{$itflow_prefix}_auto_renew" => "tinyint(1) NOT NULL DEFAULT 1", + "{$itflow_prefix}_notice_days" => "int(11) NOT NULL DEFAULT 30", + "{$itflow_prefix}_sla_low_id" => "int(11) NOT NULL DEFAULT 0", + "{$itflow_prefix}_sla_medium_id" => "int(11) NOT NULL DEFAULT 0", + "{$itflow_prefix}_sla_high_id" => "int(11) NOT NULL DEFAULT 0", + "{$itflow_prefix}_sla_urgent_id" => "int(11) NOT NULL DEFAULT 0", + ]; + if ($itflow_table === 'contracts') { + $itflow_adds += [ + 'contract_template_id' => "int(11) NOT NULL DEFAULT 0", + 'contract_contact_id' => "int(11) NOT NULL DEFAULT 0", + 'contract_owner_id' => "int(11) NOT NULL DEFAULT 0", + 'contract_notes' => "text DEFAULT NULL", + 'contract_renewed_at' => "datetime DEFAULT NULL", + 'contract_reminded_at' => "datetime DEFAULT NULL", + 'contract_cancelled_at' => "datetime DEFAULT NULL", + 'contract_cancel_reason' => "varchar(255) DEFAULT NULL", + 'contract_created_by' => "int(11) NOT NULL DEFAULT 0", + ]; + } + foreach ($itflow_adds as $itflow_name => $itflow_definition) { + if (!$itflow_column($itflow_table, $itflow_name)) { + mysqli_query($mysqli, "ALTER TABLE `$itflow_table` ADD `$itflow_name` $itflow_definition"); + } + } + } + + // An SLA with these targets - one already in Admin > SLAs, or a new one named for the template + $itflow_sla_for = function ($response_hours, $resolution_hours, $name) use ($mysqli) { + $response = intval($response_hours) * 60; + $resolution = intval($resolution_hours) * 60; + if ($response <= 0) { + return 0; + } + $found = mysqli_fetch_row(mysqli_query($mysqli, "SELECT sla_id FROM slas WHERE sla_archived_at IS NULL AND sla_response_minutes = $response + AND IFNULL(sla_resolution_minutes, 0) = $resolution ORDER BY sla_id LIMIT 1")); + if ($found) { + return intval($found[0]); + } + $name = mysqli_real_escape_string($mysqli, mb_substr($name, 0, 200)); + mysqli_query($mysqli, "INSERT INTO slas SET sla_name = '$name', sla_description = 'Made from a contract template\\'s response and resolution hours', + sla_response_minutes = $response, sla_resolution_minutes = " . ($resolution > 0 ? $resolution : 'NULL')); + return intval(mysqli_insert_id($mysqli)); + }; + + // The old type names, as keys + $itflow_types = ['fully managed' => 'managed', 'partialy managed' => 'comanaged', 'partially managed' => 'comanaged', 'co-managed' => 'comanaged', 'break/fix' => 'break_fix']; + // The old renewal frequencies, as months and whether it renews itself + $itflow_frequencies = ['manual' => [12, 0], 'annually' => [12, 1], '2 year' => [24, 1], '3 year' => [36, 1], '5 year' => [60, 1], '7 year' => [84, 1]]; + + foreach (['contract_templates' => 'contract_template', 'contracts' => 'contract'] as $itflow_table => $itflow_prefix) { + $itflow_has_hours = $itflow_column($itflow_table, "{$itflow_prefix}_sla_low_response_time"); + $itflow_has_frequency = $itflow_column($itflow_table, "{$itflow_prefix}_renewal_frequency"); + $itflow_name_column = $itflow_table === 'contract_templates' ? 'contract_template_name' : 'contract_name'; + $itflow_rows = mysqli_query($mysqli, "SELECT * FROM `$itflow_table`"); + while ($itflow_row = mysqli_fetch_assoc($itflow_rows)) { + $itflow_set = []; + if ($itflow_has_hours) { + foreach (['low' => 'Low', 'medium' => 'Medium', 'high' => 'High'] as $itflow_level => $itflow_label) { + $itflow_set["{$itflow_prefix}_sla_{$itflow_level}_id"] = $itflow_sla_for($itflow_row["{$itflow_prefix}_sla_{$itflow_level}_response_time"], + $itflow_row["{$itflow_prefix}_sla_{$itflow_level}_resolution_time"], $itflow_row[$itflow_name_column] . " - $itflow_label"); + } + // There were no urgent targets - urgent takes high's + $itflow_set["{$itflow_prefix}_sla_urgent_id"] = $itflow_set["{$itflow_prefix}_sla_high_id"]; + } + if ($itflow_has_frequency) { + [$itflow_months, $itflow_auto] = $itflow_frequencies[strtolower(trim((string) $itflow_row["{$itflow_prefix}_renewal_frequency"]))] ?? [12, 1]; + $itflow_set["{$itflow_prefix}_term_months"] = $itflow_months; + $itflow_set["{$itflow_prefix}_auto_renew"] = $itflow_auto; + } + $itflow_type = strtolower(trim((string) $itflow_row["{$itflow_prefix}_type"])); + if ($itflow_type !== '') { + $itflow_set["{$itflow_prefix}_type"] = $itflow_types[$itflow_type] ?? (in_array($itflow_type, ['managed', 'comanaged', 'block', 'time_materials', 'break_fix', 'project', 'other'], true) ? $itflow_type : 'other'); + } + // Net terms as days - "Net 30" is 30, anything without a number none + $itflow_terms = preg_replace('/\D/', '', (string) $itflow_row["{$itflow_prefix}_net_terms"]); + $itflow_set["{$itflow_prefix}_net_terms"] = $itflow_terms !== '' ? min(intval($itflow_terms), 365) : null; + // A contract's status is one of four now - other words for them become theirs, anything else Active + if ($itflow_table === 'contracts') { + $itflow_status = strtolower(trim((string) $itflow_row['contract_status'])); + $itflow_set['contract_status'] = in_array($itflow_status, ['draft', 'pending', 'new', 'proposed', 'quote', 'quoted'], true) ? 'Draft' + : (in_array($itflow_status, ['ended', 'expired', 'inactive', 'closed', 'complete', 'completed', 'lapsed'], true) ? 'Ended' + : (in_array($itflow_status, ['cancelled', 'canceled', 'terminated', 'void'], true) ? 'Cancelled' : 'Active')); + } + $itflow_sql = []; + foreach ($itflow_set as $itflow_column_name => $itflow_value) { + $itflow_sql[] = "`$itflow_column_name` = " . ($itflow_value === null ? 'NULL' : (is_int($itflow_value) ? $itflow_value : "'" . mysqli_real_escape_string($mysqli, (string) $itflow_value) . "'")); + } + $itflow_id_column = $itflow_table === 'contract_templates' ? 'contract_template_id' : 'contract_id'; + mysqli_query($mysqli, "UPDATE `$itflow_table` SET " . implode(', ', $itflow_sql) . " WHERE `$itflow_id_column` = " . intval($itflow_row[$itflow_id_column])); + } + + // The hours and the frequency are now SLAs and a term - their columns go + foreach (['sla_low_response_time', 'sla_low_resolution_time', 'sla_medium_response_time', 'sla_medium_resolution_time', 'sla_high_response_time', 'sla_high_resolution_time', 'renewal_frequency'] as $itflow_old) { + if ($itflow_column($itflow_table, "{$itflow_prefix}_$itflow_old")) { + mysqli_query($mysqli, "ALTER TABLE `$itflow_table` DROP COLUMN `{$itflow_prefix}_$itflow_old`"); + } + } + // Net terms are days now + mysqli_query($mysqli, "ALTER TABLE `$itflow_table` MODIFY `{$itflow_prefix}_net_terms` int(11) DEFAULT NULL"); + } + + // Deleting a client deletes its contracts - the foreign key used to stop the client being deleted at all + $itflow_keys = mysqli_query($mysqli, "SELECT CONSTRAINT_NAME FROM information_schema.REFERENTIAL_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA = DATABASE() AND TABLE_NAME = 'contracts' AND REFERENCED_TABLE_NAME = 'clients' AND DELETE_RULE <> 'CASCADE'"); + while ($itflow_key = mysqli_fetch_row($itflow_keys)) { + mysqli_query($mysqli, "ALTER TABLE `contracts` DROP FOREIGN KEY `" . $itflow_key[0] . "`"); + mysqli_query($mysqli, "ALTER TABLE `contracts` ADD CONSTRAINT `" . $itflow_key[0] . "` FOREIGN KEY (`contract_client_id`) REFERENCES `clients` (`client_id`) ON DELETE CASCADE"); + } + + unset($itflow_column, $itflow_table, $itflow_prefix, $itflow_adds, $itflow_name, $itflow_definition, $itflow_sla_for, $itflow_types, $itflow_frequencies, $itflow_has_hours, + $itflow_has_frequency, $itflow_name_column, $itflow_rows, $itflow_row, $itflow_set, $itflow_level, $itflow_label, $itflow_months, $itflow_auto, $itflow_type, $itflow_terms, + $itflow_status, $itflow_sql, $itflow_column_name, $itflow_value, $itflow_id_column, $itflow_old, $itflow_keys, $itflow_key); diff --git a/admin/modals/contract_template/contract_template_add.php b/admin/modals/contract_template/contract_template_add.php index ea92ae9f1..f442af3fa 100644 --- a/admin/modals/contract_template/contract_template_add.php +++ b/admin/modals/contract_template/contract_template_add.php @@ -1,9 +1,12 @@ @@ -12,184 +15,16 @@ ob_start(); - - - -
- -
diff --git a/admin/modals/contract_template/contract_template_edit.php b/admin/modals/contract_template/contract_template_edit.php index 943508eb9..1a86675ea 100644 --- a/admin/modals/contract_template/contract_template_edit.php +++ b/admin/modals/contract_template/contract_template_edit.php @@ -1,242 +1,39 @@ + +if (!$template) { ?> + + - - - -
- - + -
- diff --git a/admin/modals/contract_template/contract_template_form.php b/admin/modals/contract_template/contract_template_form.php new file mode 100644 index 000000000..33d72fdb1 --- /dev/null +++ b/admin/modals/contract_template/contract_template_form.php @@ -0,0 +1,142 @@ + + + + +
+
+
+
+ +
+ + > +
+
+
+ +
+ + +
+
+
+
+ +
+ + +
+
+
+
+ +
+ + +
+
+
+ +
+ + + days +
+
+
+
+ > + +
+
+
+
+ +
+
+ +
+ + +
+
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ +
+ + + days +
+
+
+ Leave a rate or the net terms empty and the client's own apply. + + $part) { ?> +
+ + +
+ + From Admin > SLAs. +
+ +
+ +
+
diff --git a/admin/post/contract_template.php b/admin/post/contract_template.php index 4c632b2c0..80bb89b6b 100644 --- a/admin/post/contract_template.php +++ b/admin/post/contract_template.php @@ -1,170 +1,113 @@ $name created"); - - // Redirect back - redirect(); +/* The template asked for - or a flash and back. */ +function contractTemplatePostRow($id) { + $row = contractTemplateRow($id); + if (!$row) { + flashAlert("That contract template is gone - it may have been deleted.", 'error'); + redirect(); + } + return $row; } -if (isset($_POST['edit_contract_template'])) { +if (isset($_POST['add_contract_template']) || isset($_POST['edit_contract_template'])) { validateCSRFToken(); - $contract_template_id = intval($_POST['contract_template_id']); - $name = escapeSql($_POST['name']); - $description = escapeSql($_POST['description']); - $type = escapeSql($_POST['type']); - $renewal_frequency= escapeSql($_POST['renewal_frequency']); - $support_hours = escapeSql($_POST['support_hours']); - $details = mysqli_escape_string($mysqli, $_POST['details']); - $sla_low_resp = intval($_POST['sla_low_response_time']); - $sla_med_resp = intval($_POST['sla_medium_response_time']); - $sla_high_resp = intval($_POST['sla_high_response_time']); - $sla_low_res = intval($_POST['sla_low_resolution_time']); - $sla_med_res = intval($_POST['sla_medium_resolution_time']); - $sla_high_res = intval($_POST['sla_high_resolution_time']); - $rate_standard = intval($_POST['rate_standard']); - $rate_after_hours = intval($_POST['rate_after_hours']); - $net_terms = intval($_POST['net_terms']); + $row = isset($_POST['edit_contract_template']) ? contractTemplatePostRow($_POST['contract_template_id'] ?? 0) : null; + [$fields, $error] = contractFromInput($_POST, 'template'); + if ($error !== '') { + flashAlert(escapeHtml($error) . ' The template was not saved.', 'error'); + redirect(); + } - mysqli_query($mysqli, " - UPDATE contract_templates SET - contract_template_name = '$name', - contract_template_description = '$description', - contract_template_details = '$details', - contract_template_type = '$type', - contract_template_renewal_frequency = '$renewal_frequency', - contract_template_sla_low_response_time = $sla_low_resp, - contract_template_sla_medium_response_time = $sla_med_resp, - contract_template_sla_high_response_time = $sla_high_resp, - contract_template_sla_low_resolution_time = $sla_low_res, - contract_template_sla_medium_resolution_time = $sla_med_res, - contract_template_sla_high_resolution_time = $sla_high_res, - contract_template_rate_standard = $rate_standard, - contract_template_rate_after_hours = $rate_after_hours, - contract_template_support_hours = '$support_hours', - contract_template_net_terms = $net_terms - WHERE contract_template_id = $contract_template_id - "); + $set = contractTermsSetSql($fields, 'contract_template') . ", contract_template_description = " . ($fields['description'] !== '' ? "'" . escapeSql($fields['description']) . "'" : 'NULL'); + $name = escapeSql($fields['name']); + if ($row) { + $contract_template_id = intval($row['contract_template_id']); + mysqli_query($mysqli, "UPDATE contract_templates SET $set WHERE contract_template_id = $contract_template_id"); + logAudit("Contract Template", "Edit", "$session_name changed contract template $name", 0, $contract_template_id); + flashAlert("Contract template " . escapeHtml($fields['name']) . " saved"); + } else { + mysqli_query($mysqli, "INSERT INTO contract_templates SET $set"); + $contract_template_id = mysqli_insert_id($mysqli); + logAudit("Contract Template", "Create", "$session_name created contract template $name (" . escapeSql(contractTypeLabel($fields['type'])) . ")", 0, $contract_template_id); + flashAlert("Contract template " . escapeHtml($fields['name']) . " created"); + } - // Log action - logAudit("Contract Template", "Edit", "$session_name updated contract template $name", 0, $contract_template_id); - - // Flash + redirect - flashAlert("Contract Template $name updated"); redirect(); + } -if (isset($_GET['archive_contract_template'])) { +if (isset($_GET['copy_contract_template'])) { validateCSRFToken(); - $contract_template_id = intval($_GET['archive_contract_template']); + $row = contractTemplatePostRow($_GET['copy_contract_template']); + $contract_template_id = intval($row['contract_template_id']); - $name = escapeSql(getFieldById('contract_templates', $contract_template_id, 'contract_template_name')); + // "Name (copy)", then "Name (copy 2)" and on - a name not already taken + $base = mb_substr($row['contract_template_name'], 0, 240); + $new_name = "$base (copy)"; + for ($n = 2; mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM contract_templates WHERE contract_template_name = '" . escapeSql($new_name) . "'")); $n++) { + $new_name = "$base (copy $n)"; + } - mysqli_query($mysqli, " - UPDATE contract_templates SET contract_template_archived_at = NOW() - WHERE contract_template_id = $contract_template_id - LIMIT 1 - "); + $columns = ['description', 'type', 'rate_standard', 'rate_after_hours', 'net_terms', 'support_hours', 'details', + 'term_months', 'auto_renew', 'notice_days', 'sla_low_id', 'sla_medium_id', 'sla_high_id', 'sla_urgent_id']; + $columns = implode(', ', array_map(function ($column) { return "contract_template_$column"; }, $columns)); + mysqli_query($mysqli, "INSERT INTO contract_templates (contract_template_name, $columns) + SELECT '" . escapeSql($new_name) . "', $columns FROM contract_templates WHERE contract_template_id = $contract_template_id"); + $new_id = mysqli_insert_id($mysqli); + + logAudit("Contract Template", "Create", "$session_name copied contract template " . escapeSql($row['contract_template_name']) . " as " . escapeSql($new_name), 0, $new_id); + flashAlert("Contract template " . escapeHtml($row['contract_template_name']) . " copied as " . escapeHtml($new_name) . ""); - logAudit("Contract Template", "Archive", "$session_name archived contract template $name", 0, $contract_template_id); - flashAlert("Contract Template $name archived", "danger"); redirect(); + } -if (isset($_GET['restore_contract_template'])) { +if (isset($_GET['archive_contract_template']) || isset($_GET['restore_contract_template'])) { validateCSRFToken(); - $contract_template_id = intval($_GET['restore_contract_template']); + $archive = isset($_GET['archive_contract_template']); + $row = contractTemplatePostRow($archive ? $_GET['archive_contract_template'] : $_GET['restore_contract_template']); + $contract_template_id = intval($row['contract_template_id']); - $name = escapeSql(getFieldById('contract_templates', $contract_template_id, 'contract_template_name')); + // Archived, it isn't offered on a new contract; contracts started from it are unchanged + mysqli_query($mysqli, "UPDATE contract_templates SET contract_template_archived_at = " . ($archive ? 'NOW()' : 'NULL') . " WHERE contract_template_id = $contract_template_id"); - mysqli_query($mysqli, " - UPDATE contract_templates SET contract_template_archived_at = NULL - WHERE contract_template_id = $contract_template_id - LIMIT 1 - "); + logAudit("Contract Template", $archive ? "Archive" : "Restore", "$session_name " . ($archive ? 'archived' : 'restored') . " contract template " . escapeSql($row['contract_template_name']), 0, $contract_template_id); + flashAlert("Contract template " . escapeHtml($row['contract_template_name']) . " " . ($archive ? 'archived' : 'restored'), $archive ? 'error' : 'success'); - logAudit("Contract Template", "Restore", "$session_name restored contract template $name", 0, $contract_template_id); - flashAlert("Contract Template $name restored"); redirect(); + } if (isset($_GET['delete_contract_template'])) { validateCSRFToken(); - - $contract_template_id = intval($_GET['delete_contract_template']); - $name = escapeSql(getFieldById('contract_templates', $contract_template_id, 'contract_template_name')); + $row = contractTemplatePostRow($_GET['delete_contract_template']); + $contract_template_id = intval($row['contract_template_id']); - mysqli_query($mysqli, " - DELETE FROM contract_templates - WHERE contract_template_id = $contract_template_id - LIMIT 1 - "); + // Contracts started from it keep their terms - only the link back goes + mysqli_query($mysqli, "UPDATE contracts SET contract_template_id = 0 WHERE contract_template_id = $contract_template_id"); + mysqli_query($mysqli, "DELETE FROM contract_templates WHERE contract_template_id = $contract_template_id"); + + logAudit("Contract Template", "Delete", "$session_name deleted contract template " . escapeSql($row['contract_template_name']), 0, $contract_template_id); + flashAlert("Contract template " . escapeHtml($row['contract_template_name']) . " deleted", 'error'); - logAudit("Contract Template", "Delete", "$session_name deleted contract template $name", 0, $contract_template_id); - flashAlert("Contract Template $name deleted", "danger"); redirect(); -} -?> +} diff --git a/agent/client_overview.php b/agent/client_overview.php index f2a2b2c04..a47c4ea67 100644 --- a/agent/client_overview.php +++ b/agent/client_overview.php @@ -521,6 +521,21 @@ $money_format = function ($amount) use ($currency_format, $client_currency_code, + + + Contract + + + 1 ? ' · ' . (count($overview_contracts) - 1) . ' more' : '' ?> + + None + No contract in force + + +
Terms /hr diff --git a/agent/contract.php b/agent/contract.php new file mode 100644 index 000000000..405ebf472 --- /dev/null +++ b/agent/contract.php @@ -0,0 +1,263 @@ +

Nothing to see here

Go Back"; + +} else { + + $client_id = intval($contract['contract_client_id']); + enforceClientAccess(); + + $can_edit = lookupUserPermission('module_sales') >= 2; + $can_delete = lookupUserPermission('module_sales') >= 3; + $name = escapeHtml($contract['contract_name']); + $page_title = $contract['contract_name']; + + $state = contractState($contract); + $type = CONTRACT_TYPES[$contract['contract_type']] ?? CONTRACT_TYPES['other']; + $notice = contractNoticeDate($contract); + $today = date('Y-m-d'); + $status = (string) $contract['contract_status']; + $slas = contractSlaChoices(array_map(function ($part) use ($contract) { + return intval($contract["contract_sla_{$part}_id"]); + }, CONTRACT_SLA_PRIORITIES)); + $history = auditLogHistory('Contract', $contract_id); + $currency = $session_company_currency ?? ''; + $money = function ($amount) use ($currency) { + return escapeHtml(function_exists('billingMoney') ? billingMoney($amount, $currency) : number_format((float) $amount, 2)); + }; + + // How far through its term it is + $progress = null; + if ($contract['contract_start_date'] && $contract['contract_end_date'] && in_array($state['key'], ['active', 'renewing', 'ending'], true)) { + // The current term began a term's length before it ends - or when the contract started, while it is in its first + // term (a first term a few days longer or shorter than the rest is still the first) + $months = intval($contract['contract_term_months']); + $started = strtotime($contract['contract_start_date']); + $term_start = strtotime("-$months months +1 day", strtotime($contract['contract_end_date'])); + if ($term_start < strtotime("+$months months", $started)) { + $term_start = $started; + } + $term_end = strtotime($contract['contract_end_date']); + $progress = [ + 'percent' => $term_end > $term_start ? max(0, min(100, round((time() - $term_start) / ($term_end - $term_start) * 100))) : 100, + 'days_left' => max(0, intval(floor(($term_end - strtotime($today)) / 86400))), + 'from' => date('M j, Y', $term_start), + ]; + } + + ?> + + + +
+
+ +
+

+ + +

+
+ + + From +
+
+ +
+ + + + + + + +
+ +
+ + + +
+ + +
+ +
+ + It renews itself on for another . + = $today ? 'Notice to stop it is due by ' . escapeHtml(date('M j, Y', strtotime($notice))) . ' - a good time to review it with the client.' : 'The notice date has passed.' ?> + + It ends on and doesn't renew itself. + = $today ? 'Notice is due by ' . escapeHtml(date('M j, Y', strtotime($notice))) . '.' : '' ?> Renew it to keep it going. + +
+ + + +
+ + +
+
+ +
+

Term

+
+
+
Starts
Not set' ?>
+
Ends
No end date' ?>
+
Term
+
Renews
+
Notice
+
+ +
By
+
+
Renewed
+ +
Cancelled
+
+ +
+
+
+ +
+

People

+
+
+
Client
+
Contact
' . escapeHtml($contract['contact_name']) . '' : 'None' ?>
+
Owner
No one - everyone is reminded' ?>
+
Added
+
+
+
+ + $client_id]) ?> +
+ +
+ +
+

What it covers

+
+
+
+
Support hours
+
Not set' ?>
+
+
+
Rates
+
' . $money($contract['client_rate']) . '/hr (client\'s)' ?>
+
+
+
+
Net terms
+
(client\'s)' : ''; + ?>
+
+
+
SLA by priority
+
+ + + $part) { + $sla = $slas[intval($contract["contract_sla_{$part}_id"])] ?? null; ?> + + + + + + +
+ + Archived' : '' ?> +
+ + The client's usual SLA + +
+
+
+
+ +
+

Terms

+
+ +
+ +
No terms written down. Add them
+ +
+
+ + +
+

Notes

+
+
+ +
+
+ += 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 contract_client_id = $client"; +} + +$type_filter = isset(CONTRACT_TYPES[$_GET['type'] ?? '']) ? $_GET['type'] : ''; +$type_query = $type_filter !== '' ? "AND contract_type = '" . escapeSql($type_filter) . "'" : ''; + +$views = contractViews(); +$view = isset($views[$_GET['show'] ?? '']) ? $_GET['show'] : 'active'; + +$sortable_columns = [ + 'contract_name' => "contract_name $order", + 'client_name' => "client_name $order, contract_name ASC", + 'contract_type' => "contract_type $order, contract_name ASC", + 'contract_start_date' => "contract_start_date IS NULL, contract_start_date $order", + 'contract_end_date' => "contract_end_date IS NULL, contract_end_date $order", + 'owner_name' => "user_name IS NULL, user_name $order", +]; +if (!isset($sortable_columns[$sort])) { + $sort = 'contract_end_date'; +} + +$scope_query = clientScopeSql('contract_client_id'); +$search_query = "AND (contract_name LIKE '%$q%' OR client_name LIKE '%$q%' OR contract_support_hours LIKE '%$q%' OR contract_notes LIKE '%$q%')"; +$joins = "LEFT JOIN clients ON contract_client_id = client_id LEFT JOIN users ON contract_owner_id = user_id"; +$filters = "AND contract_archived_at IS NULL $scope_query $client_query $type_query $search_query"; + +$contracts = []; +$num_rows = [0]; +$counts = array_fill_keys(array_keys($views), 0); +$stats = ['active' => 0, 'ending' => 0, 'renewing' => 0, 'draft' => 0]; +if (contractsReady()) { + $sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS contracts.*, client_name, user_name AS owner_name + FROM contracts $joins + WHERE {$views[$view]['where']} $filters + ORDER BY {$sortable_columns[$sort]}, contract_id ASC LIMIT $record_from, $record_to"); + $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); + while ($row = mysqli_fetch_assoc($sql)) { + $contracts[] = $row; + } + + $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT " . implode(', ', array_map(function ($v) { + return "COALESCE(SUM({$v['where']}), 0)"; + }, $views)) . " FROM contracts $joins WHERE 1 $filters")); + $counts = array_combine(array_keys($views), array_map('intval', $row)); + + // The figures along the top - everything in this scope, whatever the search + $soon = $views['soon']['where']; + $stats = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT + COALESCE(SUM(contract_status = 'Active'), 0) AS active, + COALESCE(SUM($soon AND contract_auto_renew = 0), 0) AS ending, + COALESCE(SUM($soon AND contract_auto_renew = 1), 0) AS renewing, + COALESCE(SUM(contract_status = 'Draft'), 0) AS draft + FROM contracts WHERE contract_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; })); +}; +$sort_link = function ($column, $label) use ($url_query_strings_sort, $sort, $disp, $order_icon) { + return '' + . $label . ($sort === $column ? " $order_icon" : '') . ''; +}; +$add_url = 'modals/contract/contract_add.php' . ($client_url ? "?client_id=$client_id" : ''); +$csrf = $_SESSION['csrf_token']; + +?> + +
+ + + + +
+ +
+
+

Contracts

+
+ + + +
+
+ +
+
+ + + + +
+
+
+ + +
+
+
+ +
+ +
+ +
+ +
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ +
+
+
+
+ + + + Not started + +
+
+ +
+ = date('Y-m-d')) { ?> +
Notice by
+ +
No one' ?> + +
+
+ 'contracts', + 'icon' => 'fa-file-contract', + 'filtered' => (bool) $q || $type_filter !== '', + 'views' => ['show'], + 'view' => emptyStatePill($views, $view, 'active', ['soon']), + 'text' => 'The agreement with each client - what it covers, its SLAs and rates, and when it renews.', + 'actions' => $can_edit ? [['label' => 'New Contract', 'modal' => $add_url, 'size' => 'lg']] : [], + ]; + require_once "../includes/filter_footer.php"; + ?> +
+ + 'quotes.php', 'rack.php' => 'racks.php', 'recurring_invoice.php' => 'recurring_invoices.php', + 'contract.php' => 'contracts.php', 'ticket.php' => 'tickets.php', ]; $client_switch_page = basename($_SERVER['PHP_SELF']); @@ -378,6 +379,18 @@ + + = 1) { ?> diff --git a/agent/includes/get_side_nav_counts.php b/agent/includes/get_side_nav_counts.php index 48fcce802..dcca52f5c 100644 --- a/agent/includes/get_side_nav_counts.php +++ b/agent/includes/get_side_nav_counts.php @@ -25,6 +25,10 @@ $num_open_invoices = $row['num']; $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('recurring_invoice_id') AS num FROM recurring_invoices WHERE recurring_invoice_archived_at IS NULL " . clientScopeSql('recurring_invoice_client_id') . "")); $num_recurring_invoices = $row['num']; +// Contracts ending or renewing soon - within a month of their notice date +$num_contracts_soon = lookupUserPermission('module_sales') >= 1 && contractsReady() + ? intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contracts WHERE contract_archived_at IS NULL AND " . contractViews()['soon']['where'] . clientScopeSql('contract_client_id')))[0]) : 0; + // Unbilled tickets - billable, done and on no invoice (Billing > Unbilled Time) $num_unbilled_tickets = $config_module_enable_accounting == 1 && $config_module_enable_ticketing == 1 && lookupUserPermission('module_sales') >= 1 ? billingUnbilledCount() : 0; diff --git a/agent/includes/inc_all_client.php b/agent/includes/inc_all_client.php index 43844d2b4..4ace1ecbf 100644 --- a/agent/includes/inc_all_client.php +++ b/agent/includes/inc_all_client.php @@ -165,6 +165,9 @@ if (isset($_GET['client_id'])) { $recurring_monthly = floatval($row['recurring_monthly']); $num_recurring_invoices = intval($row['num_recurring_invoices']); + // Contracts in force + $num_contracts = contractClientCount($client_id); + // Billable tickets done and not invoiced yet, for Unbilled Time $num_unbilled_tickets = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM tickets WHERE " . billingUnbilledSql() . " AND ticket_client_id = $client_id"))[0]); // ...and their expenses to bill on, for those who can see expenses diff --git a/agent/includes/side_nav.php b/agent/includes/side_nav.php index 2fad4c047..f6167f435 100644 --- a/agent/includes/side_nav.php +++ b/agent/includes/side_nav.php @@ -182,6 +182,17 @@

+