License templates stage 3: a template can be required of every client or of clients with certain client tags (database 3.3.0, tags kept when tags are merged); the template page shows how many of those clients have it and lists the missing ones with Make and Make for the clients missing one; the list gains a Required tab and a coverage chip; a client's Licenses page shows the licenses it should have but doesn't, opening New License from the template, and the client overview counts them under Licenses missing; the template page lists its licenses by client with seats, renewal and billing state, with views for over seats, spare seats, renewing soon, expired and not billed, an action for each view and bulk Renew, True up seats and Bill seats; true-up sets seats bought to the seats in use or a typed number; Bill seats adds a line for the template's product to each client's recurring invoice that follows the license's seats bought or in use, using seats in use for licenses with no seat limit; the Renew window now posts to the agent handler so it also works from Admin

This commit is contained in:
johnnyq
2026-10-18 21:10:29 -04:00
parent 0c12459eaf
commit b76bdd4b82
15 changed files with 1112 additions and 51 deletions

View File

@@ -6,9 +6,9 @@ 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.2.9) 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.3.0) in the same pass. Nothing else is required.
This is a big release, with fifty database steps in one go, so take a backup before you update.
This is a big release, with fifty-one database steps in one go, so take a backup before you update.
The update also clears out data that deletes in older versions left behind, all of it pointing at something that no longer exists:
@@ -49,7 +49,7 @@ Canned responses keep their names, what they say and their ticket category. One
Document templates keep their names, summaries, what they say and their images. Words in square brackets already in them are now filled in when a document is made: [Client], [Site], [Contact], [Date] and the others listed under New Features (Document templates) from the client, and the rest are asked for as plain, optional text until you set them up on the template's page - one left blank stays as it is, as before. Documents made from a template before the update don't know which one, so a template's use is counted from the update - link one to its template from the document's page to count it. No template is required of anyone, and none asks for reviews, until you set it up on its page. The starter document templates you added from Maintenance > Starter Content stay as they are; Update on that page brings them up to the new versions, which fill in from the client, ask for what they need and are reviewed on a schedule.
License templates keep everything they hold. A license called exactly what one license template is called - as the New License form named it when started from one - counts as made from that template, so a template's use starts out counted; where two templates share a name, neither is given its licenses. Other licenses don't know a template, so they count from the update. No template sets seats, a renewal term, a vendor or a product until you give it one.
License templates keep everything they hold. A license called exactly what one license template is called - as the New License form named it when started from one - counts as made from that template, so a template's use starts out counted; where two templates share a name, neither is given its licenses. Other licenses don't know a template, so they count from the update. No template sets seats, a renewal term, a vendor or a product until you give it one, and none is required of anyone until you set it up on its page.
If you are coming from 26.08 or earlier, the database update still has to be run from the command line one time, exactly as described under Upgrading to 26.09 below.
@@ -558,6 +558,11 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Renew starts on the template's term for licenses made from it.
- New licenses for several clients at once, from the template's page or the list: pick the clients, skip the ones that already have one, and give the seats, dates and order reference once.
- A license's quick look shows the product it is sold as, with its price, to anyone who can see Sales.
- Who should have it, on the template's page: every client, or the clients with certain client tags (leads and archived clients don't count). The page shows how many of them have it and which are missing it, each with Make, and Make for the clients missing one picks them all. The list counts it on each required template and has a Required tab.
- A client's Licenses shows the licenses it should have and hasn't, each starting New License from its template, and its overview counts them under Licenses missing.
- The template's page lists its licenses by client with their seats, renewal and how they are billed, with views for over seats, spare seats, renewing soon, expired and not billed. Each view has its own action - True up these, Renew these, Bill these - and licenses can be ticked for a bulk Renew, True up seats or Bill seats.
- True up seats sets each license's seats bought to what is on it now, or to a number you type.
- Bill seats puts a line for the product it is sold as on each client's recurring invoice, counting the license's seats bought or in use, so it follows them from then on - on a recurring invoice billed as often as the product, where the client has one. The Billed column shows each one's recurring invoice, a line typed in by hand that isn't its seats, and a paused recurring invoice.
- **Assets**
- The asset list has:
- type icons, colored status pills and OS icons
@@ -1557,6 +1562,10 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- `functions/software_template.php`: `softwareTemplateRow()` also returns the vendor template's name and archived date and the product's name, price, cost, currency, frequency, seat source and archived date; `softwareTemplateFields()` reads `seats`, `term`, `vendor_template_id` and `product_id` (one that exists, archived or not); new `softwareTemplateLinkId($table, $column, $id)`, `softwareTemplateRenewal($term, $purchase)`, `softwareTemplatePriceText($template)`, `softwareVendorFromTemplate($vendor_template_id, $client_id, $make = true, &$made)` (the client's vendor made from it, then one of its name, then - with `$make` - one made through `vendorFormSet()`) and `softwareTemplateMakeForClients($id, $client_ids, $post, $skip_existing = true, $make_vendor = true)` (`made`, `skipped`, `vendors`). `softwareTemplateMakeLicense($id, $client_id, $post, $make_vendor = true, &$vendor_made)` takes the template's seats when `seats` isn't posted and its term from `purchase` when `expire` is blank.
- Admin: new `admin/modals/software_template/software_template_use_several.php` (`id`) posts `make_licenses_from_template` (`client_ids[]`, `skip_existing`, `seats`, `purchase`, `expire`, `purchase_reference`) to `admin/post/software_template.php`, which redirects to the template's page. Deleting a vendor template or a product (`productDelete()`) clears it from the license templates that had it, leaving `software_template_updated_at` alone.
- Agent: the New License form's templates carry `seats`, `term`, `vendor_template_id` and `vendor`; the vendor picker is `data-software-vendor` (with `data-vendor-can-make` for someone with `module_client` 2) and its options `data-vendor-template-id`. `add_software` takes `vendor=template:N`, made with `softwareVendorFromTemplate()` when the agent has `module_client` 2. `add_software_from_template` and `make_licenses_from_template` audit a vendor they made as Vendor Create. The Renew window starts on the template's term when the licenses share one.
- Database 3.3.0: `software_templates.software_template_required` (0 no one in particular, 1 every client, 2 the clients with one of its tags) and `software_template_required_tags` (`software_template_id`, `tag_id`; cascades with either), whose tags `tagMerge()` moves too.
- `functions/software_template.php`: `SOFTWARE_TEMPLATE_REQUIRED_NONE`, `_EVERY` and `_TAGGED`; `softwareTemplateRequiredTags($ids)`, `softwareTemplateSetRequired($id, $required, $tag_ids)` (client tags only, leaving `software_template_updated_at` alone), `softwareTemplateScopeSql()`, `softwareTemplateScopeText()`, `softwareTemplateCoverage($id, $required, $tag_ids)` (`clients`, `covered`, `missing`), `softwareTemplatesMissingFor($client_id)`, `softwareTemplateLicenses($id, $product_id)` (each with `seats`, `renewal` and `billing`), `softwareTemplateBilling($licenses, $product_id)` (`how` - `seats` or `product` - `item_id`, `recurring_invoice_id`, `number`, `paused`, `quantity`, `count`, `drift`), `softwareTemplateLicenseViews($has_product)`, `softwareTemplateTrueUp($id, $seats_by_id)`, `softwareTemplateSeatsText()`, `softwareTemplateRecurringFor($client_ids)` and `softwareTemplateBill($id, $software_id, $recurring_invoice_id, $count, &$error)` (through `billingItemSave()` with the `license` seat source; one with no seat limit counts the seats in use).
- Admin: `admin/software_template.php` takes `view` (`over`, `spare`, `renewing`, `expired`, `unbilled`) and loads `js/bulk_actions.js`; `admin/software_templates.php` takes `show=required`. New windows `software_template_required.php` (`id`), `software_template_true_up.php` (`id`, `software_ids[]`) and `software_template_bill.php` (`id`, `software_ids[]`, `count`); `software_template_use_several.php` takes `missing=1`. New handlers `save_software_template_required` (`required`, `tags[]`), `true_up_software_template` (`software_ids[]`, `seats[id]`; audited as Software Edit on each license) and `bill_software_template` (`software_ids[]`, `recurring[id]`, `count`; audited as Recurring Invoice Edit).
- Agent: `agent/software.php` shows `softwareTemplatesMissingFor()` for one client (`.itflow-licenses-missing`, buttons to `software_add.php?client_id=&template_id=`); `clientOverviewAttention()` adds Licenses missing. The Renew window posts to `/agent/post.php`, so it works from Admin.
- Empty states: every list page sets `$empty_state` before including `includes/filter_footer.php`, and `includes/inc_empty_state.php` draws it with `emptyStateHtml()` (`functions/format.php`) when the list has nothing - `thing`, `icon`, `title`, `text`, `actions` (`label`, `modal` or `href`, `size`, `icon`; the first is the main one), `archived`, `view`, `filtered`, `views`, `match_title`, `match_text` and `clear_url`. `emptyStateFiltered($views)` reads the GET string for a search or filter, leaving out paging, sorting, `client_id`, `archived` and the page's views, and `emptyStateClearUrl($views)` is the page without them. `emptyStatePill($pills, $key, $default, $good)` builds a pill's own state from the page's pill array (`label`, `icon`, `title`, `alarm`), with a tick for `alarm` pills and the keys in `$good`. Files, notifications and racks call `emptyStateHtml()` in their own layout; files and notifications set `$empty_state_skip`. A page that sets nothing still gets one, worded from `$page_title`. The pages' own empty blocks (`.itflow-asset-empty` under a list) are gone. CSS: `.itflow-empty-state` with `-icon` (a grey round tile), `-title`, `-text` and `-actions`.
- Removed unused helpers and files:
- `credentialLink()`, `projectLink()`, `linkCounts()`, `assetContactAvatar()`, `clientOverviewPersonInitials()`, and `getMonthlyTax()` and `getQuarterlyTax()`, which looked a tax up by name

View File

@@ -0,0 +1,22 @@
<?php
/*
* ITFlow - Database update to version 3.3.0 (from 3.2.9)
* Included by admin/database_updates.php - do not access directly
*/
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
// Who should have a license from a template - 0 no one in particular, 1 every client, 2 the
// clients with one of its tags
mysqli_query($mysqli, "ALTER TABLE `software_templates`
ADD `software_template_required` tinyint(1) NOT NULL DEFAULT 0 AFTER `software_template_product_id`");
mysqli_query($mysqli, "CREATE TABLE `software_template_required_tags` (
`software_template_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL,
PRIMARY KEY (`software_template_id`,`tag_id`),
KEY `tag_id` (`tag_id`),
CONSTRAINT `software_template_required_tags_ibfk_1` FOREIGN KEY (`software_template_id`) REFERENCES `software_templates` (`software_template_id`) ON DELETE CASCADE,
CONSTRAINT `software_template_required_tags_ibfk_2` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`tag_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");

View File

@@ -0,0 +1,136 @@
<?php
/*
* Bill licenses made from a template on their clients' recurring invoices -
* a line for the product the template is sold as, counting each license's
* seats bought or in use, so it follows them from then on. ?id= the template;
* &software_ids[]= the licenses ticked on its page, or - without any - every
* one not billed yet. Each goes on one of its client's recurring invoices -
* an active one billed as often as the product first. Saved by
* bill_software_template (admin/post/software_template.php).
*/
require_once '../../includes/modal_header.php';
$template = softwareTemplateRow($_GET['id'] ?? 0);
ob_start();
if (!$template) { ?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-file-invoice-dollar me-2"></i>Bill seats</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body text-center text-secondary py-5">That license template no longer exists.</div>
<?php } else {
$software_template_id = intval($template['software_template_id']);
$product_id = intval($template['software_template_product_id']);
$sellable = $template['product_name'] !== null && !$template['product_archived_at'];
$all = softwareTemplateLicenses($software_template_id, $product_id);
$ids = array_filter(array_map('intval', (array) ($_GET['software_ids'] ?? [])));
$picked = $ids ? array_intersect_key($all, array_flip($ids)) : $all;
$billed = array_filter($picked, function ($row) {
return !empty($row['billing']);
});
$licenses = array_diff_key($picked, $billed);
$recurring = softwareTemplateRecurringFor(array_column($licenses, 'software_client_id'));
$count = ($_GET['count'] ?? '') === 'used' ? 'used' : 'total';
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-truncate"><i class="fa fa-fw fa-file-invoice-dollar me-2"></i>Bill seats <small class="ms-1 opacity-75"><?= escapeHtml($template['software_template_name']) ?></small></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="software_template_id" value="<?= $software_template_id ?>">
<div class="modal-body">
<?php if (!$sellable) { ?>
<div class="text-center text-secondary py-4">
<?= $template['product_name'] !== null ? 'The product it is sold as, <strong>' . escapeHtml($template['product_name']) . '</strong>, is archived.' : 'It isn\'t sold as a product yet.' ?>
Pick the product it is sold as on the template, then bill its licenses from here.
<div class="mt-3"><button type="button" class="btn btn-sm btn-outline-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/software_template/software_template_edit.php?id=<?= $software_template_id ?>"><i class="fas fa-edit me-1"></i>Edit the template</button></div>
</div>
<?php } elseif (!$licenses) { ?>
<div class="text-center text-secondary py-4"><i class="fas fa-check text-success me-1"></i><?= $picked ? 'Every one of them is billed already.' : 'No licenses made from it yet.' ?></div>
<?php } else { ?>
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
<?= productTile($template['product_name'] !== null ? (string) getFieldById('products', $product_id, 'product_type') : 'service') ?>
<div class="min-w-0 flex-grow-1">
<div class="fw-semibold"><?= escapeHtml($template['product_name']) ?></div>
<div class="small text-secondary"><?= escapeHtml(softwareTemplatePriceText($template)) ?></div>
</div>
</div>
<div class="mb-3">
<label class="form-label">Count</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-users"></i></span>
<select class="form-select" name="count">
<option value="total" <?= $count === 'total' ? 'selected' : '' ?>>The seats bought</option>
<option value="used" <?= $count === 'used' ? 'selected' : '' ?>>The seats in use - devices and users on it</option>
</select>
</div>
<div class="form-text">The line's quantity follows the license each time an invoice is made. One with no seat limit counts the seats in use.</div>
</div>
<div class="table-responsive border rounded">
<table class="table table-sm align-middle mb-0">
<thead class="table-light text-nowrap">
<tr><th class="ps-2" style="width: 2rem;"></th><th>Client</th><th class="text-end">Seats</th><th class="pe-2" style="min-width: 14rem;">Recurring invoice</th></tr>
</thead>
<tbody>
<?php foreach ($licenses as $software_id => $row) {
$client_id = intval($row['software_client_id']);
$options = $recurring[$client_id] ?? [];
// An active one billed as often as the product, then any active one, then the first
$default = 0;
foreach ($options as $recurring_id => $option) {
if (intval($option['recurring_invoice_status']) === 1 && $option['recurring_invoice_frequency'] === (string) $template['product_frequency']) {
$default = $recurring_id;
break;
}
}
$default = $default ?: (int) array_key_first($options);
?>
<tr data-bill-id="<?= $software_id ?>">
<td class="ps-2"><input class="form-check-input" type="checkbox" name="software_ids[]" value="<?= $software_id ?>" aria-label="Bill <?= escapeHtml($row['client_name']) ?>" <?= $options ? 'checked' : 'disabled' ?>></td>
<td class="min-w-0">
<div class="fw-semibold text-truncate"><?= escapeHtml($row['client_name']) ?></div>
<?php if ($row['software_name'] !== $template['software_template_name']) { ?><div class="small text-secondary text-truncate"><?= escapeHtml($row['software_name']) ?></div><?php } ?>
</td>
<td class="text-end text-nowrap small"><?= $row['seats']['total'] > 0 ? $row['seats']['total'] . ' bought' : '<span title="No seats bought to count - it counts the seats in use">No limit</span>' ?><div class="text-secondary"><?= $row['seats']['used'] ?> in use</div></td>
<td class="pe-2">
<?php if ($options) { ?>
<div class="input-group input-group-sm">
<span class="input-group-text"><i class="fa fa-fw fa-redo-alt"></i></span>
<select class="form-select" name="recurring[<?= $software_id ?>]">
<?php foreach ($options as $recurring_id => $option) { ?>
<option value="<?= $recurring_id ?>" <?= $recurring_id === $default ? 'selected' : '' ?>><?= escapeHtml($option['number'] . ' · ' . (recurringInvoiceFrequencies()[$option['recurring_invoice_frequency']] ?? $option['recurring_invoice_frequency']) . (trim((string) $option['recurring_invoice_scope']) !== '' ? ' · ' . $option['recurring_invoice_scope'] : '') . (intval($option['recurring_invoice_status']) === 1 ? '' : ' (paused)')) ?></option>
<?php } ?>
</select>
</div>
<?php } else { ?>
<span class="small text-secondary">No recurring invoice - <a href="/agent/recurring_invoices.php?client_id=<?= $client_id ?>">make one</a> first</span>
<?php } ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php if ($billed) { ?>
<div class="small text-secondary mt-2"><?= count($billed) === 1 ? '1 of the ones picked is' : count($billed) . ' of the ones picked are' ?> billed already, so not here.</div>
<?php } ?>
<?php } ?>
</div>
<div class="modal-footer">
<?php if ($sellable && $licenses) { ?>
<button type="submit" name="bill_software_template" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Add to recurring invoices</button>
<?php } ?>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i><?= $sellable && $licenses ? 'Cancel' : 'Close' ?></button>
</div>
</form>
<?php }
require_once '../../../includes/modal_footer.php';

View File

@@ -0,0 +1,89 @@
<?php
/*
* Who should have a license from a template - no one in particular, every
* client, or the clients with one of the client tags picked. ?id= the
* template. Saved by save_software_template_required
* (admin/post/software_template.php); the template's page, the clients'
* Licenses and their overviews then show the clients missing one.
*/
require_once '../../includes/modal_header.php';
$template = softwareTemplateRow($_GET['id'] ?? 0);
ob_start();
if (!$template) { ?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-clipboard-check me-2"></i>Who should have it</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body text-center text-secondary py-5">That license template no longer exists.</div>
<?php } else {
$software_template_id = intval($template['software_template_id']);
$required = intval($template['software_template_required']);
$tag_ids = array_keys(softwareTemplateRequiredTags([$software_template_id])[$software_template_id]);
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-truncate"><i class="fa fa-fw fa-clipboard-check me-2"></i>Who should have it <small class="ms-1 opacity-75"><?= escapeHtml($template['software_template_name']) ?></small></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="software_template_id" value="<?= $software_template_id ?>">
<div class="modal-body">
<div class="mb-3">
<label class="form-label">Every one of these should have a license from it</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-users"></i></span>
<select class="form-select select2" name="required" id="softwareTemplateRequired">
<option value="<?= SOFTWARE_TEMPLATE_REQUIRED_NONE ?>" <?= $required === SOFTWARE_TEMPLATE_REQUIRED_NONE ? 'selected' : '' ?>>No one in particular</option>
<option value="<?= SOFTWARE_TEMPLATE_REQUIRED_EVERY ?>" <?= $required === SOFTWARE_TEMPLATE_REQUIRED_EVERY ? 'selected' : '' ?>>Every client</option>
<option value="<?= SOFTWARE_TEMPLATE_REQUIRED_TAGGED ?>" <?= $required === SOFTWARE_TEMPLATE_REQUIRED_TAGGED ? 'selected' : '' ?>>Clients with a tag</option>
</select>
</div>
<div class="form-text">Leads and archived clients don't count. The template's page, each client's Licenses and their overview show who is missing one.</div>
</div>
<div class="mb-1" id="softwareTemplateRequiredTags" <?= $required === SOFTWARE_TEMPLATE_REQUIRED_TAGGED ? '' : 'hidden' ?>>
<label class="form-label">Client tags</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tags"></i></span>
<select class="form-select select2" name="tags[]" multiple data-placeholder="- Pick client tags -">
<?php foreach (tagOptionsFor('client', $tag_ids) as $tag) { ?>
<?= tagOptionHtml($tag, $tag_ids) ?>
<?php } ?>
</select>
</div>
<div class="form-text">Clients with any of them - Managed, say, for the endpoint protection every managed client gets.</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="save_software_template_required" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Save</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<script>
(function () {
// The tags are for "Clients with a tag" only
var required = document.getElementById('softwareTemplateRequired');
var tags = document.getElementById('softwareTemplateRequiredTags');
if (required && tags) {
required.addEventListener('change', function () {
tags.hidden = required.value !== '<?= SOFTWARE_TEMPLATE_REQUIRED_TAGGED ?>';
});
}
})();
</script>
<?php }
require_once '../../../includes/modal_footer.php';

View File

@@ -0,0 +1,103 @@
<?php
/*
* True up the seats on licenses made from a template - each license's seats
* bought set to what is on it now, or to a number you type. ?id= the
* template; &software_ids[]= the licenses ticked on its page, or - without
* any - every one whose seats bought aren't what is in use. Each starts on
* the seats in use, ticked when that is a change. Saved by
* true_up_software_template (admin/post/software_template.php). A recurring
* invoice line counting a license's seats bought follows on its next run.
*/
require_once '../../includes/modal_header.php';
$template = softwareTemplateRow($_GET['id'] ?? 0);
ob_start();
if (!$template) { ?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-balance-scale me-2"></i>True up seats</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body text-center text-secondary py-5">That license template no longer exists.</div>
<?php } else {
$software_template_id = intval($template['software_template_id']);
$all = softwareTemplateLicenses($software_template_id);
$ids = array_filter(array_map('intval', (array) ($_GET['software_ids'] ?? [])));
$licenses = $ids ? array_intersect_key($all, array_flip($ids)) : array_filter($all, function ($row) {
return $row['seats']['total'] > 0 && $row['seats']['used'] !== $row['seats']['total'];
});
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-truncate"><i class="fa fa-fw fa-balance-scale me-2"></i>True up seats <small class="ms-1 opacity-75"><?= escapeHtml($template['software_template_name']) ?></small></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="software_template_id" value="<?= $software_template_id ?>">
<div class="modal-body">
<?php if (!$licenses) { ?>
<div class="text-center text-secondary py-4"><i class="fas fa-check text-success me-1"></i>Every license made from it has the seats it is using.</div>
<?php } else { ?>
<p class="small text-secondary">Each starts on the seats in use. Untick a license to leave it as it is, or type the seats it should have - blank for no limit.</p>
<div class="table-responsive border rounded">
<table class="table table-sm align-middle mb-0">
<thead class="table-light text-nowrap">
<tr><th class="ps-2" style="width: 2rem;"></th><th>Client</th><th class="text-end">In use</th><th class="text-end">Seats now</th><th class="pe-2" style="width: 9rem;">Seats</th></tr>
</thead>
<tbody>
<?php foreach ($licenses as $software_id => $row) {
$seats = $row['seats'];
$now = $row['software_seats'] === null ? '' : (string) intval($row['software_seats']);
// Unlimited ones stay unlimited unless a number is typed
$to = $seats['total'] > 0 ? (string) $seats['used'] : $now;
?>
<tr data-true-up-id="<?= $software_id ?>">
<td class="ps-2"><input class="form-check-input" type="checkbox" name="software_ids[]" value="<?= $software_id ?>" aria-label="True up <?= escapeHtml($row['client_name']) ?>" <?= $to !== $now ? 'checked' : '' ?> data-true-up-tick></td>
<td class="min-w-0">
<div class="fw-semibold text-truncate"><?= escapeHtml($row['client_name']) ?></div>
<?php if ($row['software_name'] !== $template['software_template_name']) { ?><div class="small text-secondary text-truncate"><?= escapeHtml($row['software_name']) ?></div><?php } ?>
</td>
<td class="text-end"><?= $seats['used'] ?></td>
<td class="text-end text-nowrap"><?= $seats['total'] > 0 ? $seats['total'] . ($seats['state'] === 'over' ? ' <span class="badge rounded-pill bg-danger-subtle text-danger-emphasis fw-normal">' . $seats['over'] . ' over</span>' : '') : '<span class="text-secondary">No limit</span>' ?></td>
<td class="pe-2">
<div class="input-group input-group-sm">
<span class="input-group-text"><i class="fa fa-fw fa-users"></i></span>
<input type="number" class="form-control" name="seats[<?= $software_id ?>]" min="0" max="1000000" step="1" placeholder="No limit" value="<?= escapeHtml($to) ?>" data-now="<?= escapeHtml($now) ?>" data-true-up-seats>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="small text-secondary mt-3">A recurring invoice line counting a license's seats bought follows on its next run.</div>
<?php } ?>
</div>
<div class="modal-footer">
<?php if ($licenses) { ?>
<button type="submit" name="true_up_software_template" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>True up</button>
<?php } ?>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i><?= $licenses ? 'Cancel' : 'Close' ?></button>
</div>
</form>
<script>
(function () {
// Typing a number ticks the license when it is a change, unticks it when it isn't
document.querySelectorAll('.modal [data-true-up-seats]').forEach(function (input) {
input.addEventListener('input', function () {
var tick = input.closest('tr').querySelector('[data-true-up-tick]');
tick.checked = input.value.trim() !== input.dataset.now;
});
});
})();
</script>
<?php }
require_once '../../../includes/modal_footer.php';

View File

@@ -7,8 +7,8 @@
* vendor made from the template's vendor template, or one made for them),
* with the seats, dates and order reference given here once for all of them.
* Keys and who is on each are put on from the client's Licenses. ?id= the
* template. Made by make_licenses_from_template
* (admin/post/software_template.php).
* template; &missing=1 picks the clients it is required of that have none
* yet. Made by make_licenses_from_template (admin/post/software_template.php).
*/
require_once '../../includes/modal_header.php';
@@ -34,6 +34,13 @@ if (!$template || $template['software_template_archived_at']) { ?>
while ($row = mysqli_fetch_row($sql)) {
$has_one[intval($row[0])] = true;
}
// The clients it is required of with none yet
$picked = [];
if (!empty($_GET['missing'])) {
$tag_ids = array_keys(softwareTemplateRequiredTags([$software_template_id])[$software_template_id]);
$picked = array_keys(softwareTemplateCoverage($software_template_id, $template['software_template_required'], $tag_ids)['missing']);
}
?>
<div class="modal-header bg-dark">
@@ -55,10 +62,13 @@ if (!$template || $template['software_template_archived_at']) { ?>
$sql_clients = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql_clients)) {
$client_option_id = intval($row['client_id']); ?>
<option value="<?= $client_option_id ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?><?= isset($has_one[$client_option_id]) ? ' data-description="Already has one"' : '' ?>><?= escapeHtml($row['client_name']) ?></option>
<option value="<?= $client_option_id ?>" <?= in_array($client_option_id, $picked, true) ? 'selected' : '' ?><?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?><?= isset($has_one[$client_option_id]) ? ' data-description="Already has one"' : '' ?>><?= escapeHtml($row['client_name']) ?></option>
<?php } ?>
</select>
</div>
<?php if (!empty($_GET['missing'])) { ?>
<div class="form-text"><?= $picked ? 'The ' . count($picked) . ' client' . (count($picked) === 1 ? '' : 's') . ' it is required of with none yet.' : 'Every client it is required of has one.' ?></div>
<?php } ?>
</div>
<div class="col-12">
<div class="form-check form-switch">

View File

@@ -2,10 +2,12 @@
/*
* License templates (Admin > License Templates) - making, changing, copying,
* archiving and deleting them, and making licenses from one for several
* clients at once. The work is in functions/software_template.php; a single
* license is made from one by add_software or add_software_from_template
* (agent/post/software.php).
* archiving and deleting them, making licenses from one for several clients
* at once, saying who should have one, and looking after its licenses across
* clients - their seats trued up, and billed on the clients' recurring
* invoices. The work is in functions/software_template.php; a single license
* is made from one by add_software or add_software_from_template, and
* licenses are renewed by renew_software (agent/post/software.php).
*/
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
@@ -87,6 +89,114 @@ if (isset($_POST['make_licenses_from_template'])) {
}
if (isset($_POST['save_software_template_required'])) {
// Who should have a license from it
validateCSRFToken();
$row = softwareTemplateForRequest($_POST['software_template_id'] ?? 0);
$software_template_id = intval($row['software_template_id']);
$required = intval($_POST['required'] ?? 0);
$tag_ids = array_map('intval', (array) ($_POST['tags'] ?? []));
if ($required === SOFTWARE_TEMPLATE_REQUIRED_TAGGED && !array_filter($tag_ids)) {
flashAlert('Pick the client tags - or Every client.', 'error');
redirect();
}
softwareTemplateSetRequired($software_template_id, $required, $tag_ids);
$saved = softwareTemplateRow($software_template_id);
$scope = softwareTemplateScopeText($saved['software_template_required'], softwareTemplateRequiredTags([$software_template_id])[$software_template_id]);
$said = $scope !== '' ? "required of " . lcfirst($scope) : 'not required of anyone';
logAudit("Software Template", "Edit", "$session_name set license template " . escapeSql($row['software_template_name']) . " " . escapeSql($said), 0, $software_template_id);
flashAlert("<strong>" . escapeHtml($row['software_template_name']) . "</strong> is " . escapeHtml($said));
redirect();
}
if (isset($_POST['true_up_software_template'])) {
// The seats bought on the licenses ticked set to what was given - each its own
validateCSRFToken();
$row = softwareTemplateForRequest($_POST['software_template_id'] ?? 0);
$software_template_id = intval($row['software_template_id']);
$seats = [];
foreach (array_unique(array_filter(array_map('intval', (array) ($_POST['software_ids'] ?? [])))) as $software_id) {
$seats[$software_id] = $_POST['seats'][$software_id] ?? '';
}
if (!$seats) {
flashAlert('Tick the licenses to true up.', 'error');
redirect();
}
$changes = softwareTemplateTrueUp($software_template_id, $seats);
foreach ($changes as $software_id => $change) {
logAudit("Software", "Edit", "$session_name trued up license " . escapeSql($change['name']) . " from " . softwareTemplateSeatsText($change['from']) . " to " . softwareTemplateSeatsText($change['to']), $change['client_id'], $software_id);
}
$count = count($changes);
if ($count === 1) {
$change = reset($changes);
flashAlert("<strong>" . escapeHtml($change['client_name']) . "</strong> trued up from " . softwareTemplateSeatsText($change['from']) . " to " . softwareTemplateSeatsText($change['to']));
} else {
flashAlert($count ? "Trued up <strong>$count</strong> licenses from <strong>" . escapeHtml($row['software_template_name']) . "</strong>" : 'Nothing to change - they have those seats already', $count ? 'success' : 'warning');
}
redirect();
}
if (isset($_POST['bill_software_template'])) {
// A line for the product it is sold as on each license's recurring invoice, counting its seats
validateCSRFToken();
$row = softwareTemplateForRequest($_POST['software_template_id'] ?? 0);
$software_template_id = intval($row['software_template_id']);
$software_ids = array_values(array_unique(array_filter(array_map('intval', (array) ($_POST['software_ids'] ?? [])))));
if (!$software_ids) {
flashAlert('Tick the licenses to bill.', 'error');
redirect();
}
$count = ($_POST['count'] ?? '') === 'used' ? 'used' : 'total';
// Not the ones billed already - a second line would bill them twice
$licenses = softwareTemplateLicenses($software_template_id, $row['software_template_product_id']);
$added = 0;
$skipped = 0;
$errors = [];
foreach ($software_ids as $software_id) {
if (!isset($licenses[$software_id]) || !empty($licenses[$software_id]['billing'])) {
$skipped++;
continue;
}
$recurring_invoice_id = intval($_POST['recurring'][$software_id] ?? 0);
$item_id = softwareTemplateBill($software_template_id, $software_id, $recurring_invoice_id, $count, $error);
if (!$item_id) {
$errors[$error] = true;
continue;
}
$added++;
$client_id = intval($licenses[$software_id]['software_client_id']);
$number = billingNumber('recurring', billingRow('recurring', $recurring_invoice_id, false));
$line = (string) $row['product_name'];
logAudit("Recurring Invoice", "Edit", escapeSql("$session_name added line $line to $number, counting the seats " . ($count === 'total' ? 'bought' : 'in use') . " on license {$licenses[$software_id]['software_name']}"), $client_id, $recurring_invoice_id);
}
if ($errors && !$added) {
flashAlert(escapeHtml(implode(' ', array_keys($errors))), 'error');
redirect();
}
flashAlert("Billed <strong>$added</strong> license" . ($added === 1 ? '' : 's') . " as <strong>" . escapeHtml((string) $row['product_name']) . "</strong>"
. ($skipped ? " - $skipped billed already" : '') . ($errors ? ' - ' . escapeHtml(implode(' ', array_keys($errors))) : ''), $errors ? 'warning' : 'success');
redirect();
}
if (isset($_GET['copy_software_template'])) {
validateCSRFToken();

View File

@@ -5,9 +5,14 @@
* version, summary, type, license type, seats, how often it renews, its vendor,
* the product it is sold as and its notes), who made it and last changed it,
* and its use: how many licenses have been made from it, for how many
* clients, the seats on them, the ones renewing soon or lapsed, and the latest
* of them. New licenses can be made from here for a client or several at
* once. The work is in functions/software_template.php.
* clients, the seats on them, the ones renewing soon or lapsed - and who
* should have one, with the clients missing it. Its licenses are listed by
* client with their seats, renewal and how they are billed, in views - over
* seats, spare seats, renewing, expired, not billed - and can be trued up,
* renewed and billed on the clients' recurring invoices from here, ticked or
* a whole view at once. New licenses can be made from here for a client,
* several at once, or every client missing one. The work is in
* functions/software_template.php.
*/
require_once "includes/inc_all_admin.php";
@@ -29,20 +34,50 @@ $usage = softwareTemplateUsage([$software_template_id])[$software_template_id] ?
$type_style = softwareTypeStyle($template['software_template_type']);
$csrf = $_SESSION['csrf_token'];
// The licenses made from it, the latest first
$licenses = [];
$sql = mysqli_query($mysqli, "SELECT software_id, software_name, software_seats, software_expire, software_created_at, software_client_id, client_name, client_abbreviation,
" . softwareSeatsUsedSql('software.software_id') . " AS seats_used
FROM software JOIN clients ON client_id = software_client_id AND client_archived_at IS NULL
WHERE software_template_id = $software_template_id AND software_archived_at IS NULL
ORDER BY software_created_at DESC, software_id DESC LIMIT 25");
while ($row = mysqli_fetch_assoc($sql)) {
$licenses[] = $row;
// Its licenses by client, with how each is billed when it is sold as a product - in the view picked
$product_id = intval($template['software_template_product_id']);
$has_product = $template['product_name'] !== null;
$all_licenses = softwareTemplateLicenses($software_template_id, $product_id);
$views = softwareTemplateLicenseViews($has_product);
$view = isset($views[(string) ($_GET['view'] ?? '')]) ? (string) $_GET['view'] : '';
$view_counts = [];
foreach ($views as $key => $definition) {
$view_counts[$key] = count(array_filter($all_licenses, $definition['test']));
}
$licenses = array_filter($all_licenses, $views[$view]['test']);
$view_url = function ($key) use ($software_template_id) {
return '?' . http_build_query(array_filter(['software_template_id' => $software_template_id, 'view' => $key])) . '#softwareTemplateLicenses';
};
// Who should have one - not counted while it is archived
$required = intval($template['software_template_required']);
$required_tags = softwareTemplateRequiredTags([$software_template_id])[$software_template_id];
$scope_text = softwareTemplateScopeText($required, $required_tags);
$coverage = $required && !$archived ? softwareTemplateCoverage($software_template_id, $required, array_keys($required_tags)) : null;
$list_limit = 8;
$missing_text = $coverage && $coverage['missing'] ? (count($coverage['missing']) === 1 ? 'the client missing one' : 'the ' . count($coverage['missing']) . ' clients missing one') : '';
$edit_url = "modals/software_template/software_template_edit.php?id=$software_template_id";
$use_url = "modals/software_template/software_template_use.php?id=$software_template_id";
$several_url = "modals/software_template/software_template_use_several.php?id=$software_template_id";
$required_url = "modals/software_template/software_template_required.php?id=$software_template_id";
$true_up_url = "modals/software_template/software_template_true_up.php?id=$software_template_id";
$bill_url = "modals/software_template/software_template_bill.php?id=$software_template_id";
$renew_url = '/agent/modals/software/software_renew.php';
// What can be done to the whole of a view at once
$view_ids = function () use ($licenses) {
return implode('&', array_map(function ($id) {
return 'software_ids[]=' . $id;
}, array_keys($licenses)));
};
$view_action = [
'over' => ['label' => 'True up these', 'icon' => 'fa-balance-scale', 'url' => $true_up_url],
'spare' => ['label' => 'True up these', 'icon' => 'fa-balance-scale', 'url' => $true_up_url],
'renewing' => ['label' => 'Renew these', 'icon' => 'fa-redo-alt', 'url' => $renew_url],
'expired' => ['label' => 'Renew these', 'icon' => 'fa-redo-alt', 'url' => $renew_url],
'unbilled' => ['label' => 'Bill these', 'icon' => 'fa-file-invoice-dollar', 'url' => $bill_url],
][$view] ?? null;
$term = (string) $template['software_template_term'];
$vendor_name = (string) $template['vendor_template_name'];
@@ -87,6 +122,9 @@ $facts = array_filter([
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-label="More ways to make one"></button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="<?= $several_url ?>"><i class="fas fa-fw fa-copy me-2"></i>For several clients</a>
<?php if ($coverage && $coverage['missing']) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="<?= $several_url ?>&missing=1"><i class="fas fa-fw fa-clipboard-check me-2"></i>For <?= $missing_text ?></a>
<?php } ?>
</div>
</div>
<?php } ?>
@@ -94,6 +132,7 @@ $facts = array_filter([
<div class="dropdown">
<button class="btn btn-outline-secondary" title="More actions" type="button" data-bs-toggle="dropdown"><i class="fas fa-fw fa-ellipsis-h"></i></button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item ajax-modal" href="#" data-modal-url="<?= $required_url ?>"><i class="fas fa-fw fa-clipboard-check me-2"></i>Who should have it</a>
<a class="dropdown-item" href="post.php?copy_software_template=<?= $software_template_id ?>&csrf_token=<?= $csrf ?>"><i class="fas fa-fw fa-copy me-2"></i>Copy</a>
<?php if ($archived) { ?>
<a class="dropdown-item" href="post.php?restore_software_template=<?= $software_template_id ?>&csrf_token=<?= $csrf ?>"><i class="fas fa-fw fa-redo me-2"></i>Restore</a>
@@ -137,34 +176,105 @@ $facts = array_filter([
</div>
</div>
<div class="card mb-3">
<div class="card-header d-flex align-items-center">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-list me-2"></i>Licenses made from it</h3>
<?php if ($usage['count'] > count($licenses)) { ?><span class="ms-auto small text-secondary">The latest <?= count($licenses) ?> of <?= $usage['count'] ?></span><?php } ?>
<div class="card mb-3" id="softwareTemplateLicenses">
<div class="card-header d-flex flex-wrap align-items-center gap-2">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-list me-2"></i>Clients with it</h3>
<?php if ($all_licenses) { ?>
<div class="dropdown ms-auto" id="bulkActionButton" hidden>
<button class="btn btn-sm btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-layer-group me-1"></i>Bulk Action (<span id="selectedCount"></span>)
</button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item ajax-modal" href="#" data-modal-url="<?= $renew_url ?>" data-modal-size="lg" data-bulk="true"><i class="fas fa-fw fa-redo-alt me-2"></i>Renew</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="<?= $true_up_url ?>" data-modal-size="lg" data-bulk="true"><i class="fas fa-fw fa-balance-scale me-2"></i>True up seats</a>
<?php if ($has_product) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="<?= $bill_url ?>" data-modal-size="lg" data-bulk="true"><i class="fas fa-fw fa-file-invoice-dollar me-2"></i>Bill seats</a>
<?php } ?>
</div>
</div>
<?php } ?>
</div>
<?php if ($all_licenses) { ?>
<div class="card-header py-2">
<nav class="nav nav-pills itflow-asset-tabs flex-nowrap overflow-auto">
<?php foreach ($views as $key => $definition) {
if ($key !== '' && $key !== $view && !$view_counts[$key]) {
continue;
}
$alarm = in_array($key, ['over', 'expired', 'unbilled'], true) && $view_counts[$key]; ?>
<a class="nav-link text-nowrap <?= $key === $view ? 'active' : '' ?>" href="<?= escapeHtml($view_url($key)) ?>" title="<?= escapeHtml($definition['title']) ?>" data-license-view="<?= $key ?>">
<i class="fas fa-fw <?= $definition['icon'] ?> me-1"></i><?= escapeHtml($definition['label']) ?>
<span class="badge rounded-pill ms-1 <?= $alarm && $key !== $view ? 'text-bg-danger' : '' ?>"><?= $view_counts[$key] ?></span>
</a>
<?php } ?>
</nav>
</div>
<?php if ($view_action && $licenses && !$archived) { ?>
<div class="card-header py-2 d-flex flex-wrap align-items-center gap-2 bg-body-tertiary">
<span class="small text-secondary"><?= escapeHtml($views[$view]['title']) ?>.</span>
<button type="button" class="btn btn-sm btn-primary ms-auto ajax-modal" data-modal-size="lg" data-view-action
data-modal-url="<?= escapeHtml($view_action['url'] . (strpos($view_action['url'], '?') === false ? '?' : '&') . $view_ids()) ?>"><i class="fas fa-fw <?= $view_action['icon'] ?> me-1"></i><?= $view_action['label'] ?></button>
</div>
<?php } ?>
<?php } ?>
<?php if ($licenses) { ?>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead class="table-light text-nowrap">
<tr><th class="ps-3">Client</th><th>Seats</th><th class="d-none d-sm-table-cell">Renews</th><th class="d-none d-md-table-cell">Made</th></tr>
<tr>
<td class="ps-3 pe-0" style="width: 1rem;"><input class="form-check-input" type="checkbox" id="selectAllCheckbox" aria-label="Tick them all"></td>
<th>Client</th><th>Seats</th><th class="d-none d-sm-table-cell">Renews</th>
<?php if ($has_product) { ?><th class="d-none d-md-table-cell">Billed</th><?php } ?>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($licenses as $row) {
$renewal = softwareRenewal($row['software_expire']);
<?php foreach ($licenses as $software_id => $row) {
$client_id = intval($row['software_client_id']);
$billing = $row['billing'];
?>
<tr data-software-id="<?= intval($row['software_id']) ?>">
<td class="ps-3">
<a class="fw-semibold text-body" href="/agent/software.php?client_id=<?= intval($row['software_client_id']) ?>"><?= escapeHtml($row['client_name']) ?></a>
<tr data-software-id="<?= $software_id ?>">
<td class="ps-3 pe-0"><input class="form-check-input bulk-select" type="checkbox" name="software_ids[]" value="<?= $software_id ?>" aria-label="Tick <?= escapeHtml($row['client_name']) ?>"></td>
<td>
<a class="fw-semibold text-body" href="/agent/software.php?client_id=<?= $client_id ?>"><?= escapeHtml($row['client_name']) ?></a>
<?php if ($row['software_name'] !== $template['software_template_name']) { ?><div class="small text-secondary"><?= escapeHtml($row['software_name']) ?></div><?php } ?>
<?php if ($has_product) { ?><div class="d-md-none small text-secondary"><?= $billing ? 'Billed on ' . escapeHtml($billing['number']) : 'Not billed' ?></div><?php } ?>
</td>
<td style="min-width: 7rem;"><?= softwareSeatBar($row['seats'], $row['seats']['state'] === 'over') ?></td>
<td class="d-none d-sm-table-cell"><?= $row['renewal'] ? softwareRenewalPill($row['renewal']) : '<span class="text-secondary small">-</span>' ?></td>
<?php if ($has_product) { ?>
<td class="d-none d-md-table-cell small" data-billing="<?= $billing ? $billing['how'] : 'none' ?>">
<?php if ($billing) { ?>
<a class="text-reset" href="/agent/recurring_invoice.php?recurring_invoice_id=<?= intval($billing['recurring_invoice_id']) ?>"><i class="fas fa-fw fa-redo-alt text-secondary me-1"></i><?= escapeHtml($billing['number']) ?></a>
<?php if ($billing['paused']) { ?><span class="badge rounded-pill bg-warning-subtle text-warning-emphasis fw-normal ms-1">Paused</span><?php } ?>
<div class="text-secondary"><?= $billing['how'] === 'seats' ? 'Counts the seats ' . ($billing['count'] === 'total' ? 'bought' : 'in use') : billingQuantity($billing['quantity']) . ' typed in' ?></div>
<?php if ($billing['drift']) { ?><div class="text-warning-emphasis"><i class="fas fa-exclamation-triangle me-1"></i>Not its seats</div><?php } ?>
<?php } else { ?>
<span class="badge rounded-pill bg-warning-subtle text-warning-emphasis border border-warning-subtle fw-normal">Not billed</span>
<?php } ?>
</td>
<?php } ?>
<td class="text-end pe-3">
<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="lg" data-modal-url="<?= $renew_url ?>?id=<?= $software_id ?>"><i class="fas fa-fw fa-redo-alt text-secondary me-2"></i>Renew</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="<?= $true_up_url ?>&software_ids[]=<?= $software_id ?>"><i class="fas fa-fw fa-balance-scale text-secondary me-2"></i>True up seats</a>
<?php if ($has_product && !$billing) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="<?= $bill_url ?>&software_ids[]=<?= $software_id ?>"><i class="fas fa-fw fa-file-invoice-dollar text-secondary me-2"></i>Bill seats</a>
<?php } ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="/agent/software.php?client_id=<?= $client_id ?>"><i class="fas fa-fw fa-cube text-secondary me-2"></i>The client's Licenses</a>
</div>
</div>
</td>
<td style="min-width: 7rem;"><?= softwareSeatBar(softwareSeats($row['seats_used'], $row['software_seats']), false) ?></td>
<td class="d-none d-sm-table-cell"><?= $renewal ? softwareRenewalPill($renewal) : '<span class="text-secondary small">-</span>' ?></td>
<td class="d-none d-md-table-cell small text-secondary text-nowrap" title="<?= escapeHtml($row['software_created_at']) ?>"><?= timeAgo($row['software_created_at']) ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php } elseif ($all_licenses) { ?>
<div class="card-body small text-secondary">None of them - <a href="<?= escapeHtml($view_url('')) ?>">see them all</a>.</div>
<?php } else { ?>
<div class="card-body small text-secondary">No licenses made from it yet. Agents start one from <strong>New License</strong> on a client's Licenses<?= $archived ? '' : ', or make one from here' ?>.</div>
<?php } ?>
@@ -183,6 +293,9 @@ $facts = array_filter([
<li class="mb-1"><i class="fas fa-fw fa-users text-secondary me-1"></i><?= $usage['seats'] ? '<strong>' . $usage['used'] . '</strong> of <strong>' . $usage['seats'] . '</strong> seats in use' : '<strong>' . $usage['used'] . '</strong> seats in use' ?></li>
<?php if ($usage['renewing']) { ?><li class="mb-1 text-warning-emphasis"><i class="fas fa-fw fa-hourglass-half me-1"></i><?= $usage['renewing'] ?> renewing in the next 30 days</li><?php } ?>
<?php if ($usage['expired']) { ?><li class="mb-1 text-danger-emphasis"><i class="fas fa-fw fa-calendar-times me-1"></i><?= $usage['expired'] ?> past their renewal date</li><?php } ?>
<?php if ($has_product) { ?>
<li class="mb-1 <?= $view_counts['unbilled'] ? 'text-warning-emphasis' : 'text-success' ?>"><i class="fas fa-fw fa-file-invoice-dollar me-1"></i><?= $view_counts['unbilled'] ? $view_counts['unbilled'] . ' not billed' : 'Every one billed' ?></li>
<?php } ?>
</ul>
<?php } else { ?>
<div class="small text-secondary">No licenses made from it yet - counting started with this version of ITFlow, with the licenses already called what it is called.</div>
@@ -190,6 +303,50 @@ $facts = array_filter([
</div>
</div>
<div class="card mb-3" id="softwareTemplateCoverage">
<div class="card-header d-flex align-items-center">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-clipboard-check me-2"></i>Who should have it</h3>
<button type="button" class="btn btn-sm btn-link ms-auto ajax-modal" data-modal-url="<?= $required_url ?>"><i class="fas fa-edit me-1"></i>Set up</button>
</div>
<div class="card-body">
<?php if (!$required) { ?>
<div class="small text-secondary">No one in particular. Set it up to see which clients are missing it - every client, or the ones with a tag.</div>
<?php } elseif ($archived) { ?>
<div class="small text-secondary"><?= escapeHtml($scope_text) ?> - not counted while it is archived.</div>
<?php } else {
$percent = $coverage['clients'] ? intval(floor($coverage['covered'] * 100 / $coverage['clients'])) : 100;
?>
<div class="d-flex align-items-baseline gap-2 mb-1">
<span class="fw-semibold min-w-0 text-truncate" title="<?= escapeHtml($scope_text) ?>"><?= escapeHtml($scope_text) ?></span>
<span class="ms-auto small text-nowrap"><strong><?= $coverage['covered'] ?></strong> of <?= $coverage['clients'] ?> have it</span>
</div>
<div class="progress mb-2" role="progressbar" aria-label="Clients with it" aria-valuenow="<?= $percent ?>" aria-valuemin="0" aria-valuemax="100" style="height: 6px;">
<div class="progress-bar <?= $coverage['missing'] ? 'bg-warning' : 'bg-success' ?>" style="width: <?= $percent ?>%"></div>
</div>
<?php if ($coverage['missing']) { ?>
<div class="small text-secondary mb-1">Missing it</div>
<div class="list-group list-group-flush small mb-2">
<?php foreach (array_slice($coverage['missing'], 0, $list_limit, true) as $client_id => $client_name) { ?>
<div class="list-group-item px-0 d-flex align-items-center gap-2" data-missing-client-id="<?= $client_id ?>">
<i class="fas fa-fw fa-user text-secondary"></i>
<a class="min-w-0 flex-grow-1 text-truncate text-reset" href="/agent/software.php?client_id=<?= $client_id ?>"><?= escapeHtml($client_name) ?></a>
<button type="button" class="btn btn-sm btn-light py-0 ajax-modal" data-modal-size="lg" data-modal-url="<?= $use_url ?>&client_id=<?= $client_id ?>"><i class="fas fa-plus me-1"></i>Make</button>
</div>
<?php } ?>
</div>
<?php if (count($coverage['missing']) > $list_limit) { ?>
<div class="small text-secondary mb-2">and <?= count($coverage['missing']) - $list_limit ?> more</div>
<?php } ?>
<button type="button" class="btn btn-sm btn-outline-primary ajax-modal" data-modal-size="lg" data-modal-url="<?= $several_url ?>&missing=1"><i class="fas fa-copy me-1"></i>Make for <?= $missing_text ?></button>
<?php } elseif ($coverage['clients']) { ?>
<div class="small text-success"><i class="fas fa-fw fa-check me-1"></i>Every one of them has it.</div>
<?php } else { ?>
<div class="small text-secondary"><?= $required === SOFTWARE_TEMPLATE_REQUIRED_TAGGED ? ($required_tags ? 'No clients have ' . (count($required_tags) === 1 ? 'that tag' : 'those tags') : 'No tags picked, so no clients') : 'No clients yet' ?>.</div>
<?php } ?>
<?php } ?>
</div>
</div>
<div class="card mb-3">
<div class="card-header"><h3 class="card-title mb-0"><i class="fas fa-fw fa-info-circle me-2"></i>Details</h3></div>
<div class="card-body">
@@ -207,5 +364,7 @@ $facts = array_filter([
</div>
</div>
<script src="../js/bulk_actions.js"></script>
<?php
require_once "../includes/footer.php";

View File

@@ -7,8 +7,10 @@
* its type and license type, what a license from it starts with (seats, how
* often it renews, its vendor, the product it is sold as), how many licenses
* have been made from it and for how many clients, with their seats, when it
* was last used and last changed. New licenses can be made from one for a
* client or several at once.
* was last used and last changed. A template every client, or the clients
* with a tag, should have shows how many of them have it; the Required tab
* lists those. New licenses can be made from one for a client or several at
* once.
* A template can be changed, copied as the start of another, archived - not
* offered for new licenses, while the licenses made from it stay - or
* deleted. The work is in functions/software_template.php; the handlers are
@@ -21,7 +23,15 @@ $order = "ASC";
require_once "includes/inc_all_admin.php";
$show_archived = ($_GET['show'] ?? '') === 'archived';
// '' current, 'required' the current ones someone should have, 'archived'
$show = (string) ($_GET['show'] ?? '');
$show = in_array($show, ['required', 'archived'], true) ? $show : '';
$show_archived = $show === 'archived';
$show_where = [
'' => 'software_template_archived_at IS NULL',
'required' => 'software_template_archived_at IS NULL AND software_template_required > 0',
'archived' => 'software_template_archived_at IS NOT NULL',
][$show];
// Tab title - the file is named for the table, the page for what it holds
$page_title = 'License Templates';
@@ -48,7 +58,7 @@ $joins = "LEFT JOIN vendor_templates ON vendor_template_id = software_template_v
// Its use is the current licenses made from it, for current clients - as softwareTemplateUsage() counts them
$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS software_templates.software_template_id, software_template_name, software_template_version, software_template_description,
software_template_type, software_template_license_type, software_template_notes, software_template_created_at, software_template_updated_at, software_template_archived_at,
software_template_seats, software_template_term, vendor_template_name, product_name, product_price, product_currency_code, product_frequency, product_seat_source,
software_template_seats, software_template_term, software_template_required, vendor_template_name, product_name, product_price, product_currency_code, product_frequency, product_seat_source,
COALESCE(software_template_updated_at, software_template_created_at) AS changed_at, COALESCE(updater.user_name, creator.user_name) AS changed_by,
COALESCE(used.used_count, 0) AS used_count, used.last_used
FROM software_templates
@@ -60,7 +70,7 @@ $sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS software_templates.soft
FROM software JOIN clients ON client_id = software_client_id AND client_archived_at IS NULL
WHERE software_template_id > 0 AND software_archived_at IS NULL GROUP BY software_template_id
) used ON used.used_template_id = software_templates.software_template_id
WHERE $search AND software_template_archived_at IS " . ($show_archived ? 'NOT NULL' : 'NULL') . "
WHERE $search AND $show_where
ORDER BY {$sortable_columns[$sort]}, software_templates.software_template_id ASC
LIMIT $record_from, $record_to");
@@ -72,14 +82,24 @@ while ($row = mysqli_fetch_assoc($sql)) {
}
$usage = softwareTemplateUsage(array_keys($rows));
$counts = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(SUM(software_template_archived_at IS NULL), 0), COALESCE(SUM(software_template_archived_at IS NOT NULL), 0) FROM software_templates $joins WHERE $search"));
// How many of the clients a required one is for have it
$required_tags = softwareTemplateRequiredTags(array_keys($rows));
$coverage = [];
foreach ($rows as $template_id => $row) {
if (intval($row['software_template_required']) && !$row['software_template_archived_at']) {
$coverage[$template_id] = softwareTemplateCoverage($template_id, $row['software_template_required'], array_keys($required_tags[$template_id]));
}
}
$counts = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(SUM(software_template_archived_at IS NULL), 0), COALESCE(SUM(software_template_archived_at IS NOT NULL), 0),
COALESCE(SUM(software_template_archived_at IS NULL AND software_template_required > 0), 0) FROM software_templates $joins WHERE $search"));
$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 ($archived) {
return '?' . http_build_query(array_filter(['q' => $_GET['q'] ?? '', 'show' => $archived ? 'archived' : '']));
$pill_url = function ($show) {
return '?' . http_build_query(array_filter(['q' => $_GET['q'] ?? '', 'show' => $show]));
};
$add_url = 'modals/software_template/software_template_add.php';
@@ -96,7 +116,7 @@ $csrf = $_SESSION['csrf_token'];
</div>
<div class="card-header py-3">
<form autocomplete="off">
<?php if ($show_archived) { ?><input type="hidden" name="show" value="archived"><?php } ?>
<?php if ($show !== '') { ?><input type="hidden" name="show" value="<?= $show ?>"><?php } ?>
<div class="row g-2 align-items-center">
<div class="col-lg-5 col-md-6">
<div class="input-group">
@@ -107,8 +127,9 @@ $csrf = $_SESSION['csrf_token'];
</div>
</form>
<nav class="nav nav-pills itflow-asset-tabs mt-2">
<a class="nav-link <?= $show_archived ? '' : 'active' ?>" href="<?= escapeHtml($pill_url(false)) ?>"><i class="fas fa-fw fa-cube me-1"></i>Active <span class="badge rounded-pill ms-1"><?= intval($counts[0]) ?></span></a>
<a class="nav-link <?= $show_archived ? 'active' : '' ?>" href="<?= escapeHtml($pill_url(true)) ?>" title="Not offered for new licenses - the licenses made from them stay"><i class="fas fa-fw fa-archive me-1"></i>Archived <span class="badge rounded-pill ms-1"><?= intval($counts[1]) ?></span></a>
<a class="nav-link <?= $show === '' ? 'active' : '' ?>" href="<?= escapeHtml($pill_url('')) ?>"><i class="fas fa-fw fa-cube me-1"></i>Active <span class="badge rounded-pill ms-1"><?= intval($counts[0]) ?></span></a>
<a class="nav-link <?= $show === 'required' ? 'active' : '' ?>" href="<?= escapeHtml($pill_url('required')) ?>" title="Every client, or the clients with a tag, should have it"><i class="fas fa-fw fa-clipboard-check me-1"></i>Required <span class="badge rounded-pill ms-1"><?= intval($counts[2]) ?></span></a>
<a class="nav-link <?= $show_archived ? 'active' : '' ?>" href="<?= escapeHtml($pill_url('archived')) ?>" title="Not offered for new licenses - the licenses made from them stay"><i class="fas fa-fw fa-archive me-1"></i>Archived <span class="badge rounded-pill ms-1"><?= intval($counts[1]) ?></span></a>
</nav>
</div>
<div class="table-responsive">
@@ -154,6 +175,15 @@ $csrf = $_SESSION['csrf_token'];
<?php if ($starts) { ?>
<div class="small text-body-secondary d-flex flex-wrap column-gap-3" data-template-starts><?php foreach ($starts as $start) { ?><span class="text-nowrap"><?= $start ?></span><?php } ?></div>
<?php } ?>
<?php if (isset($coverage[$template_id])) {
$reach = $coverage[$template_id]; ?>
<div class="d-flex flex-wrap gap-1 mt-1">
<a class="badge rounded-pill fw-normal text-decoration-none <?= $reach['missing'] ? 'bg-warning-subtle text-warning-emphasis border border-warning-subtle' : 'bg-success-subtle text-success-emphasis border border-success-subtle' ?>"
href="software_template.php?software_template_id=<?= $template_id ?>#softwareTemplateCoverage" title="<?= escapeHtml(softwareTemplateScopeText($row['software_template_required'], $required_tags[$template_id])) ?>" data-template-reach>
<i class="fas fa-clipboard-check me-1"></i><?= $reach['covered'] ?> of <?= $reach['clients'] ?> clients
</a>
</div>
<?php } ?>
<?php if ($row['software_template_archived_at']) { ?>
<div class="small text-body-secondary"><i class="fas fa-fw fa-archive me-1"></i>Archived <?= date('M j, Y', strtotime($row['software_template_archived_at'])) ?></div>
<?php } ?>
@@ -193,6 +223,9 @@ $csrf = $_SESSION['csrf_token'];
<i class="fas fa-fw fa-copy text-secondary me-2"></i>For several clients
</a>
<?php } ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/software_template/software_template_required.php?id=<?= $template_id ?>">
<i class="fas fa-fw fa-clipboard-check text-secondary me-2"></i>Who should have it
</a>
<a class="dropdown-item" href="post.php?copy_software_template=<?= $template_id ?>&csrf_token=<?= $csrf ?>" title="A new template starting from this one">
<i class="fas fa-fw fa-copy text-secondary me-2"></i>Copy
</a>
@@ -225,6 +258,7 @@ $csrf = $_SESSION['csrf_token'];
'filtered' => $q !== '',
'archived' => $show_archived,
'views' => ['show'],
'view' => $show === 'required' ? ['title' => 'No required templates', 'text' => 'Set one up from its page - <strong>Who should have it</strong> - to see which clients are missing a license from it.'] : null,
'text' => 'A license you sell or look after again and again - Microsoft 365 Business Premium, an endpoint protection agent, a backup product - ready to start a client\'s from. Agents start one from <strong>New License</strong> on a client\'s Licenses.',
'actions' => [['label' => 'New License Template', 'modal' => $add_url, 'size' => 'lg']],
];

View File

@@ -47,7 +47,7 @@ ob_start();
<h5 class="modal-title text-truncate"><i class="fas fa-fw fa-redo-alt me-2"></i>Renew <?= $single ? '<strong>' . escapeHtml($licenses[0]['software_name']) . '</strong>' : '<strong>' . count($licenses) . '</strong> licenses' ?></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off" data-renew-form>
<form action="/agent/post.php" method="post" autocomplete="off" data-renew-form>
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<?php foreach ($licenses as $row) { ?><input type="hidden" name="software_ids[]" value="<?= intval($row['software_id']) ?>"><?php } ?>
<input type="hidden" name="renew_mode" value="extend" data-renew-mode>

View File

@@ -6,7 +6,9 @@
* coming up, what has lapsed) and seats (bought against in use - over means a
* true-up, none in use means paying for nothing). Tabs along the top pull
* those out; each row shows its seats as a bar and its renewal in colour.
* Names open the license page.
* Names open the license page. A client's own list says which licenses it
* should have and hasn't (license templates required of every client, or of
* the clients with its tags), each a button to make it from the template.
*/
// Default Column Sortby Filter
@@ -44,6 +46,8 @@ if (isset($_GET['client_id'])) {
enforceUserPermission('module_support');
$can_edit = lookupUserPermission('module_support') >= 2;
// The license templates this client should have a license from, and hasn't
$missing_templates = $client_url && !$archived ? softwareTemplatesMissingFor($client_id) : [];
// Deleting for good also needs Admin > Settings to allow destructive deletes
$can_delete = lookupUserPermission('module_support') >= 3 && !empty($config_destructive_deletes_enable);
@@ -209,6 +213,22 @@ while ($license_type_row = mysqli_fetch_row($sql_license_types)) {
</div>
</div>
<?php if ($missing_templates) { ?>
<!-- The license templates this client should have a license from, and hasn't -->
<div class="card-header py-2 bg-warning-subtle d-flex flex-wrap align-items-center gap-2 itflow-licenses-missing">
<span class="small text-warning-emphasis fw-semibold"><i class="fas fa-fw fa-clipboard-check me-1"></i><?= count($missing_templates) === 1 ? 'A license it should have' : 'Licenses it should have' ?>:</span>
<?php foreach ($missing_templates as $missing_id => $missing_name) { ?>
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-sm btn-light border py-0 ajax-modal" data-modal-size="lg" data-modal-url="modals/software/software_add.php?client_id=<?= $client_id ?>&template_id=<?= $missing_id ?>" title="Start it from the template" data-missing-template-id="<?= $missing_id ?>">
<i class="fas fa-plus me-1 text-secondary"></i><?= escapeHtml($missing_name) ?>
</button>
<?php } else { ?>
<span class="badge rounded-pill text-bg-light border fw-normal" data-missing-template-id="<?= $missing_id ?>"><?= escapeHtml($missing_name) ?></span>
<?php } ?>
<?php } ?>
</div>
<?php } ?>
<?php if ($tab_counts['']) { ?>
<!-- What needs a look -->
<div class="card-header py-2 itflow-asset-tabs">

18
db.sql
View File

@@ -3235,6 +3235,23 @@ CREATE TABLE `software_tags` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `software_template_required_tags`
--
DROP TABLE IF EXISTS `software_template_required_tags`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `software_template_required_tags` (
`software_template_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL,
PRIMARY KEY (`software_template_id`,`tag_id`),
KEY `tag_id` (`tag_id`),
CONSTRAINT `software_template_required_tags_ibfk_1` FOREIGN KEY (`software_template_id`) REFERENCES `software_templates` (`software_template_id`) ON DELETE CASCADE,
CONSTRAINT `software_template_required_tags_ibfk_2` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`tag_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `software_templates`
--
@@ -3254,6 +3271,7 @@ CREATE TABLE `software_templates` (
`software_template_term` varchar(10) DEFAULT NULL,
`software_template_vendor_template_id` int(11) NOT NULL DEFAULT 0,
`software_template_product_id` int(11) NOT NULL DEFAULT 0,
`software_template_required` tinyint(1) NOT NULL DEFAULT 0,
`software_template_created_at` datetime NOT NULL DEFAULT current_timestamp(),
`software_template_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(),
`software_template_archived_at` datetime DEFAULT NULL,

View File

@@ -146,6 +146,13 @@ function clientOverviewAttention($client_id, $access, $renewals) {
'detail' => 'As their templates ask',
'url' => "/agent/files.php?client_id=$client_id&type=due",
];
// License templates it should have a license from - the strip across the top of its Licenses
$items[] = [
'count' => count(softwareTemplatesMissingFor($client_id)),
'label' => 'Licenses missing', 'icon' => 'cube', 'tone' => 'warning',
'detail' => 'Ones every client like it should have',
'url' => "/agent/software.php?client_id=$client_id",
];
}
if ($access['credentials']) {

View File

@@ -16,6 +16,13 @@
* from it there and then) and the product it is sold as. Licenses can be made
* from one for several clients at once.
*
* From database 3.3.0 on a template says who should have it - every client, or
* the clients with one of its tags - so the clients missing it show on its
* page, on their Licenses and on their overview. Its licenses can be looked
* after across clients from its page: their seats trued up to what is in use,
* renewed together, and their seats billed on each client's recurring invoice
* as the product it is sold as.
*
* Shared by admin/software_templates.php, admin/software_template.php,
* admin/modals/software_template/*, admin/post/software_template.php and the
* New License window and its handlers on the agent side
@@ -31,7 +38,7 @@ function softwareTemplateRow($software_template_id) {
}
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT software_template_id, software_template_name, software_template_description, software_template_version,
software_template_type, software_template_license_type, software_template_notes, software_template_seats, software_template_term,
software_template_vendor_template_id, software_template_product_id, software_template_created_at, software_template_updated_at,
software_template_vendor_template_id, software_template_product_id, software_template_required, software_template_created_at, software_template_updated_at,
software_template_archived_at, software_template_created_by, software_template_updated_by,
creator.user_name AS created_by_name, updater.user_name AS updated_by_name,
vendor_template_name, vendor_template_archived_at, product_name, product_price, product_cost, product_currency_code, product_frequency, product_seat_source, product_archived_at
@@ -301,3 +308,340 @@ function softwareTemplateMakeForClients($software_template_id, array $client_ids
}
return $result;
}
/* ---------------------------------------------------------------- who should have one */
/** Who should have a license from a template (software_template_required). */
const SOFTWARE_TEMPLATE_REQUIRED_NONE = 0;
const SOFTWARE_TEMPLATE_REQUIRED_EVERY = 1;
const SOFTWARE_TEMPLATE_REQUIRED_TAGGED = 2;
/** The client tags templates are required by - [template id => [tag id => tag name]], in name order. */
function softwareTemplateRequiredTags(array $software_template_ids) {
global $mysqli;
$ids = array_values(array_filter(array_map('intval', $software_template_ids)));
$tags = array_fill_keys($ids, []);
if (!$ids) {
return $tags;
}
$sql = mysqli_query($mysqli, "SELECT software_template_id, tags.tag_id, tag_name FROM software_template_required_tags
JOIN tags ON tags.tag_id = software_template_required_tags.tag_id
WHERE software_template_id IN (" . implode(',', $ids) . ") ORDER BY tag_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$tags[intval($row['software_template_id'])][intval($row['tag_id'])] = (string) $row['tag_name'];
}
return $tags;
}
/*
* Set who should have a license from a template - $required one of the
* SOFTWARE_TEMPLATE_REQUIRED_ values, $tag_ids the client tags for TAGGED.
* Not a change to what a license starts with, so when it last changed stays
* as it was.
*/
function softwareTemplateSetRequired($software_template_id, $required, array $tag_ids) {
global $mysqli;
$software_template_id = intval($software_template_id);
$required = in_array(intval($required), [SOFTWARE_TEMPLATE_REQUIRED_EVERY, SOFTWARE_TEMPLATE_REQUIRED_TAGGED], true) ? intval($required) : SOFTWARE_TEMPLATE_REQUIRED_NONE;
mysqli_query($mysqli, "UPDATE software_templates SET software_template_required = $required, software_template_updated_at = software_template_updated_at
WHERE software_template_id = $software_template_id");
// Client tags only - any others are left out
$tag_ids = $required === SOFTWARE_TEMPLATE_REQUIRED_TAGGED ? array_values(array_unique(array_filter(array_map('intval', $tag_ids)))) : [];
mysqli_query($mysqli, "DELETE FROM software_template_required_tags WHERE software_template_id = $software_template_id");
if ($tag_ids) {
mysqli_query($mysqli, "INSERT INTO software_template_required_tags (software_template_id, tag_id)
SELECT $software_template_id, tag_id FROM tags WHERE tag_type = 1 AND tag_id IN (" . implode(',', $tag_ids) . ")");
}
}
/*
* The clients a template is required of, as SQL on clients: current clients,
* not leads - every one, or the ones with any of its tags (none when it has
* no tags left, or isn't required).
*/
function softwareTemplateScopeSql($required, array $tag_ids) {
$sql = "clients.client_archived_at IS NULL AND clients.client_lead = 0";
if (intval($required) === SOFTWARE_TEMPLATE_REQUIRED_EVERY) {
return $sql;
}
$tag_ids = array_values(array_filter(array_map('intval', $tag_ids)));
if (intval($required) !== SOFTWARE_TEMPLATE_REQUIRED_TAGGED || !$tag_ids) {
return '0';
}
return "$sql AND EXISTS (SELECT 1 FROM client_tags WHERE client_tags.client_id = clients.client_id AND client_tags.tag_id IN (" . implode(',', $tag_ids) . "))";
}
/** Who a template is required of, in words - '' when it isn't. */
function softwareTemplateScopeText($required, array $tags) {
if (intval($required) === SOFTWARE_TEMPLATE_REQUIRED_EVERY) {
return 'Every client';
}
if (intval($required) !== SOFTWARE_TEMPLATE_REQUIRED_TAGGED) {
return '';
}
return $tags ? 'Clients tagged ' . implode(' or ', $tags) : 'Clients with a tag - none picked';
}
/*
* How far a required template reaches - ['clients' => how many it is
* required of, 'covered' => how many of them have a current license from it,
* 'missing' => [client id => name] the rest, by name].
*/
function softwareTemplateCoverage($software_template_id, $required, array $tag_ids) {
global $mysqli;
$software_template_id = intval($software_template_id);
$coverage = ['clients' => 0, 'covered' => 0, 'missing' => []];
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, EXISTS (SELECT 1 FROM software WHERE software_client_id = clients.client_id
AND software_template_id = $software_template_id AND software_archived_at IS NULL) AS covered
FROM clients WHERE " . softwareTemplateScopeSql($required, $tag_ids) . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$coverage['clients']++;
if (intval($row['covered'])) {
$coverage['covered']++;
} else {
$coverage['missing'][intval($row['client_id'])] = (string) $row['client_name'];
}
}
return $coverage;
}
/*
* The required templates a client has no current license from - [template
* id => name]. None for an archived client or a lead.
*/
function softwareTemplatesMissingFor($client_id) {
global $mysqli;
$client_id = intval($client_id);
$missing = [];
$sql = mysqli_query($mysqli, "SELECT software_template_id, software_template_name FROM software_templates
WHERE software_template_archived_at IS NULL AND software_template_required IN (" . SOFTWARE_TEMPLATE_REQUIRED_EVERY . ", " . SOFTWARE_TEMPLATE_REQUIRED_TAGGED . ")
AND EXISTS (SELECT 1 FROM clients WHERE clients.client_id = $client_id AND clients.client_archived_at IS NULL AND clients.client_lead = 0)
AND (software_template_required = " . SOFTWARE_TEMPLATE_REQUIRED_EVERY . " OR EXISTS (SELECT 1 FROM software_template_required_tags rt
JOIN client_tags ON client_tags.tag_id = rt.tag_id AND client_tags.client_id = $client_id
WHERE rt.software_template_id = software_templates.software_template_id))
AND NOT EXISTS (SELECT 1 FROM software WHERE software_client_id = $client_id AND software.software_template_id = software_templates.software_template_id AND software_archived_at IS NULL)
ORDER BY software_template_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$missing[intval($row['software_template_id'])] = (string) $row['software_template_name'];
}
return $missing;
}
/* ---------------------------------------------------------------- its licenses across clients */
/*
* The current licenses made from a template, for current clients, by client
* name - [software id => row]: the license and its client, 'seats'
* (softwareSeats()), 'renewal' (softwareRenewal()) and 'billing'
* (softwareTemplateBilling(), with the template's $product_id).
*/
function softwareTemplateLicenses($software_template_id, $product_id = 0) {
global $mysqli;
$software_template_id = intval($software_template_id);
$licenses = [];
$sql = mysqli_query($mysqli, "SELECT software_id, software_name, software_seats, software_expire, software_created_at, software_client_id, client_name, client_abbreviation,
" . softwareSeatsUsedSql('software.software_id') . " AS seats_used
FROM software JOIN clients ON client_id = software_client_id AND client_archived_at IS NULL
WHERE software_template_id = $software_template_id AND software_archived_at IS NULL
ORDER BY client_name ASC, software_id ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$row['seats'] = softwareSeats($row['seats_used'], $row['software_seats']);
$row['renewal'] = softwareRenewal($row['software_expire']);
$licenses[intval($row['software_id'])] = $row;
}
$billing = softwareTemplateBilling($licenses, $product_id);
foreach ($licenses as $software_id => $row) {
$licenses[$software_id]['billing'] = $billing[$software_id] ?? null;
}
return $licenses;
}
/*
* How each license is billed on its client's recurring invoices (not
* archived) - [software id => ['how' => 'seats' (a line counts its seats) or
* 'product' (a line for $product_id, its quantity typed in), 'item_id',
* 'recurring_invoice_id', 'number', 'paused', 'quantity', 'count' ('used' or
* 'total', for seats), 'drift' (a typed quantity that isn't its seats)]]. Not
* there when it isn't billed. $licenses: rows with software_id,
* software_client_id, software_seats and seats_used.
*/
function softwareTemplateBilling(array $licenses, $product_id = 0) {
global $mysqli;
$product_id = intval($product_id);
$billing = [];
$by_client = [];
foreach ($licenses as $row) {
$by_client[intval($row['software_client_id'])][] = intval($row['software_id']);
}
if (!$by_client) {
return $billing;
}
$sql = mysqli_query($mysqli, "SELECT item_id, item_quantity, item_seat_source, item_seat_filter, item_product_id, recurring_invoice_id, recurring_invoice_prefix,
recurring_invoice_number, recurring_invoice_status, recurring_invoice_client_id
FROM recurring_invoice_items JOIN recurring_invoices ON recurring_invoice_id = item_recurring_invoice_id AND recurring_invoice_archived_at IS NULL
WHERE recurring_invoice_client_id IN (" . implode(',', array_keys($by_client)) . ")
AND (item_seat_source = 'license'" . ($product_id ? " OR item_product_id = $product_id" : '') . ")
ORDER BY recurring_invoice_status DESC, recurring_invoice_id ASC, item_order ASC, item_id ASC");
$product_lines = [];
while ($row = mysqli_fetch_assoc($sql)) {
$line = [
'item_id' => intval($row['item_id']), 'recurring_invoice_id' => intval($row['recurring_invoice_id']),
'number' => (string) $row['recurring_invoice_prefix'] . $row['recurring_invoice_number'], 'paused' => intval($row['recurring_invoice_status']) !== 1,
'quantity' => floatval($row['item_quantity']),
];
if ($row['item_seat_source'] === 'license') {
$filter = recurringSeatFilter('license', $row['item_seat_filter']);
$software_id = intval($filter['software_id']);
if (in_array($software_id, $by_client[intval($row['recurring_invoice_client_id'])], true) && !isset($billing[$software_id])) {
$billing[$software_id] = $line + ['how' => 'seats', 'count' => $filter['count'], 'drift' => false];
}
} elseif ($product_id && intval($row['item_product_id']) === $product_id) {
$product_lines[intval($row['recurring_invoice_client_id'])] = $product_lines[intval($row['recurring_invoice_client_id'])] ?? $line;
}
}
// A line for the product, its quantity typed in, bills the client's licenses not counted by a line of their own
foreach ($licenses as $row) {
$software_id = intval($row['software_id']);
$line = $product_lines[intval($row['software_client_id'])] ?? null;
if (isset($billing[$software_id]) || !$line) {
continue;
}
$seats = intval($row['software_seats']) > 0 ? intval($row['software_seats']) : intval($row['seats_used']);
$billing[$software_id] = $line + ['how' => 'product', 'count' => '', 'drift' => round($line['quantity'], 2) != $seats];
}
return $billing;
}
/*
* The views of a template's licenses on its page - key => [label, icon,
* title, test(row)]: all of them, over seats, spare seats, renewing in 30
* days, past their renewal date, and - when it is sold as a product - not
* billed.
*/
function softwareTemplateLicenseViews($has_product) {
$views = [
'' => ['label' => 'All', 'icon' => 'fa-list', 'title' => 'Every current license made from it', 'test' => function () {
return true;
}],
'over' => ['label' => 'Over seats', 'icon' => 'fa-exclamation-triangle', 'title' => 'More devices and users than seats bought - a true-up to bill', 'test' => function ($row) {
return $row['seats']['state'] === 'over';
}],
'spare' => ['label' => 'Spare seats', 'icon' => 'fa-chair', 'title' => 'Seats bought that nobody is on - seats to free', 'test' => function ($row) {
return $row['seats']['total'] > 0 && $row['seats']['used'] < $row['seats']['total'];
}],
'renewing' => ['label' => 'Renewing soon', 'icon' => 'fa-hourglass-half', 'title' => 'Renewing in the next 30 days', 'test' => function ($row) {
return $row['renewal'] && $row['renewal']['state'] === 'soon';
}],
'expired' => ['label' => 'Expired', 'icon' => 'fa-calendar-times', 'title' => 'Past their renewal date', 'test' => function ($row) {
return $row['renewal'] && $row['renewal']['state'] === 'expired';
}],
];
if ($has_product) {
$views['unbilled'] = ['label' => 'Not billed', 'icon' => 'fa-file-invoice-dollar', 'title' => "Not on the client's recurring invoice", 'test' => function ($row) {
return empty($row['billing']);
}];
}
return $views;
}
/*
* True up licenses from a template - [software id => seats] (blank for no
* limit). Only current licenses from it whose seats change. What changed -
* [software id => ['name', 'client_id', 'client_name', 'from', 'to']], seats
* as numbers or null.
*/
function softwareTemplateTrueUp($software_template_id, array $seats_by_id) {
global $mysqli;
$software_template_id = intval($software_template_id);
$changes = [];
foreach ($seats_by_id as $software_id => $seats) {
$software_id = intval($software_id);
$seats = trim((string) $seats);
$to = $seats === '' ? null : max(0, min(1000000, intval($seats)));
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT software_name, software_seats, software_client_id, client_name FROM software
JOIN clients ON client_id = software_client_id AND client_archived_at IS NULL
WHERE software_id = $software_id AND software_template_id = $software_template_id AND software_archived_at IS NULL"));
if (!$row) {
continue;
}
$from = $row['software_seats'] === null ? null : intval($row['software_seats']);
if ($from === $to) {
continue;
}
mysqli_query($mysqli, "UPDATE software SET software_seats = " . ($to === null ? 'NULL' : $to) . " WHERE software_id = $software_id");
$changes[$software_id] = ['name' => (string) $row['software_name'], 'client_id' => intval($row['software_client_id']), 'client_name' => (string) $row['client_name'], 'from' => $from, 'to' => $to];
}
return $changes;
}
/* Seats in words - "12 seats", "no seat limit". */
function softwareTemplateSeatsText($seats) {
return $seats === null ? 'no seat limit' : intval($seats) . ' seat' . (intval($seats) === 1 ? '' : 's');
}
/*
* The recurring invoices licenses can be billed on - [client id =>
* [recurring invoice id => row with 'number']], each client's not archived,
* the active ones first.
*/
function softwareTemplateRecurringFor(array $client_ids) {
global $mysqli;
$client_ids = array_values(array_unique(array_filter(array_map('intval', $client_ids))));
$recurring = array_fill_keys($client_ids, []);
if (!$client_ids) {
return $recurring;
}
$sql = mysqli_query($mysqli, "SELECT recurring_invoice_id, recurring_invoice_prefix, recurring_invoice_number, recurring_invoice_scope, recurring_invoice_frequency,
recurring_invoice_status, recurring_invoice_amount, recurring_invoice_currency_code, recurring_invoice_client_id
FROM recurring_invoices WHERE recurring_invoice_archived_at IS NULL AND recurring_invoice_client_id IN (" . implode(',', $client_ids) . ")
ORDER BY recurring_invoice_status DESC, recurring_invoice_id ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$row['number'] = (string) $row['recurring_invoice_prefix'] . $row['recurring_invoice_number'];
$recurring[intval($row['recurring_invoice_client_id'])][intval($row['recurring_invoice_id'])] = $row;
}
return $recurring;
}
/*
* Bill a license from a template on one of its client's recurring invoices:
* a line for the template's product - its name, description, price and tax -
* counting the license's seats bought ($count 'total') or in use ('used'),
* so it follows them from then on. One with no seat limit counts the seats in
* use - it has none bought to count. The line's id, or null with $error.
*/
function softwareTemplateBill($software_template_id, $software_id, $recurring_invoice_id, $count, &$error = '') {
global $mysqli;
$error = '';
$template = softwareTemplateRow($software_template_id);
$product = $template && intval($template['software_template_product_id']) ? productRow($template['software_template_product_id']) : null;
if (!$product) {
$error = 'It is not sold as a product - pick the product on the template first.';
return null;
}
if ($product['product_archived_at']) {
$error = 'The product it is sold as is archived - restore it, or pick another on the template.';
return null;
}
$software_id = intval($software_id);
$recurring_invoice_id = intval($recurring_invoice_id);
$license = mysqli_fetch_row(mysqli_query($mysqli, "SELECT software_client_id, software_seats FROM software WHERE software_id = $software_id
AND software_template_id = " . intval($template['software_template_id']) . " AND software_archived_at IS NULL"));
$client_id = intval($license[0] ?? 0);
if (intval($license[1] ?? 0) <= 0) {
$count = 'used';
}
if (!$client_id) {
$error = 'That license is gone, or not made from this template.';
return null;
}
if (!mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM recurring_invoices WHERE recurring_invoice_id = $recurring_invoice_id
AND recurring_invoice_client_id = $client_id AND recurring_invoice_archived_at IS NULL"))) {
$error = "That isn't one of the client's recurring invoices.";
return null;
}
return billingItemSave('recurring', $recurring_invoice_id, [
'name' => $product['product_name'], 'description' => (string) $product['product_description'],
'price' => $product['product_price'], 'tax_id' => intval($product['product_tax_id']), 'product_id' => intval($product['product_id']),
'seat_source' => 'license', 'seat_software_id' => $software_id, 'seat_count' => $count === 'total' ? 'total' : 'used', 'seat_minimum' => 0,
], 0, $error);
}

View File

@@ -690,8 +690,8 @@ function tagMerge(array $from_ids, $into_id) {
$moved = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(DISTINCT {$config['link_record']}) FROM {$config['link_table']} WHERE {$config['link_tag']} IN ($from_list)"))[0]);
mysqli_query($mysqli, "INSERT IGNORE INTO {$config['link_table']} ({$config['link_record']}, {$config['link_tag']})
SELECT DISTINCT {$config['link_record']}, $into_id FROM {$config['link_table']} WHERE {$config['link_tag']} IN ($from_list)");
// Templates that go by these tags - a ticket template's tags, the clients a document template is required of - go by the one they are merged into
foreach (['ticket_template_tags' => 'ticket_template_id', 'document_template_required_tags' => 'document_template_id'] as $table => $column) {
// Templates that go by these tags - a ticket template's tags, the clients a document or license template is required of - go by the one they are merged into
foreach (['ticket_template_tags' => 'ticket_template_id', 'document_template_required_tags' => 'document_template_id', 'software_template_required_tags' => 'software_template_id'] as $table => $column) {
mysqli_query($mysqli, "INSERT IGNORE INTO $table ($column, tag_id) SELECT DISTINCT $column, $into_id FROM $table WHERE tag_id IN ($from_list)");
}
foreach (tagSeatLineItems($from_ids) as $item_id => $filter) {