Contracts stage 1: new Contracts list and page under Billing and the client menu with type, term, start and end, auto renew, notice days, support hours, rates, net terms and an SLA per priority from Admin > SLAs (empty uses the client's own), stat tiles, Active, Due soon, Drafts, Ended and All tabs, search, type and client filters and sorting; New, Copy and Edit from a template with an owner and contact, Make active, Renew and Cancel; nightly renewal or ending and an owner reminder a month before the notice date; client overview attention items and the contract in the Financial row; Contract Templates rebuilt with Template, Cover and Terms tabs, copy, archive and restore; new functions/contract.php; fixes deleting a client that has a contract, a new template's after-hours rate not saving, rates cut to whole amounts, Net 30 saved as 0 and Edit blanking the rates; DB 3.4.2 turns the old response and resolution hours into SLAs and renewal frequency into term and auto renew, and normalises type, status and net terms

This commit is contained in:
johnnyq
2026-10-25 01:05:09 -04:00
parent 185129dd72
commit 0da515fff5
29 changed files with 2629 additions and 660 deletions

View File

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

View File

@@ -1,21 +1,66 @@
<?php
/*
* Admin > 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 '<a class="text-reset text-decoration-none" href="?' . escapeHtml($url_query_strings_sort) . '&amp;sort=' . $column . '&amp;order=' . $disp . '">'
. $label . ($sort === $column ? " $order_icon" : '') . '</a>';
};
$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()"));
<h3 class="card-title mt-2"><i class="fa fa-fw fa-file-contract me-2"></i>Contract Templates</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/contract_template/contract_template_add.php" data-modal-size="lg">
<i class="fas fa-plus me-2"></i>New Template
<i class="fas fa-plus"></i><span class="d-none d-lg-inline ms-2">New Template</span>
</button>
</div>
</div>
<div class="card-header py-3">
<form autocomplete="off">
<div class="input-group">
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search templates">
<button class="btn btn-secondary" title="Search"><i class="fa fa-search"></i></button>
<?php if ($show !== '') { ?><input type="hidden" name="show" value="<?= escapeHtml($show) ?>"><?php } ?>
<div class="row g-2 align-items-center">
<div class="col-lg-5 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 templates..." title="Name, description or support hours">
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</form>
<nav class="nav nav-pills itflow-asset-tabs mt-2">
<?php foreach ($views as $view_key => $view) { ?>
<a class="nav-link <?= $show === (string) $view_key ? 'active' : '' ?>" href="<?= escapeHtml($pill_url($view_key)) ?>" title="<?= escapeHtml($view['title']) ?>"><i class="fas fa-fw <?= $view['icon'] ?> me-1"></i><?= escapeHtml($view['label']) ?> <span class="badge rounded-pill ms-1"><?= intval($view_counts[$view_key]) ?></span></a>
<?php } ?>
</nav>
</div>
<div class="table-responsive-sm">
<table class="table table-striped table-borderless table-hover mb-0">
<thead class="text-dark <?php if ($num_rows[0] == 0) { echo "d-none"; } ?>">
<tr>
<th class="ps-3">
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=contract_template_name&order=<?= $disp ?>">
Template Name <?php if ($sort == 'contract_template_name') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=contract_template_type&order=<?= $disp ?>">
Type <?php if ($sort == 'contract_template_type') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=contract_template_renewal_frequency&order=<?= $disp ?>">
Update Frequency <?php if ($sort == 'contract_template_renewal_frequency') { echo $order_icon; } ?>
</a>
</th>
<th>SLA (L/M/H Response)</th>
<th>SLA (L/M/H Resolution)</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=contract_template_rate_standard&order=<?= $disp ?>">
Hourly Rate <?php if ($sort == 'contract_template_rate_standard') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=contract_template_rate_after_hours&order=<?= $disp ?>">
After Hours Rate <?php if ($sort == 'contract_template_rate_after_hours') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=contract_template_support_hours&order=<?= $disp ?>">
Support Hours <?php if ($sort == 'contract_template_support_hours') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=contract_template_net_terms&order=<?= $disp ?>">
Net Terms <?php if ($sort == 'contract_template_net_terms') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=contract_template_created_at&order=<?= $disp ?>">
Created <?php if ($sort == 'contract_template_created_at') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=contract_template_updated_at&order=<?= $disp ?>">
Updated <?php if ($sort == 'contract_template_updated_at') { echo $order_icon; } ?>
</a>
</th>
<th class="text-center">Action</th>
</tr>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead class="table-light text-nowrap <?php if ($num_rows[0] == 0) { echo "d-none"; } ?>">
<tr>
<th class="ps-3"><?= $sort_link('contract_template_name', 'Template') ?></th>
<th class="d-none d-md-table-cell"><?= $sort_link('contract_template_term_months', 'Term') ?></th>
<th class="d-none d-lg-table-cell">Cover</th>
<th class="text-end"><?= $sort_link('contracts', 'Contracts') ?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql)) {
$id = intval($row['contract_template_id']);
$name = escapeHtml($row['contract_template_name']);
$type = escapeHtml($row['contract_template_type']);
$freq = escapeHtml($row['contract_template_renewal_frequency']);
$sla_low_resp = escapeHtml($row['contract_template_sla_low_response_time']);
$sla_med_resp = escapeHtml($row['contract_template_sla_medium_response_time']);
$sla_high_resp = escapeHtml($row['contract_template_sla_high_response_time']);
$sla_low_res = escapeHtml($row['contract_template_sla_low_resolution_time']);
$sla_med_res = escapeHtml($row['contract_template_sla_medium_resolution_time']);
$sla_high_res = escapeHtml($row['contract_template_sla_high_resolution_time']);
$hourly_rate = escapeHtml($row['contract_template_rate_standard']);
$after_hours = escapeHtml($row['contract_template_rate_after_hours']);
$support_hours = escapeHtml($row['contract_template_support_hours']);
$net_terms = escapeHtml($row['contract_template_net_terms']);
$created = escapeHtml($row['contract_template_created_at']);
$updated = escapeHtml($row['contract_template_updated_at']);
<?php foreach ($rows as $row) {
$id = intval($row['contract_template_id']);
$name = escapeHtml($row['contract_template_name']);
$type = CONTRACT_TYPES[$row['contract_template_type']] ?? CONTRACT_TYPES['other'];
$archived = !empty($row['contract_template_archived_at']);
$edit_url = "modals/contract_template/contract_template_edit.php?id=$id";
$sla_names = [];
foreach (CONTRACT_SLA_PRIORITIES as $priority => $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']) : '',
]);
?>
<tr>
<tr data-contract-template-id="<?= $id ?>">
<td class="ps-3">
<a class="text-bold ajax-modal" href="#"
data-modal-size="xl"
data-modal-url="modals/contract_template/contract_template_edit.php?id=<?= $id ?>">
<i class="fas fa-fw fa-file-alt text-dark"></i> <?= $name ?>
</a>
<div class="mt-1 text-secondary"><?= escapeHtml($row['contract_template_description']) ?></div>
<div class="d-flex align-items-center gap-3">
<span class="itflow-asset-icon itflow-asset-tone-other d-none d-sm-inline-flex" aria-hidden="true" title="<?= escapeHtml($type['label']) ?>"><i class="fas fa-fw <?= $type['icon'] ?>"></i></span>
<div class="min-w-0">
<a class="ajax-modal fw-semibold text-body" href="#" data-modal-size="lg" data-modal-url="<?= $edit_url ?>"><?= $name ?></a>
<div class="small text-body-secondary"><?= escapeHtml(contractTypeLabel($row['contract_template_type'])) ?><?= trim((string) $row['contract_template_description']) !== '' ? ' - ' . escapeHtml($row['contract_template_description']) : '' ?></div>
<?php if ($archived) { ?>
<div class="small text-body-secondary"><i class="fas fa-fw fa-archive me-1"></i>Archived <?= date('M j, Y', strtotime($row['contract_template_archived_at'])) ?></div>
<?php } ?>
</div>
</div>
</td>
<td><?= $type ?></td>
<td><?= $freq ?></td>
<td><?= "$sla_low_resp / $sla_med_resp / $sla_high_resp" ?></td>
<td><?= "$sla_low_res / $sla_med_res / $sla_high_res" ?></td>
<td><?= $hourly_rate ?></td>
<td><?= $after_hours ?></td>
<td><?= $support_hours ?></td>
<td><?= $net_terms ?></td>
<td><?= $created ?></td>
<td><?= $updated ?></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="d-none d-md-table-cell small text-nowrap">
<?= escapeHtml(contractTermLabel($row['contract_template_term_months'])) ?>
<div class="text-body-secondary"><?= intval($row['contract_template_auto_renew']) ? 'Renews itself' : 'Renewed by hand' ?>, <?= intval($row['contract_template_notice_days']) ?> days notice</div>
</td>
<td class="d-none d-lg-table-cell small">
<?= $cover ? escapeHtml(implode(' · ', $cover)) : '<span class="text-body-tertiary">The client\'s rate and terms</span>' ?>
<div class="text-body-secondary">
<?php if ($sla_names) {
echo escapeHtml(implode(' · ', array_map(function ($sla_name, $priorities) {
return "$sla_name (" . implode(', ', $priorities) . ")";
}, array_keys($sla_names), $sla_names)));
} else { ?>
The client's usual SLAs
<?php } ?>
</div>
</td>
<td class="text-end"><?= intval($row['n_contracts']) ?: '<span class="text-body-tertiary">0</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-size="xl"
data-modal-url="modals/contract_template/contract_template_edit.php?id=<?= $id ?>">
<i class="fas fa-fw fa-edit me-2"></i>Edit
</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="<?= $edit_url ?>"><i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit</a>
<a class="dropdown-item" href="post.php?copy_contract_template=<?= $id ?>&csrf_token=<?= $csrf ?>"><i class="fas fa-fw fa-copy text-secondary me-2"></i>Copy</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_contract_template=<?= $id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<?php if ($archived) { ?>
<a class="dropdown-item" href="post.php?restore_contract_template=<?= $id ?>&csrf_token=<?= $csrf ?>"><i class="fas fa-fw fa-box-open text-secondary me-2"></i>Restore</a>
<?php } else { ?>
<a class="dropdown-item text-danger" href="post.php?archive_contract_template=<?= $id ?>&csrf_token=<?= $csrf ?>" title="Kept, but not offered on a new contract"><i class="fas fa-fw fa-archive me-2"></i>Archive</a>
<?php } ?>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_contract_template=<?= $id ?>&csrf_token=<?= $csrf ?>"
data-confirm-title="Delete <?= $name ?>?" data-confirm-text="<?= intval($row['n_contracts']) ? 'The ' . intval($row['n_contracts']) . ' contract' . (intval($row['n_contracts']) === 1 ? '' : 's') . ' started from it keep their terms.' : 'Nothing was started from it.' ?>" data-confirm-button="Delete">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
</div>
</div>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
@@ -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";
?>
<?php require_once "../includes/filter_footer.php"; ?>
</div>
<?php require_once "../includes/footer.php"; ?>
<?php
require_once "../includes/footer.php";

View File

@@ -0,0 +1,144 @@
<?php
/*
* ITFlow - Database update to version 3.4.2 (from 3.4.1)
* Included by admin/database_updates.php - do not access directly
*
* Client contracts, stage 1. Contracts and contract templates take their
* response and resolution targets from Admin > 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);

View File

@@ -1,9 +1,12 @@
<?php
/*
* New contract template. The fields are contract_template_form.php.
*/
require_once '../../includes/modal_header.php';
$contract_types_array = ['Fully Managed', 'Partialy Managed', 'Break/Fix'];
$renewal_frequency_array = ['Manual', 'Annually', '2 Year', '3 Year', '5 Year', '7 Year'];
$template = null;
ob_start();
?>
@@ -12,184 +15,16 @@ ob_start();
<h5 class="modal-title"><i class="fa fa-fw fa-file-contract me-2"></i>New Contract Template</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<!-- Tabs Navigation -->
<ul class="modal-header nav nav-pills nav-justified">
<li class="nav-item">
<a class="nav-link active" id="general-tab" data-bs-toggle="tab" href="#general" role="tab">General Info</a>
</li>
<li class="nav-item">
<a class="nav-link" id="sla-tab" data-bs-toggle="tab" href="#sla" role="tab">SLA</a>
</li>
<li class="nav-item">
<a class="nav-link" id="rates-tab" data-bs-toggle="tab" href="#rates" role="tab">Rates & Support</a>
</li>
<li class="nav-item">
<a class="nav-link" id="details-tab" data-bs-toggle="tab" href="#details" role="tab">Details</a>
</li>
</ul>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<div class="modal-body">
<div class="tab-content" id="contractTemplateTabContent">
<!-- General Info Tab -->
<div class="tab-pane fade show active" id="general" role="tabpanel">
<div class="mb-3">
<label>Template Name <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-contract"></i></span>
<input type="text" class="form-control" name="name" placeholder="Contract Template Name" maxlength="200" required autofocus>
</div>
</div>
<div class="mb-3">
<label>Template Description <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
<input type="text" class="form-control" name="description"
placeholder="Contract Template Description" maxlength="200" required>
</div>
</div>
<div class="mb-3">
<label>Contract Type <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="type" required>
<option value="">- Select Type -</option>
<?php foreach ($contract_types_array as $type) { ?>
<option><?= $type ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="mb-3">
<label>Renewal Frequency</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-sync-alt"></i></span>
<select class="form-select select2" name="renewal_frequency">
<option value="">- Select Frequency -</option>
<?php foreach ($renewal_frequency_array as $renewal_frequency) { ?>
<option><?= $renewal_frequency ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<!-- SLA Tab -->
<div class="tab-pane fade" id="sla" role="tabpanel">
<div class="row g-2">
<div class="mb-3 col-md-6">
<label>Low Priority Response (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-clock"></i></span>
<input type="number" class="form-control" name="sla_low_response_time" placeholder="e.g., 24">
</div>
</div>
<div class="mb-3 col-md-6">
<label>Low Priority Resolution (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-hourglass-half"></i></span>
<input type="number" class="form-control" name="sla_low_resolution_time" placeholder="e.g., 48">
</div>
</div>
</div>
<div class="row g-2">
<div class="mb-3 col-md-6">
<label>Medium Priority Response (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-clock"></i></span>
<input type="number" class="form-control" name="sla_medium_response_time" placeholder="e.g., 12">
</div>
</div>
<div class="mb-3 col-md-6">
<label>Medium Priority Resolution (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-hourglass-half"></i></span>
<input type="number" class="form-control" name="sla_medium_resolution_time" placeholder="e.g., 24">
</div>
</div>
</div>
<div class="row g-2">
<div class="mb-3 col-md-6">
<label>High Priority Response (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-bolt"></i></span>
<input type="number" class="form-control" name="sla_high_response_time" placeholder="e.g., 1">
</div>
</div>
<div class="mb-3 col-md-6">
<label>High Priority Resolution (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-stopwatch"></i></span>
<input type="number" class="form-control" name="sla_high_resolution_time" placeholder="e.g., 4">
</div>
</div>
</div>
</div>
<!-- Rates & Support Tab -->
<div class="tab-pane fade" id="rates" role="tabpanel">
<div class="mb-3">
<label>Standard Hourly Rate</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" name="rate_standard" placeholder="e.g., 100">
</div>
</div>
<div class="mb-3">
<label>After Hours Hourly Rate</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-moon"></i></span>
<input type="text" class="form-control" name="rate_after_hours" placeholder="e.g., 150">
</div>
</div>
<div class="mb-3">
<label>Support Hours</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="text" class="form-control" name="support_hours" placeholder="e.g., Mon-Fri 9am-5pm" maxlength="100">
</div>
</div>
<div class="mb-3">
<label>Net Terms</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-invoice-dollar"></i></span>
<input type="text" class="form-control" name="net_terms" placeholder="e.g., Net 30" maxlength="50">
</div>
</div>
</div>
<!-- Details Tab -->
<div class="tab-pane fade" id="details" role="tabpanel">
<div class="mb-3">
<textarea class="form-control tinymce" rows="6" name="details" placeholder="Enter Contract Details"></textarea>
</div>
</div>
</div>
<?php require __DIR__ . '/contract_template_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_contract_template" class="btn btn-primary text-bold">
<i class="fa fa-check me-2"></i>Create Template
</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_contract_template" 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>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';
?>

View File

@@ -1,242 +1,39 @@
<?php
/*
* Edit a contract template - contracts already started from it keep their
* own terms. The fields are contract_template_form.php.
*/
require_once '../../includes/modal_header.php';
$contract_template_id = intval($_GET['id']);
$contract_types_array = ['Fully Managed', 'Partialy Managed', 'Break/Fix'];
$update_frequency_array = ['Manual', 'Annually', '2 Year', '3 Year', '5 Year', '7 Year'];
// Fetch existing template
$sql = mysqli_query($mysqli, "SELECT contract_template_description, contract_template_details, contract_template_name,
contract_template_net_terms, contract_template_rate_after_hours,
contract_template_rate_standard, contract_template_renewal_frequency,
contract_template_sla_high_resolution_time, contract_template_sla_high_response_time,
contract_template_sla_low_resolution_time, contract_template_sla_low_response_time,
contract_template_sla_medium_resolution_time, contract_template_sla_medium_response_time,
contract_template_support_hours, contract_template_type FROM contract_templates WHERE contract_template_id = $contract_template_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
// Assign locals
$name = escapeHtml($row['contract_template_name']);
$description = escapeHtml($row['contract_template_description']);
$type = escapeHtml($row['contract_template_type']);
$renewal_frequency = escapeHtml($row['contract_template_renewal_frequency']);
$sla_low_resp = intval($row['contract_template_sla_low_response_time']);
$sla_med_resp = intval($row['contract_template_sla_medium_response_time']);
$sla_high_resp = intval($row['contract_template_sla_high_response_time']);
$sla_low_res = intval($row['contract_template_sla_low_resolution_time']);
$sla_med_res = intval($row['contract_template_sla_medium_resolution_time']);
$sla_high_res = intval($row['contract_template_sla_high_resolution_time']);
$hourly_rate = intval($row['contract_template_rate_standard']);
$after_hours = intval($row['contract_template_rate_after_hours']);
$support_hours = escapeHtml($row['contract_template_support_hours']);
$net_terms = intval($row['contract_template_net_terms']);
$details = escapeHtml($row['contract_template_details']);
$template = contractTemplateRow(intval($_GET['id'] ?? 0));
ob_start();
?>
if (!$template) { ?>
<div class="modal-body text-center text-secondary py-5">That template is gone - it may have been deleted.</div>
<?php } else { ?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-file-contract me-2"></i>Edit Contract Template</h5>
<h5 class="modal-title"><i class="fa fa-fw fa-file-contract me-2"></i>Contract Template: <strong><?= escapeHtml($template['contract_template_name']) ?></strong></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<!-- Tabs Navigation -->
<ul class="modal-header nav nav-pills nav-justified">
<li class="nav-item">
<a class="nav-link active" id="general-tab" data-bs-toggle="tab" href="#general" role="tab">General Info</a>
</li>
<li class="nav-item">
<a class="nav-link" id="sla-tab" data-bs-toggle="tab" href="#sla" role="tab">SLA</a>
</li>
<li class="nav-item">
<a class="nav-link" id="rates-tab" data-bs-toggle="tab" href="#rates" role="tab">Rates & Support</a>
</li>
<li class="nav-item">
<a class="nav-link" id="details-tab" data-bs-toggle="tab" href="#details" role="tab">Details</a>
</li>
</ul>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="contract_template_id" value="<?= $contract_template_id ?>">
<input type="hidden" name="contract_template_id" value="<?= intval($template['contract_template_id']) ?>">
<div class="modal-body">
<div class="tab-content" id="contractTemplateTabContent">
<!-- General Info Tab -->
<div class="tab-pane fade show active" id="general" role="tabpanel">
<div class="mb-3">
<label>Template Name <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-contract"></i></span>
<input type="text" class="form-control" name="name"
placeholder="Contract Template Name" maxlength="200" required autofocus
value="<?= $name ?>">
</div>
</div>
<div class="mb-3">
<label>Template Description <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
<input type="text" class="form-control" name="description"
placeholder="Contract Template Description" maxlength="200" required
value="<?= $description ?>">
</div>
</div>
<div class="mb-3">
<label>Contract Type <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="type" required>
<option value="">- Select Type -</option>
<?php foreach ($contract_types_array as $type_select) { ?>
<option <?php if ($type == $type_select) { echo "selected"; } ?>><?= $type_select ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="mb-3">
<label>Renewal Frequency</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-sync-alt"></i></span>
<select class="form-select select2" name="renewal_frequency">
<option value="">- Select Frequency -</option>
<?php foreach ($renewal_frequency_array as $renewal_frequency_select) { ?>
<option <?php if ($renewal_frequency == $renewal_frequency_select) { echo "selected"; } ?>><?= $renewal_frequency_select ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<!-- SLA Tab -->
<div class="tab-pane fade" id="sla" role="tabpanel">
<div class="row g-2">
<div class="mb-3 col-md-6">
<label>Low Priority Response (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-clock"></i></span>
<input type="number" class="form-control" name="sla_low_response_time" placeholder="e.g., 24"
value="<?= $sla_low_resp ?>">
</div>
</div>
<div class="mb-3 col-md-6">
<label>Low Priority Resolution (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-hourglass-half"></i></span>
<input type="number" class="form-control" name="sla_low_resolution_time" placeholder="e.g., 48"
value="<?= $sla_low_res ?>">
</div>
</div>
</div>
<div class="row g-2">
<div class="mb-3 col-md-6">
<label>Medium Priority Response (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-clock"></i></span>
<input type="number" class="form-control" name="sla_medium_response_time" placeholder="e.g., 12"
value="<?= $sla_med_resp ?>">
</div>
</div>
<div class="mb-3 col-md-6">
<label>Medium Priority Resolution (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-hourglass-half"></i></span>
<input type="number" class="form-control" name="sla_medium_resolution_time" placeholder="e.g., 24"
value="<?= $sla_med_res ?>">
</div>
</div>
</div>
<div class="row g-2">
<div class="mb-3 col-md-6">
<label>High Priority Response (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-bolt"></i></span>
<input type="number" class="form-control" name="sla_high_response_time" placeholder="e.g., 1"
value="<?= $sla_high_resp ?>">
</div>
</div>
<div class="mb-3 col-md-6">
<label>High Priority Resolution (hrs)</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-stopwatch"></i></span>
<input type="number" class="form-control" name="sla_high_resolution_time" placeholder="e.g., 4"
value="<?= $sla_high_res ?>">
</div>
</div>
</div>
</div>
<!-- Rates & Support Tab -->
<div class="tab-pane fade" id="rates" role="tabpanel">
<div class="mb-3">
<label>Standard Hourly Rate</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" name="rate_standard" placeholder="e.g., 100"
value="<?= $rate_standard ?>">
</div>
</div>
<div class="mb-3">
<label>After Hours Hourly Rate</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-moon"></i></span>
<input type="text" class="form-control" name="rate_after_hours" placeholder="e.g., 150"
value="<?= $rate_after_hours ?>">
</div>
</div>
<div class="mb-3">
<label>Support Hours</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="text" class="form-control" name="support_hours" placeholder="e.g., Mon-Fri 9am-5pm" maxlength="100"
value="<?= $support_hours ?>">
</div>
</div>
<div class="mb-3">
<label>Net Terms</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-invoice-dollar"></i></span>
<input type="text" class="form-control" name="net_terms" placeholder="e.g., Net 30" maxlength="50"
value="<?= $net_terms ?>">
</div>
</div>
</div>
<!-- Details Tab -->
<div class="tab-pane fade" id="details" role="tabpanel">
<div class="mb-3">
<label>Contract Details</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
<textarea class="form-control tinymce" rows="6" name="details"
placeholder="Enter Contract Details"><?= $details ?></textarea>
</div>
</div>
</div>
</div>
<?php if (!empty($template['contract_template_archived_at'])) { ?>
<div class="alert alert-secondary small py-2"><i class="fas fa-fw fa-archive me-1"></i>Archived - it isn't offered on a new contract. Restore it from the list.</div>
<?php } ?>
<?php require __DIR__ . '/contract_template_form.php'; ?>
<small class="text-secondary d-block mt-3">Contracts already started from it keep their own terms.</small>
</div>
<div class="modal-footer">
<button type="submit" name="edit_contract_template" class="btn btn-primary text-bold">
<i class="fa fa-check me-2"></i>Save Changes
</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="edit_contract_template" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Save changes</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
<?php }
require_once '../../../includes/modal_footer.php';
?>

View File

@@ -0,0 +1,142 @@
<?php
/*
* A contract template's fields, in tabs - for contract_template_add.php and
* contract_template_edit.php, which set $template (a contractTemplateRow(),
* or null when new). The same terms a contract has, without the client and
* its dates. The server checks them (contractFromInput()).
*/
isset($mysqli) || die("Direct file access is not allowed");
$t = $template ?? null;
$t_value = function ($key, $default = '') use ($t) {
return $t !== null && array_key_exists("contract_template_$key", $t) && $t["contract_template_$key"] !== null ? $t["contract_template_$key"] : $default;
};
$t_money = function ($value) {
return $value === '' || $value === null ? '' : number_format((float) $value, 2, '.', '');
};
$t_term = intval($t_value('term_months', 12));
$t_slas = contractSlaChoices($t ? array_map(function ($part) use ($t) { return intval($t["contract_template_sla_{$part}_id"]); }, CONTRACT_SLA_PRIORITIES) : []);
$tab = 'templateTab' . bin2hex(random_bytes(3));
?>
<ul class="nav nav-pills nav-justified mb-3" role="tablist">
<li class="nav-item"><a class="nav-link active" data-bs-toggle="pill" href="#<?= $tab ?>General" role="tab"><i class="fas fa-fw fa-file-contract me-1"></i>Template</a></li>
<li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#<?= $tab ?>Cover" role="tab"><i class="fas fa-fw fa-shield-alt me-1"></i>Cover</a></li>
<li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#<?= $tab ?>Terms" role="tab"><i class="fas fa-fw fa-file-alt me-1"></i>Terms</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade show active" id="<?= $tab ?>General" role="tabpanel">
<div class="row g-3 mb-3">
<div class="col-md-7">
<label class="form-label">Name <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<input type="text" class="form-control" name="name" maxlength="255" placeholder="Managed Services - Gold" value="<?= escapeHtml($t_value('name')) ?>" required<?= $t ? '' : ' autofocus' ?>>
</div>
</div>
<div class="col-md-5">
<label class="form-label">Type</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-layer-group"></i></span>
<select class="form-select" name="type">
<?php foreach (CONTRACT_TYPES as $key => $type) { ?>
<option value="<?= $key ?>"<?= $t_value('type', 'managed') === $key ? ' selected' : '' ?> title="<?= escapeHtml($type['about']) ?>"><?= escapeHtml($type['label']) ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label">Description</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
<input type="text" class="form-control" name="description" maxlength="1000" placeholder="Who it suits, and what sets it apart" value="<?= escapeHtml($t_value('description')) ?>">
</div>
</div>
<div class="row g-3 align-items-end">
<div class="col-md-4">
<label class="form-label">Term</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-history"></i></span>
<select class="form-select" name="term_months">
<?php $terms = CONTRACT_TERMS + (!isset(CONTRACT_TERMS[$t_term]) ? [$t_term => contractTermLabel($t_term)] : []);
ksort($terms);
foreach ($terms as $months => $label) { ?>
<option value="<?= $months ?>"<?= $months === $t_term ? ' selected' : '' ?>><?= escapeHtml($label) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-md-4">
<label class="form-label">Notice to end it</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-bell"></i></span>
<input type="number" class="form-control" name="notice_days" min="0" max="365" value="<?= intval($t_value('notice_days', 30)) ?>">
<span class="input-group-text">days</span>
</div>
</div>
<div class="col-md-4">
<div class="form-check form-switch mb-2">
<input class="form-check-input" type="checkbox" role="switch" name="auto_renew" value="1" id="<?= $tab ?>AutoRenew"<?= intval($t_value('auto_renew', 1)) ? ' checked' : '' ?>>
<label class="form-check-label" for="<?= $tab ?>AutoRenew">Renews itself</label>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="<?= $tab ?>Cover" role="tabpanel">
<div class="mb-3">
<label class="form-label">Support hours</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-business-time"></i></span>
<input type="text" class="form-control" name="support_hours" maxlength="100" placeholder="Mon-Fri 8am-6pm, emergencies 24/7" value="<?= escapeHtml($t_value('support_hours')) ?>">
</div>
</div>
<div class="row g-3 mb-3">
<div class="col-md-4">
<label class="form-label">Hourly rate</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" inputmode="decimal" class="form-control" name="rate_standard" placeholder="The client's" value="<?= escapeHtml($t_money($t_value('rate_standard', ''))) ?>">
</div>
</div>
<div class="col-md-4">
<label class="form-label">After hours</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-moon"></i></span>
<input type="text" inputmode="decimal" class="form-control" name="rate_after_hours" placeholder="None" value="<?= escapeHtml($t_money($t_value('rate_after_hours', ''))) ?>">
</div>
</div>
<div class="col-md-4">
<label class="form-label">Net terms</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="number" class="form-control" name="net_terms" min="0" max="365" placeholder="The client's" value="<?= escapeHtml((string) $t_value('net_terms', '')) ?>">
<span class="input-group-text">days</span>
</div>
</div>
</div>
<small class="text-secondary d-block mb-3">Leave a rate or the net terms empty and the client's own apply.</small>
<label class="form-label">SLA by ticket priority</label>
<?php foreach (CONTRACT_SLA_PRIORITIES as $priority => $part) { ?>
<div class="input-group mb-2">
<span class="input-group-text" style="width: 7rem;"><i class="fa fa-fw fa-stopwatch me-2"></i><?= $priority ?></span>
<select class="form-select" name="sla_<?= $part ?>" aria-label="<?= $priority ?> priority SLA">
<option value="0">The client's usual SLA</option>
<?php foreach ($t_slas as $sla_id => $sla) { ?>
<option value="<?= $sla_id ?>"<?= intval($t_value("sla_{$part}_id", 0)) === $sla_id ? ' selected' : '' ?>><?= escapeHtml($sla['sla_name'] . ' - ' . contractSlaTargets($sla)) ?><?= $sla['sla_archived_at'] ? ' (archived)' : '' ?></option>
<?php } ?>
</select>
</div>
<?php } ?>
<small class="text-secondary">From Admin > SLAs.</small>
</div>
<div class="tab-pane fade" id="<?= $tab ?>Terms" role="tabpanel">
<textarea class="form-control tinymce" name="details" rows="12" aria-label="Terms"><?= escapeHtml(documentHtmlPurify((string) $t_value('details'))) ?></textarea>
</div>
</div>

View File

@@ -1,170 +1,113 @@
<?php
/*
* ITFlow - GET/POST request handler for Contract Templates
* ITFlow - contract templates: add, change, copy, archive, restore and
* delete. A contract started from a template keeps its own copy of the
* terms, so changing or deleting a template leaves those contracts as they
* are. The fields are checked by contractFromInput() in functions/contract.php.
*/
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
if (isset($_POST['add_contract_template'])) {
validateCSRFToken();
// Sanitize text inputs
$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']);
// Numeric fields cast to integer
$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['hourly_rate_after_hours']);
$net_terms = intval($_POST['net_terms']);
// Insert into database (numbers not quoted)
mysqli_query($mysqli, "
INSERT INTO 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
");
$contract_template_id = mysqli_insert_id($mysqli);
// Log action
logAudit("Contract Template", "Create", "$session_name created contract template $name", 0, $contract_template_id);
// Flash message
flashAlert("Contract Template <strong>$name</strong> 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 <strong>" . escapeHtml($fields['name']) . "</strong> 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 <strong>" . escapeHtml($fields['name']) . "</strong> created");
}
// Log action
logAudit("Contract Template", "Edit", "$session_name updated contract template $name", 0, $contract_template_id);
// Flash + redirect
flashAlert("Contract Template <strong>$name</strong> 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 <strong>" . escapeHtml($row['contract_template_name']) . "</strong> copied as <strong>" . escapeHtml($new_name) . "</strong>");
logAudit("Contract Template", "Archive", "$session_name archived contract template $name", 0, $contract_template_id);
flashAlert("Contract Template <strong>$name</strong> 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 <strong>" . escapeHtml($row['contract_template_name']) . "</strong> " . ($archive ? 'archived' : 'restored'), $archive ? 'error' : 'success');
logAudit("Contract Template", "Restore", "$session_name restored contract template $name", 0, $contract_template_id);
flashAlert("Contract Template <strong>$name</strong> 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 <strong>" . escapeHtml($row['contract_template_name']) . "</strong> deleted", 'error');
logAudit("Contract Template", "Delete", "$session_name deleted contract template $name", 0, $contract_template_id);
flashAlert("Contract Template <strong>$name</strong> deleted", "danger");
redirect();
}
?>
}

View File

@@ -521,6 +521,21 @@ $money_format = function ($amount) use ($currency_format, $client_currency_code,
</span>
</a>
<?php } ?>
<?php if ($access['sales'] && contractsReady()) {
$overview_contracts = contractClientActive($client_id);
$overview_contract = $overview_contracts[0] ?? null; ?>
<a href="<?= $overview_contract && count($overview_contracts) === 1 ? 'contract.php?client_id=' . $client_id . '&contract_id=' . intval($overview_contract['contract_id']) : 'contracts.php?client_id=' . $client_id ?>" class="itflow-dash-rail-item" data-overview-contract>
<span class="small text-body-secondary">Contract</span>
<?php if ($overview_contract) {
$overview_state = contractState($overview_contract); ?>
<span class="fs-5 fw-semibold text-truncate" title="<?= escapeHtml($overview_contract['contract_name']) ?>"><?= escapeHtml($overview_contract['contract_name']) ?></span>
<span class="small <?= in_array($overview_state['key'], ['ending', 'renewing'], true) ? 'text-' . ($overview_state['key'] === 'ending' ? 'warning' : 'primary') . '-emphasis' : 'text-body-tertiary' ?>"><?= escapeHtml($overview_state['when']) ?><?= count($overview_contracts) > 1 ? ' · ' . (count($overview_contracts) - 1) . ' more' : '' ?></span>
<?php } else { ?>
<span class="fs-5 fw-semibold text-body-tertiary">None</span>
<span class="small text-body-tertiary">No contract in force</span>
<?php } ?>
</a>
<?php } ?>
<div class="itflow-dash-rail-item">
<span class="small text-body-secondary">Terms</span>
<span class="itflow-dash-money-value"><?= $money_format($client_rate) ?><span class="fs-6 fw-normal text-body-secondary">/hr</span></span>

263
agent/contract.php Normal file
View File

@@ -0,0 +1,263 @@
<?php
/*
* Contract - one agreement with a client: where it stands and when it renews
* or ends (with the notice date), what it covers (support hours, an SLA for
* each ticket priority, rates and net terms - the client's own where the
* contract sets none), its terms, the internal notes, and its history from
* the audit log. Make active, Renew, Cancel and Edit from the top. The work
* is in functions/contract.php; the handlers are agent/post/contract.php.
*/
// 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_client_overview_all.php";
$client_url = '';
}
enforceUserPermission('module_sales');
$contract_id = intval($_GET['contract_id'] ?? 0);
$contract = contractRow($contract_id);
if (!$contract || ($client_url && intval($contract['contract_client_id']) !== intval($client_id))) {
echo "<center><h1 class='text-secondary mt-5'>Nothing to see here</h1><a class='btn btn-lg btn-secondary mt-3' href='javascript:history.back()'><i class='fa fa-fw fa-arrow-left'></i> Go Back</a></center>";
} 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),
];
}
?>
<ol class="breadcrumb d-print-none">
<li class="breadcrumb-item"><a href="client_overview.php?client_id=<?= $client_id ?>"><?= escapeHtml($contract['client_name']) ?></a></li>
<li class="breadcrumb-item"><a href="contracts.php?client_id=<?= $client_id ?>">Contracts</a></li>
<li class="breadcrumb-item active"><?= $name ?></li>
</ol>
<div class="card mb-3">
<div class="card-body d-flex flex-wrap align-items-center gap-3">
<span class="itflow-asset-icon itflow-asset-icon-lg itflow-asset-tone-other" aria-hidden="true"><i class="fas fa-fw <?= $type['icon'] ?>"></i></span>
<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><?= $name ?></span>
<span class="fs-6"><?= contractStateHtml($contract) ?></span>
</h1>
<div class="text-body-secondary small d-flex flex-wrap column-gap-3 row-gap-1">
<span title="<?= escapeHtml($type['about']) ?>"><i class="fas fa-fw <?= $type['icon'] ?> me-1"></i><?= escapeHtml(contractTypeLabel($contract['contract_type'])) ?></span>
<span><i class="fas fa-fw fa-calendar-alt me-1"></i><?= escapeHtml($state['when']) ?></span>
<?php if ($contract['contract_template_name']) { ?><span><i class="fas fa-fw fa-clone me-1"></i>From <?= escapeHtml($contract['contract_template_name']) ?></span><?php } ?>
</div>
</div>
<?php if ($can_edit) { ?>
<div class="d-flex flex-wrap gap-2 d-print-none">
<?php if ($status === 'Draft') { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/contract/contract_activate.php?id=<?= $contract_id ?>"><i class="fas fa-check me-2"></i>Make active</button>
<?php } elseif ($contract['contract_end_date']) { ?>
<button type="button" class="btn btn-outline-primary ajax-modal" data-modal-url="modals/contract/contract_renew.php?id=<?= $contract_id ?>"><i class="fas fa-sync-alt me-2"></i>Renew</button>
<?php } ?>
<button type="button" class="btn btn-outline-secondary ajax-modal" data-modal-size="lg" data-modal-url="modals/contract/contract_edit.php?id=<?= $contract_id ?>"><i class="fas fa-edit me-2"></i>Edit</button>
<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 ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/contract/contract_add.php?client_id=<?= $client_id ?>&copy=<?= $contract_id ?>"><i class="fas fa-fw fa-copy text-secondary me-2"></i>Copy</a>
<?php if ($status === 'Active') { ?>
<a class="dropdown-item text-danger ajax-modal" href="#" data-modal-url="modals/contract/contract_cancel.php?id=<?= $contract_id ?>"><i class="fas fa-fw fa-ban me-2"></i>Cancel</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_contract=<?= $contract_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-title="Delete <?= $name ?>?" data-confirm-text="It goes for good. Cancel it instead to keep a record of it." data-confirm-button="Delete">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
</div>
</div>
</div>
<?php } ?>
</div>
<?php if ($progress) { ?>
<div class="card-footer bg-transparent">
<div class="d-flex flex-wrap justify-content-between small text-body-secondary mb-1">
<span>This term since <?= escapeHtml($progress['from']) ?></span>
<span><?= number_format($progress['days_left']) ?> day<?= $progress['days_left'] === 1 ? '' : 's' ?> left</span>
</div>
<div class="progress" style="height: .5rem;" role="progressbar" aria-label="How far through its term" aria-valuenow="<?= $progress['percent'] ?>" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar bg-<?= $state['tone'] === 'warning' ? 'warning' : ($state['tone'] === 'primary' ? 'primary' : 'success') ?>" style="width: <?= $progress['percent'] ?>%"></div>
</div>
</div>
<?php } ?>
</div>
<?php if (in_array($state['key'], ['renewing', 'ending'], true) && $notice !== '') { ?>
<div class="alert alert-<?= $state['key'] === 'ending' ? 'warning' : 'info' ?> d-flex flex-wrap align-items-center gap-2 mb-3" data-contract-notice>
<i class="fas fa-fw <?= $state['icon'] ?>"></i>
<div class="me-auto">
<?php if ($state['key'] === 'renewing') { ?>
<strong>It renews itself on <?= escapeHtml(date('M j, Y', strtotime('+1 day', strtotime($contract['contract_end_date'])))) ?></strong> for another <?= escapeHtml(contractTermLabel($contract['contract_term_months'])) ?>.
<?= $notice >= $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.' ?>
<?php } else { ?>
<strong>It ends on <?= escapeHtml(date('M j, Y', strtotime($contract['contract_end_date']))) ?></strong> and doesn't renew itself.
<?= $notice >= $today ? 'Notice is due by ' . escapeHtml(date('M j, Y', strtotime($notice))) . '.' : '' ?> Renew it to keep it going.
<?php } ?>
</div>
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-sm btn-<?= $state['key'] === 'ending' ? 'warning' : 'info' ?> ajax-modal" data-modal-url="modals/contract/contract_renew.php?id=<?= $contract_id ?>">Renew</button>
<?php } ?>
</div>
<?php } ?>
<div class="row g-3">
<div class="col-xl-4 col-lg-5">
<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>Term</h3></div>
<div class="card-body">
<dl class="itflow-asset-dl mb-0">
<dt>Starts</dt><dd><?= $contract['contract_start_date'] ? escapeHtml(date('M j, Y', strtotime($contract['contract_start_date']))) : '<span class="text-body-secondary">Not set</span>' ?></dd>
<dt>Ends</dt><dd><?= $contract['contract_end_date'] ? escapeHtml(date('M j, Y', strtotime($contract['contract_end_date']))) : '<span class="text-body-secondary">No end date</span>' ?></dd>
<dt>Term</dt><dd><?= escapeHtml(contractTermLabel($contract['contract_term_months'])) ?></dd>
<dt>Renews</dt><dd><?= intval($contract['contract_auto_renew']) ? 'By itself, for another term' : 'Only when renewed' ?></dd>
<dt>Notice</dt>
<dd>
<?= intval($contract['contract_notice_days']) ? intval($contract['contract_notice_days']) . ' days' : 'None' ?>
<?php if ($notice !== '' && $status === 'Active') { ?><div class="small text-body-secondary">By <?= escapeHtml(date('M j, Y', strtotime($notice))) ?></div><?php } ?>
</dd>
<?php if ($contract['contract_renewed_at']) { ?><dt>Renewed</dt><dd title="<?= escapeHtml($contract['contract_renewed_at']) ?>"><?= escapeHtml(date('M j, Y', strtotime($contract['contract_renewed_at']))) ?></dd><?php } ?>
<?php if ($status === 'Cancelled') { ?>
<dt>Cancelled</dt>
<dd><?= $contract['contract_cancelled_at'] ? escapeHtml(date('M j, Y', strtotime($contract['contract_cancelled_at']))) : '' ?><?php if ($contract['contract_cancel_reason']) { ?><div class="small text-body-secondary"><?= escapeHtml($contract['contract_cancel_reason']) ?></div><?php } ?></dd>
<?php } ?>
</dl>
</div>
</div>
<div class="card mb-3">
<div class="card-header"><h3 class="card-title mb-0"><i class="fas fa-fw fa-users text-secondary me-2"></i>People</h3></div>
<div class="card-body">
<dl class="itflow-asset-dl mb-0">
<dt>Client</dt><dd><a href="client_overview.php?client_id=<?= $client_id ?>"><?= escapeHtml($contract['client_name']) ?></a></dd>
<dt>Contact</dt><dd><?= $contract['contact_name'] ? '<a href="contact.php?client_id=' . $client_id . '&contact_id=' . intval($contract['contract_contact_id']) . '">' . escapeHtml($contract['contact_name']) . '</a>' : '<span class="text-body-secondary">None</span>' ?></dd>
<dt>Owner</dt><dd><?= $contract['owner_name'] ? escapeHtml($contract['owner_name']) : '<span class="text-body-secondary">No one - everyone is reminded</span>' ?></dd>
<dt>Added</dt><dd title="<?= escapeHtml($contract['contract_created_at']) ?>"><?= timeAgo($contract['contract_created_at']) ?></dd>
</dl>
</div>
</div>
<?= auditLogHistoryCard($history, ['client_id' => $client_id]) ?>
</div>
<div class="col-xl-8 col-lg-7">
<div class="card mb-3">
<div class="card-header"><h3 class="card-title mb-0"><i class="fas fa-fw fa-shield-alt text-secondary me-2"></i>What it covers</h3></div>
<div class="card-body">
<div class="row g-3">
<div class="col-md-6">
<div class="small text-body-secondary text-uppercase fw-semibold mb-1">Support hours</div>
<div><?= $contract['contract_support_hours'] ? escapeHtml($contract['contract_support_hours']) : '<span class="text-body-secondary">Not set</span>' ?></div>
</div>
<div class="col-md-6">
<div class="small text-body-secondary text-uppercase fw-semibold mb-1">Rates</div>
<div><?= $contract['contract_rate_standard'] !== null ? $money($contract['contract_rate_standard']) . '/hr' : '<span title="The client\'s own rate">' . $money($contract['client_rate']) . '/hr <span class="text-body-secondary small">(client\'s)</span></span>' ?></div>
<div class="small text-body-secondary"><?= $contract['contract_rate_after_hours'] !== null ? $money($contract['contract_rate_after_hours']) . '/hr after hours' : 'No after-hours rate' ?></div>
</div>
<div class="col-md-6">
<div class="small text-body-secondary text-uppercase fw-semibold mb-1">Net terms</div>
<div><?php
$terms = $contract['contract_net_terms'] !== null ? intval($contract['contract_net_terms']) : intval($contract['client_net_terms']);
echo $terms ? "Net $terms" : 'Due on receipt';
echo $contract['contract_net_terms'] === null ? ' <span class="text-body-secondary small">(client\'s)</span>' : '';
?></div>
</div>
</div>
<div class="small text-body-secondary text-uppercase fw-semibold mt-3 mb-1">SLA by priority</div>
<div class="table-responsive">
<table class="table table-sm table-borderless mb-0" data-contract-slas>
<tbody>
<?php foreach (CONTRACT_SLA_PRIORITIES as $priority => $part) {
$sla = $slas[intval($contract["contract_sla_{$part}_id"])] ?? null; ?>
<tr>
<td class="ps-0" style="width: 7rem;"><?= ticketPriorityHtml($priority, 'detail') ?></td>
<td>
<?php if ($sla) { ?>
<span class="fw-semibold"><?= escapeHtml($sla['sla_name']) ?></span><?= $sla['sla_archived_at'] ? ' <span class="badge text-bg-secondary">Archived</span>' : '' ?>
<div class="small text-body-secondary"><?= escapeHtml(contractSlaTargets($sla)) ?></div>
<?php } else { ?>
<span class="text-body-secondary">The client's usual SLA</span>
<?php } ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header"><h3 class="card-title mb-0"><i class="fas fa-fw fa-file-alt text-secondary me-2"></i>Terms</h3></div>
<div class="card-body">
<?php if (trim(strip_tags((string) $contract['contract_details'])) !== '') { ?>
<div class="prettyContent" style="overflow-wrap: anywhere;"><?= documentHtmlPurify((string) $contract['contract_details']) ?></div>
<?php } else { ?>
<div class="small text-body-secondary">No terms written down.<?php if ($can_edit) { ?> <a class="ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/contract/contract_edit.php?id=<?= $contract_id ?>">Add them</a><?php } ?></div>
<?php } ?>
</div>
</div>
<?php if (trim((string) $contract['contract_notes']) !== '') { ?>
<div class="card mb-3">
<div class="card-header"><h3 class="card-title mb-0"><i class="fas fa-fw fa-sticky-note text-secondary me-2"></i>Notes</h3></div>
<div class="card-body"><div style="white-space: pre-wrap;"><?= escapeHtml($contract['contract_notes']) ?></div></div>
</div>
<?php } ?>
</div>
</div>
<?php }
require_once "../includes/footer.php";

287
agent/contracts.php Normal file
View File

@@ -0,0 +1,287 @@
<?php
/*
* Contracts - one client's agreements, or every one the agent can see. Along
* the top, how many are in force, how many end soon without renewing, how
* many renew soon (a chance to review them with the client) and the drafts.
* Tabs: Active (the default), Due soon (within a month of their notice
* date), Drafts, Ended (ended or cancelled) and All. The work is in
* functions/contract.php; the handlers are agent/post/contract.php.
*/
// Default Column Sortby/Order Filter
$sort = "contract_end_date";
$order = "ASC";
// 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_query = "AND contract_client_id = $client_id";
$client_url = "client_id=$client_id&";
} else {
require_once "includes/inc_all.php";
$client_query = '';
$client_url = '';
}
enforceUserPermission('module_sales');
$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 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 '<a class="text-reset text-decoration-none" href="?' . escapeHtml($url_query_strings_sort) . '&amp;sort=' . $column . '&amp;order=' . $disp . '">'
. $label . ($sort === $column ? " $order_icon" : '') . '</a>';
};
$add_url = 'modals/contract/contract_add.php' . ($client_url ? "?client_id=$client_id" : '');
$csrf = $_SESSION['csrf_token'];
?>
<div class="row g-3 mb-3">
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $view === 'active' ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['show' => 'active'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-check-circle me-1"></i>In force</div>
<div class="itflow-billing-stat-value"><?= intval($stats['active']) ?></div>
<div class="itflow-billing-stat-note">Active contracts</div>
</a>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $view === 'soon' ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['show' => 'soon'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-exclamation-triangle me-1"></i>Ending soon</div>
<div class="itflow-billing-stat-value <?= $stats['ending'] ? 'text-warning-emphasis' : '' ?>"><?= intval($stats['ending']) ?></div>
<div class="itflow-billing-stat-note">Won't renew themselves</div>
</a>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat" href="<?= escapeHtml($filter_url(['show' => 'soon'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-sync-alt me-1"></i>Renewing soon</div>
<div class="itflow-billing-stat-value"><?= intval($stats['renewing']) ?></div>
<div class="itflow-billing-stat-note">Time to review them with the client</div>
</a>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $view === 'draft' ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['show' => 'draft'])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-pencil-alt me-1"></i>Drafts</div>
<div class="itflow-billing-stat-value"><?= intval($stats['draft']) ?></div>
<div class="itflow-billing-stat-note">Not in force yet</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-fw fa-file-contract me-2"></i>Contracts</h3>
<div class="card-tools">
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-size="lg" data-modal-url="<?= escapeHtml($add_url) ?>"><i class="fas fa-plus"></i><span class="d-none d-lg-inline ms-2">New Contract</span></button>
<?php } ?>
</div>
</div>
<div class="card-header py-3">
<form autocomplete="off">
<?php if ($client_url) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } ?>
<input type="hidden" name="show" value="<?= escapeHtml($view) ?>">
<div class="row g-2 align-items-center">
<div class="<?= $client_url ? 'col-lg-8' : 'col-lg-6' ?> 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 contracts..." title="Name, client, support hours or notes">
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
</div>
</div>
<div class="<?= $client_url ? 'col-lg-4' : 'col-lg-3' ?> col-md-6">
<select class="form-select select2" name="type" onchange="this.form.submit()" aria-label="Type">
<option value="">- Any type -</option>
<?php foreach (CONTRACT_TYPES as $key => $type) { ?>
<option value="<?= $key ?>" <?= $type_filter === $key ? 'selected' : '' ?> data-icon="fas <?= $type['icon'] ?>"><?= escapeHtml($type['label']) ?></option>
<?php } ?>
</select>
</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
if (contractsReady()) {
$sql_clients_filter = mysqli_query($mysqli, "SELECT DISTINCT client_id, client_name, client_abbreviation FROM clients
JOIN contracts ON contract_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>
<?php } ?>
</div>
</form>
<nav class="nav nav-pills itflow-asset-tabs mt-2 flex-nowrap overflow-auto">
<?php foreach ($views as $key => $v) {
$alarm = $key === 'soon' && $counts[$key]; ?>
<a class="nav-link text-nowrap <?= $view === $key ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['show' => $key])) ?>"<?= !empty($v['title']) ? ' title="' . escapeHtml($v['title']) . '"' : '' ?>>
<?php if ($v['icon'] !== '') { ?><i class="fas fa-fw <?= $v['icon'] ?> me-1"></i><?php } ?><?= $v['label'] ?>
<span class="badge rounded-pill ms-1 <?= $alarm ? 'text-bg-warning' : '' ?>"><?= $counts[$key] ?></span>
</a>
<?php } ?>
</nav>
</div>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead class="<?= $num_rows[0] ? '' : 'd-none' ?> text-nowrap table-light">
<tr>
<th class="ps-3"><?= $sort_link('contract_name', 'Contract') ?></th>
<?php if (!$client_url) { ?>
<th><?= $sort_link('client_name', 'Client') ?></th>
<?php } ?>
<th class="d-none d-md-table-cell"><?= $sort_link('contract_start_date', 'Term') ?></th>
<th><?= $sort_link('contract_end_date', 'Renewal') ?></th>
<th class="d-none d-xl-table-cell"><?= $sort_link('owner_name', 'Owner') ?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($contracts as $row) {
$contract_id = intval($row['contract_id']);
$row_client_id = intval($row['contract_client_id']);
$row_url = "contract.php?client_id=$row_client_id&contract_id=$contract_id";
$state = contractState($row);
$type = CONTRACT_TYPES[$row['contract_type']] ?? CONTRACT_TYPES['other'];
$notice = contractNoticeDate($row);
?>
<tr data-contract-id="<?= $contract_id ?>">
<td class="ps-3">
<div class="d-flex align-items-center gap-3">
<span class="itflow-asset-icon itflow-asset-tone-other d-none d-sm-inline-flex" aria-hidden="true" title="<?= escapeHtml($type['label']) ?>"><i class="fas fa-fw <?= $type['icon'] ?>"></i></span>
<div class="min-w-0">
<a class="fw-semibold" href="<?= $row_url ?>"><?= escapeHtml($row['contract_name']) ?></a>
<div class="small text-body-secondary"><?= escapeHtml(contractTypeLabel($row['contract_type'])) ?></div>
</div>
</div>
</td>
<?php if (!$client_url) { ?>
<td><a class="text-reset" href="contracts.php?client_id=<?= $row_client_id ?>"><?= escapeHtml($row['client_name']) ?></a></td>
<?php } ?>
<td class="d-none d-md-table-cell text-nowrap small">
<?php if ($row['contract_start_date']) { ?>
<?= escapeHtml(date('M j, Y', strtotime($row['contract_start_date']))) ?><?= $row['contract_end_date'] ? ' - ' . escapeHtml(date('M j, Y', strtotime($row['contract_end_date']))) : '' ?>
<?php } else { ?>
<span class="text-body-tertiary">Not started</span>
<?php } ?>
<div class="text-body-secondary"><?= escapeHtml(contractTermLabel($row['contract_term_months'])) ?><?= intval($row['contract_auto_renew']) ? ', renews itself' : '' ?></div>
</td>
<td class="text-nowrap">
<?= contractStateHtml($row) ?>
<div class="small text-body-secondary"><?= escapeHtml($state['when']) ?></div>
<?php if ($notice !== '' && in_array($state['key'], ['renewing', 'ending', 'active'], true) && $notice >= date('Y-m-d')) { ?>
<div class="small <?= in_array($state['key'], ['renewing', 'ending'], true) ? 'text-warning-emphasis' : 'text-body-tertiary' ?>">Notice by <?= escapeHtml(date('M j, Y', strtotime($notice))) ?></div>
<?php } ?>
</td>
<td class="d-none d-xl-table-cell small"><?= $row['owner_name'] ? escapeHtml($row['owner_name']) : '<span class="text-body-tertiary">No one</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" href="<?= $row_url ?>"><i class="fas fa-fw fa-eye text-secondary me-2"></i>Open</a>
<?php if ($can_edit) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/contract/contract_edit.php?id=<?= $contract_id ?>"><i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit</a>
<?php if ($row['contract_status'] !== 'Draft' && $row['contract_end_date']) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/contract/contract_renew.php?id=<?= $contract_id ?>"><i class="fas fa-fw fa-sync-alt text-secondary me-2"></i>Renew</a>
<?php } ?>
<?php } ?>
<?php if ($can_delete) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_contract=<?= $contract_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-title="Delete <?= escapeHtml($row['contract_name']) ?>?" data-confirm-text="It goes for good. Cancel it instead to keep a record of it." data-confirm-button="Delete">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
</div>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php
$empty_state = [
'thing' => '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";
?>
</div>
<?php require_once "../includes/footer.php";

View File

@@ -29,6 +29,7 @@
'quote.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 @@
</a>
</li>
<li class="nav-item">
<a href="/agent/contracts.php?client_id=<?= $client_id ?>" class="nav-link <?php if (in_array(basename($_SERVER["PHP_SELF"]), ['contracts.php', 'contract.php'], true)) { echo "active"; } ?>">
<i class="nav-icon fas fa-file-contract"></i>
<p>
Contracts
<?php if (!empty($num_contracts)) { ?>
<span class="right badge" title="In force"><?= intval($num_contracts) ?></span>
<?php } ?>
</p>
</a>
</li>
<?php } ?>
<?php if (lookupUserPermission("module_financial") >= 1) { ?>

View File

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

View File

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

View File

@@ -182,6 +182,17 @@
</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/contracts.php" class="nav-link <?php if (in_array(basename($_SERVER["PHP_SELF"]), ['contracts.php', 'contract.php'], true)) { echo "active"; } ?>">
<i class="nav-icon fas fa-file-contract"></i>
<p>
Contracts
<?php if (!empty($num_contracts_soon)) { ?>
<span class="right badge text-bg-warning" data-bs-toggle="tooltip" title="Ending or renewing soon"><?= intval($num_contracts_soon) ?></span>
<?php } ?>
</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/products.php" class="nav-link <?php if (in_array(basename($_SERVER["PHP_SELF"]), ['products.php', 'product.php', 'products_count.php'], true)) { echo "active"; } ?>">
<i class="nav-icon fas fa-box-open"></i>

View File

@@ -0,0 +1,50 @@
<?php
/*
* Make a draft contract active - from the day picked, with an end date from
* its term when it has none.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$contract = contractRow(intval($_GET['id'] ?? 0));
if ($contract) {
$client_id = intval($contract['contract_client_id']);
enforceClientAccess();
}
ob_start();
if (!$contract || $contract['contract_status'] !== 'Draft') { ?>
<div class="modal-body text-center text-secondary py-5"><?= $contract ? 'It is already in force.' : 'That contract is gone - it may have been deleted.' ?></div>
<?php } else {
$start = $contract['contract_start_date'] ?: date('Y-m-d'); ?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-check me-2"></i>Make <strong><?= escapeHtml($contract['contract_name']) ?></strong> active</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="contract_id" value="<?= intval($contract['contract_id']) ?>">
<div class="modal-body">
<label class="form-label">In force from</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="start_date" value="<?= escapeHtml($start) ?>" required>
</div>
<small class="text-secondary">
<?= $contract['contract_end_date'] ? 'It ends on ' . escapeHtml(date('M j, Y', strtotime($contract['contract_end_date']))) . '.' : 'It runs for ' . escapeHtml(contractTermLabel($contract['contract_term_months'])) . ' from then.' ?>
<?= intval($contract['contract_auto_renew']) ? 'Then it renews itself.' : '' ?>
</small>
</div>
<div class="modal-footer">
<button type="submit" name="activate_contract" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Make active</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,46 @@
<?php
/*
* New contract - ?client_id= starts it for that client (without one, the
* client is picked here), and ?copy= starts it as a copy of another
* contract. The fields are contract_form.php.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$form_contract = null;
$form_copy = null;
$form_client_id = intval($_GET['client_id'] ?? 0);
if (!empty($_GET['copy'])) {
$form_copy = contractRow(intval($_GET['copy']));
if ($form_copy) {
$form_client_id = intval($form_copy['contract_client_id']);
}
}
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-contract me-2"></i><?= $form_copy ? 'Copy Contract' : 'New Contract' ?><?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 require __DIR__ . '/contract_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_contract" 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>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -0,0 +1,64 @@
<?php
/*
* Cancel a contract - its last day (it stays in force until then, and won't
* renew) and why. It is kept, under Ended.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$contract = contractRow(intval($_GET['id'] ?? 0));
if ($contract) {
$client_id = intval($contract['contract_client_id']);
enforceClientAccess();
}
ob_start();
if (!$contract || $contract['contract_status'] !== 'Active') { ?>
<div class="modal-body text-center text-secondary py-5"><?= $contract ? 'Only an active contract can be cancelled.' : 'That contract is gone - it may have been deleted.' ?></div>
<?php } else {
$notice = contractNoticeDate($contract);
$last_day = date('Y-m-d');
if ($contract['contract_end_date'] && $notice !== '' && $notice >= date('Y-m-d')) {
$last_day = (string) $contract['contract_end_date'];
} ?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-ban me-2"></i>Cancel <strong><?= escapeHtml($contract['contract_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="contract_id" value="<?= intval($contract['contract_id']) ?>">
<div class="modal-body">
<?php if ($notice !== '') { ?>
<p class="small <?= $notice >= date('Y-m-d') ? 'text-secondary' : 'text-warning-emphasis' ?>">
<i class="fas fa-fw fa-bell me-1"></i><?= intval($contract['contract_notice_days']) ?> days notice - <?= $notice >= date('Y-m-d') ? 'given by ' . escapeHtml(date('M j, Y', strtotime($notice))) . ', it ends on ' . escapeHtml(date('M j, Y', strtotime($contract['contract_end_date']))) . '.' : 'the notice date, ' . escapeHtml(date('M j, Y', strtotime($notice))) . ', has passed.' ?>
</p>
<?php } ?>
<div class="mb-3">
<label class="form-label">Last day in force</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar-times"></i></span>
<input type="date" class="form-control" name="last_day" value="<?= escapeHtml($last_day) ?>" required>
</div>
</div>
<div class="mb-1">
<label class="form-label">Why</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="reason" maxlength="255" placeholder="Moving to another provider, bought out, closing down">
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="cancel_contract" class="btn btn-danger text-bold"><i class="fas fa-ban me-2"></i>Cancel contract</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Keep it</button>
</div>
</form>
<?php }
require_once '../../../includes/modal_footer.php';

View File

@@ -0,0 +1,43 @@
<?php
/*
* Edit a contract. The fields are contract_form.php; making a draft active,
* renewing and cancelling have windows of their own.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$form_contract = contractRow(intval($_GET['id'] ?? 0));
$form_copy = null;
$form_client_id = $form_contract ? intval($form_contract['contract_client_id']) : 0;
if ($form_client_id) {
$client_id = $form_client_id;
enforceClientAccess();
}
ob_start();
if (!$form_contract) { ?>
<div class="modal-body text-center text-secondary py-5">That contract is gone - it may have been deleted.</div>
<?php } else { ?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-file-contract me-2"></i>Contract: <strong><?= escapeHtml($form_contract['contract_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="contract_id" value="<?= intval($form_contract['contract_id']) ?>">
<div class="modal-body">
<?php require __DIR__ . '/contract_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="edit_contract" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save changes</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,307 @@
<?php
/*
* A contract's fields, in tabs - for contract_add.php and contract_edit.php,
* which set $form_contract (a contractRow(), or null when new), $form_copy (a
* contract being copied, or null) and $form_client_id (0 to pick the client
* here). Agreement: the template it starts from, the client, name, type,
* contact, owner, and its term - start, length, end, renewal and notice.
* Cover: support hours, rates, net terms and an SLA for each priority.
* Terms: the agreement's words. Notes: internal. Picking a template fills
* the fields from it, and the end date follows the start and term until it
* is changed (js/contract_form.js). The server checks it all again
* (contractFromInput()).
*/
isset($mysqli) || die("Direct file access is not allowed");
$c = $form_contract ?? $form_copy ?? null;
$c_new = empty($form_contract);
$c_client_id = intval($c['contract_client_id'] ?? $form_client_id);
$c_templates = $c_new ? contractTemplates() : [];
$c_slas = contractSlaChoices($c ? array_map(function ($part) use ($c) { return intval($c["contract_sla_{$part}_id"]); }, CONTRACT_SLA_PRIORITIES) : []);
$c_value = function ($key, $default = '') use ($c) {
return $c !== null && array_key_exists("contract_$key", $c) && $c["contract_$key"] !== null ? $c["contract_$key"] : $default;
};
$c_start = $c_new ? date('Y-m-d') : (string) $c_value('start_date');
$c_term = intval($c_value('term_months', 12));
$c_end = $c_new ? contractTermEnd($c_start, $c_term) : (string) $c_value('end_date');
$c_money = function ($value) {
return $value === '' || $value === null ? '' : number_format((float) $value, 2, '.', '');
};
// The clients to pick from, and their contacts - shown for the client picked
$c_clients = [];
$c_contacts = [];
$client_where = $c_client_id ? "client_id = $c_client_id" : "client_archived_at IS NULL " . clientScopeSql('clients.client_id');
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, client_rate, client_net_terms FROM clients WHERE $client_where ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$c_clients[intval($row['client_id'])] = $row;
}
if ($c_clients) {
$sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_title, contact_client_id, contact_primary FROM contacts
WHERE contact_client_id IN (" . implode(',', array_keys($c_clients)) . ") AND (contact_archived_at IS NULL OR contact_id = " . intval($c_value('contact_id', 0)) . ")
ORDER BY contact_primary DESC, contact_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$c_contacts[] = $row;
}
}
$c_contact_id = intval($c_value('contact_id', 0));
if ($c_new && !$c_contact_id && $c_client_id) {
foreach ($c_contacts as $contact) {
if (intval($contact['contact_primary']) === 1 && intval($contact['contact_client_id']) === $c_client_id) {
$c_contact_id = intval($contact['contact_id']);
break;
}
}
}
$c_owner_id = intval($c_value('owner_id', $c_new ? ($session_user_id ?? 0) : 0));
$c_owners = [];
$sql = mysqli_query($mysqli, "SELECT user_id, user_name FROM users WHERE user_type = 1 AND (user_archived_at IS NULL OR user_id = $c_owner_id) ORDER BY user_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$c_owners[intval($row['user_id'])] = $row['user_name'];
}
// The templates, for filling the fields from one
$c_template_data = [];
foreach ($c_templates as $template_id => $template) {
$c_template_data[$template_id] = [
'name' => $template['contract_template_name'], 'type' => $template['contract_template_type'], 'term_months' => intval($template['contract_template_term_months']),
'auto_renew' => intval($template['contract_template_auto_renew']), 'notice_days' => intval($template['contract_template_notice_days']),
'rate_standard' => $c_money($template['contract_template_rate_standard']), 'rate_after_hours' => $c_money($template['contract_template_rate_after_hours']),
'net_terms' => $template['contract_template_net_terms'] === null ? '' : intval($template['contract_template_net_terms']), 'support_hours' => (string) $template['contract_template_support_hours'],
'details' => documentHtmlPurify((string) $template['contract_template_details']),
];
foreach (CONTRACT_SLA_PRIORITIES as $part) {
$c_template_data[$template_id]["sla_$part"] = intval($template["contract_template_sla_{$part}_id"]);
}
}
$tab = 'contractTab' . bin2hex(random_bytes(3));
?>
<div data-contract-form>
<?php if ($c_template_data) { ?>
<script type="application/json" data-contract-templates><?= json_encode($c_template_data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?></script>
<?php } ?>
<ul class="nav nav-pills nav-justified mb-3" role="tablist">
<li class="nav-item"><a class="nav-link active" data-bs-toggle="pill" href="#<?= $tab ?>Agreement" role="tab"><i class="fas fa-fw fa-file-contract me-1"></i>Agreement</a></li>
<li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#<?= $tab ?>Cover" role="tab"><i class="fas fa-fw fa-shield-alt me-1"></i>Cover</a></li>
<li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#<?= $tab ?>Terms" role="tab"><i class="fas fa-fw fa-file-alt me-1"></i>Terms</a></li>
<li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#<?= $tab ?>Notes" role="tab"><i class="fas fa-fw fa-sticky-note me-1"></i>Notes</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade show active" id="<?= $tab ?>Agreement" role="tabpanel">
<?php if ($c_template_data) { ?>
<div class="mb-3">
<label class="form-label">Start from a template</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-clone"></i></span>
<select class="form-select" name="template_id" data-contract-template>
<option value="0">- None -</option>
<?php foreach ($c_templates as $template_id => $template) { ?>
<option value="<?= $template_id ?>"<?= intval($c_value('template_id', 0)) === $template_id ? ' selected' : '' ?>><?= escapeHtml($template['contract_template_name']) ?></option>
<?php } ?>
</select>
</div>
<small class="text-secondary">Fills in the type, term, cover and terms from it - change any of them after.</small>
</div>
<?php } else { ?>
<input type="hidden" name="template_id" value="<?= intval($c_value('template_id', 0)) ?>">
<?php } ?>
<?php if (count($c_clients) > 1 || !$c_client_id) { ?>
<div class="mb-3">
<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-user"></i></span>
<select class="form-select select2" name="client_id" required data-contract-client>
<option value="">- Pick a client -</option>
<?php foreach ($c_clients as $client_option_id => $client_option) { ?>
<option value="<?= $client_option_id ?>"<?= selectOptionClient($client_option_id, $client_option['client_name'], $client_option['client_abbreviation'] ?? '') ?>><?= escapeHtml($client_option['client_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<?php } else { ?>
<input type="hidden" name="client_id" value="<?= $c_client_id ?>" data-contract-client>
<?php } ?>
<div class="row g-3 mb-3">
<div class="col-md-7">
<label class="form-label">Name <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<input type="text" class="form-control" name="name" maxlength="255" placeholder="Managed Services Agreement" value="<?= escapeHtml($form_copy ? $c_value('name') . ' (copy)' : $c_value('name')) ?>" required<?= $c_new ? ' autofocus' : '' ?> data-contract-field="name">
</div>
</div>
<div class="col-md-5">
<label class="form-label">Type</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-layer-group"></i></span>
<select class="form-select" name="type" data-contract-field="type">
<?php foreach (CONTRACT_TYPES as $key => $type) { ?>
<option value="<?= $key ?>"<?= $c_value('type', 'managed') === $key ? ' selected' : '' ?> title="<?= escapeHtml($type['about']) ?>"><?= escapeHtml($type['label']) ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="row g-3 mb-3">
<div class="col-md-6">
<label class="form-label">Contact at the client</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-address-card"></i></span>
<select class="form-select" name="contact_id" data-contract-contact>
<option value="0">- None -</option>
<?php foreach ($c_contacts as $contact) { ?>
<option value="<?= intval($contact['contact_id']) ?>" data-client="<?= intval($contact['contact_client_id']) ?>"<?= intval($contact['contact_id']) === $c_contact_id ? ' selected' : '' ?><?= $c_client_id && intval($contact['contact_client_id']) !== $c_client_id ? ' hidden' : '' ?>><?= escapeHtml($contact['contact_name'] . ($contact['contact_title'] ? " - {$contact['contact_title']}" : '')) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-md-6">
<label class="form-label">Owner</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user-tie"></i></span>
<select class="form-select" name="owner_id">
<option value="0">- No one -</option>
<?php foreach ($c_owners as $user_id => $user_name) { ?>
<option value="<?= $user_id ?>"<?= $user_id === $c_owner_id ? ' selected' : '' ?>><?= escapeHtml($user_name) ?></option>
<?php } ?>
</select>
</div>
<small class="text-secondary">Reminded before it renews or ends.</small>
</div>
</div>
<?php if ($c_new) { ?>
<div class="mb-3">
<label class="form-label">Status</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-flag"></i></span>
<select class="form-select" name="status">
<option value="Active">Active - in force from its start date</option>
<option value="Draft">Draft - not in force yet</option>
</select>
</div>
</div>
<?php } ?>
<div class="row g-3 mb-3">
<div class="col-md-4">
<label class="form-label">Starts</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="start_date" value="<?= escapeHtml($c_start) ?>" data-contract-start>
</div>
</div>
<div class="col-md-4">
<label class="form-label">Term</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-history"></i></span>
<select class="form-select" name="term_months" data-contract-field="term_months" data-contract-term>
<?php $terms = CONTRACT_TERMS + ($c_term && !isset(CONTRACT_TERMS[$c_term]) ? [$c_term => contractTermLabel($c_term)] : []);
ksort($terms);
foreach ($terms as $months => $label) { ?>
<option value="<?= $months ?>"<?= $months === $c_term ? ' selected' : '' ?>><?= escapeHtml($label) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-md-4">
<label class="form-label">Ends</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar-check"></i></span>
<input type="date" class="form-control" name="end_date" value="<?= escapeHtml($c_end) ?>" data-contract-end<?= $c_new ? '' : ' data-touched="1"' ?>>
</div>
</div>
</div>
<div class="row g-3 align-items-end">
<div class="col-md-6">
<div class="form-check form-switch mb-2">
<input class="form-check-input" type="checkbox" role="switch" name="auto_renew" value="1" id="<?= $tab ?>AutoRenew"<?= intval($c_value('auto_renew', 1)) ? ' checked' : '' ?> data-contract-field="auto_renew">
<label class="form-check-label" for="<?= $tab ?>AutoRenew">Renews itself for another term</label>
</div>
</div>
<div class="col-md-6">
<label class="form-label">Notice to end it</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-bell"></i></span>
<input type="number" class="form-control" name="notice_days" min="0" max="365" value="<?= intval($c_value('notice_days', 30)) ?>" data-contract-field="notice_days">
<span class="input-group-text">days</span>
</div>
</div>
</div>
<small class="text-secondary d-block mt-2" data-contract-notice-note></small>
</div>
<div class="tab-pane fade" id="<?= $tab ?>Cover" role="tabpanel">
<div class="mb-3">
<label class="form-label">Support hours</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-business-time"></i></span>
<input type="text" class="form-control" name="support_hours" maxlength="100" placeholder="Mon-Fri 8am-6pm, emergencies 24/7" value="<?= escapeHtml($c_value('support_hours')) ?>" data-contract-field="support_hours">
</div>
</div>
<div class="row g-3 mb-3">
<div class="col-md-4">
<label class="form-label">Hourly rate</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" inputmode="decimal" class="form-control" name="rate_standard" placeholder="The client's" value="<?= escapeHtml($c_money($c_value('rate_standard', ''))) ?>" data-contract-field="rate_standard">
</div>
</div>
<div class="col-md-4">
<label class="form-label">After hours</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-moon"></i></span>
<input type="text" inputmode="decimal" class="form-control" name="rate_after_hours" placeholder="None" value="<?= escapeHtml($c_money($c_value('rate_after_hours', ''))) ?>" data-contract-field="rate_after_hours">
</div>
</div>
<div class="col-md-4">
<label class="form-label">Net terms</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="number" class="form-control" name="net_terms" min="0" max="365" placeholder="The client's" value="<?= escapeHtml((string) $c_value('net_terms', '')) ?>" data-contract-field="net_terms">
<span class="input-group-text">days</span>
</div>
</div>
</div>
<small class="text-secondary d-block mb-3">Leave a rate or the net terms empty and the client's own apply.</small>
<label class="form-label">SLA by ticket priority</label>
<?php foreach (CONTRACT_SLA_PRIORITIES as $priority => $part) { ?>
<div class="input-group mb-2">
<span class="input-group-text" style="width: 7rem;"><i class="fa fa-fw fa-stopwatch me-2"></i><?= $priority ?></span>
<select class="form-select" name="sla_<?= $part ?>" data-contract-field="sla_<?= $part ?>" aria-label="<?= $priority ?> priority SLA">
<option value="0">The client's usual SLA</option>
<?php foreach ($c_slas as $sla_id => $sla) { ?>
<option value="<?= $sla_id ?>"<?= intval($c_value("sla_{$part}_id", 0)) === $sla_id ? ' selected' : '' ?>><?= escapeHtml($sla['sla_name'] . ' - ' . contractSlaTargets($sla)) ?><?= $sla['sla_archived_at'] ? ' (archived)' : '' ?></option>
<?php } ?>
</select>
</div>
<?php } ?>
<small class="text-secondary">From Admin > SLAs.</small>
</div>
<div class="tab-pane fade" id="<?= $tab ?>Terms" role="tabpanel">
<textarea class="form-control tinymce" name="details" rows="12" aria-label="Terms" data-contract-field="details"><?= escapeHtml(documentHtmlPurify((string) $c_value('details'))) ?></textarea>
</div>
<div class="tab-pane fade" id="<?= $tab ?>Notes" role="tabpanel">
<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="notes" rows="8" maxlength="10000" placeholder="For your team - what was agreed, who to talk to about renewing"><?= escapeHtml($c_value('notes')) ?></textarea>
</div>
<small class="text-secondary">Only agents see these.</small>
</div>
</div>
</div>
<script src="/js/contract_form.js"></script>

View File

@@ -0,0 +1,55 @@
<?php
/*
* Renew a contract - to a new last day, another term on from its end (or
* from today, for one that ended a while ago). An ended or cancelled
* contract is active again.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
$contract = contractRow(intval($_GET['id'] ?? 0));
if ($contract) {
$client_id = intval($contract['contract_client_id']);
enforceClientAccess();
}
ob_start();
if (!$contract || $contract['contract_status'] === 'Draft' || !$contract['contract_end_date']) { ?>
<div class="modal-body text-center text-secondary py-5"><?= $contract ? 'Only a contract with an end date can be renewed - a draft is made active first.' : 'That contract is gone - it may have been deleted.' ?></div>
<?php } else {
$end = (string) $contract['contract_end_date'];
$from = $end >= date('Y-m-d', strtotime('-1 day')) ? $end : date('Y-m-d', strtotime('-1 day'));
$new_end = contractNextEnd($from, $contract['contract_term_months']); ?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-sync-alt me-2"></i>Renew <strong><?= escapeHtml($contract['contract_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="contract_id" value="<?= intval($contract['contract_id']) ?>">
<div class="modal-body">
<p class="mb-3">
<?= contractStateHtml($contract) ?>
It <?= $end >= date('Y-m-d') ? 'ends' : 'ended' ?> on <?= escapeHtml(date('M j, Y', strtotime($end))) ?>.
<?= in_array($contract['contract_status'], ['Ended', 'Cancelled'], true) ? 'Renewing makes it active again.' : '' ?>
</p>
<label class="form-label">New last day</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar-check"></i></span>
<input type="date" class="form-control" name="end_date" value="<?= escapeHtml($new_end) ?>" min="<?= escapeHtml(date('Y-m-d')) ?>" required>
</div>
<small class="text-secondary">Another <?= escapeHtml(contractTermLabel($contract['contract_term_months'])) ?>. Its owner is reminded again before this one ends.</small>
</div>
<div class="modal-footer">
<button type="submit" name="renew_contract" class="btn btn-primary text-bold"><i class="fas fa-sync-alt me-2"></i>Renew</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

@@ -331,6 +331,7 @@ if (isset($_GET['delete_client'])) {
}
mysqli_query($mysqli, "DELETE FROM tickets WHERE ticket_client_id = $client_id");
mysqli_query($mysqli, "DELETE FROM trips WHERE trip_client_id = $client_id");
mysqli_query($mysqli, "DELETE FROM contracts WHERE contract_client_id = $client_id");
mysqli_query($mysqli, "DELETE FROM vendors WHERE vendor_client_id = $client_id");
//Delete Client Files

141
agent/post/contract.php Normal file
View File

@@ -0,0 +1,141 @@
<?php
/*
* ITFlow - contracts: add, change, copy (through add), make a draft active,
* renew, cancel and delete. Needs Sales - to change, or to delete. The work
* is in functions/contract.php.
*/
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
/* The contract posted, after the checks every action makes - or a flash and back. */
function contractPostRow($id) {
global $client_id;
$row = contractRow($id);
if (!$row) {
flashAlert("That contract is gone - it may have been deleted.", 'error');
redirect();
}
$client_id = intval($row['contract_client_id']);
enforceClientAccess();
return $row;
}
if (isset($_POST['add_contract']) || isset($_POST['edit_contract'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$row = isset($_POST['edit_contract']) ? contractPostRow($_POST['contract_id'] ?? 0) : null;
$input = $_POST;
if ($row) {
// A contract stays with its client, and in its status - those change through their own actions
$input['client_id'] = $row['contract_client_id'];
$input['status'] = $row['contract_status'] === 'Draft' ? 'Draft' : 'Active';
}
[$fields, $error] = contractFromInput($input, 'contract');
if ($error !== '') {
flashAlert(escapeHtml($error) . ' The contract was not saved.', 'error');
redirect();
}
$client_id = $fields['client_id'];
enforceClientAccess();
if ($row) {
$contract_id = intval($row['contract_id']);
$changes = contractUpdate($row, $fields);
if ($changes) {
logAudit("Contract", "Edit", "$session_name changed contract " . escapeSql($row['contract_name']) . ": " . escapeSql(implode('; ', $changes)), $client_id, $contract_id);
}
flashAlert("Contract <strong>" . escapeHtml($fields['name']) . "</strong> saved");
} else {
$contract_id = contractCreate($fields);
logAudit("Contract", "Create", "$session_name added " . strtolower($fields['status']) . " contract " . escapeSql($fields['name']) . " (" . escapeSql(contractTypeLabel($fields['type'])) . ")"
. ($fields['start_date'] !== '' ? " from " . escapeSql($fields['start_date']) : '') . ($fields['end_date'] !== '' ? " to " . escapeSql($fields['end_date']) : ''), $client_id, $contract_id);
flashAlert("Contract <strong>" . escapeHtml($fields['name']) . "</strong> added" . ($fields['status'] === 'Draft' ? ' as a draft' : ''));
redirect("contract.php?client_id=$client_id&contract_id=$contract_id");
}
redirect();
}
if (isset($_POST['activate_contract'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$row = contractPostRow($_POST['contract_id'] ?? 0);
$start = trim((string) ($_POST['start_date'] ?? ''));
if ($row['contract_status'] !== 'Draft' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $start) || !strtotime($start)) {
flashAlert("Pick the day it is in force from.", 'error');
redirect();
}
if ($row['contract_end_date'] && $row['contract_end_date'] < $start) {
flashAlert("It ends before that day - change its end date first.", 'error');
redirect();
}
$end = contractActivate($row, $start);
logAudit("Contract", "Edit", "$session_name made contract " . escapeSql($row['contract_name']) . " active from " . escapeSql($start) . ($end !== '' ? " to " . escapeSql($end) : ''), $client_id, intval($row['contract_id']));
flashAlert("Contract <strong>" . escapeHtml($row['contract_name']) . "</strong> is active");
redirect();
}
if (isset($_POST['renew_contract'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$row = contractPostRow($_POST['contract_id'] ?? 0);
$end = trim((string) ($_POST['end_date'] ?? ''));
if ($row['contract_status'] === 'Draft' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $end) || !strtotime($end) || $end < date('Y-m-d') || ($row['contract_end_date'] && $end <= $row['contract_end_date'])) {
flashAlert("Pick a new last day - after its current one, and not in the past.", 'error');
redirect();
}
contractRenew($row, $end);
logAudit("Contract", "Edit", "$session_name renewed contract " . escapeSql($row['contract_name']) . " to " . escapeSql($end), $client_id, intval($row['contract_id']));
flashAlert("Contract <strong>" . escapeHtml($row['contract_name']) . "</strong> renewed to " . date('M j, Y', strtotime($end)));
redirect();
}
if (isset($_POST['cancel_contract'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$row = contractPostRow($_POST['contract_id'] ?? 0);
$last_day = trim((string) ($_POST['last_day'] ?? ''));
$reason = mb_substr(trim(strip_tags((string) ($_POST['reason'] ?? ''))), 0, 255);
if ($row['contract_status'] !== 'Active' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $last_day) || !strtotime($last_day)
|| ($row['contract_start_date'] && $last_day < $row['contract_start_date'])) {
flashAlert("Pick its last day - not before it started.", 'error');
redirect();
}
contractCancel($row, $last_day, $reason);
logAudit("Contract", "Edit", "$session_name cancelled contract " . escapeSql($row['contract_name']) . ", last day " . escapeSql($last_day) . ($reason !== '' ? " - " . escapeSql($reason) : ''), $client_id, intval($row['contract_id']));
flashAlert("Contract <strong>" . escapeHtml($row['contract_name']) . "</strong> cancelled" . ($last_day >= date('Y-m-d') ? " - in force until " . date('M j, Y', strtotime($last_day)) : ''), 'error');
redirect();
}
if (isset($_GET['delete_contract'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 3);
$row = contractPostRow($_GET['delete_contract']);
mysqli_query($mysqli, "DELETE FROM contracts WHERE contract_id = " . intval($row['contract_id']));
logAudit("Contract", "Delete", "$session_name deleted contract " . escapeSql($row['contract_name']), $client_id, intval($row['contract_id']));
flashAlert("Contract <strong>" . escapeHtml($row['contract_name']) . "</strong> deleted", 'error');
redirect("contracts.php?client_id=$client_id");
}

View File

@@ -226,6 +226,12 @@ if ($config_whitelabel_enabled && !validateWhitelabelKey($config_whitelabel_key)
}
// CONTRACTS - renew the ones that renew themselves, end the ones that don't, and remind owners before the notice date
$contracts_done = contractsNightly();
if (array_sum($contracts_done)) {
logApp("Cron", "info", "Contracts: {$contracts_done['renewed']} renewed, {$contracts_done['ended']} ended, {$contracts_done['reminded']} owner(s) reminded");
}
// GET NOTIFICATIONS
// DOMAINS EXPIRING

43
db.sql
View File

@@ -1051,21 +1051,21 @@ CREATE TABLE `contract_templates` (
`contract_template_name` varchar(255) NOT NULL,
`contract_template_description` text DEFAULT NULL,
`contract_template_type` varchar(50) DEFAULT NULL,
`contract_template_sla_low_response_time` int(11) DEFAULT NULL,
`contract_template_sla_low_resolution_time` int(11) DEFAULT NULL,
`contract_template_sla_medium_response_time` int(11) DEFAULT NULL,
`contract_template_sla_medium_resolution_time` int(11) DEFAULT NULL,
`contract_template_sla_high_response_time` int(11) DEFAULT NULL,
`contract_template_sla_high_resolution_time` int(11) DEFAULT NULL,
`contract_template_rate_standard` decimal(10,2) DEFAULT NULL,
`contract_template_rate_after_hours` decimal(10,2) DEFAULT NULL,
`contract_template_net_terms` varchar(50) DEFAULT NULL,
`contract_template_net_terms` int(11) DEFAULT NULL,
`contract_template_support_hours` varchar(100) DEFAULT NULL,
`contract_template_renewal_frequency` varchar(50) DEFAULT NULL,
`contract_template_details` text DEFAULT NULL,
`contract_template_created_at` datetime DEFAULT current_timestamp(),
`contract_template_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(),
`contract_template_archived_at` datetime DEFAULT NULL,
`contract_template_term_months` int(11) NOT NULL DEFAULT 12,
`contract_template_auto_renew` tinyint(1) NOT NULL DEFAULT 1,
`contract_template_notice_days` int(11) NOT NULL DEFAULT 30,
`contract_template_sla_low_id` int(11) NOT NULL DEFAULT 0,
`contract_template_sla_medium_id` int(11) NOT NULL DEFAULT 0,
`contract_template_sla_high_id` int(11) NOT NULL DEFAULT 0,
`contract_template_sla_urgent_id` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`contract_template_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -1082,12 +1082,6 @@ CREATE TABLE `contracts` (
`contract_name` varchar(255) NOT NULL,
`contract_status` varchar(50) NOT NULL,
`contract_type` varchar(50) NOT NULL,
`contract_sla_low_response_time` int(11) DEFAULT NULL,
`contract_sla_low_resolution_time` int(11) DEFAULT NULL,
`contract_sla_medium_response_time` int(11) DEFAULT NULL,
`contract_sla_medium_resolution_time` int(11) DEFAULT NULL,
`contract_sla_high_response_time` int(11) DEFAULT NULL,
`contract_sla_high_resolution_time` int(11) DEFAULT NULL,
`contract_details` text DEFAULT NULL,
`contract_client_id` int(11) DEFAULT NULL,
`contract_client_name` varchar(255) DEFAULT NULL,
@@ -1102,17 +1096,32 @@ CREATE TABLE `contracts` (
`contract_agent_signature_date` datetime DEFAULT NULL,
`contract_rate_standard` decimal(10,2) DEFAULT NULL,
`contract_rate_after_hours` decimal(10,2) DEFAULT NULL,
`contract_net_terms` varchar(50) DEFAULT NULL,
`contract_net_terms` int(11) DEFAULT NULL,
`contract_support_hours` varchar(100) DEFAULT NULL,
`contract_start_date` date DEFAULT NULL,
`contract_end_date` date DEFAULT NULL,
`contract_renewal_frequency` varchar(50) DEFAULT NULL,
`contract_created_at` datetime DEFAULT current_timestamp(),
`contract_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(),
`contract_archived_at` datetime DEFAULT NULL,
`contract_term_months` int(11) NOT NULL DEFAULT 12,
`contract_auto_renew` tinyint(1) NOT NULL DEFAULT 1,
`contract_notice_days` int(11) NOT NULL DEFAULT 30,
`contract_sla_low_id` int(11) NOT NULL DEFAULT 0,
`contract_sla_medium_id` int(11) NOT NULL DEFAULT 0,
`contract_sla_high_id` int(11) NOT NULL DEFAULT 0,
`contract_sla_urgent_id` int(11) NOT NULL DEFAULT 0,
`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,
PRIMARY KEY (`contract_id`),
KEY `contract_client_id` (`contract_client_id`),
CONSTRAINT `contracts_ibfk_1` FOREIGN KEY (`contract_client_id`) REFERENCES `clients` (`client_id`)
CONSTRAINT `contracts_ibfk_1` FOREIGN KEY (`contract_client_id`) REFERENCES `clients` (`client_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

View File

@@ -78,6 +78,7 @@ require_once __DIR__ . '/functions/client_export.php';
require_once __DIR__ . '/functions/share.php';
require_once __DIR__ . '/functions/billing.php';
require_once __DIR__ . '/functions/payment_method.php';
require_once __DIR__ . '/functions/contract.php';
require_once __DIR__ . '/functions/products.php';
require_once __DIR__ . '/functions/billing_email.php';
require_once __DIR__ . '/functions/billing_pay.php';

View File

@@ -48,6 +48,7 @@ function auditLogKinds() {
'Project' => ['icon' => 'fa-project-diagram', 'module' => 'module_support', 'table' => 'projects', 'id' => 'project_id', 'name' => "CONCAT(project_prefix, project_number, ' - ', project_name)", 'client' => 'project_client_id', 'url' => '/agent/project.php?{client_q}project_id={id}'],
'Quote' => ['icon' => 'fa-comment-dollar', 'module' => 'module_sales', 'table' => 'quotes', 'id' => 'quote_id', 'name' => "CONCAT(quote_prefix, quote_number)", 'client' => 'quote_client_id', 'url' => '/agent/quote.php?quote_id={id}'],
'Invoice' => ['icon' => 'fa-file-invoice', 'module' => 'module_sales', 'table' => 'invoices', 'id' => 'invoice_id', 'name' => "CONCAT(invoice_prefix, invoice_number)", 'client' => 'invoice_client_id', 'url' => '/agent/invoice.php?invoice_id={id}'],
'Contract' => ['icon' => 'fa-file-contract', 'module' => 'module_sales', 'table' => 'contracts', 'id' => 'contract_id', 'name' => 'contract_name', 'client' => 'contract_client_id', 'url' => '/agent/contract.php?contract_id={id}'],
'Recurring Invoice' => ['icon' => 'fa-redo-alt', 'module' => 'module_sales', 'table' => 'recurring_invoices', 'id' => 'recurring_invoice_id', 'name' => "CONCAT(recurring_invoice_prefix, recurring_invoice_number)", 'client' => 'recurring_invoice_client_id', 'url' => '/agent/recurring_invoice.php?recurring_invoice_id={id}'],
'Product' => ['icon' => 'fa-box-open', 'module' => 'module_sales', 'table' => 'products', 'id' => 'product_id', 'name' => 'product_name', 'url' => '/agent/product.php?product_id={id}'],
'Expense' => ['icon' => 'fa-shopping-cart', 'module' => 'module_financial', 'table' => 'expenses', 'id' => 'expense_id', 'name' => 'expense_description', 'client' => 'expense_client_id', 'url' => '/agent/expenses.php?open={id}'],

View File

@@ -77,6 +77,22 @@ function clientOverviewAttention($client_id, $access, $renewals) {
'detail' => $overdue_count ? dashboardMoney($overdue_amount) . ' outstanding' : null,
'url' => "/agent/invoices.php?client_id=$client_id&status=Overdue",
];
// A contract coming up to its notice date - the same rule as contracts.php?show=soon
if (contractsReady()) {
$soon = contractViews()['soon']['where'];
$items[] = [
'count' => dashboardCount("SELECT COUNT(contract_id) FROM contracts WHERE contract_client_id = $client_id AND contract_archived_at IS NULL AND $soon AND contract_auto_renew = 0"),
'label' => 'Contracts ending', 'icon' => 'file-contract', 'tone' => 'warning',
'detail' => "They don't renew themselves",
'url' => "/agent/contracts.php?client_id=$client_id&show=soon",
];
$items[] = [
'count' => dashboardCount("SELECT COUNT(contract_id) FROM contracts WHERE contract_client_id = $client_id AND contract_archived_at IS NULL AND $soon AND contract_auto_renew = 1"),
'label' => 'Contracts renewing', 'icon' => 'sync-alt', 'tone' => 'info',
'detail' => 'Time to review them with the client',
'url' => "/agent/contracts.php?client_id=$client_id&show=soon",
];
}
if ($access['tickets']) {
$items[] = [
'count' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE " . billingUnbilledSql() . " AND ticket_client_id = $client_id"),

577
functions/contract.php Normal file
View File

@@ -0,0 +1,577 @@
<?php
/*
* Client contracts - the agreement with each client: what kind it is, when
* it starts and ends, whether it renews itself and how much notice ending it
* takes, the SLA for each ticket priority (from Admin > SLAs), the hourly
* rates, net terms and support hours, and who looks after it. A contract is
* a Draft until it is made Active; the nightly job (contractsNightly())
* renews an auto-renewing one when its term ends, ends one that doesn't, and
* reminds its owner before the notice date comes. Cancelled ones are kept.
*
* Templates (Admin > Contract Templates) hold the same terms, to start a
* contract from. agent/contracts.php, agent/contract.php and their windows
* and handlers (agent/post/contract.php) are built on these.
*/
/** The kinds of contract - key => label, icon and what it means. */
const CONTRACT_TYPES = [
'managed' => ['label' => 'Fully managed', 'icon' => 'fa-shield-alt', 'about' => 'A fixed monthly fee covers support and looking after everything'],
'comanaged' => ['label' => 'Co-managed', 'icon' => 'fa-handshake', 'about' => 'Shared with the client\'s own IT people'],
'block' => ['label' => 'Block hours', 'icon' => 'fa-hourglass-half', 'about' => 'Hours paid for up front, drawn down as work is done'],
'time_materials' => ['label' => 'Time and materials', 'icon' => 'fa-clock', 'about' => 'Billed for the time and parts each job takes'],
'break_fix' => ['label' => 'Break/fix', 'icon' => 'fa-wrench', 'about' => 'Fixed when something breaks, billed per job'],
'project' => ['label' => 'Project', 'icon' => 'fa-project-diagram', 'about' => 'One piece of work, with a start and an end'],
'other' => ['label' => 'Other', 'icon' => 'fa-file-contract', 'about' => ''],
];
/** The term lengths offered, in months. Any other number can be typed. */
const CONTRACT_TERMS = [1 => 'Monthly', 3 => '3 months', 6 => '6 months', 12 => '1 year', 24 => '2 years', 36 => '3 years', 60 => '5 years'];
/** How many days before the notice date the owner is reminded. */
const CONTRACT_REMINDER_DAYS = 30;
/** The ticket priorities a contract sets an SLA for - priority => column part. */
const CONTRACT_SLA_PRIORITIES = ['Low' => 'low', 'Medium' => 'medium', 'High' => 'high', 'Urgent' => 'urgent'];
/** Whether the 3.4.2 update has run - the contracts tables as these functions read them. */
function contractsReady() {
global $mysqli;
static $ready = null;
if ($ready === null) {
// The pages define the version; the nightly job and other scripts don't, so read it
if (defined('CURRENT_DATABASE_VERSION')) {
$version = CURRENT_DATABASE_VERSION;
} else {
$result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1");
$version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0';
}
$ready = version_compare($version, '3.4.2', '>=');
}
return $ready;
}
/** A contract with its client, contact, owner and template names - or null. */
function contractRow($contract_id) {
global $mysqli;
$contract_id = intval($contract_id);
if ($contract_id <= 0 || !contractsReady()) {
return null;
}
return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contracts.*, client_name, client_rate, client_net_terms, contact_name, contact_email, user_name AS owner_name, user_email AS owner_email,
contract_template_name
FROM contracts
LEFT JOIN clients ON contract_client_id = client_id
LEFT JOIN contacts ON contract_contact_id = contact_id
LEFT JOIN users ON contract_owner_id = user_id
LEFT JOIN contract_templates ON contracts.contract_template_id = contract_templates.contract_template_id
WHERE contract_id = $contract_id LIMIT 1")) ?: null;
}
/** A template, or null. */
function contractTemplateRow($contract_template_id) {
global $mysqli;
$contract_template_id = intval($contract_template_id);
if ($contract_template_id <= 0 || !contractsReady()) {
return null;
}
return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM contract_templates WHERE contract_template_id = $contract_template_id LIMIT 1")) ?: null;
}
/* The templates in use - id => row, by name. */
function contractTemplates() {
global $mysqli;
$templates = [];
if (!contractsReady()) {
return $templates;
}
$sql = mysqli_query($mysqli, "SELECT * FROM contract_templates WHERE contract_template_archived_at IS NULL ORDER BY contract_template_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$templates[intval($row['contract_template_id'])] = $row;
}
return $templates;
}
/** A type's label - the key's, or the text itself for one ITFlow doesn't know. */
function contractTypeLabel($type) {
return CONTRACT_TYPES[(string) $type]['label'] ?? ((string) $type !== '' ? (string) $type : 'Contract');
}
/** A term in words - "1 year", "18 months". */
function contractTermLabel($months) {
$months = intval($months);
if (isset(CONTRACT_TERMS[$months])) {
return CONTRACT_TERMS[$months];
}
if ($months > 0 && $months % 12 === 0) {
return ($months / 12) . ' years';
}
return $months === 1 ? '1 month' : "$months months";
}
/** The last day of a term that starts on $start and runs $months months - 'Y-m-d'. */
function contractTermEnd($start, $months) {
$start = strtotime((string) $start);
if (!$start || intval($months) <= 0) {
return '';
}
return date('Y-m-d', strtotime('+' . intval($months) . ' months -1 day', $start));
}
/** The day after the last day of the term following one that ends on $end - its new last day. */
function contractNextEnd($end, $months) {
$end = strtotime((string) $end);
if (!$end || intval($months) <= 0) {
return '';
}
return contractTermEnd(date('Y-m-d', strtotime('+1 day', $end)), $months);
}
/** The last day notice can be given to stop it renewing (or to end it) - '' when it has no end date. */
function contractNoticeDate(array $row) {
if (empty($row['contract_end_date'])) {
return '';
}
return date('Y-m-d', strtotime('-' . max(0, intval($row['contract_notice_days'])) . ' days', strtotime($row['contract_end_date'])));
}
/** When the owner is reminded - CONTRACT_REMINDER_DAYS before the notice date. */
function contractReminderDate(array $row) {
$notice = contractNoticeDate($row);
return $notice !== '' ? date('Y-m-d', strtotime('-' . CONTRACT_REMINDER_DAYS . ' days', strtotime($notice))) : '';
}
/*
* Where a contract stands - key, label, Bootstrap tone, icon and a line
* saying when: draft, upcoming (active but not started), active, renewing
* (auto-renews soon), ending (ends soon and won't renew), ended, cancelled.
*/
function contractState(array $row, $today = null) {
$today = $today ?? date('Y-m-d');
$status = (string) $row['contract_status'];
$start = (string) ($row['contract_start_date'] ?? '');
$end = (string) ($row['contract_end_date'] ?? '');
$day = function ($date) {
return date('M j, Y', strtotime($date));
};
if ($status === 'Cancelled') {
return ['key' => 'cancelled', 'label' => 'Cancelled', 'tone' => 'secondary', 'icon' => 'fa-ban',
'when' => $end !== '' && $end >= $today ? 'Cancelled - in force until ' . $day($end) : 'Cancelled' . (!empty($row['contract_cancelled_at']) ? ' ' . $day($row['contract_cancelled_at']) : '')];
}
if ($status === 'Draft') {
return ['key' => 'draft', 'label' => 'Draft', 'tone' => 'secondary', 'icon' => 'fa-pencil-alt', 'when' => 'Not in force yet'];
}
if ($status === 'Ended' || ($end !== '' && $end < $today && !intval($row['contract_auto_renew']))) {
return ['key' => 'ended', 'label' => 'Ended', 'tone' => 'dark', 'icon' => 'fa-flag-checkered', 'when' => $end !== '' ? 'Ended ' . $day($end) : 'Ended'];
}
if ($start !== '' && $start > $today) {
return ['key' => 'upcoming', 'label' => 'Starts soon', 'tone' => 'info', 'icon' => 'fa-hourglass-start', 'when' => 'Starts ' . $day($start)];
}
if ($end === '') {
return ['key' => 'active', 'label' => 'Active', 'tone' => 'success', 'icon' => 'fa-check-circle', 'when' => 'No end date'];
}
$remind = contractReminderDate($row);
if (intval($row['contract_auto_renew'])) {
if ($remind !== '' && $today >= $remind) {
return ['key' => 'renewing', 'label' => 'Renews soon', 'tone' => 'primary', 'icon' => 'fa-sync-alt',
'when' => 'Renews ' . $day(date('Y-m-d', strtotime('+1 day', strtotime($end))))];
}
return ['key' => 'active', 'label' => 'Active', 'tone' => 'success', 'icon' => 'fa-check-circle', 'when' => 'Renews ' . $day(date('Y-m-d', strtotime('+1 day', strtotime($end))))];
}
if ($remind !== '' && $today >= $remind) {
return ['key' => 'ending', 'label' => 'Ends soon', 'tone' => 'warning', 'icon' => 'fa-exclamation-triangle', 'when' => 'Ends ' . $day($end)];
}
return ['key' => 'active', 'label' => 'Active', 'tone' => 'success', 'icon' => 'fa-check-circle', 'when' => 'Ends ' . $day($end)];
}
/** A contract's state as a badge. */
function contractStateHtml(array $row) {
$state = contractState($row);
return '<span class="badge rounded-pill text-bg-' . $state['tone'] . '" title="' . escapeHtml($state['when']) . '"><i class="fas fa-fw ' . $state['icon'] . ' me-1"></i>' . escapeHtml($state['label']) . '</span>';
}
/*
* The list's tabs - key => label, icon and SQL. Due soon is active, with an
* end date within its notice period and a month before it.
*/
function contractViews() {
$soon = "contract_status = 'Active' AND contract_end_date IS NOT NULL AND contract_end_date <= CURDATE() + INTERVAL (contract_notice_days + " . CONTRACT_REMINDER_DAYS . ") DAY";
return [
'active' => ['label' => 'Active', 'icon' => 'fa-check-circle', 'where' => "contract_status = 'Active'", 'title' => 'In force, or starting soon'],
'soon' => ['label' => 'Due soon', 'icon' => 'fa-hourglass-end', 'where' => $soon, 'title' => 'Renewing or ending - within a month of their notice date'],
'draft' => ['label' => 'Drafts', 'icon' => 'fa-pencil-alt', 'where' => "contract_status = 'Draft'", 'title' => 'Not in force yet'],
'ended' => ['label' => 'Ended', 'icon' => 'fa-flag-checkered', 'where' => "contract_status IN ('Ended', 'Cancelled')", 'title' => 'Ended or cancelled'],
'all' => ['label' => 'All', 'icon' => '', 'where' => '1 = 1'],
];
}
/* The SLAs a contract can pick - id => row, the ones in use and any it already has. */
function contractSlaChoices(array $keep = []) {
global $mysqli;
$keep = array_filter(array_map('intval', $keep));
$choices = [];
$sql = mysqli_query($mysqli, "SELECT sla_id, sla_name, sla_response_minutes, sla_resolution_minutes, sla_archived_at FROM slas
WHERE sla_archived_at IS NULL" . ($keep ? " OR sla_id IN (" . implode(',', $keep) . ")" : '') . " ORDER BY sla_response_minutes ASC, sla_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$choices[intval($row['sla_id'])] = $row;
}
return $choices;
}
/** An SLA's targets in words - "Respond in 1 hr, resolve in 8 hrs". */
function contractSlaTargets(array $sla) {
$text = 'Respond in ' . slaMinutesText($sla['sla_response_minutes']);
if (intval($sla['sla_resolution_minutes'] ?? 0) > 0) {
$text .= ', resolve in ' . slaMinutesText($sla['sla_resolution_minutes']);
}
return $text;
}
/** Minutes in words - "45 min", "4 hrs", "2 days". */
function slaMinutesText($minutes) {
$minutes = intval($minutes);
if ($minutes > 0 && $minutes % 1440 === 0 && $minutes >= 2880) {
return ($minutes / 1440) . ' days';
}
if ($minutes >= 60 && $minutes % 60 === 0) {
return ($minutes / 60) . ($minutes === 60 ? ' hr' : ' hrs');
}
if ($minutes >= 60) {
return round($minutes / 60, 1) . ' hrs';
}
return "$minutes min";
}
/*
* The fields of a contract or a template, from a form - [$fields, $error].
* $kind 'contract' or 'template'. Money and days that are left empty are
* null: the client's own rate and terms apply.
*/
function contractFromInput(array $in, $kind = 'contract') {
global $mysqli;
$text = function ($key, $max) use ($in) {
return mb_substr(trim(preg_replace('/\s+/u', ' ', strip_tags((string) ($in[$key] ?? '')))), 0, $max);
};
$money = function ($key) use ($in) {
$value = trim((string) ($in[$key] ?? ''));
if ($value === '') {
return null;
}
$number = function_exists('billingNumberInput') ? billingNumberInput($value) : (is_numeric($value) ? floatval($value) : null);
return $number === null ? false : round($number, 2);
};
$f = [
'name' => $text('name', 255),
'type' => isset(CONTRACT_TYPES[(string) ($in['type'] ?? '')]) ? (string) $in['type'] : 'managed',
'description' => $text('description', 1000),
'term_months' => intval($in['term_months'] ?? 12),
'auto_renew' => !empty($in['auto_renew']) ? 1 : 0,
'notice_days' => intval($in['notice_days'] ?? 30),
'rate_standard' => $money('rate_standard'),
'rate_after_hours' => $money('rate_after_hours'),
'net_terms' => trim((string) ($in['net_terms'] ?? '')) === '' ? null : intval($in['net_terms']),
'support_hours' => $text('support_hours', 100),
'details' => isset($in['details']) ? documentHtmlPurify((string) $in['details']) : null,
'sla' => [],
];
foreach (CONTRACT_SLA_PRIORITIES as $priority => $part) {
$f['sla'][$part] = intval($in["sla_$part"] ?? 0);
}
if ($kind === 'contract') {
$f += [
'client_id' => intval($in['client_id'] ?? 0),
'contact_id' => intval($in['contact_id'] ?? 0),
'owner_id' => intval($in['owner_id'] ?? 0),
'template_id' => intval($in['template_id'] ?? 0),
'status' => in_array($in['status'] ?? '', ['Draft', 'Active'], true) ? $in['status'] : 'Draft',
'start_date' => trim((string) ($in['start_date'] ?? '')),
'end_date' => trim((string) ($in['end_date'] ?? '')),
'notes' => mb_substr(trim((string) ($in['notes'] ?? '')), 0, 10000),
];
}
if ($f['name'] === '') {
return [$f, 'Give it a name.'];
}
if ($f['term_months'] < 1 || $f['term_months'] > 120) {
return [$f, 'A term is 1 to 120 months.'];
}
if ($f['notice_days'] < 0 || $f['notice_days'] > 365) {
return [$f, 'Notice is 0 to 365 days.'];
}
if ($f['rate_standard'] === false || $f['rate_after_hours'] === false || ($f['rate_standard'] ?? 0) < 0 || ($f['rate_after_hours'] ?? 0) < 0) {
return [$f, 'A rate is an amount, such as 125.00 - or leave it empty for the client\'s own.'];
}
if ($f['net_terms'] !== null && ($f['net_terms'] < 0 || $f['net_terms'] > 365)) {
return [$f, 'Net terms are 0 to 365 days - or leave them empty for the client\'s own.'];
}
$slas = contractSlaChoices(array_values($f['sla']));
foreach ($f['sla'] as $part => $sla_id) {
if ($sla_id && !isset($slas[$sla_id])) {
return [$f, 'Pick an SLA from the list.'];
}
}
if ($kind === 'contract') {
if (!$f['client_id'] || !mysqli_num_rows(mysqli_query($mysqli, "SELECT client_id FROM clients WHERE client_id = {$f['client_id']} AND client_archived_at IS NULL" . clientScopeSql('client_id')))) {
return [$f, 'Pick a client you can open.'];
}
foreach (['start_date', 'end_date'] as $date) {
if ($f[$date] !== '' && (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $f[$date]) || !strtotime($f[$date]))) {
return [$f, 'A date is a day, like 2026-11-01.'];
}
}
if ($f['start_date'] !== '' && $f['end_date'] !== '' && $f['end_date'] < $f['start_date']) {
return [$f, 'It ends before it starts.'];
}
if ($f['status'] === 'Active' && $f['start_date'] === '') {
return [$f, 'An active contract needs a start date.'];
}
if ($f['contact_id'] && !mysqli_num_rows(mysqli_query($mysqli, "SELECT contact_id FROM contacts WHERE contact_id = {$f['contact_id']} AND contact_client_id = {$f['client_id']}"))) {
return [$f, 'Pick one of the client\'s contacts.'];
}
if ($f['owner_id'] && !mysqli_num_rows(mysqli_query($mysqli, "SELECT user_id FROM users WHERE user_id = {$f['owner_id']} AND user_type = 1 AND user_archived_at IS NULL"))) {
return [$f, 'Pick an agent to look after it.'];
}
if ($f['template_id'] && !contractTemplateRow($f['template_id'])) {
$f['template_id'] = 0;
}
}
return [$f, ''];
}
/** The SET clause shared by contracts and templates - $prefix 'contract' or 'contract_template'. */
function contractTermsSetSql(array $f, $prefix) {
global $mysqli;
$money = function ($value) {
return $value === null ? 'NULL' : sprintf('%.2f', $value);
};
$sql = [
"{$prefix}_name = '" . escapeSql($f['name']) . "'",
"{$prefix}_type = '" . escapeSql($f['type']) . "'",
"{$prefix}_term_months = {$f['term_months']}",
"{$prefix}_auto_renew = {$f['auto_renew']}",
"{$prefix}_notice_days = {$f['notice_days']}",
"{$prefix}_rate_standard = " . $money($f['rate_standard']),
"{$prefix}_rate_after_hours = " . $money($f['rate_after_hours']),
"{$prefix}_net_terms = " . ($f['net_terms'] === null ? 'NULL' : intval($f['net_terms'])),
"{$prefix}_support_hours = " . ($f['support_hours'] !== '' ? "'" . escapeSql($f['support_hours']) . "'" : 'NULL'),
];
foreach ($f['sla'] as $part => $sla_id) {
$sql[] = "{$prefix}_sla_{$part}_id = " . intval($sla_id);
}
if ($f['details'] !== null) {
// Purified HTML - escapeSql() would strip its tags
$sql[] = "{$prefix}_details = '" . mysqli_real_escape_string($mysqli, $f['details']) . "'";
}
return implode(', ', $sql);
}
/** The SET clause for a contract's own fields. */
function contractSetSql(array $f) {
global $mysqli;
// The notes are plain text, shown escaped - kept as written, < and all
return contractTermsSetSql($f, 'contract') . ",
contract_client_id = {$f['client_id']}, contract_contact_id = {$f['contact_id']}, contract_owner_id = {$f['owner_id']}, contract_template_id = {$f['template_id']},
contract_start_date = " . ($f['start_date'] !== '' ? "'" . escapeSql($f['start_date']) . "'" : 'NULL') . ",
contract_end_date = " . ($f['end_date'] !== '' ? "'" . escapeSql($f['end_date']) . "'" : 'NULL') . ",
contract_notes = " . ($f['notes'] !== '' ? "'" . mysqli_real_escape_string($mysqli, $f['notes']) . "'" : 'NULL');
}
/** A new contract - its id. */
function contractCreate(array $f) {
global $mysqli, $session_user_id;
mysqli_query($mysqli, "INSERT INTO contracts SET " . contractSetSql($f) . ", contract_status = '" . escapeSql($f['status']) . "', contract_created_by = " . intval($session_user_id ?? 0));
return intval(mysqli_insert_id($mysqli));
}
/*
* Save a contract's fields - what changed, as phrases for the audit log. A
* new end date means a new term, so the owner is reminded again.
*/
function contractUpdate(array $row, array $f) {
global $mysqli;
$id = intval($row['contract_id']);
$reset = (string) $row['contract_end_date'] !== $f['end_date'] ? ', contract_reminded_at = NULL' : '';
mysqli_query($mysqli, "UPDATE contracts SET " . contractSetSql($f) . "$reset WHERE contract_id = $id");
$changes = [];
$was = [
'name' => (string) $row['contract_name'], 'type' => contractTypeLabel($row['contract_type']), 'start' => (string) $row['contract_start_date'], 'end' => (string) $row['contract_end_date'],
'term' => contractTermLabel($row['contract_term_months']), 'notice' => intval($row['contract_notice_days']) . ' days notice',
'standard rate' => $row['contract_rate_standard'] === null ? 'the client\'s' : sprintf('%.2f', $row['contract_rate_standard']),
'after-hours rate' => $row['contract_rate_after_hours'] === null ? 'the client\'s' : sprintf('%.2f', $row['contract_rate_after_hours']),
'net terms' => $row['contract_net_terms'] === null ? 'the client\'s' : intval($row['contract_net_terms']) . ' days',
'support hours' => (string) $row['contract_support_hours'],
];
$now = [
'name' => $f['name'], 'type' => contractTypeLabel($f['type']), 'start' => $f['start_date'], 'end' => $f['end_date'],
'term' => contractTermLabel($f['term_months']), 'notice' => $f['notice_days'] . ' days notice',
'standard rate' => $f['rate_standard'] === null ? 'the client\'s' : sprintf('%.2f', $f['rate_standard']),
'after-hours rate' => $f['rate_after_hours'] === null ? 'the client\'s' : sprintf('%.2f', $f['rate_after_hours']),
'net terms' => $f['net_terms'] === null ? 'the client\'s' : $f['net_terms'] . ' days',
'support hours' => $f['support_hours'],
];
foreach ($was as $label => $value) {
if ($value !== $now[$label]) {
$changes[] = "$label from " . ($value !== '' ? $value : 'none') . ' to ' . ($now[$label] !== '' ? $now[$label] : 'none');
}
}
if (intval($row['contract_auto_renew']) !== $f['auto_renew']) {
$changes[] = $f['auto_renew'] ? 'renews itself' : 'no longer renews itself';
}
foreach ($f['sla'] as $part => $sla_id) {
if (intval($row["contract_sla_{$part}_id"]) !== $sla_id) {
$changes[] = "$part priority SLA changed";
}
}
if (intval($row['contract_owner_id']) !== $f['owner_id']) {
$changes[] = 'owner changed';
}
if (intval($row['contract_contact_id']) !== $f['contact_id']) {
$changes[] = 'contact changed';
}
if (trim((string) $row['contract_notes']) !== $f['notes']) {
$changes[] = 'notes changed';
}
if ($f['details'] !== null && (string) $row['contract_details'] !== $f['details']) {
$changes[] = 'terms changed';
}
return $changes;
}
/* Make a draft active from $start (a 'Y-m-d'), with an end date from its term when it has none. */
function contractActivate(array $row, $start) {
global $mysqli;
$end = !empty($row['contract_end_date']) ? (string) $row['contract_end_date'] : contractTermEnd($start, $row['contract_term_months']);
mysqli_query($mysqli, "UPDATE contracts SET contract_status = 'Active', contract_start_date = '" . escapeSql($start) . "', contract_end_date = " . ($end !== '' ? "'" . escapeSql($end) . "'" : 'NULL') . ",
contract_reminded_at = NULL WHERE contract_id = " . intval($row['contract_id']));
return $end;
}
/*
* Renew a contract to a new last day - an active one goes on, an ended or
* cancelled one is active again. The owner will be reminded again before
* the new term ends.
*/
function contractRenew(array $row, $new_end) {
global $mysqli;
mysqli_query($mysqli, "UPDATE contracts SET contract_status = 'Active', contract_end_date = '" . escapeSql($new_end) . "', contract_renewed_at = NOW(), contract_reminded_at = NULL,
contract_cancelled_at = NULL, contract_cancel_reason = NULL WHERE contract_id = " . intval($row['contract_id']));
}
/* Cancel a contract - its last day is $last_day (it stays in force until then), and why. */
function contractCancel(array $row, $last_day, $reason) {
global $mysqli;
mysqli_query($mysqli, "UPDATE contracts SET contract_status = 'Cancelled', contract_cancelled_at = NOW(), contract_end_date = '" . escapeSql($last_day) . "', contract_auto_renew = 0,
contract_cancel_reason = " . ($reason !== '' ? "'" . escapeSql($reason) . "'" : 'NULL') . " WHERE contract_id = " . intval($row['contract_id']));
}
/*
* The night's work, run by cron/nightly_tasks.php - [renewed, ended,
* reminded] for the log:
* - an active contract whose last day has passed renews for another term
* when it renews itself (as many terms as it takes to reach today), and
* ends when it doesn't;
* - the owner of one coming up to its notice date is reminded, once a term,
* by email and in ITFlow - or everyone, when it has no owner.
*/
function contractsNightly($today = null) {
global $mysqli;
$today = $today ?? date('Y-m-d');
$done = ['renewed' => 0, 'ended' => 0, 'reminded' => 0];
if (!contractsReady()) {
return $done;
}
$sql = mysqli_query($mysqli, "SELECT contract_id FROM contracts WHERE contract_status = 'Active' AND contract_archived_at IS NULL
AND contract_end_date IS NOT NULL AND contract_end_date < '" . escapeSql($today) . "'");
while ($id = mysqli_fetch_row($sql)) {
$row = contractRow($id[0]);
if (!$row) {
continue;
}
$name = escapeSql($row['contract_name']);
if (intval($row['contract_auto_renew'])) {
$end = (string) $row['contract_end_date'];
while ($end !== '' && $end < $today) {
$end = contractNextEnd($end, $row['contract_term_months']);
}
contractRenew($row, $end);
logAudit("Contract", "Edit", "Contract $name renewed itself to " . escapeSql($end), intval($row['contract_client_id']), intval($row['contract_id']));
$done['renewed']++;
} else {
mysqli_query($mysqli, "UPDATE contracts SET contract_status = 'Ended' WHERE contract_id = " . intval($row['contract_id']));
logAudit("Contract", "Edit", "Contract $name ended on " . escapeSql($row['contract_end_date']), intval($row['contract_client_id']), intval($row['contract_id']));
appNotify("Contract", "Contract $name for " . escapeSql($row['client_name']) . " has ended", "/agent/contract.php?client_id=" . intval($row['contract_client_id']) . "&contract_id=" . intval($row['contract_id']), intval($row['contract_client_id']), intval($row['contract_id']));
$done['ended']++;
}
}
$sql = mysqli_query($mysqli, "SELECT contract_id FROM contracts WHERE contract_status = 'Active' AND contract_archived_at IS NULL AND contract_reminded_at IS NULL
AND contract_end_date IS NOT NULL AND contract_end_date >= '" . escapeSql($today) . "'
AND contract_end_date <= '" . escapeSql($today) . "' + INTERVAL (contract_notice_days + " . CONTRACT_REMINDER_DAYS . ") DAY");
while ($id = mysqli_fetch_row($sql)) {
$row = contractRow($id[0]);
if (!$row) {
continue;
}
contractRemind($row);
mysqli_query($mysqli, "UPDATE contracts SET contract_reminded_at = NOW() WHERE contract_id = " . intval($row['contract_id']));
$done['reminded']++;
}
return $done;
}
/* Tell the owner a contract is coming up to its notice date - in ITFlow, and by email. */
function contractRemind(array $row) {
global $config_base_url;
$client_id = intval($row['contract_client_id']);
$url = "/agent/contract.php?client_id=$client_id&contract_id=" . intval($row['contract_id']);
$renews = intval($row['contract_auto_renew']) === 1;
$notice = contractNoticeDate($row);
// A notice date already gone by isn't a date to give notice by - say it has passed
$notice_open = $notice !== '' && $notice >= date('Y-m-d');
$end = (string) $row['contract_end_date'];
$what = $renews ? 'renews itself on ' . date('M j, Y', strtotime('+1 day', strtotime($end))) : 'ends on ' . date('M j, Y', strtotime($end));
appNotify("Contract", escapeSql("Contract {$row['contract_name']} for {$row['client_name']} $what" . ($notice_open ? ' - notice by ' . date('M j, Y', strtotime($notice)) : '')), $url, $client_id, intval($row['contract_id']));
if (!empty($row['owner_email'])) {
$passed = $notice !== '' && !$notice_open ? ' Its notice date, ' . date('F j, Y', strtotime($notice)) . ', has passed.' : '';
emailQueue([['email' => $row['owner_email'], 'name' => $row['owner_name'], 'footnote' => 'You look after this contract in ITFlow.']], "Contract " . ($renews ? 'renewal' : 'ending') . ": {$row['contract_name']} - {$row['client_name']}", [
'kind' => 'Contract', 'tone' => $renews ? 'primary' : 'warning',
'title' => $row['contract_name'] . ' ' . $what,
'intro' => [$renews
? "It renews for another " . contractTermLabel($row['contract_term_months']) . ($notice_open ? " unless notice is given by " . date('F j, Y', strtotime($notice)) . ". Now is the time to review it with the client." : ".$passed")
: "It doesn't renew itself. Renew it, or let the client know it is ending" . ($notice_open ? " - notice is due by " . date('F j, Y', strtotime($notice)) . "." : ".$passed")],
'summary' => array_filter([
'Client' => (string) $row['client_name'],
'Type' => contractTypeLabel($row['contract_type']),
'Term' => (!empty($row['contract_start_date']) ? date('M j, Y', strtotime($row['contract_start_date'])) . ' to ' : 'Until ') . date('M j, Y', strtotime($end)),
'Notice' => $notice !== '' ? ($notice_open ? 'By ' : 'Passed - ') . date('M j, Y', strtotime($notice)) : '',
]),
'button' => ['label' => 'Open the contract', 'url' => "https://$config_base_url$url"],
]);
}
}
/* How many contracts a client has that are active - for the client menu. */
function contractClientCount($client_id) {
global $mysqli;
if (!contractsReady()) {
return 0;
}
return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contracts WHERE contract_client_id = " . intval($client_id) . " AND contract_status = 'Active' AND contract_archived_at IS NULL"))[0]);
}
/* A client's contracts in force now, soonest ending first - for the overview. */
function contractClientActive($client_id) {
global $mysqli;
$rows = [];
if (!contractsReady()) {
return $rows;
}
$sql = mysqli_query($mysqli, "SELECT * FROM contracts WHERE contract_client_id = " . intval($client_id) . " AND contract_status = 'Active' AND contract_archived_at IS NULL
ORDER BY contract_end_date IS NULL, contract_end_date ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
}
return $rows;
}

147
js/contract_form.js Normal file
View File

@@ -0,0 +1,147 @@
// New Contract, Copy and Edit (agent/modals/contract/contract_form.php).
// Picking a template fills the type, term, renewal, notice, cover and terms
// from it. Picking the client shows only that client's contacts. The end
// date follows the start and the term - a term's length less a day - until
// it is changed by hand, and the line under the term says when notice is
// due. The server checks it all again.
//
// Wrapped in an IIFE because a modal can be opened, closed and opened again
// in one page load, which re-runs this file.
(function () {
// 'Y-m-d' a term's length after $start, less a day - contractTermEnd() in functions/contract.php
function termEnd(start, months) {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(start || '');
if (!m || !(months > 0)) {
return '';
}
const year = Number(m[1]);
const month = Number(m[2]) - 1 + Number(months);
const day = Number(m[3]);
// PHP's +N months rolls an overflowing day into the next month (Jan 31 + 1 month is Mar 3) - so does Date
const end = new Date(Date.UTC(year, month, day));
end.setUTCDate(end.getUTCDate() - 1);
return end.toISOString().slice(0, 10);
}
function niceDate(ymd) {
const d = new Date(ymd + 'T00:00:00Z');
return isNaN(d) ? ymd : d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' });
}
document.querySelectorAll('[data-contract-form]:not([data-wired])').forEach(function (form) {
form.setAttribute('data-wired', '1');
const templateData = form.querySelector('[data-contract-templates]');
const templates = templateData ? JSON.parse(templateData.textContent) : {};
const template = form.querySelector('[data-contract-template]');
const client = form.querySelector('[data-contract-client]');
const contact = form.querySelector('[data-contract-contact]');
const start = form.querySelector('[data-contract-start]');
const term = form.querySelector('[data-contract-term]');
const end = form.querySelector('[data-contract-end]');
const noticeNote = form.querySelector('[data-contract-notice-note]');
const field = function (name) {
return form.querySelector('[data-contract-field="' + name + '"]');
};
function drawNotice() {
const days = Number(field('notice_days').value || 0);
if (!end.value) {
noticeNote.textContent = 'No end date - it runs until it is cancelled.';
return;
}
const notice = new Date(end.value + 'T00:00:00Z');
notice.setUTCDate(notice.getUTCDate() - days);
const renews = field('auto_renew').checked;
noticeNote.textContent = (renews ? 'Renews itself after ' : 'Ends on ') + niceDate(end.value)
+ (days ? ' - notice ' + (renews ? 'to stop it ' : '') + 'by ' + niceDate(notice.toISOString().slice(0, 10)) + '.' : '.');
}
function followTerm() {
if (!end.dataset.touched && start.value) {
end.value = termEnd(start.value, Number(term.value));
}
drawNotice();
}
// Only the client's own contacts
function filterContacts() {
if (!client || !contact) {
return;
}
const id = client.value;
Array.prototype.forEach.call(contact.options, function (option) {
if (option.value === '0') {
return;
}
const mine = option.dataset.client === id;
option.hidden = !mine;
if (!mine && option.selected) {
contact.value = '0';
}
});
}
function setValue(name, value) {
const input = field(name);
if (!input) {
return;
}
if (input.type === 'checkbox') {
input.checked = Boolean(Number(value));
} else if (input.tagName === 'TEXTAREA' && window.tinymce) {
const editor = tinymce.get().filter(function (ed) { return ed.getElement() === input; })[0];
if (editor) {
editor.setContent(value || '');
}
input.value = value || '';
} else {
input.value = value === null || value === undefined ? '' : value;
}
input.dispatchEvent(new Event('change', { bubbles: true }));
}
if (template) {
template.addEventListener('change', function () {
const t = templates[template.value];
if (!t) {
return;
}
// The template's name only when nothing is written yet
if (!field('name').value.trim()) {
setValue('name', t.name);
}
['type', 'auto_renew', 'notice_days', 'rate_standard', 'rate_after_hours', 'net_terms', 'support_hours', 'details',
'sla_low', 'sla_medium', 'sla_high', 'sla_urgent'].forEach(function (name) {
setValue(name, t[name]);
});
// A term the list doesn't have is added to it
if (!Array.prototype.some.call(term.options, function (o) { return Number(o.value) === t.term_months; })) {
term.add(new Option(t.term_months + ' months', t.term_months));
}
term.value = String(t.term_months);
followTerm();
});
}
if (client && client.tagName === 'SELECT') {
client.addEventListener('change', filterContacts);
// Select2 changes the select without a native event
if (window.jQuery) {
window.jQuery(client).on('change', filterContacts);
}
filterContacts();
}
start.addEventListener('change', followTerm);
term.addEventListener('change', followTerm);
end.addEventListener('input', function () {
end.dataset.touched = '1';
drawNotice();
});
field('notice_days').addEventListener('input', drawNotice);
field('auto_renew').addEventListener('change', drawNotice);
drawNotice();
});
})();