From b76bdd4b824e7408518aa4482de5afdd0d11a112 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Sun, 18 Oct 2026 21:10:29 -0400 Subject: [PATCH] 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 --- CHANGELOG.md | 15 +- admin/database_updates/3.3.0.php | 22 ++ .../software_template_bill.php | 136 +++++++ .../software_template_required.php | 89 +++++ .../software_template_true_up.php | 103 ++++++ .../software_template_use_several.php | 16 +- admin/post/software_template.php | 118 +++++- admin/software_template.php | 209 +++++++++-- admin/software_templates.php | 56 ++- agent/modals/software/software_renew.php | 2 +- agent/software.php | 22 +- db.sql | 18 + functions/client_overview.php | 7 + functions/software_template.php | 346 +++++++++++++++++- functions/tags.php | 4 +- 15 files changed, 1112 insertions(+), 51 deletions(-) create mode 100644 admin/database_updates/3.3.0.php create mode 100644 admin/modals/software_template/software_template_bill.php create mode 100644 admin/modals/software_template/software_template_required.php create mode 100644 admin/modals/software_template/software_template_true_up.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 302d3c5b9..6c03b57cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/admin/database_updates/3.3.0.php b/admin/database_updates/3.3.0.php new file mode 100644 index 000000000..b8cac99df --- /dev/null +++ b/admin/database_updates/3.3.0.php @@ -0,0 +1,22 @@ + + + + + + +
+ + + + + +
+ + + + + + + +
+ + + + + + + +
+ + + + + + + 0 && $row['seats']['used'] !== $row['seats']['total']; + }); + ?> + + +
+ + + + + +
+ + + + 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']); + } ?> + +
+
diff --git a/admin/post/software_template.php b/admin/post/software_template.php index d106c8f92..a715bf03b 100644 --- a/admin/post/software_template.php +++ b/admin/post/software_template.php @@ -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("" . escapeHtml($row['software_template_name']) . " 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("" . escapeHtml($change['client_name']) . " trued up from " . softwareTemplateSeatsText($change['from']) . " to " . softwareTemplateSeatsText($change['to'])); + } else { + flashAlert($count ? "Trued up $count licenses from " . escapeHtml($row['software_template_name']) . "" : '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 $added license" . ($added === 1 ? '' : 's') . " as " . escapeHtml((string) $row['product_name']) . "" + . ($skipped ? " - $skipped billed already" : '') . ($errors ? ' - ' . escapeHtml(implode(' ', array_keys($errors))) : ''), $errors ? 'warning' : 'success'); + + redirect(); + +} + if (isset($_GET['copy_software_template'])) { validateCSRFToken(); diff --git a/admin/software_template.php b/admin/software_template.php index ae891fabb..1e2223642 100644 --- a/admin/software_template.php +++ b/admin/software_template.php @@ -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([
@@ -94,6 +132,7 @@ $facts = array_filter([ -
-
-

Licenses made from it

- count($licenses)) { ?>The latest of +
+
+

Clients with it

+ + +
+ +
+ +
+ +
+ . + +
+ +
- + + + + + + - $row) { + $client_id = intval($row['software_client_id']); + $billing = $row['billing']; ?> - - + + + + + + + + - - -
ClientSeatsRenewsMade
ClientSeatsRenewsBilled
- +
+
+
+
-' ?> + + + Paused +
+
Not its seats
+ + Not billed + +
+ -' ?>
+ +
None of them - see them all.
No licenses made from it yet. Agents start one from New License on a client's Licenses.
@@ -183,6 +293,9 @@ $facts = array_filter([
  • ' . $usage['used'] . ' of ' . $usage['seats'] . ' seats in use' : '' . $usage['used'] . ' seats in use' ?>
  • renewing in the next 30 days
  • past their renewal date
  • + +
  • +
    No licenses made from it yet - counting started with this version of ITFlow, with the licenses already called what it is called.
    @@ -190,6 +303,50 @@ $facts = array_filter([
    +
    +
    +

    Who should have it

    + +
    +
    + +
    No one in particular. Set it up to see which clients are missing it - every client, or the ones with a tag.
    + +
    - not counted while it is archived.
    + +
    + + of have it +
    +
    +
    +
    + +
    Missing it
    +
    + $client_name) { ?> +
    + + + +
    + +
    + $list_limit) { ?> +
    and more
    + + + +
    Every one of them has it.
    + +
    .
    + + +
    +
    +

    Details

    @@ -207,5 +364,7 @@ $facts = array_filter([
    + + '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 '' . $label . ($sort === $column ? " $order_icon" : '') . ''; }; -$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'];
    - +
    @@ -107,8 +127,9 @@ $csrf = $_SESSION['csrf_token'];
    @@ -154,6 +175,15 @@ $csrf = $_SESSION['csrf_token'];
    + + +
    Archived
    @@ -193,6 +223,9 @@ $csrf = $_SESSION['csrf_token']; For several clients + + Who should have it + Copy @@ -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 - Who should have it - 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 New License on a client\'s Licenses.', 'actions' => [['label' => 'New License Template', 'modal' => $add_url, 'size' => 'lg']], ]; diff --git a/agent/modals/software/software_renew.php b/agent/modals/software/software_renew.php index 03d8f16cf..f70964de4 100644 --- a/agent/modals/software/software_renew.php +++ b/agent/modals/software/software_renew.php @@ -47,7 +47,7 @@ ob_start();
    -
    + diff --git a/agent/software.php b/agent/software.php index a711e60cc..f004bc30b 100644 --- a/agent/software.php +++ b/agent/software.php @@ -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)) {
    + + +
    + : + $missing_name) { ?> + + + + + + +
    + +
    diff --git a/db.sql b/db.sql index 8e525043c..ef4cedb43 100644 --- a/db.sql +++ b/db.sql @@ -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, diff --git a/functions/client_overview.php b/functions/client_overview.php index a8288f2da..e1fec4a25 100644 --- a/functions/client_overview.php +++ b/functions/client_overview.php @@ -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']) { diff --git a/functions/software_template.php b/functions/software_template.php index bdae13321..2825ea7cf 100644 --- a/functions/software_template.php +++ b/functions/software_template.php @@ -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); +} diff --git a/functions/tags.php b/functions/tags.php index 6400be269..191212b5a 100644 --- a/functions/tags.php +++ b/functions/tags.php @@ -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) {