diff --git a/CHANGELOG.md b/CHANGELOG.md index 973f8e306..0fa168d91 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.1.2) 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.1.3) in the same pass. Nothing else is required. -This is a big release, with thirty-three database steps in one go, so take a backup before you update. +This is a big release, with thirty-four 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: @@ -33,6 +33,8 @@ Every account is given a kind - checking, savings, credit card, cash or payment Taxes keep their names and rates, now kept to four decimal places. No client has a rate of its own or is tax exempt, and there is no default rate, so new lines start untaxed as before until you pick one in Admin > Taxes. Billed time, trips and expenses stay untaxed until you switch them on there. Discounts now come off before tax on invoices and quotes that are still open, the next time they are edited (see Breaking Changes, Taxes). No expense has tax recorded on it until you add it, so Tax Collected shows no tax paid on purchases for the months before. +Tags keep their names, colors, icons and records. A color saved as a word, such as dark or primary, becomes the color it stands for, a short one such as #abc is written out in full, and a tag with no color, or one that isn't a color, turns grey, so its pills can be read (see Bug Fixes). An icon saved with `fas fa-` in front keeps just its name. A tag archived in an older version now counts as archived (see Breaking Changes, Tags). + 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. ### Breaking Changes and Notes @@ -128,6 +130,12 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Tax Rates in the Admin menu is now Taxes. - A line on a rate made of parts is taxed part by part, each to the cent, so its tax can be a cent off the whole rate times the line. - Tax Collected now shows tax by part, so a rate made of a state's and a county's part shows two rows, and a part named the same on two rates shows one. Its sales are net of discounts, where they used to be the lines before any discount, and archived payments no longer count. It still counts as payments come in unless you switch it to Invoiced. +- Tags: + - Archiving a tag now does something: it stays on the records that have it, but isn't offered in record forms, the tag picker or the list and export filters, unless a record or filter already has it. A tag archived in an older version is archived now too - restore it from the Archived tab in Admin > Tags. + - The + beside the Tags field in record forms is gone. Admins type the new tag's name into the field instead, and it is made when the record is saved. Other agents pick from the tags there are, as before - the + never worked for them. + - A tag's name is now unique within its kind, in any case: a second client tag called VIP can't be made, though an asset tag can be. Tags already named alike keep their names. Typing a name that exists into a record form picks that tag. + - A tag that a recurring invoice line counts users or devices by can't be deleted. Archive it, or merge it into another tag, which moves the line along with it. + - Pills now have dark text on light colors such as yellow and light blue, where every pill had white text. - Notifications now follow access too. An agent only sees notifications for clients and areas they can open, so someone without sales access no longer sees invoice and quote notifications. - Drop-downs: Tom Select is gone, replaced by ITFlow's own picker. It works the way you are used to: type to search, tick several in a multi-select, and type a new value in fields that allow it, such as ticket watchers. See Developer Updates if you have custom pages that used Tom Select. - Several small windows are gone because the change is now made where the value is shown: @@ -744,6 +752,18 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Exports: invoices can add Subtotal, Discount, Tax and Tax by Part; quotes and recurring invoices Tax; expenses Before Tax, Tax and Tax Rate; and clients Tax Rate, Tax Exempt, Exemption Certificate and Exemption Expires. They are off until ticked. - API: clients take `client_default_tax_id`, `client_tax_exempt`, `client_tax_exempt_number` and `client_tax_exempt_expires`, and a new invoice line takes `tax_id` `default` for the client's usual rate. A new endpoint reads the taxes with their parts. Invoices and quotes add their subtotal, tax, tax by part and registration numbers, invoice lines name their rate, and expenses include their tax. - Demo data: both taxes have a registration number, Allegheny County Sales Tax is made of the state's 6% - named PA Sales Tax, so Tax Collected adds the two up together - and the county's 1%, each client has its rate, the church and the charter school are tax exempt, one with a certificate that has run out, and what the company buys for its own use pays sales tax. +- **Tags** (rebuilt) + - Admin > Tags lists each kind's tags - clients, locations, contacts, credentials, assets, vendors and domains, down the side with how many each has. Each tag shows as it looks on a record, with its description, how many records have it (and how many of those are archived), opening that list filtered by it, and the recurring invoice lines that count users or devices by it. + - Search by name or description, sort by name or by most used, and Current and Archived tabs. + - Each tag has Edit, Merge into..., a link to its records, Archive or Restore, and Delete, which asks first and says how many records lose the tag. Tick several for Merge into one, Archive or Restore, and Delete. + - The tag window shows the tag as it will look while you change it: + - its name, and what it is for, which can be changed while nothing has the tag yet + - a description, shown when you point at the tag and in the tag picker, which searches it too + - a color from the swatches, or any other from the color picker or typed as a hex value - the text on the pill is dark or white, whichever reads + - an icon from the grid, which you can search, or any Font Awesome icon by its name + - Merge moves every record with the merged tags onto the one you keep, once each, and the recurring invoice lines that count by them count by it. The others are deleted. + - Record forms: an admin types a new tag's name into the Tags field and picks Add or presses Enter, and the tag is made, with the next color along, when the record is saved - nothing reloads and nothing typed is lost. Typing the name of an archived tag brings it back. + - A recurring invoice line counting by a tag keeps it in its window once the tag is archived, or when the client no longer has anything with it, so saving the line doesn't drop it. ### Bug Fixes @@ -828,6 +848,10 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Recurring tickets: if cron missed a night, that recurring ticket stopped raising tickets until someone fixed its next run date. The missed ticket is now raised on the next run and the schedule carries on. - Networks: Export from All Clients with no client picked did not work. - The add category button on the products filter did nothing. +- Tags: saving a client, contact or asset with the same tag picked twice stopped with an error, and those forms took any tag sent with them, another kind's included. Every record form now keeps only its own kind's tags, each once. +- Tags: the + beside the Tags field in record forms opened Admin's New Tag window, which reloaded the page and lost what had been typed into the form, and showed an error to anyone who wasn't an admin. +- Tags: a tag saved with no color, or a color word such as dark, showed white text on no color at all. +- Tags: the Archived button on Admin > Tags showed the same tags as without it, as nothing could be archived. - Messages, hints and window titles were reworded where they were unclear, and bulk windows say "1 asset" or "3 assets" correctly. ### Developer Updates @@ -1188,6 +1212,16 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Exports: `invoice_subtotal`, `invoice_discount_amount`, `invoice_tax` and `invoice_tax_parts`, `quote_tax` (up front, from `quoteLineGroups()`), `recurring_invoice_tax`, `expense_before_tax`, `expense_tax_amount` and `expense_tax_rate`, and `client_tax_rate`, `client_tax_exempt_display`, `client_tax_exempt_number` and `client_tax_exempt_expires`, all `default => false`. The quote and recurring invoice exports select their ids for it. - API: `api/v1/taxes/read.php` (`tax_id`, `archived`; each rate with `tax_components` and `tax_default`), mapped to `module_sales`. `billingApiTaxFields($type, $row)` adds `invoice_subtotal`, `invoice_tax`, `invoice_taxes` (`name`, `amount`) and `invoice_tax_registrations` to `api/v1/invoices/read.php`, and the `quote_` ones to `api/v1/quotes/read.php`. `api/v1/invoice_items/read.php` adds `tax_name` and `tax_percent`. - Seeds: `demoDataTaxes()` names Allegheny County's state part PA Sales Tax, and the company's own-use purchases (office supplies, tools, equipment, the van) carry PA Sales Tax. +- Tags (database 3.1.3): + - New `tags.tag_description` (`varchar(255)`, NULL). The migration writes every `tag_color` as `#rrggbb` (short hex grows, an eight-digit one loses its alpha, Bootstrap's color words become their hex, anything else `#6c757d`) and every `tag_icon` as the bare Font Awesome name (`fas fa-` and anything but `a-z0-9-` taken off, NULL when empty). + - `functions/tags.php`: `tagEntity()` adds `title`, `plural` and `icon`, and `tagsForRecords()` adds `tag_description` and `tag_archived_at`. New: `TAG_COLORS` and `TAG_ICONS` (what the tag window offers), `tagColor()` (`#rrggbb`, grey otherwise), `tagTextColor()` (`#212529` or `#fff` by luminance), `tagIcon()` (the bare name, `tag` when none), `tagPill($tag)`, `tagKinds()` (type => entity), `tagKindPhrase($type)`, `tagEntityByType($type)` (adds `entity`), `tagRow()`, `tagUsageCounts()`, `tagUsageBreakdown()` (`all`, `archived`), `tagUsage()`, `tagSeatLineItems($tag_ids)`, `tagSeatLineCounts()`, `tagSeatLines()`, `tagFromInput($in, $existing)` (returns `[$fields, $error]`: `name`, `description`, `type`, `color`, `icon`), `tagCreate()`, `tagUpdate()`, `tagArchive()`, `tagRestore()`, `tagDelete($tag_id, &$error)` (refused while a seat line counts by it), `tagMerge($from_ids, $into_id)` (same kind only; records moved, seat filters repointed, returns how many records), `tagOptionsFor($entity, $keep_ids)`, `tagOptionsHtml($entity, $selected)` and `tagSetForRecord($entity, $record_id, $values)`. + - `tagSetForRecord()` is the one save for a record form's `tags[]`: numeric values are tag ids, anything else (from an admin) a typed name, matched case-insensitively or made with `tagNextColor()`. Only that kind's tags are kept, each once, and an archived tag only on a record that already had it. `agent/post/client.php`, `contact.php` and `asset.php` call it, and `locationSetTags()`, `credentialSetTags()`, `vendorSetTags()` and `domainSetTags()` now wrap it. + - The record forms' Tags fields are `` with `data-tags="true"` for admins, and their links to `admin/modals/tag/tag_add.php` are gone. The list pages' tag filters and the seven export windows leave out archived tags that aren't chosen. + - `tagPills()` and `tagPill()` set `--itflow-tag-text` beside `--itflow-tag-color`, and a pill's title leads with the description. `agent/ajax.php`: `tag_picker` returns each tag's `description` (with "Archived"), `tag_picker_set` refuses putting an archived tag on (409), and `tag_picker_create` matches case-insensitively and restores an archived match. `js/tag_picker.js` shows and searches the description. + - Admin: `admin/tags.php` is rebuilt (`type`, `q`, `sort=use`, `archived`), with `admin/modals/tag/tag_form.php` shared by `tag_add.php` (`type`) and `tag_edit.php` (`id`), the new `tag_merge.php` (`tag_ids[]`), and `js/tag_form.js`. `admin/post/tag.php`: `add_tag` and `edit_tag` (`tag_id`, `name`, `type`, `description`, `color`, `icon`), GET `archive_tag`, `restore_tag` and `delete_tag`, POST `merge_tags` (`tag_ids[]`, `into_tag_id`), and `bulk_archive_tags`, `bulk_restore_tags` and `bulk_delete_tags` (`tag_ids[]`). Audit entries are Tag Create, Edit, Archive, Restore, Delete and Merge, naming the kind. + - Removed: `agent/post/tag.php` and `agent/post/tag_model.php` (an older copy of `add_tag` for the window opened from agent pages), and `admin/post/tag_model.php`. + - `agent/modals/billing/billing_item.php` adds a seat line's own tag to its choices when `recurringSeatOptions()` leaves it out. + - CSS: `.itflow-tag` takes its text color from `--itflow-tag-text`; new `.itflow-tag-swatch`, `.itflow-tag-icons`, `.itflow-tag-icon` and `.itflow-tag-icon-custom`. - 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.1.3.php b/admin/database_updates/3.1.3.php new file mode 100644 index 000000000..006e7818f --- /dev/null +++ b/admin/database_updates/3.1.3.php @@ -0,0 +1,37 @@ + Tags + mysqli_query($mysqli, "ALTER TABLE `tags` ADD COLUMN `tag_description` varchar(255) DEFAULT NULL AFTER `tag_name`"); + + // Every colour as #rrggbb, so a pill's text can be picked to read on it - + // short hex grows to six digits, Bootstrap's colour names become theirs, + // and anything else (an empty colour, "dark") becomes grey + $tag_named_colors = [ + 'primary' => '#0d6efd', 'secondary' => '#6c757d', 'success' => '#198754', 'danger' => '#dc3545', 'warning' => '#ffc107', + 'info' => '#0dcaf0', 'light' => '#adb5bd', 'dark' => '#343a40', 'blue' => '#0d6efd', 'indigo' => '#6610f2', 'purple' => '#6f42c1', + 'pink' => '#d63384', 'red' => '#dc3545', 'orange' => '#fd7e14', 'yellow' => '#ffc107', 'green' => '#198754', 'teal' => '#20c997', + 'cyan' => '#0dcaf0', 'gray' => '#6c757d', 'grey' => '#6c757d', 'black' => '#212529', 'white' => '#adb5bd', + ]; + $sql = mysqli_query($mysqli, "SELECT tag_id, tag_color, tag_icon FROM tags"); + while ($row = mysqli_fetch_assoc($sql)) { + $color = strtolower(trim((string) $row['tag_color'])); + if (preg_match('/^#([0-9a-f])([0-9a-f])([0-9a-f])$/', $color, $m)) { + $color = "#$m[1]$m[1]$m[2]$m[2]$m[3]$m[3]"; + } elseif (preg_match('/^#[0-9a-f]{8}$/', $color)) { + $color = substr($color, 0, 7); + } elseif (!preg_match('/^#[0-9a-f]{6}$/', $color)) { + $color = $tag_named_colors[$color] ?? '#6c757d'; + } + // An icon is the Font Awesome name alone - "fa-star" and "fas fa-star" are "star" + $icon = preg_replace('/^(fa[srb]? +)?fa-/', '', strtolower(trim((string) $row['tag_icon']))); + $icon = preg_replace('/[^a-z0-9-]/', '', $icon); + $tag_id = intval($row['tag_id']); + mysqli_query($mysqli, "UPDATE tags SET tag_color = '$color', tag_icon = " . ($icon === '' ? 'NULL' : "'$icon'") . " WHERE tag_id = $tag_id"); + } diff --git a/admin/modals/tag/tag_add.php b/admin/modals/tag/tag_add.php index 9c17f5e6d..dc593b331 100644 --- a/admin/modals/tag/tag_add.php +++ b/admin/modals/tag/tag_add.php @@ -2,90 +2,25 @@ require_once '../../includes/modal_header.php'; -$type_display = ''; +$tag = null; +$type = tagEntityByType(intval($_GET['type'] ?? 0)) ? intval($_GET['type']) : 1; -if (isset($_GET['type'])) { - $type = intval($_GET['type']); - - if ($type === 1) { - $type_display = "Client"; - } elseif($type === 2) { - $type_display = "Location"; - } elseif ($type === 3) { - $type_display = "Contact"; - } elseif ($type === 4) { - $type_display = "Credential"; - } elseif ($type === 5) { - $type_display = "Asset"; - } elseif ($type === 6) { - $type_display = "Vendor"; - } elseif ($type === 7) { - $type_display = "Domain"; - } -} ob_start(); ?>
-
diff --git a/admin/modals/tag/tag_edit.php b/admin/modals/tag/tag_edit.php index 48a266bb5..ae88ea80a 100644 --- a/admin/modals/tag/tag_edit.php +++ b/admin/modals/tag/tag_edit.php @@ -2,38 +2,20 @@ require_once '../../includes/modal_header.php'; -$tag_id = intval($_GET['id']); - -$sql = mysqli_query($mysqli, "SELECT tag_color, tag_icon, tag_name, tag_type FROM tags WHERE tag_id = $tag_id LIMIT 1"); - -$row = mysqli_fetch_assoc($sql); -$tag_name = escapeHtml($row['tag_name']); -$tag_type = intval($row['tag_type']); -$tag_color = escapeHtml($row['tag_color']); -$tag_icon = escapeHtml($row['tag_icon']); - -if ($tag_type == 1) { - $tag_type_display = "Client"; -} elseif ( $tag_type == 2) { - $tag_type_display = "Location"; -} elseif ( $tag_type == 3) { - $tag_type_display = "Contact"; -} elseif ( $tag_type == 4) { - $tag_type_display = "Credential"; - } elseif ( $tag_type == 5) { - $tag_type_display = "Asset"; -} elseif ($tag_type == 6) { - $tag_type_display = "Vendor"; -} elseif ($tag_type == 7) { - $tag_type_display = "Domain"; -} else { - $tag_type_display = "Unknown"; -} +$tag = tagRow(intval($_GET['id'] ?? 0)); ob_start(); -?> + +if (!$tag) { ?> + + +
@@ -41,31 +23,10 @@ ob_start();
- + +
+
+ Looks like + + + + + + + + +
+ +
+
+ +
+ + data-tag-name> +
+
+
+ +
+ + +
+ + In use, so it stays + +
+
+ +
+ +
+ + +
+ Shown on the tag and in the tag picker +
+ +
+ +
+
+ + + +
+
+ + + +
+
+
+ +
+ + +
+ + +
+
+ + + + + +
+
+
+ + diff --git a/admin/modals/tag/tag_merge.php b/admin/modals/tag/tag_merge.php new file mode 100644 index 000000000..083670717 --- /dev/null +++ b/admin/modals/tag/tag_merge.php @@ -0,0 +1,114 @@ + 1) { + $into = $merging; + uasort($into, function ($a, $b) use ($usage) { + return ($usage[intval($b['tag_id'])] ?? 0) <=> ($usage[intval($a['tag_id'])] ?? 0) ?: strcasecmp($a['tag_name'], $b['tag_name']); + }); + } + foreach (tagOptionsFor($kind['entity']) as $row) { + if (!isset($merging[intval($row['tag_id'])])) { + $into[intval($row['tag_id'])] = $row; + } + } +} +$keep_id = count($merging) > 1 ? intval(array_key_first($into)) : 0; + +// What merging does, in words +$records = $lines = 0; +if ($kind) { + // Each record once, though it may have more than one of them + $records = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(DISTINCT {$kind['link_record']}) FROM {$kind['link_table']} + WHERE {$kind['link_tag']} IN (" . implode(',', array_keys($merging)) . ")"))[0]); +} +foreach ($merging as $merge_id => $row) { + $lines += $seat_lines[$merge_id] ?? 0; +} +$one = count($merging) === 1; +$merge_text = ''; +if ($kind) { + $merge_text = ($records ? 'The ' . number_format($records) . ' ' . ($records === 1 ? strtolower($kind['title']) . ' with ' . ($one ? 'it gets' : 'one of these gets') : $kind['plural'] . ' with ' . ($one ? 'it get' : 'these get')) . ' the tag you keep instead.' + : 'Nothing has ' . ($one ? 'it' : 'these') . ' yet.') + . ($lines ? ' ' . ($lines === 1 ? 'The recurring invoice line counting by ' . ($one ? 'it counts' : 'them counts') : "The $lines recurring invoice lines counting by " . ($one ? 'it count' : 'them count')) . ' by the kept tag from now on.' : '') + . ($one ? ' It is then deleted.' : ' The others are then deleted.') . " This can't be undone."; +} + +ob_start(); + +?> + + + + + + + + +
+ + $row) { ?> + + + + + +
+ + + Tags) - making, changing, merging, archiving and deleting + * them. The work is in functions/tags.php. */ defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); +// "asset" - what a tag is for, for the audit log and messages +$tag_kind_word = function ($row) { + return strtolower(tagEntityByType($row['tag_type'] ?? 0)['title'] ?? 'unknown'); +}; + +// "12 assets" / "1 asset" +$tag_records_text = function ($n, $type) { + $kind = tagEntityByType($type); + return number_format($n) . ' ' . ($n === 1 ? strtolower($kind['title'] ?? 'record') : ($kind['plural'] ?? 'records')); +}; + if (isset($_POST['add_tag'])) { validateCSRFToken(); - require_once 'tag_model.php'; + [$fields, $error] = tagFromInput($_POST); + if ($error !== '') { + flashAlert(escapeHtml($error), 'error'); + redirect(); + } - mysqli_query($mysqli,"INSERT INTO tags SET tag_name = '$name', tag_type = $type, tag_color = '$color', tag_icon = '$icon'"); + $tag_id = tagCreate($fields); + $kind = $tag_kind_word(['tag_type' => $fields['type']]); - $tag_id = mysqli_insert_id($mysqli); + logAudit("Tag", "Create", "$session_name created $kind tag " . escapeSql($fields['name']), 0, $tag_id); - logAudit("Tag", "Create", "$session_name created tag $name", 0, $tag_id); + flashAlert(ucfirst($kind) . " tag " . escapeHtml($fields['name']) . " created"); - flashAlert("Tag " . stripslashes($name) . " created"); - - redirect(); + redirect("tags.php?type=" . intval($fields['type'])); } @@ -28,15 +43,61 @@ if (isset($_POST['edit_tag'])) { validateCSRFToken(); - require_once 'post/tag_model.php'; + $tag_id = intval($_POST['tag_id'] ?? 0); + $row = tagRow($tag_id); + if (!$row) { + flashAlert("That tag is gone - it may have been merged into another, or deleted", 'error'); + redirect(); + } - $tag_id = intval($_POST['tag_id']); + [$fields, $error] = tagFromInput($_POST, $row); + if ($error !== '') { + flashAlert(escapeHtml($error), 'error'); + redirect(); + } - mysqli_query($mysqli,"UPDATE tags SET tag_name = '$name', tag_color = '$color', tag_icon = '$icon' WHERE tag_id = $tag_id"); + tagUpdate($tag_id, $fields); + $kind = $tag_kind_word(['tag_type' => $fields['type']]); + $moved = intval($row['tag_type']) !== intval($fields['type']); + $renamed = $row['tag_name'] !== $fields['name']; - logAudit("Tag", "Edit", "$session_name edited tag $name", 0, $tag_id); + logAudit("Tag", "Edit", "$session_name edited $kind tag " . escapeSql($fields['name']) + . ($renamed ? " (was " . escapeSql($row['tag_name']) . ")" : '') + . ($moved ? " - moved from " . $tag_kind_word($row) . " tags" : ''), 0, $tag_id); - flashAlert("Tag " . stripslashes($name) . " saved"); + flashAlert("Tag " . escapeHtml($fields['name']) . " saved" . ($moved ? " - it's " . tagKindPhrase($fields['type']) . " now" : '')); + + redirect($moved ? "tags.php?type=" . intval($fields['type']) . ($row['tag_archived_at'] ? '&archived=1' : '') : null); + +} + +if (isset($_GET['archive_tag'])) { + + validateCSRFToken(); + + $row = tagRow(intval($_GET['archive_tag'])); + if ($row && !$row['tag_archived_at']) { + tagArchive($row['tag_id']); + $used = tagUsage($row['tag_id']); + logAudit("Tag", "Archive", "$session_name archived " . $tag_kind_word($row) . " tag " . escapeSql($row['tag_name']), 0, intval($row['tag_id'])); + flashAlert("Tag " . escapeHtml($row['tag_name']) . " archived - " + . ($used ? "it stays on its " . $tag_records_text($used, $row['tag_type']) . ", but isn't offered for tagging" : "it isn't offered for tagging")); + } + + redirect(); + +} + +if (isset($_GET['restore_tag'])) { + + validateCSRFToken(); + + $row = tagRow(intval($_GET['restore_tag'])); + if ($row && $row['tag_archived_at']) { + tagRestore($row['tag_id']); + logAudit("Tag", "Restore", "$session_name restored " . $tag_kind_word($row) . " tag " . escapeSql($row['tag_name']), 0, intval($row['tag_id'])); + flashAlert("Tag " . escapeHtml($row['tag_name']) . " restored"); + } redirect(); @@ -46,15 +107,115 @@ if (isset($_GET['delete_tag'])) { validateCSRFToken(); - $tag_id = intval($_GET['delete_tag']); + $row = tagRow(intval($_GET['delete_tag'])); + if (!$row) { + redirect(); + } - $tag_name = escapeSql(getFieldById('tags', $tag_id, 'tag_name')); + $used = tagUsage($row['tag_id']); + $error = ''; + if (!tagDelete($row['tag_id'], $error)) { + flashAlert($error !== '' ? escapeHtml($error) : "That tag is gone", 'error'); + redirect(); + } - mysqli_query($mysqli,"DELETE FROM tags WHERE tag_id = $tag_id"); + logAudit("Tag", "Delete", "$session_name deleted " . $tag_kind_word($row) . " tag " . escapeSql($row['tag_name']) + . ($used ? ", taking it off " . $tag_records_text($used, $row['tag_type']) : '')); - logAudit("Tag", "Delete", "$session_name deleted tag $tag_name"); - - flashAlert("Tag " . stripslashes($tag_name) . " deleted", 'error'); + flashAlert("Tag " . escapeHtml($row['tag_name']) . " deleted" . ($used ? " and taken off " . $tag_records_text($used, $row['tag_type']) : ''), 'error'); + + redirect(); + +} + +if (isset($_POST['merge_tags'])) { + + validateCSRFToken(); + + $into = tagRow(intval($_POST['into_tag_id'] ?? 0)); + if (!$into) { + flashAlert("Pick the tag to keep", 'error'); + redirect(); + } + $into_id = intval($into['tag_id']); + + // Their names before they go - other tags of the same kind only + $from = []; + foreach (array_unique(array_map('intval', (array) ($_POST['tag_ids'] ?? []))) as $from_id) { + $from_row = $from_id !== $into_id ? tagRow($from_id) : null; + if ($from_row && intval($from_row['tag_type']) === intval($into['tag_type'])) { + $from[$from_id] = $from_row['tag_name']; + } + } + if (!$from) { + flashAlert("Pick another " . $tag_kind_word($into) . " tag to merge into " . escapeHtml($into['tag_name']), 'error'); + redirect(); + } + + $moved = tagMerge(array_keys($from), $into_id); + + logAudit("Tag", "Merge", "$session_name merged " . $tag_kind_word($into) . " " . (count($from) === 1 ? 'tag' : 'tags') . " " . escapeSql(implode(', ', $from)) . " into " . escapeSql($into['tag_name']) + . ($moved ? " - " . $tag_records_text($moved, $into['tag_type']) : ''), 0, $into_id); + + flashAlert("Merged " . implode(', ', array_map(function ($name) { + return '' . escapeHtml($name) . ''; + }, $from)) . " into " . escapeHtml($into['tag_name']) . "" + . ($moved ? " - the " . $tag_records_text($moved, $into['tag_type']) . " that had " . (count($from) === 1 ? 'it' : 'them') . " have it now" : '')); + + redirect(); + +} + +if (isset($_POST['bulk_archive_tags']) || isset($_POST['bulk_restore_tags'])) { + + validateCSRFToken(); + + $archive = isset($_POST['bulk_archive_tags']); + $count = 0; + foreach (array_unique(array_map('intval', (array) ($_POST['tag_ids'] ?? []))) as $tag_id) { + $row = tagRow($tag_id); + if (!$row || (bool) $row['tag_archived_at'] === $archive) { + continue; + } + if ($archive) { + tagArchive($tag_id); + } else { + tagRestore($tag_id); + } + logAudit("Tag", $archive ? "Archive" : "Restore", "$session_name " . ($archive ? 'archived ' : 'restored ') . $tag_kind_word($row) . " tag " . escapeSql($row['tag_name']), 0, $tag_id); + $count++; + } + + flashAlert(($archive ? "Archived " : "Restored ") . $count . ($count === 1 ? " tag" : " tags") . ($archive && $count ? " - they stay on their records, but aren't offered for tagging" : '')); + + redirect(); + +} + +if (isset($_POST['bulk_delete_tags'])) { + + validateCSRFToken(); + + $deleted = $kept = $records = 0; + foreach (array_unique(array_map('intval', (array) ($_POST['tag_ids'] ?? []))) as $tag_id) { + $row = tagRow($tag_id); + if (!$row) { + continue; + } + $used = tagUsage($tag_id); + $error = ''; + if (!tagDelete($tag_id, $error)) { + $kept += $error !== '' ? 1 : 0; + continue; + } + logAudit("Tag", "Delete", "$session_name deleted " . $tag_kind_word($row) . " tag " . escapeSql($row['tag_name']) + . ($used ? ", taking it off " . $tag_records_text($used, $row['tag_type']) : '')); + $deleted++; + $records += $used; + } + + flashAlert("Deleted $deleted " . ($deleted === 1 ? 'tag' : 'tags') . ($records ? ", taken off " . number_format($records) . ($records === 1 ? ' record' : ' records') : '') + . ($kept ? ". Kept $kept that recurring invoice lines count by - archive " . ($kept === 1 ? 'it' : 'them') . ", or merge " . ($kept === 1 ? 'it' : 'them') . " into another tag" : ''), $kept ? 'warning' : 'error'); redirect(); diff --git a/admin/post/tag_model.php b/admin/post/tag_model.php deleted file mode 100644 index 65ee99f73..000000000 --- a/admin/post/tag_model.php +++ /dev/null @@ -1,7 +0,0 @@ - Tags - the tags for each kind of record: clients, locations, + * contacts, credentials, assets, vendors and domains. + * + * Each tag shows as it looks on a record, with its description and how many + * records have it (opening that list filtered by it). A tag can be changed, + * merged into another of its kind, archived - it stays on its records but + * isn't offered for new tagging - or deleted. The work is in + * functions/tags.php; the handlers are admin/post/tag.php. + */ require_once "includes/inc_all_admin.php"; -if (isset($_GET['type'])) { - $type_filter = intval($_GET['type']); -} else { - $type_filter = 1; +$kinds = []; +foreach (tagKinds() as $kind_type => $kind_entity) { + $kinds[$kind_type] = tagEntity($kind_entity); +} +$type = intval($_GET['type'] ?? 1); +$type = isset($kinds[$type]) ? $type : 1; +$kind = $kinds[$type]; +$show_archived = isset($_GET['archived']); +$by_use = ($_GET['sort'] ?? '') === 'use'; + +$usage = tagUsageBreakdown(); +$seat_lines = tagSeatLineCounts(); + +$search_sql = $q !== '' ? "AND (tag_name LIKE '%$q%' OR tag_description LIKE '%$q%')" : ''; +$tags = []; +$sql = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_description, tag_type, tag_color, tag_icon, tag_created_at, tag_archived_at FROM tags + WHERE tag_type = $type AND tag_archived_at IS " . ($show_archived ? 'NOT NULL' : 'NULL') . " $search_sql ORDER BY tag_name ASC"); +while ($row = mysqli_fetch_assoc($sql)) { + $row['used'] = $usage[intval($row['tag_id'])] ?? ['all' => 0, 'archived' => 0]; + $row['lines'] = $seat_lines[intval($row['tag_id'])] ?? 0; + $tags[] = $row; +} +if ($by_use) { + // Most used first; the query put them in name order, and usort keeps that order for equal counts + usort($tags, function ($a, $b) { + return $b['used']['all'] <=> $a['used']['all']; + }); } -// Tag types shown in the left nav -$tag_types = [ - 1 => ['label' => 'Client', 'icon' => 'fa-users'], - 2 => ['label' => 'Location', 'icon' => 'fa-map-marker-alt'], - 3 => ['label' => 'Contact', 'icon' => 'fa-address-book'], - 4 => ['label' => 'Credential', 'icon' => 'fa-key'], - 5 => ['label' => 'Asset', 'icon' => 'fa-desktop'], - 6 => ['label' => 'Vendor', 'icon' => 'fa-building'], - 7 => ['label' => 'Domain', 'icon' => 'fa-globe'], -]; - -// Label for the selected type -$tag_type_display = $tag_types[$type_filter]['label'] ?? 'Unknown'; - -$sql = mysqli_query( - $mysqli, - "SELECT SQL_CALC_FOUND_ROWS tag_color, tag_icon, tag_id, tag_name FROM tags - WHERE tag_name LIKE '%$q%' - AND tag_type = $type_filter - ORDER BY $sort $order LIMIT $record_from, $record_to" -); - -$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); - -// Row count per type for the nav badges -$tag_type_counts = []; -$sql_tag_type_counts = mysqli_query($mysqli, "SELECT tag_type, COUNT(tag_id) AS tag_type_count FROM tags GROUP BY tag_type"); -while ($row = mysqli_fetch_assoc($sql_tag_type_counts)) { - $tag_type_counts[intval($row['tag_type'])] = intval($row['tag_type_count']); +// Current tags of each kind for the nav, and this kind's archived ones for the tab +$kind_counts = []; +$archived_count = 0; +$sql = mysqli_query($mysqli, "SELECT tag_type, SUM(tag_archived_at IS NULL), SUM(tag_archived_at IS NOT NULL) FROM tags GROUP BY tag_type"); +while ($row = mysqli_fetch_row($sql)) { + $kind_counts[intval($row[0])] = intval($row[1]); + if (intval($row[0]) === $type) { + $archived_count = intval($row[2]); + } } +// This page with some of its query changed - null drops a key +$page_url = function (array $change = []) use ($type, $show_archived, $by_use, $q) { + $query = array_merge(['type' => $type, 'q' => $q !== '' ? stripslashes($q) : null, 'sort' => $by_use ? 'use' : null, 'archived' => $show_archived ? 1 : null], $change); + return 'tags.php?' . http_build_query(array_filter($query, function ($v) { + return $v !== null; + })); +}; + +// "12 assets" / "1 asset" +$records_text = function ($n) use ($kind) { + return number_format($n) . ' ' . ($n === 1 ? strtolower($kind['title']) : $kind['plural']); +}; +$kind_word = strtolower($kind['title']); +$csrf = $_SESSION['csrf_token']; + ?> -
-
-

