From 8e24607a0a0ea8c0037f8d8cfcfbc1126ab4d7dc Mon Sep 17 00:00:00 2001 From: johnnyq Date: Wed, 28 Oct 2026 23:51:45 -0400 Subject: [PATCH] Contracts: refuse impossible dates (2026-02-30) when adding, editing, activating, renewing, cancelling or starting from a template instead of failing on save; keep each term to the day of the month it started on or the last day of a shorter month so month-end contracts no longer drift (PHP, nightly renewal, the Renew window, templates, Standard terms and contract_form.js); withdraw signing requests still waiting on the client or a countersignature when a contract is cancelled, when it ends nightly or when its client is archived (singly or in bulk), and refuse signing or countersigning on ended, cancelled or archived-client contracts through the link, the portal and Countersign; leave archived clients' contracts alone nightly (no renewing, ending or reminders), keep them out of the all-clients list, Due soon and the side menu count, and refuse sending them to sign; count a self-renewing contract as due soon and remind about it only when its notice date falls within its term, so Standard terms and monthly contracts with 30 days' notice no longer remind every term; keep drawing and adding prepaid hours on a cancelled contract until its last day; refuse deleting a contract once tickets drew on its prepaid hours or it was signed by both, showing why in place of Delete; changelog updated --- CHANGELOG.md | 20 +- agent/contract.php | 29 ++- agent/contracts.php | 29 ++- agent/includes/get_side_nav_counts.php | 2 +- agent/modals/contract/contract_hours_add.php | 4 +- agent/modals/contract/contract_renew.php | 3 +- agent/post/client.php | 10 +- agent/post/contract.php | 27 ++- client/functions.php | 4 +- functions/contract.php | 218 ++++++++++++++++--- functions/contract_hours.php | 26 ++- functions/contract_signature.php | 61 +++++- js/contract_form.js | 6 +- 13 files changed, 349 insertions(+), 90 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6eac8d99..414460684 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,7 +35,7 @@ Payment methods are all offered for money in and out, as before, until you say o 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. +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 with something to do - ending, or renewing with notice to give during the term - and the owner is emailed once a contract has one. An archived client's contracts are left as they are. Look over Contracts once after the update if end dates weren't kept up to date. No contract is out for signature after the update - signing starts when you send one (see New Features, Contracts). A signature already stored on a contract, put there by hand or by a script, is kept as a copy recorded before signing came to ITFlow, under the contract's Signing. @@ -1173,11 +1173,12 @@ If you are coming from 26.08 or earlier, the database update still has to be run - 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. A client has no rates, terms or SLAs of its own - its contract's are what it is billed on. Leave a rate, the net terms or an SLA empty and the default applies, from Admin > Settings > Defaults and Admin > SLAs. - - 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, Signing (out for signature, or waiting for you to countersign), 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, when notice is due and where its signing stands. 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 - a draft sent to sign becomes active once both sides have signed, or make it active yourself. Copy starts a new contract from an existing one. + - 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, Signing (out for signature, or waiting for you to countersign), 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, when notice is due and where its signing stands. Due soon is within a month of the notice date, when there is something to do: a contract ending, or one renewing itself with notice to give during its term - not one with no notice, like Standard terms, or with notice as long as its term. The menu shows how many are due soon. Across every client, an archived client's contracts are left out - they are on its own page. + - 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. A term from the 31st ends the day before the 31st, or before the last day of a shorter month - a monthly contract from Jan 31 runs to Feb 27, then Mar 30. Save it as active, or as a draft - a draft sent to sign becomes active once both sides have signed, or make it active yourself. 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. + - 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; a request to sign it still out, or waiting on your countersignature, is withdrawn. Make active takes the day a draft starts and sets its end a term later. A date that isn't a real day, like Feb 30, is refused. + - Delete is for a contract made by mistake. One that tickets' time was drawn from, or that was signed by both, stays - cancel it instead, or put its tickets back first - and its menu says why in place of Delete. + - Every night, a contract that renews itself is renewed for another term once it ends, each term starting on the day of the month it started (or the last day of a shorter month) unless its end date was set to another day, and one that doesn't is marked ended. A month before its notice date, when there is something to do - it ends, or it renews itself and notice is given during its term - 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. Nothing is sent for a contract with no notice to give, like Standard terms, or notice as long as its term, like a monthly one with 30 days' notice. An archived client's contracts are left as they are - not renewed, ended or reminded of - until the client is restored. - 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). - Each contract is also a document - who it is between, the agreement in a few lines (type, term, renewal, notice, support hours, rates and when invoices are due), the response times for each priority, its terms and a place for both sides to sign. Preview it, print it or download it as a PDF. @@ -1186,7 +1187,8 @@ If you are coming from 26.08 or earlier, the database update still has to be run - When they have signed, whoever looks after the contract is emailed and agents are told in ITFlow. Countersign signs it for your side, and then the client is emailed the PDF signed by both. A draft becomes active from its start date, or from that day when it has none. - The contract's Signing card says where it stands - sent, opened, signed or countersigned - with when and from where. It has the link to copy, Send the link again, Withdraw, the copy sent or signed to view or download, and the requests before it. The signed PDF ends with how it was signed: when it was sent and opened, who signed it, when and from which IP address, and the document's fingerprint. - Changing a contract while it is out for signature withdraws the request when what it says has changed, so no one signs an old version. Send it again for the new one. A signed contract that no longer matches the copy signed says so. - - Prepaid hours. A contract can include hours each month - set under Cover in the contract and template windows - and the hours a client buys are added on its page with Add hours: how many, the price, the day they were bought and the day they run out, and a note, with a draft invoice for them if you like. Hours included each month are for that month only. + - Nothing is signed on a contract that was cancelled or has ended, or whose client was archived. Its request still out, or waiting on your countersignature, is withdrawn - when it is cancelled, when the client is archived (one or several at once), and by the nightly job when it ends - and the link, the portal and Countersign refuse it. It isn't sent to sign while the client is archived. + - Prepaid hours. A contract can include hours each month - set under Cover in the contract and template windows - and the hours a client buys are added on its page with Add hours: how many, the price, the day they were bought and the day they run out, and a note, with a draft invoice for them if you like. Hours included each month are for that month only. Time is drawn from them while the contract is active, and once it is cancelled, until its last day - hours can be added until then too. - Every night the time on the client's billable tickets done since is drawn from those hours, ticket by ticket, rounded the way Billing Time in Admin > Settings > Invoice says: the oldest ticket first, from the hours that run out first, and only from hours that cover the day the ticket was done. A ticket they cover leaves Unbilled Time. One they run out on part way stays there with the rest, billed at the usual rate. Draw now does it straight away, from the contract or the client's Unbilled Time. Each ticket's history says what it drew, and a ticket worked on again after it was covered goes back to Unbilled Time for the extra time. - The contract's Prepaid hours card shows what is left and of how much, what runs out when, each block of hours with its days, what was used of it and its invoice, and the tickets drawn from them. Put back returns a ticket's hours and bills it as usual, and the nightly draw leaves it alone until Draw it on the ticket. Hours nothing was drawn from can be deleted. Once a ticket is invoiced, its hours stay drawn. - Set Tell the owner under, and when the hours left fall below it, whoever looks after the contract is emailed and agents are told in ITFlow - once, until more hours are added. Agents are also told when the hours run out part way through a ticket. @@ -2123,6 +2125,12 @@ If you are coming from 26.08 or earlier, the database update still has to be run - New `functions/ticket_mention.php`, loaded by `functions.php`: `ticketMentionsReady()` (3.5.3 has run - until then a mention is left as posted and nobody is told), `ticketMentionAgents($client_id)` (active agents with Support at Read or an admin role, let at the client by `user_client_permissions`), `ticketMentionOffer()` and `ticketMentionAgentsAttr()` (the picker's list, without you, as `data-mention-agents` JSON), `ticketMentionSpan()`, `ticketMentionsFromHtml($html, $client_id, $internal)` ([html, user ids] - each mention rewritten with the agent's current name, or unwrapped to its text when they can't open the ticket or the reply isn't internal), `ticketMentionsSync($reply_id, $user_ids)` (returns the ones added), `ticketMentionsForTicket()`, `ticketMentionedSql($user_id)`, `ticketMentionUrl()` (`#reply-{id}`), `ticketMentionsTell()` (a `Ticket` notification and `ticketMailMentioned()`, not to the author; returns user_id => name) and `ticketMentionNames()`. - `add_ticket_reply`, `edit_ticket_reply` and `redact_ticket_reply` run the reply through `ticketMentionsFromHtml()` before saving and `ticketMentionsSync()` after; add and edit tell the agents added and write ticket history, and redact tells nobody. `bulk_ticket_reply` leaves mentions as text. `add_ticket_reply` no longer sends the "updated Ticket" notification to an assignee or creator the note mentions. - `ticketAgentEmailContent()` has the kind `mentioned` (`by`, `message`, `reply_id`), and `emailPreviewCatalog()` adds `agent_mentioned`. `agent/ticket.php` gives each reply card `id="reply-{id}"` and `data-reply-mentions-me`, `agent/tickets.php` adds the `show=mentioned` view, and `js/app.js` adds `itflowMentionAutocompleter()` to the `.tinymce` and `.tinymceTicket` editors, with the `[data-mention-hint]` and `[data-mention-public]` lines beside them. +- Contracts, dates and what stops once one is over: + - `functions/contract.php`: new `contractDateValid($date)` (a real day written Y-m-d), used by `contractFromInput()`, `contractFromTemplateAdd()`, `contractStandardTermsAdd()` and the `activate_contract`, `renew_contract` and `cancel_contract` handlers, where 2026-02-30 passed `strtotime()` and failed on saving. New `contractAddMonths($date, $months, $day = 0)` and `contractAnchorDay($row)` (its start's day, while its term ends on the day before it - 0 when its end date was set to another day); `contractTermEnd($start, $months, $day = 0)` and `contractNextEnd($end, $months, $day = 0)` keep to day `$day` of the month (the start's own by default), or the last day of a shorter month, in place of PHP's `+N months` overflow. `contractsNightly()`, `contract_renew.php`, `contractFromTemplateAdd()` and `contractStandardTermsAdd()` pass the contract's start day, and `termEnd()` in `js/contract_form.js` works it out the same. + - New `contractDueSoonSql($today = null)`: active, within `CONTRACT_REMINDER_DAYS` of its notice date, and ending (`contract_auto_renew` 0) or renewing with `contract_notice_days` > 0 and its notice date after the day its term started. `contractViews()`'s `soon` (the Due soon tab, the side menu count and the client overview's tiles) and `contractsNightly()`'s reminder use it, and `contractState()` gives `renewing` on the same rule, through the new `contractNoticeInTerm($row)`. New `contractClientLiveSql($column = 'contract_client_id')` (the client isn't archived), used by `contractsNightly()`'s renewals, endings and reminders, `agent/contracts.php` across every client (rows, tabs and figures) and `get_side_nav_counts.php`. + - `functions/contract_signature.php`: new `contractSignatureWithdrawStale($client_id = 0, $contract_id = 0)` withdraws the rounds waiting on the client or a countersignature on contracts Ended or Cancelled, or of archived clients - `contract_signature_withdrawn_reason` The contract was cancelled, The contract ended or The client was archived - and returns how many. `cancel_contract` (audit Withdraw, and the flash), `archive_client`, `bulk_archive_clients` and `contractsNightly()` (`withdrawn` in what it returns) run it. New `contractSignatureOpenSql()`: `contractSignatureClientSign()` and `contractSignatureAgentSign()` sign only while the contract is a draft or active and its client isn't archived. `contractSignatureSelectSql()` adds `client_archived_at`, and `contractSignatureState()` gives `withdrawn` for a round still waiting on such a contract. `portalContractSentSql(false)` (To sign) keeps to drafts and active contracts, and `send_contract_signature` refuses an archived client. + - `functions/contract_hours.php`: new `contractHoursLive($row, $today = null)` and `contractHoursLiveSql($today = null)` - active, or cancelled with its end date not passed - used by `contractClientHours()`, `contractHoursEnsureMonthly()`, `contractHoursNightly()`, `add_contract_hours`, `contract_hours_add.php` and the contract page's Prepaid hours card (`data-contract-hours-until` while a cancelled one is drawn from). + - New `contractDeleteBlocker($row)`, `contractDeleteBlockers($rows)` (id => why, for rows with `contract_id` and `contract_status`) and `contractDeleteWarning($row)`. `delete_contract` refuses a contract with prepaid hours drawn (`contract_block_use_hours` > 0) or a round signed by both, and `contract.php` and `contracts.php` show why (`data-delete-blocked`) in place of Delete. ### Library Updates diff --git a/agent/contract.php b/agent/contract.php index dba682ff7..a00f65e9b 100644 --- a/agent/contract.php +++ b/agent/contract.php @@ -69,9 +69,11 @@ if (!$contract || ($client_url && intval($contract['contract_client_id']) !== in $hours = contractHoursSummary($blocks); $show_hours = $hours_on && contractHasHours($contract, $blocks); $hours_uses = $show_hours ? contractHoursUses($contract_id, 20) : []; - $can_hours = $hours_on && $can_edit && !in_array($status, ['Ended', 'Cancelled'], true); + // Drawn from while active, and once cancelled, until its last day + $hours_live = $hours_on && contractHoursLive($contract, $today); + $can_hours = $hours_on && $can_edit && ($status === 'Draft' || $hours_live); $hours_alert = $hours_on ? floatval($contract['contract_hours_alert']) : 0; - $hours_low = $show_hours && $status === 'Active' && $hours['bought'] > 0 && ($hours['left'] <= 0 || ($hours_alert > 0 && $hours['left'] < $hours_alert)); + $hours_low = $show_hours && $hours_live && $hours['bought'] > 0 && ($hours['left'] <= 0 || ($hours_alert > 0 && $hours['left'] < $hours_alert)); // In force today - its SLAs, rates and net terms are the client's - and the recurring invoice that bills it $in_force = contractInForceOn($contract, $today); $billing_on = contractBillingReady() && intval($config_module_enable_accounting) === 1; @@ -154,12 +156,17 @@ if (!$contract || ($client_url && intval($contract['contract_client_id']) !== in Cancel - + - - Delete - + + + + + Delete + + @@ -437,7 +444,7 @@ if (!$contract || ($client_url && intval($contract['contract_client_id']) !== in

Prepaid hours

- 0) { ?> + 0) { ?>
@@ -456,7 +463,7 @@ if (!$contract || ($client_url && intval($contract['contract_client_id']) !== in 0) { ?> Of · used - No hours to draw from 0 && $status !== 'Active' ? ' until it is active' : '' ?> + No hours to draw from 0 && $status === 'Draft' ? ' until it is active' : '' ?>
@@ -480,8 +487,10 @@ if (!$contract || ($client_url && intval($contract['contract_client_id']) !== in - +
Time is drawn from them only while the contract is active.
+ +
Cancelled - time is drawn from them until its last day, .
0 ? 'Running low.' : 'All used.' ?> Time beyond them goes to Unbilled Time to bill as usual.
diff --git a/agent/contracts.php b/agent/contracts.php index 94ed74046..dd0cb985c 100644 --- a/agent/contracts.php +++ b/agent/contracts.php @@ -7,7 +7,8 @@ * Tabs: Active (the default), Due soon (within a month of their notice * date), Signing (out for signature, or to countersign), Drafts, Ended * (ended or cancelled) and All. Each row says where its signing stands, - * and how many prepaid hours are left on it. + * and how many prepaid hours are left on it. Across every client, archived + * clients' contracts are left out - they are on the client's own page. * The work is in functions/contract.php; the handlers are * agent/post/contract.php. */ @@ -23,7 +24,8 @@ if (isset($_GET['client_id'])) { $client_url = "client_id=$client_id&"; } else { require_once "includes/inc_all.php"; - $client_query = ''; + // An archived client's contracts are on their own page, not here + $client_query = "AND " . contractClientLiveSql(); $client_url = ''; } @@ -35,7 +37,7 @@ $can_delete = lookupUserPermission('module_sales') >= 3; $client = ''; if (!$client_url && !empty($_GET['client'])) { $client = intval($_GET['client']); - $client_query = "AND contract_client_id = $client"; + $client_query = "AND contract_client_id = $client AND " . contractClientLiveSql(); } $type_filter = isset(CONTRACT_TYPES[$_GET['type'] ?? '']) ? $_GET['type'] : ''; @@ -66,7 +68,7 @@ $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 + $sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS contracts.*, client_name, client_archived_at, 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"); @@ -82,11 +84,16 @@ if (contractsReady()) { $sql = mysqli_query($mysqli, "SELECT contract_signature_id, contract_signature_contract_id, contract_signature_url_key, contract_signature_sent_at, contract_signature_viewed_at, contract_signature_client_name, contract_signature_client_signed_at, contract_signature_agent_signed_at, contract_signature_withdrawn_at FROM contract_signatures WHERE contract_signature_id IN (SELECT MAX(contract_signature_id) FROM contract_signatures WHERE contract_signature_contract_id IN ($ids) GROUP BY contract_signature_contract_id)"); + $by_id = array_column($contracts, null, 'contract_id'); while ($round = mysqli_fetch_assoc($sql)) { - $signing[intval($round['contract_signature_contract_id'])] = contractSignatureState($round); + $id = intval($round['contract_signature_contract_id']); + $signing[$id] = contractSignatureState($round + array_intersect_key($by_id[$id] ?? [], ['contract_status' => 1, 'client_archived_at' => 1])); } } + // The ones that can't be deleted, and why + $delete_blocked = $can_delete ? contractDeleteBlockers($contracts) : []; + // Prepaid hours left on each $hours_left = contractHoursLeftFor(array_column($contracts, 'contract_id')); @@ -287,10 +294,14 @@ $csrf = $_SESSION['csrf_token']; - - Delete - + + + + + Delete + + diff --git a/agent/includes/get_side_nav_counts.php b/agent/includes/get_side_nav_counts.php index dcca52f5c..f72a80440 100644 --- a/agent/includes/get_side_nav_counts.php +++ b/agent/includes/get_side_nav_counts.php @@ -27,7 +27,7 @@ $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; + ? intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contracts WHERE contract_archived_at IS NULL AND " . contractClientLiveSql() . " 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/modals/contract/contract_hours_add.php b/agent/modals/contract/contract_hours_add.php index 2d9718852..56109f9fa 100644 --- a/agent/modals/contract/contract_hours_add.php +++ b/agent/modals/contract/contract_hours_add.php @@ -19,9 +19,9 @@ if ($contract) { ob_start(); -if (!$contract || !contractHoursReady() || in_array($contract['contract_status'], ['Ended', 'Cancelled'], true)) { ?> +if (!$contract || !contractHoursReady() || !($contract['contract_status'] === 'Draft' || contractHoursLive($contract))) { ?> = date('Y-m-d', strtotime('-1 day')) ? $end : date('Y-m-d', strtotime('-1 day')); - $new_end = contractNextEnd($from, $contract['contract_term_months']); ?> + // Carried on from its last day, on the day of the month it started; from today, a term from today + $new_end = contractNextEnd($from, $contract['contract_term_months'], $from === $end ? contractAnchorDay($contract) : 0); ?>