diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c03b57cb..dbd553ae2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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, and none is required of anyone until you set it up on its page. +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. Maintenance > Starter Content has a new License Templates pack to add. 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. @@ -563,6 +563,10 @@ If you are coming from 26.08 or earlier, the database update still has to be run - 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. + - Export and import: Admin > License Templates exports every current template, the ones picked (archived ones too, if you like), or one from its page or its row, as a file to import into another ITFlow or keep. Each goes with what a license made from it starts with, its vendor template - never its account number or code - and the name of the product it is sold as; not who should have it, which is each install's own call. Importing, its vendor is the vendor template of that name, added from the file when there isn't one, and it is sold as the product of that name when there is one - prices are yours, so no product is added. One already here by name is left as it is, added as well under a name of its own, or replaced - keeping its licenses, who should have it and, unless the file's product is here, its own product. A new one comes in required of no one. + - Starter Content has a License Templates pack: Microsoft 365 Business Basic, Standard and Premium, Exchange Online, Google Workspace, Bitdefender GravityZone, ESET PROTECT, Proofpoint Essentials, Bitwarden Teams, a FortiGate security bundle, Veeam Backup & Replication, Veeam Backup for Microsoft 365, Acronis Cyber Protect Cloud, Synology Active Backup, Adobe Acrobat Pro and Creative Cloud, QuickBooks Online, Zoom and Windows Server with its CALs. Each comes with its type, how it is licensed, how often it renews, notes on how it is licensed and assigned, and its vendor, and is sold as the product of the same name once the Products & Services pack is here. Who should have each is yours to set. Update brings the ones you added up to the current version. + - The New License Template button's menu has Import, Export, the report and the starter ones. + - Reports > License Templates: for each template, the licenses made from it in the period against the period before, its current licenses and clients, their seats in use against bought - over and spare - the ones renewing in the next 30 days or expired, how many of the clients that should have one do and, for anyone who can see Sales, how many are billed and what that comes to a month. By client too: the licenses each should have, the ones missing, licenses over seats, renewals and the ones not billed. One client can be picked, and each can be exported. - **Assets** - The asset list has: - type icons, colored status pills and OS icons @@ -1566,6 +1570,9 @@ If you are coming from 26.08 or earlier, the database update still has to be run - `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. + - Export and import: new `functions/software_template_transfer.php` - `softwareTemplatesExport($ids, $archived)` (the file's contents: `format` itflow-license-templates, `version` 1, `templates`, each with `name`, `version`, `description`, `type`, `license_type`, `notes`, `seats`, `term`, `vendor` - `name` and the `SOFTWARE_TEMPLATE_FILE_VENDOR_FIELDS`, or null - and `product` by name), `softwareTemplatesExportFileName()`, `softwareTemplatesImportRead($contents, &$error)` (checks and tidies a file, and takes the starter pack's array the same way), `softwareTemplateImportVendor($vendor, &$made)`, `softwareTemplateImportProduct($name)` (current products only), `softwareTemplatesImport($templates, $existing, $only_existing)` (`skip`, `copy` or `replace`; `added`, `replaced`, `skipped`, `vendors`, `products` not found, `ids`) and `softwareTemplatesImportSummary()`. Handlers in `admin/post/software_template.php`: POST `export_software_templates` (`software_template_ids[]`, `archived`), GET `export_software_template` and POST `import_software_templates` (`file`, `existing`), with `admin/modals/software_template/software_template_export.php` and `software_template_import.php`. Audit entries are Software Template Export and Import. + - Starter Content: new `license_templates` pack, after `products` so a load of every pack links the products - `starterContentLicenseTemplates()` in the file format, `starterLoadLicenseTemplates()` through `softwareTemplatesImport()`, and `starterUpdateLicenseTemplates()` with the `update_starter_license_templates` handler. + - Report: `agent/reports/license_templates.php` (`client_id` and the period; `export=csv` by template, `table=clients` by client; the billing columns only with `module_sales`), `license_templates` in `reportCatalog()` under Clients & Documentation. - 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/modals/software_template/software_template_export.php b/admin/modals/software_template/software_template_export.php new file mode 100644 index 000000000..884c524de --- /dev/null +++ b/admin/modals/software_template/software_template_export.php @@ -0,0 +1,55 @@ + + + +
+ + + + + +
+ + + + +
+ + + + + +
+ + 20 * 1024 * 1024) { + flashAlert('That file is too big to be license templates.', 'error'); + redirect('software_templates.php'); + } + $templates = softwareTemplatesImportRead(file_get_contents($file['tmp_name']), $import_error); + if ($templates === null) { + flashAlert(escapeHtml($import_error), 'error'); + redirect('software_templates.php'); + } + $existing = in_array($_POST['existing'] ?? '', ['skip', 'copy', 'replace'], true) ? $_POST['existing'] : 'skip'; + $counts = softwareTemplatesImport($templates, $existing); + + logAudit("Software Template", "Import", "$session_name imported license templates from " . escapeSql(mb_substr((string) $file['name'], 0, 100)) . " - {$counts['added']} added, {$counts['replaced']} replaced, {$counts['skipped']} skipped" + . ($counts['vendors'] ? ", {$counts['vendors']} vendor templates added" : '')); + + flashAlert(softwareTemplatesImportSummary($counts), $counts['products'] ? 'warning' : ($counts['added'] || $counts['replaced'] ? 'success' : 'info')); + + redirect('software_templates.php'); + +} diff --git a/admin/post/starter_content.php b/admin/post/starter_content.php index 470290292..4da838d53 100644 --- a/admin/post/starter_content.php +++ b/admin/post/starter_content.php @@ -106,6 +106,26 @@ if (isset($_POST['update_starter_document_templates'])) { } +if (isset($_POST['update_starter_license_templates'])) { + + // The starter license templates already here, brought up to this version + validateCSRFToken(); + + require_once 'starter_content_model.php'; + + $counts = starterUpdateLicenseTemplates(); + + if ($counts['replaced']) { + logAudit("Starter Content", "Edit", "$session_name brought {$counts['replaced']} starter license templates up to date"); + flashAlert("Brought {$counts['replaced']} starter license templates up to date" . ($counts['vendors'] ? " - with {$counts['vendors']} vendor template" . ($counts['vendors'] === 1 ? '' : 's') . " they come from" : '')); + } else { + flashAlert("None of the starter license templates are here to update - add them instead", 'info'); + } + + redirect(); + +} + if (isset($_POST['load_demo_data'])) { validateCSRFToken(); diff --git a/admin/post/starter_content_model.php b/admin/post/starter_content_model.php index d78588ac5..3cd321b82 100644 --- a/admin/post/starter_content_model.php +++ b/admin/post/starter_content_model.php @@ -76,6 +76,15 @@ function starterContentPacks() { 'description' => 'Recurring services, labor rates, project work and hardware lines. Prices are starting points - hardware and resold SKUs come in at zero.', 'requires' => 'categories', ], + 'license_templates' => [ + 'label' => 'License Templates', + 'icon' => 'fa-cube', + 'description' => "The licenses an MSP sells and looks after - Microsoft 365, Google Workspace, endpoint protection, email security, backup, password management and the desktop apps clients run - each with its type, how it is licensed, how often it renews and what to know about it, its vendor, and the product it is sold as once Products & Services is here. Who should have each is yours to set on its page.", + 'update' => [ + 'button' => 'update_starter_license_templates', + 'confirm' => 'Bring the %d starter license templates you have up to date? Their summary, type, license type, seats, renewal term, vendor and notes are replaced with this version - changes you made to them are lost. Their licenses and who should have them stay as they are.', + ], + ], ]; } @@ -167,6 +176,8 @@ function starterContentLoad($mysqli, $pack, $dry_run = false) { return starterLoadDocumentTemplates($mysqli, $dry_run); case 'products': return starterLoadProducts($mysqli, $dry_run); + case 'license_templates': + return starterLoadLicenseTemplates($mysqli, $dry_run); } return 0; } @@ -211,6 +222,8 @@ function starterContentTotal($pack) { return count(starterContentDocumentTemplates()); case 'products': return count(starterContentProducts()); + case 'license_templates': + return count(starterContentLicenseTemplates()); } return 0; } @@ -428,6 +441,37 @@ function starterUpdateDocumentTemplates() { return documentTemplatesImport($templates, 'replace', true); } +// ------------------------------ +// starterLoadLicenseTemplates +// Through the license template import. One whose name a template here +// already has, archived or not, is left alone. Its vendor is the vendor +// template of that name - added from here when there is none - and it is +// sold as the product of that name when there is one. +// ------------------------------ +function starterLoadLicenseTemplates($mysqli, $dry_run = false) { + $templates = softwareTemplatesImportRead(['format' => SOFTWARE_TEMPLATE_FILE_FORMAT, 'version' => SOFTWARE_TEMPLATE_FILE_VERSION, 'templates' => starterContentLicenseTemplates()]); + if ($dry_run) { + $existing = starterExistingNames($mysqli, 'software_templates', 'software_template_name'); + return count(array_filter($templates, function ($template) use ($existing) { + return !isset($existing[mb_strtolower($template['name'])]); + })); + } + return softwareTemplatesImport($templates, 'skip')['added']; +} + +// ------------------------------ +// starterUpdateLicenseTemplates +// The starter license templates already here, brought up to this library's +// version - their summary, type, license type, seats, renewal term, vendor +// and notes replaced, and the product they are sold as when it is here. Their +// licenses, and who should have them, stay. +// Returns the import's counts (softwareTemplatesImport()). +// ------------------------------ +function starterUpdateLicenseTemplates() { + $templates = softwareTemplatesImportRead(['format' => SOFTWARE_TEMPLATE_FILE_FORMAT, 'version' => SOFTWARE_TEMPLATE_FILE_VERSION, 'templates' => starterContentLicenseTemplates()]); + return softwareTemplatesImport($templates, 'replace', true); +} + // ------------------------------ // starterLoadProducts // Products are filed under income categories. A category that is not present @@ -1857,3 +1901,117 @@ function starterContentProducts() { return $products; } + +// ------------------------------ +// starterContentLicenseTemplates +// In the license templates file format (functions/software_template_transfer.php): +// name, version, description, type (a software type from the categories every +// install starts with), license_type, notes, seats (none - each client has its +// own), term (how often it renews, from when it was bought), vendor (as in the +// vendor templates pack, made from here when it isn't) and product (the one +// of that name in the Products & Services pack, when it is here). Who should +// have each is left to the MSP, on the template's page. +// ------------------------------ +function starterContentLicenseTemplates() { + + $vendors = []; + foreach (starterContentVendorTemplates() as $vendor) { + $vendors[$vendor[0]] = ['name' => $vendor[0], 'description' => $vendor[1], 'website' => $vendor[2]]; + } + $template = function ($name, $description, $type, $license_type, $term, $vendor, $product, array $notes) use ($vendors) { + return [ + 'name' => $name, 'version' => '', 'description' => $description, 'type' => $type, 'license_type' => $license_type, + 'notes' => implode("\n\n", $notes), 'seats' => null, 'term' => $term, 'vendor' => $vendors[$vendor] ?? null, 'product' => $product, + ]; + }; + $m365_notes = [ + 'Licenses are assigned to users in the Microsoft 365 admin center (admin.microsoft.com), under Billing > Licenses - each user with one takes a seat.', + 'On an annual commitment seats can be added at any time but only taken away at renewal, so true up the seats before the renewal date.', + "The tenant's global admin login belongs in Credentials, and its domains under Domains.", + ]; + + return [ + + // Productivity and email + $template('Microsoft 365 Business Basic', 'Web and mobile Office apps, Exchange mail, Teams and OneDrive', 'Productivity Suite', 'User', '1y', 'Microsoft', 'Microsoft 365 Business Basic', $m365_notes), + $template('Microsoft 365 Business Standard', 'Desktop Office apps, Exchange mail, Teams and OneDrive', 'Productivity Suite', 'User', '1y', 'Microsoft', 'Microsoft 365 Business Standard', $m365_notes), + $template('Microsoft 365 Business Premium', 'Business Standard with Intune, Entra ID P1 and Defender for Business', 'Productivity Suite', 'User', '1y', 'Microsoft', 'Microsoft 365 Business Premium', array_merge($m365_notes, [ + "Devices are enrolled in Intune - keep the enrolment, compliance and conditional access policies with the client's documentation.", + ])), + $template('Exchange Online (Plan 1)', 'A mailbox, without the Office apps - for staff who only need mail', 'Software as a Service (SaaS)', 'User', '1y', 'Microsoft', 'Microsoft 365 Exchange Online Plan 1', [ + 'Assigned to users in the Microsoft 365 admin center, under Billing > Licenses. Shared mailboxes need no license until they pass their size limit or need an archive.', + "The tenant's global admin login belongs in Credentials.", + ]), + $template('Google Workspace Business Standard', 'Gmail, Drive, Meet and the Docs editors', 'Productivity Suite', 'User', '1y', 'Google', null, [ + 'Licenses are assigned in the Google Admin console (admin.google.com), under Billing. Every active user takes one.', + 'On the Annual plan seats can be added at any time but not taken away until it renews; the Flexible plan is billed monthly for the users there are.', + "The super admin login belongs in Credentials, and the client's domain under Domains.", + ]), + + // Security + $template('Bitdefender GravityZone Business Security', 'Endpoint protection for workstations and servers', 'Security Software', 'Device', '1y', 'Bitdefender', 'Endpoint Protection', [ + 'Agents are installed from a package made in the GravityZone console - each device with an agent takes a seat.', + 'Removing the agent needs the uninstall password set in its policy - keep it in Credentials.', + ]), + $template('ESET PROTECT', 'Endpoint protection managed from the ESET PROTECT console', 'Security Software', 'Device', '1y', 'ESET', 'Endpoint Protection', [ + 'Devices are deployed and managed from the ESET PROTECT console - each activated device takes a seat.', + 'The license is in ESET PRO (or the MSP portal); keep that login and the console login in Credentials.', + ]), + $template('Proofpoint Essentials', 'Email security - spam, phishing and malware filtering in front of the mailboxes', 'Software as a Service (SaaS)', 'User', '1y', 'Proofpoint', 'Email Security', [ + "Licensed per protected mailbox. The client's MX records point at Proofpoint, and the mail server only takes mail from it - keep the connector settings with the client's documentation.", + 'Users added in the Proofpoint console, or synced from the directory, take a seat.', + ]), + $template('Bitwarden Teams', 'Shared password vault for the business', 'Software as a Service (SaaS)', 'User', '1y', 'Bitwarden', 'Password Manager', [ + "Each member of the client's organization takes a seat. Collections decide who sees which logins.", + "The organization owner's login, and its recovery code, belong in Credentials.", + ]), + $template('Fortinet FortiGate Security Bundle', 'Threat protection, web filtering and support for a FortiGate firewall', 'Security Software', 'Device', '1y', 'Fortinet', null, [ + "Registered to the firewall's serial number in FortiCare - one per firewall. When it lapses the firewall keeps passing traffic, but its threat and web filtering signatures stop updating.", + 'Renewal is by the contract code applied in FortiCare - keep the FortiCare login in Credentials.', + ]), + + // Backup + $template('Veeam Backup & Replication', 'Image based backup and replication for servers and virtual machines', 'System Software', 'Device', '1y', 'Veeam', 'Managed Backup - Server', [ + 'Licensed per protected workload - each server or virtual machine backed up takes an instance. The license file is installed on the backup server.', + 'Keep the Veeam account login, and the encryption password for the backup jobs, in Credentials - without it encrypted backups cannot be restored.', + ]), + $template('Veeam Backup for Microsoft 365', "Backup of the client's Exchange Online, OneDrive, SharePoint and Teams", 'System Software', 'User', '1y', 'Veeam', 'Microsoft 365 Backup', [ + 'Licensed per protected user. It reaches the tenant through an app registration in Entra ID, and backs up to its own repository.', + "Keep the repository location and the app registration with the client's documentation.", + ]), + $template('Acronis Cyber Protect Cloud', 'Backup and protection for workstations and servers, billed on use', 'System Software', 'Usage-based', '1m', 'Acronis', 'Managed Backup - Workstation', [ + 'Billed monthly on what is protected and stored, from the Acronis partner portal - the seats here are what was protected at the last count.', + 'Agents are installed from the client tenant in the Acronis console.', + ]), + $template('Synology Active Backup for Business', 'Backup of PCs, servers and Microsoft 365 to a Synology NAS', 'System Software', 'Site', '', 'Synology', null, [ + 'Comes with a Synology NAS - there is no key and nothing to renew. Agents installed on each device back up to the NAS.', + "Keep the NAS login in Credentials, and the NAS itself in the client's assets.", + ]), + + // Business applications + $template('Adobe Acrobat Pro', 'Create, edit, sign and convert PDFs', 'Desktop Application', 'User', '1y', 'Adobe', null, [ + 'Named user licensing - assigned to users in the Adobe Admin Console (adminconsole.adobe.com). A user signs in to Acrobat to use it.', + ]), + $template('Adobe Creative Cloud All Apps', 'Photoshop, Illustrator, InDesign and the rest of the Creative Cloud apps', 'Desktop Application', 'User', '1y', 'Adobe', null, [ + 'Named user licensing - assigned to users in the Adobe Admin Console. Each user can sign in on two computers at once.', + ]), + $template('QuickBooks Online Plus', 'Accounting, invoicing and bill paying', 'Software as a Service (SaaS)', 'Subscription', '1m', 'Intuit', null, [ + 'Usually the client\'s own subscription, billed to them by Intuit each month - the plan sets how many users it has.', + "The primary admin is normally the client's owner or accountant; note who it is here.", + ]), + $template('Zoom Workplace Pro', 'Meetings, chat and whiteboards', 'Software as a Service (SaaS)', 'User', '1y', 'Zoom', null, [ + "Licensed users are assigned in the Zoom admin portal; basic users don't take a seat.", + ]), + + // Operating systems + $template('Windows Server Standard', 'The server operating system, licensed by core', 'Operating System', 'Perpetual', '', 'Microsoft', null, [ + 'Licensed by the physical cores in the server - at least 8 cores per processor and 16 per server. Standard covers two virtual machines on the licensed server; licensing its cores again covers two more.', + 'Users and devices that use the server need Windows Server CALs as well.', + ]), + $template('Windows Server CAL', 'Client access licenses for users or devices that use a Windows Server', 'Operating System', 'User', '', 'Microsoft', null, [ + 'One per user, or per device, that reaches a Windows Server - not per server. Remote Desktop sessions need Remote Desktop Services CALs on top.', + ]), + + ]; + +} diff --git a/admin/software_template.php b/admin/software_template.php index 1e2223642..641a09dee 100644 --- a/admin/software_template.php +++ b/admin/software_template.php @@ -134,6 +134,7 @@ $facts = array_filter([ + + + + + diff --git a/functions.php b/functions.php index 8d4542635..c883a8e5a 100644 --- a/functions.php +++ b/functions.php @@ -58,6 +58,7 @@ require_once __DIR__ . '/functions/canned_response.php'; require_once __DIR__ . '/functions/canned_response_transfer.php'; require_once __DIR__ . '/functions/document_template.php'; require_once __DIR__ . '/functions/document_template_transfer.php'; +require_once __DIR__ . '/functions/software_template_transfer.php'; require_once __DIR__ . '/functions/project.php'; require_once __DIR__ . '/functions/service.php'; require_once __DIR__ . '/functions/client_export.php'; diff --git a/functions/reports.php b/functions/reports.php index 1f85b271a..da3271216 100644 --- a/functions/reports.php +++ b/functions/reports.php @@ -180,6 +180,10 @@ function reportCatalog() { 'title' => 'Document Templates', 'icon' => 'fa-file-alt', 'module' => 'module_support', 'feature' => ['itdoc'], 'description' => 'How often each document template is used, how many of the clients that should have a document from one do, and the documents due a review - by template and by client.', ], + 'license_templates' => [ + 'title' => 'License Templates', 'icon' => 'fa-cube', 'module' => 'module_support', 'feature' => ['itdoc'], + 'description' => 'How much each license template is used, the seats on its licenses against the ones bought, how many of the clients that should have one do, and how many are billed - by template and by client.', + ], 'credential_rotation' => [ 'title' => 'Credential Rotation', 'icon' => 'fa-key', 'module' => 'module_credential', 'feature' => ['itdoc'], 'description' => 'Passwords that have not changed in a while, oldest first.', diff --git a/functions/software_template_transfer.php b/functions/software_template_transfer.php new file mode 100644 index 000000000..9531e5f94 --- /dev/null +++ b/functions/software_template_transfer.php @@ -0,0 +1,259 @@ + License Templates exports them + * (export_software_templates) and imports them (import_software_templates); + * the MSP starter pack on Maintenance > Starter Content is loaded the same way. + * + * The file is JSON: {"format": "itflow-license-templates", "version": 1, + * "exported_at", "templates": [...]}. Each template carries what a license + * made from it starts with - its name, version, summary, type, license type, + * notes, seats and renewal term - its vendor, as the vendor template it comes + * from (its name, summary, phone, email, website, hours, SLA and notes, never + * an account number or code), and the name of the product it is sold as. Not + * who should have one: that is the call of the install it goes into - a new + * one comes in required of no one, and one replaced keeps its own. Coming in, + * a vendor template is matched by name, and made from the file when there is + * none; a product only by name - prices are yours, so none is made. + */ + +const SOFTWARE_TEMPLATE_FILE_FORMAT = 'itflow-license-templates'; +const SOFTWARE_TEMPLATE_FILE_VERSION = 1; + +/** The vendor template fields that go in a file - its own account numbers and codes don't. */ +const SOFTWARE_TEMPLATE_FILE_VENDOR_FIELDS = ['description' => 200, 'phone_country_code' => 10, 'phone' => 200, 'extension' => 200, 'email' => 200, 'website' => 200, 'hours' => 200, 'sla' => 200, 'notes' => 0]; + +/* + * Templates as a file's contents (an array, for json_encode()) - the ones in + * $ids, or every current one when $ids is empty, and the archived ones too + * with $archived. + */ +function softwareTemplatesExport(array $ids = [], $archived = false) { + global $mysqli; + $ids = array_values(array_filter(array_map('intval', $ids))); + $where = $ids ? 'software_template_id IN (' . implode(',', $ids) . ')' : ($archived ? '1 = 1' : 'software_template_archived_at IS NULL'); + $templates = []; + $sql = mysqli_query($mysqli, "SELECT software_templates.*, vendor_templates.*, product_name FROM software_templates + LEFT JOIN vendor_templates ON vendor_template_id = software_template_vendor_template_id AND software_template_vendor_template_id > 0 + LEFT JOIN products ON product_id = software_template_product_id AND software_template_product_id > 0 + WHERE $where ORDER BY software_template_name ASC, software_template_id ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $vendor = null; + if ($row['vendor_template_name'] !== null) { + $vendor = ['name' => (string) $row['vendor_template_name']]; + foreach (array_keys(SOFTWARE_TEMPLATE_FILE_VENDOR_FIELDS) as $field) { + $vendor[$field] = (string) $row["vendor_template_$field"]; + } + } + $templates[] = [ + 'name' => (string) $row['software_template_name'], + 'version' => (string) $row['software_template_version'], + 'description' => (string) $row['software_template_description'], + 'type' => (string) $row['software_template_type'], + 'license_type' => (string) $row['software_template_license_type'], + 'notes' => (string) $row['software_template_notes'], + 'seats' => $row['software_template_seats'] === null ? null : intval($row['software_template_seats']), + 'term' => (string) $row['software_template_term'], + 'vendor' => $vendor, + 'product' => $row['product_name'] !== null ? (string) $row['product_name'] : null, + ]; + } + return ['format' => SOFTWARE_TEMPLATE_FILE_FORMAT, 'version' => SOFTWARE_TEMPLATE_FILE_VERSION, 'exported_at' => date('c'), 'templates' => $templates]; +} + +/** A file name for an export - its one template's name, or the date. */ +function softwareTemplatesExportFileName(array $export) { + $templates = $export['templates'] ?? []; + if (count($templates) === 1) { + $slug = trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($templates[0]['name'])), '-'); + return 'license-template-' . ($slug !== '' ? substr($slug, 0, 60) : 'export') . '.json'; + } + return 'license-templates-' . date('Y-m-d') . '.json'; +} + +/* One line of text from a file, tidied - no markup, no runs of spaces, no longer than $max. */ +function softwareTemplateFileText($value, $max) { + return is_scalar($value) ? trim(mb_substr(preg_replace('/\s+/u', ' ', strip_tags((string) $value)), 0, $max)) : ''; +} + +/* Notes from a file - no markup, their lines kept, no longer than $max. */ +function softwareTemplateFileNotes($value, $max = 20000) { + return is_scalar($value) ? trim(mb_substr(str_replace("\r\n", "\n", strip_tags((string) $value)), 0, $max)) : ''; +} + +/* + * A file's templates, read and checked - from what export wrote, or the + * starter pack. Each made safe: text tidied, seats a whole number or none, a + * renewal term that is one, its vendor with a name and only the fields a + * vendor template has, its product a name. A template with no type is Other. + * Null with $error saying why the file can't be used. + */ +function softwareTemplatesImportRead($contents, &$error = '') { + $data = is_array($contents) ? $contents : json_decode((string) $contents, true); + if (!is_array($data) || ($data['format'] ?? '') !== SOFTWARE_TEMPLATE_FILE_FORMAT || !isset($data['templates']) || !is_array($data['templates'])) { + $error = "That isn't a license templates file - export one from Admin > License Templates."; + return null; + } + if (intval($data['version'] ?? 0) > SOFTWARE_TEMPLATE_FILE_VERSION) { + $error = 'That file was made by a newer version of ITFlow - update this one first.'; + return null; + } + if (count($data['templates']) > 500) { + $error = 'That file holds more than 500 license templates - split it up.'; + return null; + } + + $templates = []; + foreach ($data['templates'] as $t) { + $name = is_array($t) ? softwareTemplateFileText($t['name'] ?? '', 200) : ''; + if ($name === '') { + continue; + } + $vendor = null; + $vendor_name = is_array($t['vendor'] ?? null) ? softwareTemplateFileText($t['vendor']['name'] ?? '', 200) : ''; + if ($vendor_name !== '') { + $vendor = ['name' => $vendor_name]; + foreach (SOFTWARE_TEMPLATE_FILE_VENDOR_FIELDS as $field => $max) { + $vendor[$field] = $max ? softwareTemplateFileText($t['vendor'][$field] ?? '', $max) : softwareTemplateFileNotes($t['vendor'][$field] ?? ''); + } + } + $seats = $t['seats'] ?? null; + $term = is_string($t['term'] ?? null) ? $t['term'] : ''; + $type = softwareTemplateFileText($t['type'] ?? '', 200); + $templates[] = [ + 'name' => $name, + 'version' => softwareTemplateFileText($t['version'] ?? '', 200), + 'description' => softwareTemplateFileText($t['description'] ?? '', 500), + 'type' => $type !== '' ? $type : 'Other', + 'license_type' => softwareTemplateFileText($t['license_type'] ?? '', 200), + 'notes' => softwareTemplateFileNotes($t['notes'] ?? ''), + 'seats' => is_numeric($seats) ? max(0, min(1000000, intval($seats))) : null, + 'term' => isset(SOFTWARE_RENEWAL_TERMS[$term]) ? $term : '', + 'vendor' => $vendor, + 'product' => softwareTemplateFileText($t['product'] ?? '', 200), + ]; + } + if (!$templates) { + $error = 'There are no license templates in that file.'; + return null; + } + return $templates; +} + +/* + * The vendor template for a file's vendor - one here by its name (a current + * one first), or one made from the file ($made says so). Its id. + */ +function softwareTemplateImportVendor(array $vendor, &$made = false) { + global $mysqli; + $made = false; + $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT vendor_template_id FROM vendor_templates WHERE LOWER(vendor_template_name) = LOWER('" . escapeSql($vendor['name']) . "') + ORDER BY vendor_template_archived_at IS NOT NULL, vendor_template_id ASC LIMIT 1")); + if ($row) { + return intval($row[0]); + } + $set = ["vendor_template_name = '" . escapeSql($vendor['name']) . "'"]; + foreach (array_keys(SOFTWARE_TEMPLATE_FILE_VENDOR_FIELDS) as $field) { + $value = (string) ($vendor[$field] ?? ''); + if (in_array($field, ['phone_country_code', 'phone', 'extension'], true)) { + $value = preg_replace('/[^0-9]/', '', $value); + } + if ($field === 'website') { + $value = preg_replace('#^https?://#i', '', $value); + } + $set[] = "vendor_template_$field = '" . escapeSql($value) . "'"; + } + mysqli_query($mysqli, "INSERT INTO vendor_templates SET " . implode(', ', $set)); + $made = true; + return intval(mysqli_insert_id($mysqli)); +} + +/* The product a file's template is sold as - a current one here by its name. Its id, or 0. */ +function softwareTemplateImportProduct($name) { + global $mysqli; + if ((string) $name === '') { + return 0; + } + $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT product_id FROM products WHERE LOWER(product_name) = LOWER('" . escapeSql($name) . "') AND product_archived_at IS NULL + ORDER BY product_id ASC LIMIT 1")); + return intval($row[0] ?? 0); +} + +/* + * Bring in templates read by softwareTemplatesImportRead(). One whose name is + * already here is skipped ($existing 'skip'), added under a name of its own + * ('copy') or has what the file says put in its place ('replace') - its name, + * version, summary, type, license type, notes, seats, renewal term and + * vendor, and the product it is sold as when the file's is here (else it + * keeps its own). Its licenses stay made from it, and who should have one + * stays as it was; a new one is required of no one. $only_existing: bring in + * only the ones already here (to update them). ['added', 'replaced', + * 'skipped', 'vendors' made, 'products' - the names of the products not here, + * 'ids' of those added or replaced]. + */ +function softwareTemplatesImport(array $templates, $existing = 'skip', $only_existing = false) { + global $mysqli; + $counts = ['added' => 0, 'replaced' => 0, 'skipped' => 0, 'vendors' => 0, 'products' => [], 'ids' => []]; + $here = []; + $sql = mysqli_query($mysqli, "SELECT software_template_id, software_template_name, software_template_product_id FROM software_templates ORDER BY software_template_id"); + while ($row = mysqli_fetch_assoc($sql)) { + $key = mb_strtolower($row['software_template_name']); + $here[$key] = $here[$key] ?? ['id' => intval($row['software_template_id']), 'product_id' => intval($row['software_template_product_id'])]; + } + + foreach ($templates as $t) { + $id = $here[mb_strtolower($t['name'])]['id'] ?? 0; + if (($only_existing && !$id) || ($id && $existing === 'skip')) { + $counts['skipped']++; + continue; + } + $name = $t['name']; + if ($id && $existing === 'copy') { + for ($n = 2; isset($here[mb_strtolower($name)]); $n++) { + $name = mb_substr($t['name'], 0, 190) . " ($n)"; + } + $id = 0; + } + $replacing = $id > 0; + + $vendor_template_id = 0; + if ($t['vendor']) { + $vendor_template_id = softwareTemplateImportVendor($t['vendor'], $vendor_made); + $counts['vendors'] += $vendor_made ? 1 : 0; + } + $product_id = softwareTemplateImportProduct($t['product']); + if ($t['product'] !== '' && !$product_id) { + $counts['products'][mb_strtolower($t['product'])] = $t['product']; + } + if (!$product_id && $replacing) { + $product_id = $here[mb_strtolower($t['name'])]['product_id']; + } + + $saved = softwareTemplateSave($id, [ + 'name' => $name, 'version' => $t['version'], 'description' => $t['description'], 'type' => $t['type'], 'license_type' => $t['license_type'], + 'notes' => $t['notes'], 'seats' => $t['seats'], 'term' => $t['term'], 'vendor_template_id' => $vendor_template_id, 'product_id' => $product_id, + ]); + $here[mb_strtolower($name)] = ['id' => $saved, 'product_id' => $product_id]; + $counts[$replacing ? 'replaced' : 'added']++; + $counts['ids'][] = $saved; + } + $counts['products'] = array_values($counts['products']); + return $counts; +} + +/* What an import did, in words - for its message. HTML. */ +function softwareTemplatesImportSummary(array $counts) { + $parts = []; + foreach (['added' => 'added', 'replaced' => 'replaced', 'skipped' => 'already here, left as they were'] as $key => $word) { + if ($counts[$key]) { + $parts[] = '' . $counts[$key] . ' ' . $word; + } + } + $products = $counts['products']; + return ucfirst(implode(', ', $parts) ?: 'nothing brought in') + . ($counts['vendors'] ? '. Added ' . $counts['vendors'] . ' vendor template' . ($counts['vendors'] === 1 ? '' : 's') . ' they come from' : '') + . ($products ? '. Not sold as ' . escapeHtml(implode(', ', array_slice($products, 0, 5))) . (count($products) > 5 ? ' and ' . (count($products) - 5) . ' more' : '') + . ' - ' . (count($products) === 1 ? 'that product isn\'t' : 'those products aren\'t') . ' here, so pick what each is sold as on its page' : '') + . '.'; +}