Tags

-
- -
+
+
+

Tags

+
+
- -
-
- - -
- -
- - -
-
- - - - -
-
-
- - -
-
-
- Archived -
-
-
-
-
- - "> - - - - - - - - - - - - - - - -
- - Name - - Action
- - - - - -
-
-
-
-
- strtolower($tag_type_display) . ' tags', - 'icon' => 'fa-tags', - 'views' => ['type'], - 'actions' => [['label' => "New $tag_type_display Tag", 'modal' => "modals/tag/tag_add.php?type=$type_filter"]], - ]; - ?> -
- + +
+ +
+ +
+
+
+ + + +
+ + +
+
+ Name + Most used +
+ + +
+
+ +
+ +
+ + + + + + + + + + + + + ' . $records_text($used) . '' + . ($used_archived ? ' (' . number_format($used_archived) . ' archived)' : '') + : '' . ($tag['tag_archived_at'] ? 'Nothing has it' : 'Nothing yet') . ''; + $lines_html = $lines + ? '
Counted on ' . $lines . ' recurring invoice ' . ($lines === 1 ? 'line' : 'lines') . '
' + : ''; + $delete_text = $used + ? 'It comes off the ' . $records_text($used) . ' that ' . ($used === 1 ? 'has' : 'have') . ' it. To keep it on them but stop offering it, archive it instead.' + : 'Nothing has it, so no record changes.'; + ?> + + + + + + + + +
+
+ +
+
TagOnAction
+
+ +
+
+ + +
+ +
+ +
Archived
+ +
+ + + + +
+
+
+ + + "$kind_word tags", + 'title' => $show_archived ? "No archived $kind_word tags" : "No $kind_word tags yet", + 'text' => $show_archived ? 'An archived tag stays on its records, but isn\'t offered for tagging or in the filters.' : 'Tags sort and filter ' . $kind['plural'] . ' - "VIP", "Managed", "Retiring soon".', + 'icon' => 'fa-tags', + 'filtered' => $q !== '', + 'clear_url' => $page_url(['q' => null]), + 'actions' => $show_archived ? [] : [['label' => "New {$kind['title']} Tag", 'modal' => "modals/tag/tag_add.php?type=$type"]], + ]) ?> + +
+
+
+ + + + [] ]; + // An archived tag is only offered to take it off the records that still have it $sql = mysqli_query($mysqli, - "SELECT tag_id, tag_name, tag_color, tag_icon, + "SELECT tag_id, tag_name, tag_description, tag_color, tag_icon, tag_archived_at, (SELECT COUNT(*) FROM {$config['link_table']} WHERE {$config['link_tag']} = tags.tag_id AND {$config['link_record']} IN ($ids)) AS chosen FROM tags @@ -124,11 +125,15 @@ if (isset($_GET['tag_picker'])) { ORDER BY tag_name ASC" ); while ($row = mysqli_fetch_assoc($sql)) { + if ($row['tag_archived_at'] && !intval($row['chosen'])) { + continue; + } $response['tags'][] = [ 'id' => intval($row['tag_id']), 'name' => $row['tag_name'], - 'color' => preg_match('/^(#[0-9a-f]{3,8}|[a-z]{3,24})$/i', trim((string) $row['tag_color'])) ? trim($row['tag_color']) : '', - 'icon' => preg_replace('/[^a-z0-9-]/', '', strtolower((string) $row['tag_icon'])) ?: 'tag', + 'description' => trim((string) $row['tag_description']) . ($row['tag_archived_at'] ? (trim((string) $row['tag_description']) !== '' ? ' - ' : '') . 'Archived' : ''), + 'color' => tagColor($row['tag_color']), + 'icon' => tagIcon($row['tag_icon']), 'chosen' => intval($row['chosen']) ]; } @@ -169,15 +174,17 @@ if (isset($_POST['tag_picker_set']) || isset($_POST['tag_picker_create'])) { } $name_sql = escapeSql($name); - // Typing the name of a tag that already exists just picks it - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT tag_id FROM tags WHERE tag_type = $type AND tag_name = '$name_sql' LIMIT 1")); + // Typing the name of a tag that already exists just picks it - an archived one comes back + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT tag_id, tag_archived_at FROM tags WHERE tag_type = $type AND LOWER(tag_name) = LOWER('$name_sql') LIMIT 1")); if ($row) { $tag_id = intval($row['tag_id']); + if ($row['tag_archived_at']) { + tagRestore($tag_id); + logAudit("Tag", "Restore", "$session_name restored {$config['label']} tag $name_sql", 0, $tag_id); + } } else { - $color = tagNextColor($type); - mysqli_query($mysqli, "INSERT INTO tags SET tag_name = '$name_sql', tag_type = $type, tag_color = '$color', tag_icon = 'tag'"); - $tag_id = mysqli_insert_id($mysqli); - logAudit("Tag", "Create", "$session_name created tag $name_sql", 0, $tag_id); + $tag_id = tagCreate(['name' => $name, 'description' => '', 'type' => $type, 'color' => tagNextColor($type), 'icon' => 'tag']); + logAudit("Tag", "Create", "$session_name created {$config['label']} tag $name_sql", 0, $tag_id); } $on = true; @@ -187,12 +194,18 @@ if (isset($_POST['tag_picker_set']) || isset($_POST['tag_picker_create'])) { } // The tag has to be one of this kind of record's tags - $tag = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT tag_name FROM tags WHERE tag_id = $tag_id AND tag_type = $type")); + $tag = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT tag_name, tag_archived_at FROM tags WHERE tag_id = $tag_id AND tag_type = $type")); if (!$tag) { http_response_code(404); echo json_encode(['error' => 'That tag no longer exists.']); exit(); } + // An archived tag can come off records, not go on more + if ($on && $tag['tag_archived_at']) { + http_response_code(409); + echo json_encode(['error' => 'That tag is archived.']); + exit(); + } $tag_name = escapeSql($tag['tag_name']); $changed = 0; diff --git a/agent/assets.php b/agent/assets.php index c0ed8b285..49cdc8a68 100644 --- a/agent/assets.php +++ b/agent/assets.php @@ -320,7 +320,7 @@ $search_noun = $type_filter ? $asset_type_tabs[$type_filter]['label'] : 'assets' $sql_tags_filter = mysqli_query($mysqli, " SELECT tag_id, tag_name, tag_color, tag_icon FROM tags - WHERE tag_type = 5 + WHERE tag_type = 5 AND (tag_archived_at IS NULL OR tag_id IN ($tag_filter)) AND ( EXISTS (SELECT 1 FROM asset_tags JOIN assets ON asset_id = asset_tag_asset_id WHERE asset_tag_tag_id = tag_id " . clientScopeSql('asset_client_id') . " $client_query) diff --git a/agent/clients.php b/agent/clients.php index 87789dc02..9ee47e3ad 100644 --- a/agent/clients.php +++ b/agent/clients.php @@ -198,7 +198,7 @@ $client_tickets = []; if ($clients) { $page_ids = implode(',', array_keys($clients)); - $sql_tags = mysqli_query($mysqli, "SELECT client_tags.client_id, tags.tag_id, tag_name, tag_color, tag_icon + $sql_tags = mysqli_query($mysqli, "SELECT client_tags.client_id, tags.tag_id, tag_name, tag_description, tag_color, tag_icon FROM client_tags JOIN tags ON tags.tag_id = client_tags.tag_id WHERE client_tags.client_id IN ($page_ids) ORDER BY tag_name"); @@ -375,7 +375,7 @@ $total_leads = intval($row['leads']); SELECT tags.tag_id, tags.tag_name, MAX(tags.tag_color) AS tag_color, MAX(tags.tag_icon) AS tag_icon FROM tags LEFT JOIN client_tags ON client_tags.tag_id = tags.tag_id - WHERE tag_type = 1 + WHERE tag_type = 1 AND (tags.tag_archived_at IS NULL OR tags.tag_id IN ($tag_filter)) GROUP BY tags.tag_id, tags.tag_name HAVING COUNT(client_tags.client_id) > 0 OR tags.tag_id IN ($tag_filter) ORDER BY tags.tag_name diff --git a/agent/contacts.php b/agent/contacts.php index 4f6635551..f3089eb70 100644 --- a/agent/contacts.php +++ b/agent/contacts.php @@ -289,7 +289,7 @@ $search_noun = $role_filter ? strtolower($contact_role_tabs[$role_filter]['label $sql_tags_filter = mysqli_query($mysqli, " SELECT tag_id, tag_name, tag_color, tag_icon FROM tags - WHERE tag_type = 3 + WHERE tag_type = 3 AND (tag_archived_at IS NULL OR tag_id IN ($tag_filter)) AND ( EXISTS (SELECT 1 FROM contact_tags JOIN contacts ON contacts.contact_id = contact_tags.contact_id WHERE contact_tags.tag_id = tags.tag_id " . clientScopeSql('contact_client_id') . " $client_query) diff --git a/agent/credentials.php b/agent/credentials.php index ae0733581..044a27747 100644 --- a/agent/credentials.php +++ b/agent/credentials.php @@ -204,7 +204,7 @@ $filter_url = function ($changes) use ($client_url) { // Tags in use on credentials in this scope, plus any already picked $sql_tags_filter = mysqli_query($mysqli, " SELECT tag_id, tag_name, tag_color, tag_icon FROM tags - WHERE tag_type = 4 + WHERE tag_type = 4 AND (tag_archived_at IS NULL OR tag_id IN ($tag_filter)) AND ( EXISTS (SELECT 1 FROM credential_tags JOIN credentials ON credentials.credential_id = credential_tags.credential_id WHERE credential_tags.tag_id = tags.tag_id " . clientScopeSql('credential_client_id') . " $client_query) diff --git a/agent/domains.php b/agent/domains.php index d7a0acd80..7b861ff35 100644 --- a/agent/domains.php +++ b/agent/domains.php @@ -179,7 +179,7 @@ $bulk_vendor_options = $can_edit ? domainVendorChoices($client_url ? $client_id // Tags in use on domains in this scope, plus any already picked $sql_tags_filter = mysqli_query($mysqli, " SELECT tag_id, tag_name, tag_color, tag_icon FROM tags - WHERE tag_type = 7 + WHERE tag_type = 7 AND (tag_archived_at IS NULL OR tag_id IN ($tag_filter)) AND ( EXISTS (SELECT 1 FROM domain_tags JOIN domains ON domains.domain_id = domain_tags.domain_id WHERE domain_tags.tag_id = tags.tag_id " . clientScopeSql('domain_client_id') . " $client_query) diff --git a/agent/includes/inc_all_client.php b/agent/includes/inc_all_client.php index b8c72dc2e..43844d2b4 100644 --- a/agent/includes/inc_all_client.php +++ b/agent/includes/inc_all_client.php @@ -81,7 +81,7 @@ if (isset($_GET['client_id'])) { // Client Tags - raw rows, drawn by tagPills() (functions/tags.php) $client_tags = []; - $sql_client_tags = mysqli_query($mysqli, "SELECT tags.tag_id, tag_name, tag_color, tag_icon FROM client_tags JOIN tags ON client_tags.tag_id = tags.tag_id WHERE client_id = $client_id ORDER BY tag_name ASC"); + $sql_client_tags = mysqli_query($mysqli, "SELECT tags.tag_id, tag_name, tag_description, tag_color, tag_icon FROM client_tags JOIN tags ON client_tags.tag_id = tags.tag_id WHERE client_id = $client_id ORDER BY tag_name ASC"); while ($row = mysqli_fetch_assoc($sql_client_tags)) { $client_tags[] = $row; } diff --git a/agent/locations.php b/agent/locations.php index d61b49509..378e6397f 100644 --- a/agent/locations.php +++ b/agent/locations.php @@ -172,7 +172,7 @@ $locations_counts = locationCounts(array_keys($locations)); // Tags in use on locations in this scope, plus any already picked $sql_tags_filter = mysqli_query($mysqli, " SELECT tag_id, tag_name, tag_color, tag_icon FROM tags - WHERE tag_type = 2 + WHERE tag_type = 2 AND (tag_archived_at IS NULL OR tag_id IN ($tag_filter)) AND ( EXISTS (SELECT 1 FROM location_tags JOIN locations ON locations.location_id = location_tags.location_id WHERE location_tags.tag_id = tags.tag_id " . clientScopeSql('location_client_id') . " $client_query) diff --git a/agent/modals/asset/asset_export.php b/agent/modals/asset/asset_export.php index a4030365f..04ac834f5 100644 --- a/agent/modals/asset/asset_export.php +++ b/agent/modals/asset/asset_export.php @@ -124,16 +124,7 @@ ob_start();
diff --git a/agent/modals/asset/asset_form.php b/agent/modals/asset/asset_form.php index 5a5efde36..bd48ae579 100644 --- a/agent/modals/asset/asset_form.php +++ b/agent/modals/asset/asset_form.php @@ -74,8 +74,6 @@ while ($row = mysqli_fetch_assoc($sql)) { $os_suggestions[] = ['label' => $row['asset_os'], 'value' => $row['asset_os']]; } -$sql_tags_select = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_color, tag_icon FROM tags WHERE tag_type = 5 ORDER BY tag_name ASC"); - $asset_ip_is_dhcp = $asset_ip === 'DHCP'; // Leading icons that follow what is picked or typed: the status in its @@ -188,15 +186,9 @@ $asset_form_icons = [
- > + -
diff --git a/agent/modals/billing/billing_item.php b/agent/modals/billing/billing_item.php index b45d77203..2c6891554 100644 --- a/agent/modals/billing/billing_item.php +++ b/agent/modals/billing/billing_item.php @@ -101,6 +101,13 @@ ob_start(); $seat_options = recurringSeatOptions($client_id); $seat_source = (string) ($item['item_seat_source'] ?? ''); $seat_filter = recurringSeatFilter($seat_source, $item['item_seat_filter'] ?? ''); + // The line's own tag stays offered once archived, or on nothing the client has now, so saving doesn't drop it + $seat_tag = intval($seat_filter['tag'] ?? 0); + $seat_tag_key = ['contacts' => 'contact_tags', 'assets' => 'asset_tags'][$seat_source] ?? ''; + if ($seat_tag && $seat_tag_key && !isset($seat_options[$seat_tag_key][$seat_tag]) && ($seat_tag_row = tagRow($seat_tag))) { + $seat_options[$seat_tag_key][$seat_tag] = ['tag_id' => $seat_tag, 'tag_name' => $seat_tag_row['tag_name'] . ($seat_tag_row['tag_archived_at'] ? ' (archived)' : ''), + 'n' => intval(recurringSeatCount($client_id, $seat_source, ['tag' => $seat_tag]))]; + } $seat_minimum = floatval($item['item_seat_minimum'] ?? 0); ?>
diff --git a/agent/modals/client/client_add.php b/agent/modals/client/client_add.php index 0ffe12824..0002f86fe 100644 --- a/agent/modals/client/client_add.php +++ b/agent/modals/client/client_add.php @@ -8,8 +8,6 @@ $leads_filter = intval($_GET['lead'] ?? 0); // Selects $referral_sql = mysqli_query($mysqli, "SELECT category_name FROM categories WHERE category_type = 'Referral' AND category_archived_at IS NULL ORDER BY category_name ASC"); -$sql_tags_select = mysqli_query($mysqli, "SELECT tag_id, tag_name FROM tags WHERE tag_type = 1 ORDER BY tag_name ASC"); - $net_terms_array = array ( '0'=>'On Receipt', '7'=>'7 Days', @@ -121,21 +119,9 @@ ob_start();
- > + -
diff --git a/agent/modals/client/client_edit.php b/agent/modals/client/client_edit.php index 479249d93..d0c319cc1 100644 --- a/agent/modals/client/client_edit.php +++ b/agent/modals/client/client_edit.php @@ -159,22 +159,9 @@ ob_start();
- > + -
diff --git a/agent/modals/client/client_export.php b/agent/modals/client/client_export.php index f932a3637..5998895c7 100644 --- a/agent/modals/client/client_export.php +++ b/agent/modals/client/client_export.php @@ -113,16 +113,7 @@ ob_start();
diff --git a/agent/modals/contact/contact_export.php b/agent/modals/contact/contact_export.php index c3d55552d..808cf3603 100644 --- a/agent/modals/contact/contact_export.php +++ b/agent/modals/contact/contact_export.php @@ -102,16 +102,7 @@ ob_start();
diff --git a/agent/modals/contact/contact_form.php b/agent/modals/contact/contact_form.php index 5f77dd972..6776d4cea 100644 --- a/agent/modals/contact/contact_form.php +++ b/agent/modals/contact/contact_form.php @@ -31,8 +31,6 @@ if ($client_id) { } } -$sql_tags_select = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_color, tag_icon FROM tags WHERE tag_type = 3 ORDER BY tag_name ASC"); - // The roles, with what each one does $contact_roles = [ 'contact_important' => ['label' => 'Important', 'icon' => 'fa-star', 'value' => $contact_important, 'help' => 'Pinned to the top of the contacts list.'], @@ -242,15 +240,9 @@ $contact_roles = [
- > + -
diff --git a/agent/modals/credential/credential_export.php b/agent/modals/credential/credential_export.php index 517706f3b..48dc380a1 100644 --- a/agent/modals/credential/credential_export.php +++ b/agent/modals/credential/credential_export.php @@ -77,16 +77,7 @@ ob_start();
diff --git a/agent/modals/credential/credential_form.php b/agent/modals/credential/credential_form.php index 96c8292ce..f1da9c686 100644 --- a/agent/modals/credential/credential_form.php +++ b/agent/modals/credential/credential_form.php @@ -40,8 +40,6 @@ if ($client_id) { } } -$sql_tags_select = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_color, tag_icon FROM tags WHERE tag_type = 4 ORDER BY tag_name ASC"); - $form_id = 'credentialForm' . ($credential_form_mode === 'edit' ? $credential_id : 'New'); ?> @@ -205,17 +203,9 @@ $form_id = 'credentialForm' . ($credential_form_mode === 'edit' ? $credential_id
- > + - - -
diff --git a/agent/modals/domain/domain_export.php b/agent/modals/domain/domain_export.php index 6f47700ba..bf3ee8479 100644 --- a/agent/modals/domain/domain_export.php +++ b/agent/modals/domain/domain_export.php @@ -95,12 +95,7 @@ ob_start();
diff --git a/agent/modals/domain/domain_form.php b/agent/modals/domain/domain_form.php index e92feb432..7f6fa8cf5 100644 --- a/agent/modals/domain/domain_form.php +++ b/agent/modals/domain/domain_form.php @@ -28,8 +28,6 @@ if ($client_id) { } } -$sql_tags_select = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_color, tag_icon FROM tags WHERE tag_type = 7 ORDER BY tag_name ASC"); - $form_id = 'domainForm' . ($domain_form_mode === 'edit' ? $domain_id : 'New'); ?> @@ -169,17 +167,9 @@ $form_id = 'domainForm' . ($domain_form_mode === 'edit' ? $domain_id : 'New');
- > + - - -

