Starter Content: Clear out unused beside a pack's counts archives what came from the pack and nothing uses yet, listed in a window with ticks, in-use items kept, rechecked on save, with Undo and a total in At a glance

This commit is contained in:
johnnyq
2026-11-20 15:16:44 -05:00
parent e85f780182
commit 9203880dfd
7 changed files with 373 additions and 10 deletions

View File

@@ -211,20 +211,26 @@ function starterMinutesText($minutes) {
* A pack's Pick which - its items not here yet, each ticked, shown as they
* will look with what they are for, and Preview where there is more to see.
* $form is the id of the form the ticks go with, when they sit outside it (a
* table row's Add). $items from starterContentItems().
* pack's Add). $items from starterContentItems(), or starterContentUnused()'s
* for Clear out unused, which shows the list open ($open) and without Preview,
* as Preview shows the library's version rather than the one here.
*/
function starterPickHtml($pack, array $items, $form = '') {
function starterPickHtml($pack, array $items, $form = '', $open = false) {
if (!$items) {
return '';
}
$form_attr = $form !== '' ? ' form="' . escapeHtml($form) . '"' : '';
$previews = in_array($pack, starterPreviewPacks(), true);
$previews = !$open && in_array($pack, starterPreviewPacks(), true);
$kind = $pack === 'tags' ? ' is-pills' : '';
ob_start(); ?>
<?php if ($open) { ?>
<div class="itflow-starter-pick" data-starter-pick-list>
<?php } else { ?>
<details class="itflow-starter-pick mt-1" data-starter-pick-list>
<summary class="small">Pick which</summary>
<?php } ?>
<input type="hidden" name="picked[<?= escapeHtml($pack) ?>]" value="1"<?= $form_attr ?>>
<div class="itflow-starter-pick-tools small mt-2">
<div class="itflow-starter-pick-tools small<?= $open ? '' : ' mt-2' ?>">
<button type="button" class="btn btn-link btn-sm p-0 align-baseline" data-starter-all>All</button>
<span class="text-body-secondary" aria-hidden="true">·</span>
<button type="button" class="btn btn-link btn-sm p-0 align-baseline" data-starter-none>None</button>
@@ -255,7 +261,7 @@ function starterPickHtml($pack, array $items, $form = '') {
<?php } ?>
</div>
</div>
</details>
<?= $open ? '</div>' : '</details>' ?>
<?php return ob_get_clean();
}

View File

@@ -0,0 +1,62 @@
<?php
/*
* Clear out unused - from a pack's row on Maintenance > Starter Content (?pack=).
* Its items that are here and nothing uses (starterContentUnused()), every one
* ticked; Archive them (clear_starter_unused, admin/post/starter_content.php)
* archives the ones ticked. js/starter_content.js keeps the count in step.
*/
require_once '../../includes/modal_header.php';
defined('FROM_STARTER_CONTENT') || define('FROM_STARTER_CONTENT', true);
require_once __DIR__ . '/../../post/starter_content_model.php';
require_once __DIR__ . '/../../includes/starter_content_pick.php';
$pack = (string) ($_GET['pack'] ?? '');
$packs = starterContentPacks();
if (!isset($packs[$pack]) || !starterPackRecords($pack)) {
exit('<div class="modal-body">There is no pack by that name.</div>');
}
$pack_details = $packs[$pack];
$unused = starterContentUnused($mysqli, $pack);
$items = $unused['items'];
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-broom me-2"></i>Clear Out Unused <?= escapeHtml($pack_details['label']) ?></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off" data-starter-pick>
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<div class="modal-body">
<?php if ($items) { ?>
<p class="mb-2">
<span class="fw-semibold">These came from the pack, and nothing uses them yet.</span>
<span class="text-body-secondary">They're archived, not deleted - Undo puts them back straight after, and any can be restored later from its own list's Archived view.</span>
</p>
<?php if ($unused['in_use']) { ?>
<p class="small text-body-secondary mb-2"><i class="fas fa-fw fa-check text-success me-1"></i><?= intval($unused['in_use']) ?> more from the pack <?= $unused['in_use'] === 1 ? 'is' : 'are' ?> in use, so <?= $unused['in_use'] === 1 ? 'it stays' : 'they stay' ?>.</p>
<?php } ?>
<p class="small fw-semibold mb-2" data-starter-count data-starter-format="clear"><?= count($items) ?> to archive</p>
<?= starterPickHtml($pack, $items, '', true) ?>
<?php } else { ?>
<p class="mb-0 text-body-secondary">Everything from the pack that's here is in use - there's nothing to clear out.</p>
<?php } ?>
</div>
<div class="modal-footer">
<?php if ($items) { ?>
<button type="submit" name="clear_starter_unused" value="<?= escapeHtml($pack) ?>" class="btn btn-danger text-bold" data-starter-add>
<i class="fas fa-fw fa-archive me-2"></i>Archive them
</button>
<?php } ?>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -57,6 +57,49 @@ if (isset($_POST['load_starter_content'])) {
}
/*
* Clear out unused - a pack's items that are here and nothing uses, archived
* (admin/modals/starter_content/starter_clear.php ticks which). Checked again
* here, so one put to use since the window opened stays. Undo puts them back.
*/
if (isset($_POST['clear_starter_unused'])) {
validateCSRFToken();
require_once 'starter_content_model.php';
$starter_content_packs = starterContentPacks();
$pack = (string) $_POST['clear_starter_unused'];
if (!isset($starter_content_packs[$pack]) || !starterPackRecords($pack)) {
flashAlert("Unknown starter content pack", 'error');
redirect();
}
$only = null;
if (isset($_POST['picked'][$pack])) {
$only = array_map('strval', array_filter((array) ($_POST['items'][$pack] ?? []), 'is_string'));
if (!$only) {
flashAlert("Nothing is ticked - tick what to archive", 'info');
redirect();
}
}
$label = $starter_content_packs[$pack]['label'];
[$archived, $before] = starterClearUnused($mysqli, $pack, $only);
$count = count($archived);
if ($count) {
logAudit("Starter Content", "Archive", "$session_name archived $count unused from the starter $label pack");
flashAlert("Archived <strong>$count</strong> unused from " . escapeHtml($label));
undoOfferChanges($before, "<strong>{n}</strong> from " . escapeHtml($label) . " put back", 'module_client');
} else {
flashAlert("Nothing to archive - those are in use now, or already archived", 'info');
}
redirect();
}
if (isset($_POST['update_starter_ticket_templates'])) {
// The starter ticket templates already here, brought up to this version

View File

@@ -358,6 +358,229 @@ function starterContentItems($mysqli, $pack) {
return $items;
}
// ------------------------------
// starterPackRecords
// Where a pack's items land - the table, its id, name and archived columns,
// what narrows it to the pack's kind of record, and what a library row is
// matched on: kind and name, as Add finds them, and a product's code too, as
// an install may well have a line of its own by that name.
// ------------------------------
function starterPackRecords($pack) {
$packs = [
'categories' => ['table' => 'categories', 'id' => 'category_id', 'name' => 'category_name', 'archived' => 'category_archived_at', 'kind' => 'category_type'],
'tags' => ['table' => 'tags', 'id' => 'tag_id', 'name' => 'tag_name', 'archived' => 'tag_archived_at', 'kind' => 'tag_type'],
'ticket_templates' => ['table' => 'ticket_templates', 'id' => 'ticket_template_id', 'name' => 'ticket_template_name', 'archived' => 'ticket_template_archived_at'],
'project_templates' => ['table' => 'project_templates', 'id' => 'project_template_id', 'name' => 'project_template_name', 'archived' => 'project_template_archived_at'],
'canned_responses' => ['table' => 'canned_responses', 'id' => 'canned_response_id', 'name' => 'canned_response_name', 'archived' => 'canned_response_archived_at', 'where' => 'canned_response_user_id = 0'],
'vendor_templates' => ['table' => 'vendor_templates', 'id' => 'vendor_template_id', 'name' => 'vendor_template_name', 'archived' => 'vendor_template_archived_at'],
'document_templates' => ['table' => 'document_templates', 'id' => 'document_template_id', 'name' => 'document_template_name', 'archived' => 'document_template_archived_at'],
'products' => ['table' => 'products', 'id' => 'product_id', 'name' => 'product_name', 'archived' => 'product_archived_at', 'kind' => 'product_code'],
'license_templates' => ['table' => 'software_templates', 'id' => 'software_template_id', 'name' => 'software_template_name', 'archived' => 'software_template_archived_at'],
];
return $packs[$pack] ?? null;
}
/* A library row as starterPackHere() keys what is here - kind (a product's code)|name, lower cased. */
function starterPackMatchKey($pack, $row) {
switch ($pack) {
case 'categories':
return mb_strtolower($row['type'] . '|' . $row['name']);
case 'tags':
return mb_strtolower($row[0] . '|' . $row[1]);
case 'products':
return mb_strtolower($row[2] . '|' . $row[0]);
}
return mb_strtolower(starterItemName($pack, $row));
}
// ------------------------------
// starterPackHere
// The records here, not archived, that a pack's rows match - key as
// starterPackMatchKey() => record id. One kept under the name it had
// (starterRenamed()) is the same item.
// ------------------------------
function starterPackHere($mysqli, $pack) {
$r = starterPackRecords($pack);
if (!$r) {
return [];
}
$kind = $r['kind'] ?? '';
$sql = mysqli_query($mysqli, "SELECT {$r['id']}, {$r['name']}" . ($kind ? ", $kind" : '') . " FROM {$r['table']}
WHERE {$r['archived']} IS NULL" . (isset($r['where']) ? " AND {$r['where']}" : '') . " ORDER BY {$r['id']}");
$here = [];
while ($row = mysqli_fetch_assoc($sql)) {
$key = mb_strtolower(($kind ? $row[$kind] . '|' : '') . $row[$r['name']]);
$here[$key] = $here[$key] ?? intval($row[$r['id']]);
}
foreach (starterRenamed($pack) as $old => $new) {
$type = strpos($old, '|') !== false ? substr($old, 0, strpos($old, '|') + 1) : '';
$new_key = mb_strtolower($type . $new);
if (!isset($here[$new_key]) && isset($here[$old])) {
$here[$new_key] = $here[$old];
}
}
return $here;
}
// ------------------------------
// starterPackUsed
// Of these record ids, the ones something uses - id => true. Used is
// anything that points at it: a category on a ticket, invoice, expense,
// product, budget or template, or with categories under it; a tag on any
// record, template or seat count; a ticket template a ticket, recurring
// ticket or project template was made from or uses, or with its request form
// on; a project template a project was raised from (its tickets' history says
// so); a canned response ever put in a reply; a vendor, document or license
// template something was made from; a product on a line, an asset, an order
// or a license template, or with stock or prices of its own.
// ------------------------------
function starterPackUsed($mysqli, $pack, array $ids) {
$ids = array_values(array_unique(array_filter(array_map('intval', $ids))));
if (!$ids) {
return [];
}
$in = implode(',', $ids);
$used = [];
$queries = [];
switch ($pack) {
case 'categories':
// What Admin > Categories counts for each kind, and what it doesn't
foreach (['Expense', 'Income', 'Referral', 'Ticket'] as $kind) {
foreach (array_keys(categoryUsage($kind)) as $category_id) {
$used[intval($category_id)] = true;
}
}
$queries = [
"SELECT ticket_template_category_id FROM ticket_templates WHERE ticket_template_category_id IN ($in)",
"SELECT config_quick_ticket_category FROM settings WHERE config_quick_ticket_category IN ($in)",
"SELECT rmm_provider_alert_category_id FROM rmm_providers WHERE rmm_provider_alert_category_id IN ($in)",
"SELECT ai_triage_category_id FROM ai_ticket_triage WHERE ai_triage_category_id IN ($in)",
"SELECT category_parent FROM categories WHERE category_parent IN ($in) AND category_archived_at IS NULL",
];
break;
case 'tags':
// Every table that links a tag to something
$sql = mysqli_query($mysqli, "SELECT TABLE_NAME, COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME <> 'tags' AND (COLUMN_NAME = 'tag_id' OR COLUMN_NAME LIKE '%\\_tag\\_id')");
while ($row = mysqli_fetch_row($sql)) {
$queries[] = "SELECT `{$row[1]}` FROM `{$row[0]}` WHERE `{$row[1]}` IN ($in)";
}
foreach (array_keys(tagSeatLineCounts()) as $tag_id) {
$used[intval($tag_id)] = true;
}
break;
case 'ticket_templates':
$queries = [
"SELECT ticket_template_id FROM tickets WHERE ticket_template_id IN ($in)",
"SELECT recurring_ticket_ticket_template_id FROM recurring_tickets WHERE recurring_ticket_ticket_template_id IN ($in)",
"SELECT ticket_template_id FROM project_template_ticket_templates WHERE ticket_template_id IN ($in)",
"SELECT ticket_template_id FROM ticket_templates WHERE ticket_template_portal = 1 AND ticket_template_id IN ($in)",
];
break;
case 'project_templates':
// A project doesn't keep its template - the tickets it raised say which in their history
$names = [];
$sql = mysqli_query($mysqli, "SELECT project_template_id, project_template_name FROM project_templates WHERE project_template_id IN ($in)");
while ($row = mysqli_fetch_row($sql)) {
$names[intval($row[0])] = $row[1];
}
foreach ($names as $project_template_id => $name) {
$like = escapeSql(addcslashes("raised the ticket from project template $name", '%_'));
if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_history WHERE ticket_history_description LIKE '%$like' LIMIT 1"))) {
$used[$project_template_id] = true;
}
}
break;
case 'canned_responses':
$queries = ["SELECT canned_response_use_canned_response_id FROM canned_response_uses WHERE canned_response_use_canned_response_id IN ($in)"];
break;
case 'vendor_templates':
$queries = [
"SELECT vendor_template_id FROM vendors WHERE vendor_template_id IN ($in)",
"SELECT software_template_vendor_template_id FROM software_templates WHERE software_template_vendor_template_id IN ($in) AND software_template_archived_at IS NULL",
];
break;
case 'document_templates':
$queries = ["SELECT document_template_id FROM documents WHERE document_template_id IN ($in)"];
break;
case 'products':
$queries = [
"SELECT item_product_id FROM invoice_items WHERE item_product_id IN ($in)",
"SELECT item_product_id FROM quote_items WHERE item_product_id IN ($in)",
"SELECT item_product_id FROM recurring_invoice_items WHERE item_product_id IN ($in)",
"SELECT asset_product_id FROM assets WHERE asset_product_id IN ($in)",
"SELECT order_item_product_id FROM order_items WHERE order_item_product_id IN ($in)",
"SELECT po_item_product_id FROM po_items WHERE po_item_product_id IN ($in)",
"SELECT stock_product_id FROM product_stock WHERE stock_product_id IN ($in)",
"SELECT price_product_id FROM product_prices WHERE price_product_id IN ($in)",
"SELECT software_template_product_id FROM software_templates WHERE software_template_product_id IN ($in) AND software_template_archived_at IS NULL",
];
break;
case 'license_templates':
$queries = ["SELECT software_template_id FROM software WHERE software_template_id IN ($in)"];
break;
}
foreach ($queries as $query) {
$sql = mysqli_query($mysqli, str_replace('SELECT ', 'SELECT DISTINCT ', $query));
while ($sql && ($row = mysqli_fetch_row($sql))) {
$used[intval($row[0])] = true;
}
}
return array_intersect_key($used, array_flip($ids));
}
// ------------------------------
// starterContentUnused
// A pack's items that are here and nothing uses - for Clear out unused, in
// starterContentItems()' shape with the record's 'id' - and how many of the
// pack that are here are in use: ['items' => [...], 'in_use' => n].
// ------------------------------
function starterContentUnused($mysqli, $pack) {
$here = starterPackHere($mysqli, $pack);
$found = [];
foreach (starterContentRows($pack) as $row) {
$id = $here[starterPackMatchKey($pack, $row)] ?? 0;
if ($id && !isset($found[$id])) {
$found[$id] = $row;
}
}
$used = starterPackUsed($mysqli, $pack, array_keys($found));
$items = [];
foreach ($found as $id => $row) {
if (!isset($used[$id])) {
$items[] = ['key' => starterItemKey($pack, $row), 'name' => starterItemName($pack, $row), 'group' => starterItemGroup($pack, $row), 'row' => $row, 'id' => $id];
}
}
return ['items' => $items, 'in_use' => count($found) - count($items)];
}
// ------------------------------
// starterClearUnused
// Archives a pack's unused items - those of $only (starterItemKey()s) when
// given - checked again as it goes. Archived, not deleted: each comes back
// from its own list's Archived view. Add still counts an archived one as
// here, as it does any other, so it isn't made again beside it.
// Returns [record ids archived, undoSnapshot() of them before].
// ------------------------------
function starterClearUnused($mysqli, $pack, $only = null) {
$r = starterPackRecords($pack);
if (!$r) {
return [[], null];
}
$ids = [];
foreach (starterContentUnused($mysqli, $pack)['items'] as $item) {
if ($only === null || in_array($item['key'], $only, true)) {
$ids[] = intval($item['id']);
}
}
if (!$ids) {
return [[], null];
}
$before = undoSnapshot($r['table'], $r['id'], $ids, [$r['archived']]);
mysqli_query($mysqli, "UPDATE {$r['table']} SET {$r['archived']} = NOW() WHERE {$r['archived']} IS NULL AND {$r['id']} IN (" . implode(',', $ids) . ")");
return [$ids, $before];
}
// ------------------------------
// starterContentStatus
// Per pack totals for the page - how many the library holds, how many are

View File

@@ -6,6 +6,7 @@
* it is and the one thing to do at the top, the packs and the demo data under it, and at a glance
* and how it works to the side. Pick which and Preview are includes/starter_content_pick.php, shared
* with Get started's Starter content step; js/starter_content.js keeps the ticks and counts in step.
* Clear out unused, beside a pack's counts, opens modals/starter_content/starter_clear.php.
*/
require_once "includes/inc_all_admin.php";
@@ -17,17 +18,20 @@ require_once "includes/starter_content_pick.php";
$starter_content_packs = starterContentPacks();
// Each pack's items not here yet - for Pick which, and how many Add brings
// Each pack's items not here yet - for Pick which, and how many Add brings - and how many of
// the ones here nothing uses, for Clear out unused
$starter_content_items = [];
$starter_content_status = [];
$total_in_library = $total_missing = 0;
$total_in_library = $total_missing = $total_unused = 0;
foreach ($starter_content_packs as $pack => $pack_details) {
$starter_content_items[$pack] = starterContentItems($mysqli, $pack);
$total = starterContentTotal($pack);
$missing = count($starter_content_items[$pack]);
$starter_content_status[$pack] = ['total' => $total, 'missing' => $missing, 'present' => $total - $missing];
$unused = $total - $missing ? count(starterContentUnused($mysqli, $pack)['items']) : 0;
$starter_content_status[$pack] = ['total' => $total, 'missing' => $missing, 'present' => $total - $missing, 'unused' => $unused];
$total_in_library += $total;
$total_missing += $missing;
$total_unused += $unused;
}
$total_present = $total_in_library - $total_missing;
@@ -104,6 +108,14 @@ if (!$total_missing) {
<span data-starter-count data-starter-more="<?= $pack_status['present'] ? 1 : 0 ?>"><?= intval($pack_status['missing']) ?> <?= $pack_status['present'] ? 'more ' : '' ?>to add</span><?php if ($pack_status['present']) { ?> · <?= intval($pack_status['present']) ?> of <?= intval($pack_status['total']) ?> here<?php } ?>
</span>
<?php } ?>
<?php if ($pack_status['unused']) { ?>
<!-- The ones here that nothing uses, archived from a window that lists them -->
<span class="small text-body-secondary">·
<button type="button" class="btn btn-link btn-sm p-0 align-baseline text-decoration-none ajax-modal" data-modal-url="/admin/modals/starter_content/starter_clear.php?pack=<?= urlencode($pack) ?>" data-modal-size="lg" data-starter-clear>
<i class="fas fa-broom me-1"></i>Clear out <?= intval($pack_status['unused']) ?> unused
</button>
</span>
<?php } ?>
</div>
<div class="small text-body-secondary itflow-gs-pack-about" title="<?= escapeHtml($pack_details['description']) ?>"><?= escapeHtml($pack_details['description']) ?></div>
<?php if ($needs_first) { ?>
@@ -228,6 +240,10 @@ if (!$total_missing) {
<span class="text-body-secondary">To add</span>
<span class="text-end fw-semibold"><?= $total_missing ? $total_missing : '<span class="text-success-emphasis"><i class="fas fa-check me-1"></i>None</span>' ?></span>
</li>
<li class="list-group-item d-flex justify-content-between gap-3">
<span class="text-body-secondary">Here but unused</span>
<span class="text-end fw-semibold"><?= $total_unused ?></span>
</li>
<li class="list-group-item d-flex justify-content-between gap-3">
<span class="text-body-secondary">Demo data</span>
<span class="text-end fw-semibold"><?= $demo_data_loaded ? "$demo_data_loaded of $demo_data_total clients" : 'Not added' ?></span>
@@ -244,6 +260,7 @@ if (!$total_missing) {
<li>Adding never changes or removes anything. A name you already have is skipped, so a pack can be added again to bring back something deleted - never a duplicate.</li>
<li><strong>Pick which</strong>, under a pack, lists what it would add as it will look, with a preview of each template. Untick what you don't want.</li>
<li><strong>Update</strong> brings templates and canned responses added from an earlier version up to this one - it replaces what they hold.</li>
<li><strong>Clear out unused</strong> archives what came from a pack and nothing uses yet - anything in use stays, and Undo puts them back.</li>
<li>Request forms come with the ticket templates, turned off. Canned responses come in shared. Products are priced as starting points - hardware and resold licensing at zero.</li>
</ul>
</div>