Domain ID

diff --git a/agent/modals/location/location_export.php b/agent/modals/location/location_export.php index 99d12da69..fd40e63b4 100644 --- a/agent/modals/location/location_export.php +++ b/agent/modals/location/location_export.php @@ -77,16 +77,7 @@ ob_start();
diff --git a/agent/modals/location/location_form.php b/agent/modals/location/location_form.php index 2ce8d5e88..5d8ff7536 100644 --- a/agent/modals/location/location_form.php +++ b/agent/modals/location/location_form.php @@ -32,8 +32,6 @@ if ($client_id) { } } -$sql_tags_select = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_color, tag_icon FROM tags WHERE tag_type = 2 ORDER BY tag_name ASC"); - $form_id = 'locationForm' . ($location_form_mode === 'edit' ? $location_id : 'New'); ?> @@ -103,15 +101,9 @@ $form_id = 'locationForm' . ($location_form_mode === 'edit' ? $location_id : 'Ne
- > + -
diff --git a/agent/modals/vendor/vendor_export.php b/agent/modals/vendor/vendor_export.php index b22474711..f7231e0ac 100644 --- a/agent/modals/vendor/vendor_export.php +++ b/agent/modals/vendor/vendor_export.php @@ -81,12 +81,7 @@ ob_start();
diff --git a/agent/modals/vendor/vendor_form.php b/agent/modals/vendor/vendor_form.php index 2aaa83821..efb7fdf76 100644 --- a/agent/modals/vendor/vendor_form.php +++ b/agent/modals/vendor/vendor_form.php @@ -36,8 +36,6 @@ while ($row = mysqli_fetch_assoc($sql)) { } } -$sql_tags_select = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_color, tag_icon FROM tags WHERE tag_type = 6 ORDER BY tag_name ASC"); - $form_id = 'vendorForm' . ($vendor_form_mode === 'edit' ? $vendor_id : 'New'); ?> @@ -118,17 +116,9 @@ $form_id = 'vendorForm' . ($vendor_form_mode === 'edit' ? $vendor_id : 'New');
- > + - - -
diff --git a/agent/post/asset.php b/agent/post/asset.php index 4ea899029..dd0920a7d 100644 --- a/agent/post/asset.php +++ b/agent/post/asset.php @@ -43,13 +43,8 @@ if (isset($_POST['add_asset'])) { $asset_id = mysqli_insert_id($mysqli); - // Add Tags - if (isset($_POST['tags'])) { - foreach($_POST['tags'] as $tag) { - $tag = intval($tag); - mysqli_query($mysqli, "INSERT INTO asset_tags SET asset_tag_asset_id = $asset_id, asset_tag_tag_id = $tag"); - } - } + // Tags - asset tags only, and an admin can type a new one in (functions/tags.php) + tagSetForRecord('asset', $asset_id, (array) ($_POST['tags'] ?? [])); // Add Photo if (isset($_FILES['file']['tmp_name'])) { @@ -163,17 +158,8 @@ if (isset($_POST['edit_asset'])) { mysqli_query($mysqli,"UPDATE assets SET asset_photo = NULL WHERE asset_id = $asset_id"); } - // Tags - // Delete existing tags - mysqli_query($mysqli, "DELETE FROM asset_tags WHERE asset_tag_asset_id = $asset_id"); - - // Add new tags - if (isset($_POST['tags'])) { - foreach($_POST['tags'] as $tag) { - $tag = intval($tag); - mysqli_query($mysqli, "INSERT INTO asset_tags SET asset_tag_asset_id = $asset_id, asset_tag_tag_id = $tag"); - } - } + // Tags - asset tags only, and an admin can type a new one in (functions/tags.php) + tagSetForRecord('asset', $asset_id, (array) ($_POST['tags'] ?? [])); // Add to History mysqli_query($mysqli,"INSERT INTO asset_history SET asset_history_status = '$status', asset_history_description = '$session_name updated $name', asset_history_asset_id = $asset_id"); diff --git a/agent/post/client.php b/agent/post/client.php index 4e6b028a7..eada229fa 100644 --- a/agent/post/client.php +++ b/agent/post/client.php @@ -72,13 +72,8 @@ if (isset($_POST['add_client'])) { $extended_log_description .= ", primary contact $contact added"; } - // Add tags - if (isset($_POST['tags'])) { - foreach ($_POST['tags'] as $tag) { - $tag = intval($tag); - mysqli_query($mysqli, "INSERT INTO client_tags SET client_id = $client_id, tag_id = $tag"); - } - } + // Tags - client tags only, and an admin can type a new one in (functions/tags.php) + tagSetForRecord('client', $client_id, (array) ($_POST['tags'] ?? [])); // Create domain and SSL certificate - the website's domain, tidied, looked up // like any other; one whose lookup finds nothing is still added, without records @@ -144,15 +139,8 @@ if (isset($_POST['edit_client'])) { logAudit("Category", "Create", "$session_name created referral category $referral"); } - // Tags - delete existing and re-insert - mysqli_query($mysqli, "DELETE FROM client_tags WHERE client_id = $client_id"); - - if (isset($_POST['tags'])) { - foreach ($_POST['tags'] as $tag) { - $tag = intval($tag); - mysqli_query($mysqli, "INSERT INTO client_tags SET client_id = $client_id, tag_id = $tag"); - } - } + // Tags - client tags only, and an admin can type a new one in (functions/tags.php) + tagSetForRecord('client', $client_id, (array) ($_POST['tags'] ?? [])); // Ticket SLA assignments (fields only rendered when active SLAs exist) if (isset($_POST['client_sla_low'])) { diff --git a/agent/post/contact.php b/agent/post/contact.php index bdb3ec76b..0eac3f409 100644 --- a/agent/post/contact.php +++ b/agent/post/contact.php @@ -42,13 +42,8 @@ if (isset($_POST['add_contact'])) { $contact_id = mysqli_insert_id($mysqli); - // Add Tags - if (isset($_POST['tags'])) { - foreach($_POST['tags'] as $tag) { - $tag = intval($tag); - mysqli_query($mysqli, "INSERT INTO contact_tags SET contact_id = $contact_id, tag_id = $tag"); - } - } + // Tags - contact tags only, and an admin can type a new one in (functions/tags.php) + tagSetForRecord('contact', $contact_id, (array) ($_POST['tags'] ?? [])); //Update Primary contact in clients if primary contact is checked if ($contact_primary == 1) { @@ -174,17 +169,8 @@ if (isset($_POST['edit_contact'])) { mysqli_query($mysqli,"UPDATE contacts SET contact_photo = NULL WHERE contact_id = $contact_id"); } - // Tags - // Delete existing tags - mysqli_query($mysqli, "DELETE FROM contact_tags WHERE contact_id = $contact_id"); - - // Add new tags - if (isset($_POST['tags'])) { - foreach($_POST['tags'] as $tag) { - $tag = intval($tag); - mysqli_query($mysqli, "INSERT INTO contact_tags SET contact_id = $contact_id, tag_id = $tag"); - } - } + // Tags - contact tags only, and an admin can type a new one in (functions/tags.php) + tagSetForRecord('contact', $contact_id, (array) ($_POST['tags'] ?? [])); // Update Primary contact in clients if primary contact is checked if ($contact_primary == 1) { diff --git a/agent/post/tag.php b/agent/post/tag.php deleted file mode 100644 index 60c401bec..000000000 --- a/agent/post/tag.php +++ /dev/null @@ -1,25 +0,0 @@ -" . stripslashes($name) . " created"); - - redirect(); - -} diff --git a/agent/post/tag_model.php b/agent/post/tag_model.php deleted file mode 100644 index 65ee99f73..000000000 --- a/agent/post/tag_model.php +++ /dev/null @@ -1,7 +0,0 @@ - implode(', ', $set), 'name' => $name, 'expire' => $expire]; } -/** Replace a domain's tags with these - domain tags (type 7) only. */ +/** Replace a domain's tags with these - domain tags only, and an admin can type a new one in (tagSetForRecord()). */ function domainSetTags($domain_id, $tag_ids) { - global $mysqli; - $domain_id = intval($domain_id); - mysqli_query($mysqli, "DELETE FROM domain_tags WHERE domain_id = $domain_id"); - $tag_ids = array_values(array_unique(array_filter(array_map('intval', (array) $tag_ids)))); - if (!$tag_ids) { - return; - } - mysqli_query($mysqli, "INSERT IGNORE INTO domain_tags (domain_id, tag_id) - SELECT $domain_id, tag_id FROM tags WHERE tag_type = 7 AND tag_id IN (" . implode(',', $tag_ids) . ")"); + tagSetForRecord('domain', $domain_id, (array) $tag_ids); } /** diff --git a/functions/location.php b/functions/location.php index f68c199ce..00e4d577f 100644 --- a/functions/location.php +++ b/functions/location.php @@ -155,17 +155,9 @@ function locationFormSet($post, $client_id) { return implode(', ', $set); } -/** Replace a location's tags with these - location tags (type 2) only. */ +/** Replace a location's tags with these - location tags only, and an admin can type a new one in (tagSetForRecord()). */ function locationSetTags($location_id, $tag_ids) { - global $mysqli; - $location_id = intval($location_id); - mysqli_query($mysqli, "DELETE FROM location_tags WHERE location_id = $location_id"); - $tag_ids = array_values(array_unique(array_filter(array_map('intval', (array) $tag_ids)))); - if (!$tag_ids) { - return; - } - mysqli_query($mysqli, "INSERT IGNORE INTO location_tags (location_id, tag_id) - SELECT $location_id, tag_id FROM tags WHERE tag_type = 2 AND tag_id IN (" . implode(',', $tag_ids) . ")"); + tagSetForRecord('location', $location_id, (array) $tag_ids); } /** Make this the client's one primary location - what the client header and overview show. */ diff --git a/functions/tags.php b/functions/tags.php index 5b277e8f3..5c28c398a 100644 --- a/functions/tags.php +++ b/functions/tags.php @@ -7,37 +7,47 @@ * pills that open the list filtered to that tag, then a "+" pill that opens * the tag picker (js/tag_picker.js). The picker ticks tags on and off in * place through agent/ajax.php and redraws the pills from the HTML this file - * returns, so the page never reloads and nothing goes through a modal. + * returns, so the page never reloads and nothing goes through a modal. The + * record forms save their Tags field through tagSetForRecord(). + * + * Admin > Tags (admin/tags.php) makes, changes, merges, archives and deletes + * them. An archived tag stays on the records that have it, but isn't offered + * for new tagging or in the list filters. */ /* What differs between the seven kinds of tagged record. */ function tagEntity($entity) { $entities = [ 'client' => [ + 'title' => 'Client', 'plural' => 'clients', 'icon' => 'fa-users', 'type' => 1, 'label' => 'client', 'module' => 'module_client', 'link_table' => 'client_tags', 'link_record' => 'client_id', 'link_tag' => 'tag_id', 'table' => 'clients', 'id' => 'client_id', 'client' => 'client_id', 'name' => 'client_name', 'log' => 'Client', 'list' => 'clients.php' ], 'location' => [ + 'title' => 'Location', 'plural' => 'locations', 'icon' => 'fa-map-marker-alt', 'type' => 2, 'label' => 'location', 'module' => 'module_client', 'link_table' => 'location_tags', 'link_record' => 'location_id', 'link_tag' => 'tag_id', 'table' => 'locations', 'id' => 'location_id', 'client' => 'location_client_id', 'name' => 'location_name', 'log' => 'Location', 'list' => 'locations.php' ], 'contact' => [ + 'title' => 'Contact', 'plural' => 'contacts', 'icon' => 'fa-address-book', 'type' => 3, 'label' => 'contact', 'module' => 'module_client', 'link_table' => 'contact_tags', 'link_record' => 'contact_id', 'link_tag' => 'tag_id', 'table' => 'contacts', 'id' => 'contact_id', 'client' => 'contact_client_id', 'name' => 'contact_name', 'log' => 'Contact', 'list' => 'contacts.php' ], 'credential' => [ + 'title' => 'Credential', 'plural' => 'credentials', 'icon' => 'fa-key', 'type' => 4, 'label' => 'credential', 'module' => 'module_credential', 'link_table' => 'credential_tags', 'link_record' => 'credential_id', 'link_tag' => 'tag_id', 'table' => 'credentials', 'id' => 'credential_id', 'client' => 'credential_client_id', 'name' => 'credential_name', 'log' => 'Credential', 'list' => 'credentials.php' ], 'asset' => [ + 'title' => 'Asset', 'plural' => 'assets', 'icon' => 'fa-desktop', 'type' => 5, 'label' => 'asset', 'module' => 'module_client', 'link_table' => 'asset_tags', 'link_record' => 'asset_tag_asset_id', 'link_tag' => 'asset_tag_tag_id', 'table' => 'assets', 'id' => 'asset_id', 'client' => 'asset_client_id', 'name' => 'asset_name', @@ -45,12 +55,14 @@ function tagEntity($entity) { ], // A vendor of no client is one of ours - a supplier, which is the financial module's 'vendor' => [ + 'title' => 'Vendor', 'plural' => 'vendors', 'icon' => 'fa-building', 'type' => 6, 'label' => 'vendor', 'module' => 'module_client', 'module_ours' => 'module_financial', 'link_table' => 'vendor_tags', 'link_record' => 'vendor_id', 'link_tag' => 'tag_id', 'table' => 'vendors', 'id' => 'vendor_id', 'client' => 'vendor_client_id', 'name' => 'vendor_name', 'log' => 'Vendor', 'list' => 'vendors.php' ], 'domain' => [ + 'title' => 'Domain', 'plural' => 'domains', 'icon' => 'fa-globe', 'type' => 7, 'label' => 'domain', 'module' => 'module_support', 'link_table' => 'domain_tags', 'link_record' => 'domain_id', 'link_tag' => 'tag_id', 'table' => 'domains', 'id' => 'domain_id', 'client' => 'domain_client_id', 'name' => 'domain_name', @@ -61,7 +73,7 @@ function tagEntity($entity) { return $entities[$entity] ?? null; } -/* Tag rows (tag_id, tag_name, tag_color, tag_icon) for each record, in one query. */ +/* Tag rows (tag_id, tag_name, tag_description, tag_color, tag_icon, tag_archived_at) for each record, in one query. */ function tagsForRecords($entity, array $record_ids) { global $mysqli; @@ -73,7 +85,7 @@ function tagsForRecords($entity, array $record_ids) { } $sql = mysqli_query($mysqli, - "SELECT {$config['link_record']} AS record_id, tags.tag_id, tag_name, tag_color, tag_icon + "SELECT {$config['link_record']} AS record_id, tags.tag_id, tag_name, tag_description, tag_color, tag_icon, tag_archived_at FROM {$config['link_table']} JOIN tags ON tags.tag_id = {$config['link_table']}.{$config['link_tag']} WHERE {$config['link_record']} IN (" . implode(',', $record_ids) . ") @@ -118,9 +130,11 @@ function tagPills($entity, $record_id, array $tags, $filter = '', $can_edit = nu foreach ($tags as $tag) { $tag_id = intval($tag['tag_id']); $name = escapeHtml($tag['tag_name']); - $color = preg_match('/^(#[0-9a-f]{3,8}|[a-z]{3,24})$/i', trim((string) $tag['tag_color'])) ? trim($tag['tag_color']) : 'var(--bs-secondary)'; - $icon = preg_replace('/[^a-z0-9-]/', '', strtolower((string) $tag['tag_icon'])) ?: 'tag'; - $html .= '' + $color = tagColor($tag['tag_color']); + $icon = tagIcon($tag['tag_icon'] ?? ''); + $about = trim((string) ($tag['tag_description'] ?? '')); + $html .= '' . '' . $name . ''; } @@ -180,7 +194,7 @@ function tagRecordsEditable($entity, array $record_ids) { return count($records) === count($record_ids) ? $records : false; } -/* A colour for a tag made from the picker - the next one round the palette. */ +/* A colour for a new tag - the next one round the palette. */ function tagNextColor($type) { global $mysqli; @@ -189,3 +203,376 @@ function tagNextColor($type) { return $palette[intval($row[0]) % count($palette)]; } + +/* The colours offered in the tag window - any other can be picked too. */ +const TAG_COLORS = ['#0d6efd', '#6610f2', '#6f42c1', '#d63384', '#dc3545', '#fd7e14', '#ffc107', '#198754', '#20c997', '#0dcaf0', '#795548', '#6c757d', '#343a40', '#001f3f']; + +/* Icons offered in the tag window, by what they suit - any Font Awesome solid icon's name works. */ +const TAG_ICONS = [ + 'tag', 'star', 'crown', 'heart', 'flag', 'bookmark', 'bolt', 'fire', 'gem', 'thumbs-up', + 'exclamation-triangle', 'exclamation-circle', 'ban', 'lock', 'shield-alt', 'user-shield', 'user-secret', 'eye-slash', 'skull-crossbones', 'biohazard', + 'user', 'user-tie', 'users', 'user-graduate', 'user-md', 'handshake', 'building', 'industry', 'store', 'home', + 'hospital', 'school', 'church', 'balance-scale', 'gavel', 'landmark', 'university', 'piggy-bank', 'dollar-sign', 'file-invoice-dollar', + 'desktop', 'laptop', 'server', 'hdd', 'database', 'print', 'mobile-alt', 'tablet-alt', 'phone', 'fax', + 'network-wired', 'wifi', 'ethernet', 'globe', 'cloud', 'envelope', 'microchip', 'memory', 'plug', 'battery-full', + 'key', 'fingerprint', 'id-card', 'certificate', 'clock', 'calendar-alt', 'hourglass-half', 'sync-alt', 'archive', 'tools', + 'wrench', 'cog', 'cogs', 'code', 'terminal', 'bug', 'robot', 'rocket', 'leaf', 'recycle', + 'map-marker-alt', 'truck', 'car', 'plane', 'box', 'boxes', 'warehouse', 'flask', 'graduation-cap', 'trophy', +]; + +/* A tag's colour as #rrggbb - grey for anything else. */ +function tagColor($color) { + $color = strtolower(trim((string) $color)); + if (preg_match('/^#([0-9a-f])([0-9a-f])([0-9a-f])$/', $color, $m)) { + return "#$m[1]$m[1]$m[2]$m[2]$m[3]$m[3]"; + } + return preg_match('/^#[0-9a-f]{6}$/', $color) ? $color : '#6c757d'; +} + +/* Dark or white text, whichever reads on a colour. */ +function tagTextColor($color) { + $color = tagColor($color); + $channel = function ($hex) { + $c = hexdec($hex) / 255; + return $c <= 0.03928 ? $c / 12.92 : pow(($c + 0.055) / 1.055, 2.4); + }; + $luminance = 0.2126 * $channel(substr($color, 1, 2)) + 0.7152 * $channel(substr($color, 3, 2)) + 0.0722 * $channel(substr($color, 5, 2)); + return $luminance > 0.4 ? '#212529' : '#fff'; +} + +/* A tag's icon - a Font Awesome name ("star"), or the plain tag. */ +function tagIcon($icon) { + $icon = preg_replace('/^(fa[srb]? +)?fa-/', '', strtolower(trim((string) $icon))); + $icon = preg_replace('/[^a-z0-9-]/', '', $icon); + return $icon !== '' ? mb_substr($icon, 0, 50) : 'tag'; +} + +/* One tag as a pill, with nowhere to go - for Admin > Tags and the windows. */ +function tagPill(array $tag) { + $color = tagColor($tag['tag_color'] ?? ''); + $about = trim((string) ($tag['tag_description'] ?? '')); + return '' + . '' . escapeHtml($tag['tag_name']) . ''; +} + +/* The seven kinds by tag type - type => the entity's key in tagEntity(). */ +function tagKinds() { + return [1 => 'client', 2 => 'location', 3 => 'contact', 4 => 'credential', 5 => 'asset', 6 => 'vendor', 7 => 'domain']; +} + +/* "an asset tag", "a client tag" - for messages. */ +function tagKindPhrase($type) { + $word = strtolower(tagEntityByType($type)['title'] ?? 'unknown'); + return (in_array($word[0], ['a', 'e', 'i', 'o', 'u'], true) ? 'an ' : 'a ') . $word . ' tag'; +} + +/* The tagEntity() of a tag type - or null. */ +function tagEntityByType($type) { + $entity = tagKinds()[intval($type)] ?? null; + return $entity ? tagEntity($entity) + ['entity' => $entity] : null; +} + +/* One tag, or null. */ +function tagRow($tag_id) { + global $mysqli; + $tag_id = intval($tag_id); + return $tag_id ? (mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_description, tag_type, tag_color, tag_icon, tag_created_at, tag_archived_at + FROM tags WHERE tag_id = $tag_id LIMIT 1")) ?: null) : null; +} + +/* How many records have each tag - tag_id => count, every kind (archived records too). */ +function tagUsageCounts() { + return array_map(function ($u) { + return $u['all']; + }, tagUsageBreakdown()); +} + +/* How many records have each tag, and how many of those are archived - tag_id => ['all' => n, 'archived' => n]. */ +function tagUsageBreakdown() { + global $mysqli; + $counts = []; + foreach (tagKinds() as $entity) { + $config = tagEntity($entity); + $archived = str_replace('_id', '_archived_at', $config['id']); + $sql = mysqli_query($mysqli, "SELECT {$config['link_tag']}, COUNT(*), SUM({$config['table']}.$archived IS NOT NULL) FROM {$config['link_table']} + JOIN {$config['table']} ON {$config['table']}.{$config['id']} = {$config['link_table']}.{$config['link_record']} GROUP BY {$config['link_tag']}"); + while ($row = mysqli_fetch_row($sql)) { + $counts[intval($row[0])] = ['all' => intval($row[1]), 'archived' => intval($row[2])]; + } + } + return $counts; +} + +/* How many records have one tag. */ +function tagUsage($tag_id) { + return tagUsageCounts()[intval($tag_id)] ?? 0; +} + +/* The recurring invoice lines that count users or devices with any of these tags ("Users tagged VIP") - item id => its seat filter. */ +function tagSeatLineItems(array $tag_ids) { + global $mysqli; + $tag_ids = array_map('intval', $tag_ids); + $items = []; + // The filter is JSON written by recurringSeatFilter(); read in PHP rather than with SQL's JSON functions + $sql = mysqli_query($mysqli, "SELECT item_id, item_seat_source, item_seat_filter FROM recurring_invoice_items + WHERE item_seat_source IN ('contacts', 'assets') AND item_seat_filter LIKE '%\"tag\"%'"); + while ($row = mysqli_fetch_assoc($sql)) { + $filter = recurringSeatFilter($row['item_seat_source'], $row['item_seat_filter']); + if (in_array(intval($filter['tag'] ?? 0), $tag_ids, true)) { + $items[intval($row['item_id'])] = $filter; + } + } + return $items; +} + +/* How many recurring invoice lines count by each tag - tag_id => count, for the tags any line counts by. */ +function tagSeatLineCounts() { + global $mysqli; + $counts = []; + $sql = mysqli_query($mysqli, "SELECT item_seat_source, item_seat_filter FROM recurring_invoice_items + WHERE item_seat_source IN ('contacts', 'assets') AND item_seat_filter LIKE '%\"tag\"%'"); + while ($row = mysqli_fetch_assoc($sql)) { + $tag_id = intval(recurringSeatFilter($row['item_seat_source'], $row['item_seat_filter'])['tag'] ?? 0); + if ($tag_id) { + $counts[$tag_id] = ($counts[$tag_id] ?? 0) + 1; + } + } + return $counts; +} + +/* How many recurring invoice lines count by a tag. */ +function tagSeatLines($tag_id) { + return count(tagSeatLineItems([$tag_id])); +} + +/* + * A tag from the tag window - [$fields, $error]. $in: name, description, + * color, icon, and type (a new tag, or one nothing has yet). Raw values; + * tagCreate() and tagUpdate() escape them. + */ +function tagFromInput(array $in, $existing = null) { + global $mysqli; + // Stored without markup (escapeSql() strips it), so checked without it + $name = trim(mb_substr(preg_replace('/\s+/', ' ', strip_tags((string) ($in['name'] ?? ''))), 0, 200)); + $description = trim(mb_substr(preg_replace('/\s+/', ' ', strip_tags((string) ($in['description'] ?? ''))), 0, 255)); + $type = $existing ? intval($existing['tag_type']) : intval($in['type'] ?? 0); + if ($existing && isset($in['type']) && intval($in['type']) !== $type) { + if (tagUsage($existing['tag_id']) || tagSeatLines($existing['tag_id'])) { + return [null, 'A tag can only move to another kind while nothing has it']; + } + $type = intval($in['type']); + } + if (!tagEntityByType($type)) { + return [null, 'Pick what the tag is for']; + } + if ($name === '') { + return [null, 'A tag needs a name']; + } + // Unique within its kind - a tag already sharing its name with another can still be saved under it + $kept_name = $existing && intval($existing['tag_type']) === $type && mb_strtolower($existing['tag_name']) === mb_strtolower($name); + $exclude = $existing ? 'AND tag_id != ' . intval($existing['tag_id']) : ''; + $same = $kept_name ? null : mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT tag_name FROM tags WHERE tag_type = $type AND LOWER(tag_name) = LOWER('" . escapeSql($name) . "') $exclude LIMIT 1")); + if ($same) { + return [null, 'There is already ' . tagKindPhrase($type) . ' called ' . $same['tag_name']]; + } + $color = trim((string) ($in['color'] ?? '')); + $color = preg_match('/^#([0-9a-f]{3}|[0-9a-f]{6})$/i', $color) ? tagColor($color) : ($existing ? tagColor($existing['tag_color']) : tagNextColor($type)); + return [['name' => $name, 'description' => $description, 'type' => $type, 'color' => $color, 'icon' => tagIcon($in['icon'] ?? '')], '']; +} + +/* The SET list for a tag's fields. */ +function tagSetSql(array $f) { + return "tag_name = '" . escapeSql($f['name']) . "', tag_description = " . ($f['description'] !== '' ? "'" . escapeSql($f['description']) . "'" : 'NULL') . ", + tag_type = " . intval($f['type']) . ", tag_color = '" . escapeSql($f['color']) . "', tag_icon = '" . escapeSql($f['icon']) . "'"; +} + +/* Make a tag. Its id. */ +function tagCreate(array $fields) { + global $mysqli; + mysqli_query($mysqli, "INSERT INTO tags SET " . tagSetSql($fields)); + return intval(mysqli_insert_id($mysqli)); +} + +/* Save a tag's name, description, colour, icon (and kind, while unused). */ +function tagUpdate($tag_id, array $fields) { + global $mysqli; + mysqli_query($mysqli, "UPDATE tags SET " . tagSetSql($fields) . " WHERE tag_id = " . intval($tag_id)); +} + +/* Archive a tag - kept on its records, no longer offered. */ +function tagArchive($tag_id) { + global $mysqli; + mysqli_query($mysqli, "UPDATE tags SET tag_archived_at = NOW() WHERE tag_archived_at IS NULL AND tag_id = " . intval($tag_id)); +} + +/* Offer an archived tag again. */ +function tagRestore($tag_id) { + global $mysqli; + mysqli_query($mysqli, "UPDATE tags SET tag_archived_at = NULL WHERE tag_id = " . intval($tag_id)); +} + +/* + * Delete a tag - it comes off every record that has it (the link tables + * cascade). Refused while a recurring invoice line counts by it, as the line + * would count nothing: archive it, or merge it into another. Whether it went. + */ +function tagDelete($tag_id, &$error = '') { + global $mysqli; + $tag_id = intval($tag_id); + if ($lines = tagSeatLines($tag_id)) { + $error = $lines === 1 ? 'A recurring invoice line counts users or devices with it - archive it, or merge it into another tag' : "$lines recurring invoice lines count users or devices with it - archive it, or merge it into another tag"; + return false; + } + mysqli_query($mysqli, "DELETE FROM tags WHERE tag_id = $tag_id"); + return mysqli_affected_rows($mysqli) > 0; +} + +/* + * Merge tags into one of the same kind: every record with one of them gets + * $into_id instead, recurring invoice lines counting by them count by it, and + * they are deleted. How many records changed hands. + */ +function tagMerge(array $from_ids, $into_id) { + global $mysqli; + $into = tagRow($into_id); + if (!$into) { + return 0; + } + $config = tagEntityByType($into['tag_type']); + $into_id = intval($into['tag_id']); + $from_ids = array_values(array_diff(array_unique(array_filter(array_map('intval', $from_ids))), [$into_id])); + if (!$from_ids) { + return 0; + } + // Only tags of the same kind + $from_list = implode(',', $from_ids); + $from_ids = []; + $sql = mysqli_query($mysqli, "SELECT tag_id FROM tags WHERE tag_id IN ($from_list) AND tag_type = " . intval($into['tag_type'])); + while ($row = mysqli_fetch_row($sql)) { + $from_ids[] = intval($row[0]); + } + if (!$from_ids) { + return 0; + } + $from_list = implode(',', $from_ids); + $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)"); + foreach (tagSeatLineItems($from_ids) as $item_id => $filter) { + $filter['tag'] = $into_id; + mysqli_query($mysqli, "UPDATE recurring_invoice_items SET item_seat_filter = '" . escapeSql(json_encode($filter)) . "' WHERE item_id = " . intval($item_id)); + } + mysqli_query($mysqli, "DELETE FROM tags WHERE tag_id IN ($from_list)"); + return $moved; +} + +/* + * The tags a record form offers - this kind's, not archived, plus any the + * record already has. Rows of tag_id, tag_name, tag_description, tag_color, + * tag_icon. + */ +function tagOptionsFor($entity, array $keep_ids = []) { + global $mysqli; + $config = tagEntity($entity); + if (!$config) { + return []; + } + $keep = array_values(array_filter(array_map('intval', $keep_ids))); + $keep_sql = $keep ? ' OR tag_id IN (' . implode(',', $keep) . ')' : ''; + $rows = []; + $sql = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_description, tag_color, tag_icon, tag_archived_at FROM tags + WHERE tag_type = {$config['type']} AND (tag_archived_at IS NULL$keep_sql) ORDER BY tag_name ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $rows[] = $row; + } + return $rows; +} + +/* A record form's Tags options - the tagOptionsFor() rows as '; + } + return $html; +} + +/* + * Set a record's tags from a form's Tags field. $values are tag ids, or - + * typed into the field by an admin - the names of new tags, made with the + * next colour. Only this kind's tags count, each once; an archived tag only + * stays when the record already had it. Returns the tag ids it now has. + */ +function tagSetForRecord($entity, $record_id, array $values) { + global $mysqli, $session_is_admin, $session_name; + $config = tagEntity($entity); + $record_id = intval($record_id); + if (!$config || !$record_id) { + return []; + } + $link = $config['link_table']; + $link_record = $config['link_record']; + $link_tag = $config['link_tag']; + $type = $config['type']; + + $had = []; + $sql = mysqli_query($mysqli, "SELECT $link_tag FROM $link WHERE $link_record = $record_id"); + while ($row = mysqli_fetch_row($sql)) { + $had[] = intval($row[0]); + } + + $ids = []; + foreach ($values as $value) { + $value = trim((string) $value); + if (preg_match('/^[1-9][0-9]*$/', $value)) { + $ids[] = intval($value); + } elseif ($value !== '' && !empty($session_is_admin)) { + // A new tag typed in - or the one of that name already there + $name = trim(mb_substr(preg_replace('/\s+/', ' ', strip_tags($value)), 0, 200)); + if ($name === '') { + continue; + } + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT tag_id, tag_archived_at FROM tags WHERE tag_type = $type AND LOWER(tag_name) = LOWER('" . escapeSql($name) . "') LIMIT 1")); + if ($row) { + // Typing an archived tag's name brings it back, as in the tag picker + if ($row['tag_archived_at']) { + tagRestore($row['tag_id']); + logAudit('Tag', 'Restore', escapeSql(stripslashes((string) $session_name) . " restored {$config['label']} tag $name"), 0, intval($row['tag_id'])); + } + $ids[] = intval($row['tag_id']); + } else { + $tag_id = tagCreate(['name' => $name, 'description' => '', 'type' => $type, 'color' => tagNextColor($type), 'icon' => 'tag']); + logAudit('Tag', 'Create', escapeSql(stripslashes((string) $session_name) . " created {$config['label']} tag $name"), 0, $tag_id); + $ids[] = $tag_id; + } + } + } + $ids = array_values(array_unique($ids)); + + // This kind's tags only; archived ones only when already there + $keep = []; + if ($ids) { + $sql = mysqli_query($mysqli, "SELECT tag_id, tag_archived_at FROM tags WHERE tag_type = $type AND tag_id IN (" . implode(',', $ids) . ")"); + while ($row = mysqli_fetch_assoc($sql)) { + if (!$row['tag_archived_at'] || in_array(intval($row['tag_id']), $had, true)) { + $keep[] = intval($row['tag_id']); + } + } + } + + $remove = array_diff($had, $keep); + if ($remove) { + mysqli_query($mysqli, "DELETE FROM $link WHERE $link_record = $record_id AND $link_tag IN (" . implode(',', $remove) . ")"); + } + foreach (array_diff($keep, $had) as $tag_id) { + mysqli_query($mysqli, "INSERT IGNORE INTO $link SET $link_record = $record_id, $link_tag = $tag_id"); + } + sort($keep); + return $keep; +} diff --git a/functions/vendor.php b/functions/vendor.php index 1663f5bd3..70285ac2c 100644 --- a/functions/vendor.php +++ b/functions/vendor.php @@ -223,17 +223,9 @@ function vendorFormSet($post) { return implode(', ', $set); } -/** Replace a vendor's tags with these - vendor tags (type 6) only. */ +/** Replace a vendor's tags with these - vendor tags only, and an admin can type a new one in (tagSetForRecord()). */ function vendorSetTags($vendor_id, $tag_ids) { - global $mysqli; - $vendor_id = intval($vendor_id); - mysqli_query($mysqli, "DELETE FROM vendor_tags WHERE vendor_id = $vendor_id"); - $tag_ids = array_values(array_unique(array_filter(array_map('intval', (array) $tag_ids)))); - if (!$tag_ids) { - return; - } - mysqli_query($mysqli, "INSERT IGNORE INTO vendor_tags (vendor_id, tag_id) - SELECT $vendor_id, tag_id FROM tags WHERE tag_type = 6 AND tag_id IN (" . implode(',', $tag_ids) . ")"); + tagSetForRecord('vendor', $vendor_id, (array) $tag_ids); } /** A template's fields as they go on a vendor - for New from template. Raw, or null. */ diff --git a/js/tag_form.js b/js/tag_form.js new file mode 100644 index 000000000..90ec98038 --- /dev/null +++ b/js/tag_form.js @@ -0,0 +1,159 @@ +// New Tag and Edit Tag (admin/modals/tag/tag_form.php). The preview shows the +// tag as it will look while its name, colour and icon change - its text dark +// or white by the colour's luminance, like tagTextColor() in +// functions/tags.php. A swatch, the colour picker or a typed hex sets the +// colour. The search narrows the icons; a whole Font Awesome icon name that +// isn't in the list can be used too. The server checks it all again. +// +// Wrapped in an IIFE because a modal can be opened, closed and opened again +// in one page load, which re-runs this file. + +(function () { + + // Dark or white text on a #rrggbb colour + function textColor(value) { + const channel = function (hex) { + const c = parseInt(hex, 16) / 255; + return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); + }; + const luminance = 0.2126 * channel(value.substr(1, 2)) + 0.7152 * channel(value.substr(3, 2)) + 0.0722 * channel(value.substr(5, 2)); + return luminance > 0.4 ? '#212529' : '#fff'; + } + + // Whether Font Awesome draws an icon by this name + function iconExists(probe, name) { + probe.className = 'fas fa-' + name; + const content = window.getComputedStyle(probe, '::before').content; + return content !== '' && content !== 'none' && content !== 'normal'; + } + + document.querySelectorAll('[data-tag-form]:not([data-wired])').forEach(function (form) { + form.setAttribute('data-wired', '1'); + + const preview = form.querySelector('[data-tag-preview]'); + const previewName = form.querySelector('[data-tag-preview-name]'); + const previewIcon = form.querySelector('[data-tag-preview-icon]'); + const name = form.querySelector('[data-tag-name]'); + const color = form.querySelector('[data-tag-color]'); + const hex = form.querySelector('[data-tag-color-hex]'); + const swatches = form.querySelectorAll('[data-tag-swatch]'); + const icon = form.querySelector('[data-tag-icon]'); + const search = form.querySelector('[data-tag-icon-search]'); + const choices = form.querySelectorAll('[data-tag-icon-choice]'); + const custom = form.querySelector('[data-tag-icon-custom]'); + const none = form.querySelector('[data-tag-icon-none]'); + const probe = document.createElement('i'); + probe.style.position = 'absolute'; + probe.style.visibility = 'hidden'; + form.appendChild(probe); + + function setColor(value, from) { + value = String(value).trim().toLowerCase(); + if (value.charAt(0) !== '#') { + value = '#' + value; + } + if (/^#[0-9a-f]{3}$/.test(value)) { + value = '#' + value[1] + value[1] + value[2] + value[2] + value[3] + value[3]; + } + if (!/^#[0-9a-f]{6}$/.test(value)) { + return; + } + if (from !== color) { + color.value = value; + } + if (from !== hex) { + hex.value = value; + } + preview.style.setProperty('--itflow-tag-color', value); + preview.style.setProperty('--itflow-tag-text', textColor(value)); + swatches.forEach(function (swatch) { + const on = swatch.dataset.tagSwatch === value; + swatch.classList.toggle('active', on); + swatch.setAttribute('aria-pressed', on ? 'true' : 'false'); + }); + } + + function setIcon(value) { + icon.value = value; + previewIcon.className = 'fas fa-fw fa-' + value; + choices.forEach(function (choice) { + const on = choice.dataset.tagIconChoice === value; + choice.classList.toggle('active', on); + choice.setAttribute('aria-pressed', on ? 'true' : 'false'); + }); + custom.classList.toggle('active', custom.dataset.icon === value); + } + + function filterIcons() { + const term = search.value.trim().toLowerCase().replace(/^(fa[srb]?\s+)?fa-/, '').replace(/\s+/g, '-'); + let shown = 0; + let exact = false; + choices.forEach(function (choice) { + const match = term === '' || choice.dataset.tagIconChoice.indexOf(term) !== -1; + choice.hidden = !match; + shown += match ? 1 : 0; + exact = exact || choice.dataset.tagIconChoice === term; + }); + const usable = term !== '' && !exact && /^[a-z0-9-]+$/.test(term) && iconExists(probe, term); + custom.hidden = !usable; + if (usable) { + custom.dataset.icon = term; + custom.querySelector('i').className = 'fas fa-fw fa-' + term + ' me-1'; + custom.querySelector('span').textContent = 'Use ' + term; + custom.classList.toggle('active', icon.value === term); + } + none.hidden = shown > 0 || usable; + return shown; + } + + name.addEventListener('input', function () { + previewName.textContent = name.value.trim() || 'New tag'; + }); + swatches.forEach(function (swatch) { + swatch.addEventListener('click', function () { + setColor(swatch.dataset.tagSwatch); + }); + }); + color.addEventListener('input', function () { + setColor(color.value, color); + }); + hex.addEventListener('input', function () { + setColor(hex.value, hex); + }); + hex.addEventListener('change', function () { + hex.value = color.value; + }); + // Enter in a colour or search box picks, rather than saving the tag + hex.addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + hex.value = color.value; + } + }); + + choices.forEach(function (choice) { + choice.addEventListener('click', function () { + setIcon(choice.dataset.tagIconChoice); + }); + }); + custom.addEventListener('click', function () { + setIcon(custom.dataset.icon); + }); + search.addEventListener('input', filterIcons); + search.addEventListener('keydown', function (e) { + if (e.key !== 'Enter') { + return; + } + e.preventDefault(); + const visible = Array.prototype.filter.call(choices, function (choice) { + return !choice.hidden; + }); + if (!custom.hidden) { + setIcon(custom.dataset.icon); + } else if (visible.length === 1) { + setIcon(visible[0].dataset.tagIconChoice); + } + }); + }); + +})(); diff --git a/js/tag_picker.js b/js/tag_picker.js index 0ab8e0b97..bc2043f04 100644 --- a/js/tag_picker.js +++ b/js/tag_picker.js @@ -287,7 +287,8 @@ data.tags.forEach(function (tag) { var name = fold(tag.name); - if (terms.length && !terms.every(function (t) { return name.indexOf(t) !== -1; })) { + var haystack = name + ' ' + fold(tag.description); + if (terms.length && !terms.every(function (t) { return haystack.indexOf(t) !== -1; })) { return; } if (name === fold(self.query.trim())) { @@ -314,8 +315,9 @@ var text = make('span', 'itflow-select-text'); text.appendChild(make('span', 'itflow-select-label', tag.name)); - if (some) { - text.appendChild(make('span', 'itflow-select-description', tag.chosen + ' of ' + data.records)); + var about = [tag.description || '', some ? tag.chosen + ' of ' + data.records : ''].filter(Boolean).join(' · '); + if (about) { + text.appendChild(make('span', 'itflow-select-description', about)); } node.appendChild(text); list.appendChild(node);