Warranty lookup by serial number: Admin > Warranty Lookup sets up Dell with a TechDirect key, HP with a Warranty API key and Lenovo through its support site with no key, each with Save and test; the search button beside Warranty expires on the asset form fills the empty warranty and purchase dates and offers the maker's date beside one already set, and Bulk Action > Look Up Warranty on Assets fills many at once with each answer listed and noted in the asset's history; database 4.4.4; 26.12.6 changelog

This commit is contained in:
johnnyq
2026-12-04 21:53:24 -05:00
parent 66e418449c
commit 36503ca768
15 changed files with 1212 additions and 2 deletions

View File

@@ -6,11 +6,12 @@ This file documents all notable changes made to ITFlow.
### Upgrading to 26.12.6
Update from Maintenance > Update as usual. There is no database change.
Update from Maintenance > Update as usual. This release has one database change: 4.4.4 adds the settings for Warranty Lookup.
- If you have switched a module off in Admin > Settings > Modules - IT documentation, ticketing, invoicing and accounting or any of the others - check that you meant it before updating. Its pages, bookmarks to them and links in old emails stop opening, and the nightly run stops doing its work: with ticketing off, no recurring tickets are raised and resolved tickets aren't closed; with invoicing and accounting off, no recurring invoices or expenses are made, no autopay is charged and no payment reminders go out; with IT documentation off, no domain, certificate, warranty or service review notifications, and shared links - logins, files, documents and IT documentation exports sent to clients - don't open. Switch it back on and the next run picks up what is due, and shared links that haven't run out open again.
- API keys get a 403 saying which module is off for anything of a module that is switched off - tickets with ticketing off, assets and credentials with IT documentation off, invoices with invoicing off.
- Contacts imported before with a ? in place of an accented letter keep it. Import the same file again with **A contact already here** set to **Update it** and their names are put right - contacts are matched by email. Anything else imported that way, such as a location or vendor, is matched by its name, so correct those by hand.
- The warranty lookup button shows beside **Warranty expires** on the asset form straight after the update, as Lenovo needs no key and is switched on. It only asks Lenovo when someone clicks it. Switch Lenovo off in Admin > Warranty Lookup if you'd rather ITFlow didn't ask Lenovo's support site at all.
### New Features & Updates
@@ -19,6 +20,8 @@ Update from Maintenance > Update as usual. There is no database change.
- The client portal leaves out what is switched off too. With ticketing off, a contact sees no Tickets, New Ticket, open tickets, approvals or request forms, and portal search doesn't look through tickets; with IT documentation off, their home lists no devices. A link someone was sent - to a ticket, invoice, quote or contract, or a shared login or file - for a module that is now off says it isn't available, without mentioning settings.
- Maintenance > Cron shows the jobs of a module that is off as **Not in use**, saying which module: the Ticket Email Parser, Ticket SLA Monitor, Ticket Pictures and AI Triage with ticketing off, the Domain and Certificate Refreshers with IT documentation off, and Payment Provider Fees with invoicing off.
- Audit logs and notifications still name a ticket, invoice or asset of a module that is off, without linking it. The quick looks - a contact, location, vendor or ticket at a glance - leave out what is off too, and a quote's files from the client can still be downloaded with IT documentation off.
- Look up an asset's warranty by its serial number. On an asset's Purchase tab, the search button beside **Warranty expires** asks its maker - Dell, HP or Lenovo - and fills in when its warranty runs out and, as **Purchased**, when it began: for a Dell, the day it shipped. To do many at once, tick them on Assets and choose **Bulk Action > Look Up Warranty** - each one's answer is listed as it comes in. Only empty dates are filled in: a date already on an asset is never changed, and on the form the maker's is offered beside it to use instead. Each date filled in is noted in the asset's History. An asset is matched by its make, or with no make by its model - Latitude, OptiPlex, ThinkPad, EliteBook and the like. HP Enterprise servers aren't looked up.
- Admin > Warranty Lookup, under Integrations, sets up each maker. Dell needs a TechDirect Warranty API key and HP an HP Warranty API key, which each approve by hand - HP doesn't give its to every IT company. Lenovo needs none: ITFlow asks Lenovo's support site as its own pages do, which can stop working when Lenovo changes the site. **Save and test** beside each one tries a serial number with what you've entered. HP works through each lookup as a job, so its answers can take a few minutes. It's part of IT documentation, and goes with it when that module is off.
### Bug Fixes
@@ -37,6 +40,8 @@ Update from Maintenance > Update as usual. There is no database change.
- UniFi: `rmmUnifiGatewayModel($model)` (`functions/rmm_unifi.php`) knows a gateway by its model code or name - UDM, UDR, UDW, UCG, UXG, EFG, USG, UGW, or a name starting Dream, Cloud Gateway or Gateway - but not the Express (UX, UX7), which is a site's gateway or an access point in someone else's network. The official Network API's `features` say `gateway` for some gateways only - a UCG Fiber comes as `switching`, an EFG with none - so `rmmUnifiNetworkDeviceType($features, $model)` takes `gateway` or the model, then `accessPoint` before `switching`, as an in-wall access point has both. `rmmUnifiControllerDevice()` takes a gateway by its `type` (`ugw`, `udm`, `uxg`), its model, or a `wan1` with an `ifname` or `ip`. Assets already brought in follow `rmmAssetFollow()`'s usual rule: a type the sync wrote is updated, one changed in ITFlow is left.
- Microsoft 365 mail: `mailMicrosoftConnectScope($way)` (`functions/mail_graph.php`) - `graph` asks for `openid profile offline_access https://graph.microsoft.com/.default`, `exchange` for the IMAP and SMTP scopes as before. The OAuth tab's `oauth_connect_way` picker sets it - `mailMicrosoftConnectWay()`: Graph before a first connect, then Graph when `mailGraphState()` has a mail permission - and `$_SESSION['mail_oauth_way']` carries it to `admin/oauth_microsoft_mail_callback.php`, which redeems the code for the same. `prompt=consent` is now `prompt=select_account`. The callback keeps the access token as `config_mail_oauth_access_token` only for an Exchange sign-in, as a Graph one isn't XOAUTH2's, goes through `mailGraphHttp()` and `MAIL_MICROSOFT_LOGIN_URL`, and ends with `mailMicrosoftCheck($send_ms, $read_ms, $fresh_exchange)`, which Test OAuth Token Refresh now uses for Microsoft too: Graph's Mail.Send and Mail.ReadWrite first, then `mailMicrosoftExchangeToken()` only for a side Graph doesn't cover. `js/settings.js` leaves a `[data-settings-untracked]` field out of a settings form's unsaved changes.
- Saved cards: `billingStripeCardSave($stripe, $client_id, $customer, $pm)` (`functions/billing_pay.php`) is how every client-added card is saved - `autopayCheckoutFinish()`, `cardUpdateFinish()` and the client portal's `stripe_save_card` in `client/post.php`, which matched only Stripe's payment method ID, a new one each time a card is entered. It matches `card.fingerprint` among the cards on the client's Stripe customer (`billingStripeCardTwins()`, one `allPaymentMethods` call), points the oldest saved row at the new payment method and its description, clearing `saved_payment_update_key` when the expiry changed as `cardRefresh()` does, detaches the one it replaced (`billingStripeCardDetach()`) and merges any other copies in (`billingStripeCardMerge()`: `recurring_payments` moved, payment method detached, row deleted), under a per-client `GET_LOCK`. Stripe not answering falls back to saving a new row, as before. `billingStripeCardTwinsNightly()` in `cron/nightly_tasks.php`, before `cardExpiryNightly()`, merges cards already saved twice - only for clients with two saved cards of the same brand and last four digits, keeping the one that runs out last.
- Warranty lookup: `functions/warranty.php`. `warrantyMaker($make, $model)` gives `dell`, `hp`, `lenovo` or `''` (HPE and Hewlett Packard Enterprise `''`); `warrantySettings()` opens the keys, sealed with `secretSeal(..., 'warranty')`, and `warrantyAnyReady()` says whether any maker is set up. `warrantyLookup($items)` takes `key => ['maker', 'serial']` and answers each with `warrantyFound()` or `warrantyNotFound($why, $kind)` - `kind` `found`, `missing`, `skip`, `error` or `pending`, `end` the latest coverage end, `start` Dell's `shipDate` or the earliest start, `coverage` the name of the one ending last. Dell: an OAuth client-credentials token from `auth/oauth/v2/token` (form fields, then Basic), then `PROD/sbil/eapi/v5/asset-entitlements`, 100 tags a call. Lenovo: `us/en/api/v4/mse/getproducts?productId=` for its product ID, then `ds_warranties` from its `products/{id}/warranty` page - active contracts and every base warranty. HP: one `productwarranty/v2/jobs` job a batch (`warrantyHpStart()`), answered `pending` with the job ID, which `warrantyHpCheck()` polls. `warrantyApply()` writes only an empty `asset_warranty_expire` or `asset_purchase_date`, with an `asset_history` row and `logAudit()`. The hosts are `WARRANTY_DELL_URL`, `WARRANTY_HP_URL` and `WARRANTY_LENOVO_URL`, which config.php can define first.
- `agent/ajax.php` answers `warranty_lookup` - an asset form's `make`, `model` and `serial` (`{answer}`), or up to 25 `asset_ids` (`{results}`, written) - and `warranty_hp_check`, an HP job ID asked after with the same `asset_ids` or `serial` (`{done: false}` until HP has finished) - with IT documentation on (`moduleOffText('itdoc')` otherwise), Support at Modify, and `hasClientAccess()` for each asset. `js/warranty_lookup.js` drives the form's `[data-warranty-lookup]` button and `agent/modals/asset/asset_bulk_warranty.php` (up to 500 assets, 5 a request, HP polled every 10 seconds for up to 15 minutes). `admin/settings_warranty.php` and `admin/post/settings_warranty.php` are the `warranty` page in `settingsPages()`, its own group in `adminNavGroups()`, mapped to `itdoc` in `modulePaths()`. Database 4.4.4 adds `config_warranty_dell_client_id`, `config_warranty_dell_client_secret`, `config_warranty_hp_client_id`, `config_warranty_hp_client_secret` and `config_warranty_lenovo` (default 1) to `settings`.
## [26.12.5]

View File

@@ -0,0 +1,33 @@
<?php
/*
* ITFlow - Database update to version 4.4.4 (from 4.4.3)
* Included by admin/database_updates.php - do not access directly
*
* Warranty lookup (functions/warranty.php) - an asset's warranty end and purchase date filled from
* its serial number, by its manufacturer (Admin > Warranty Lookup):
* settings.config_warranty_dell_client_id / _secret - a Dell TechDirect Warranty API key; the
* secret sealed (secretSeal(), 'warranty')
* settings.config_warranty_hp_client_id / _secret - an HP Warranty API key, the same
* settings.config_warranty_lenovo - Lenovo serials looked up on Lenovo's support site, which needs
* no key; on by default
*
* Re-runnable: each column is added only where it isn't there.
*/
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
$itflow_warranty_columns = [
['config_warranty_dell_client_id', "varchar(200) DEFAULT NULL"],
['config_warranty_dell_client_secret', "text DEFAULT NULL"],
['config_warranty_hp_client_id', "varchar(200) DEFAULT NULL"],
['config_warranty_hp_client_secret', "text DEFAULT NULL"],
['config_warranty_lenovo', "tinyint(1) NOT NULL DEFAULT 1"],
];
foreach ($itflow_warranty_columns as [$itflow_column, $itflow_definition]) {
$itflow_column_exists = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = '$itflow_column' LIMIT 1");
if (!$itflow_column_exists || mysqli_num_rows($itflow_column_exists) === 0) {
mysqli_query($mysqli, "ALTER TABLE `settings` ADD `$itflow_column` $itflow_definition");
}
}

View File

@@ -173,6 +173,8 @@
<p>Phone Systems</p>
</a>
</li>
<?php // Asset warranties from Dell, HP and Lenovo (functions/warranty.php) - with IT documentation ?>
<?= adminNavGroupItemHtml('warranty') ?>
<li class="nav-item">
<a href="/admin/identity_providers.php" class="nav-link <?= (basename($_SERVER['PHP_SELF']) == 'identity_providers.php' ? 'active' : '') ?>">
<i class="nav-icon fas fa-id-badge"></i>

View File

@@ -0,0 +1,87 @@
<?php
/*
* Admin > Warranty Lookup (admin/settings_warranty.php). edit_warranty_settings saves the keys: a
* secret typed in is sealed (secretSeal(), 'warranty'), one left empty is kept, and an empty client
* ID forgets its secret. test_warranty_lookup saves the same way, then looks the serial number typed
* beside it up with that manufacturer (functions/warranty.php) and says what came back - HP is
* waited on for up to half a minute.
*/
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
if (isset($_POST['edit_warranty_settings']) || isset($_POST['test_warranty_lookup'])) {
validateCSRFToken();
$before = settingsCurrent(['config_warranty_dell_client_id', 'config_warranty_dell_client_secret', 'config_warranty_hp_client_id',
'config_warranty_hp_client_secret', 'config_warranty_lenovo']);
$after = [];
$errors = [];
foreach (['dell', 'hp'] as $maker) {
$id = trim((string) ($_POST["config_warranty_{$maker}_client_id"] ?? ''));
$secret = trim((string) ($_POST["config_warranty_{$maker}_client_secret"] ?? ''));
if (mb_strlen($id) > 200) {
$errors["config_warranty_{$maker}_client_id"] = 'Up to 200 characters.';
}
if (mb_strlen($secret) > 500) {
$errors["config_warranty_{$maker}_client_secret"] = 'Up to 500 characters.';
}
if ($id !== '' && $secret === '' && trim((string) $before["config_warranty_{$maker}_client_secret"]) === '') {
$errors["config_warranty_{$maker}_client_secret"] = 'Its secret is needed too.';
}
// Sealed with this install's key - or as typed on an install without one, which reads either
$sealed = $secret !== '' ? (secretSeal($secret, 'warranty') ?: $secret) : (string) $before["config_warranty_{$maker}_client_secret"];
$after["config_warranty_{$maker}_client_id"] = $id;
$after["config_warranty_{$maker}_client_secret"] = $id === '' ? '' : $sealed;
}
$after['config_warranty_lenovo'] = !empty($_POST['config_warranty_lenovo']) ? 1 : 0;
if ($errors) {
settingsRefuse('warranty', $errors);
}
$changed = settingsSave('warranty', $before, $after);
if (isset($_POST['test_warranty_lookup'])) {
$maker = (string) $_POST['test_warranty_lookup'];
$makers = warrantyMakers();
$serial = strtoupper(trim((string) ($_POST["warranty_test_$maker"] ?? '')));
$saved = $changed ? 'Saved. ' : '';
if (!isset($makers[$maker])) {
redirect();
}
if (!warrantySettings()['ready'][$maker]) {
flashAlert($saved . escapeHtml($maker === 'lenovo' ? 'Lenovo lookups are off - switch them on to test.' : "{$makers[$maker]} isn't set up - put in its key and secret first."), 'error');
redirect();
}
if ($serial === '') {
flashAlert($saved . 'Type a serial number beside <strong>Save and test</strong> to look one up.', 'warning');
redirect();
}
if ($maker === 'hp') {
// HP works through a job - waited on for up to half a minute
$job = warrantyHpStart([$serial]);
$result = warrantyNotFound($job['error'], 'error');
if ($job['job'] !== '') {
$result = warrantyNotFound("HP took the lookup and is still working through it - try again in a minute.", 'skip');
for ($waited = 0; $waited < 30; $waited += 3) {
sleep(3);
$check = warrantyHpCheck($job['job'], [$serial]);
if ($check['done']) {
$result = $check['error'] !== '' ? warrantyNotFound($check['error'], 'error') : ($check['results'][$serial] ?? warrantyNotFound("doesn't know serial number $serial"));
break;
}
}
}
} else {
$result = warrantyLookup(['test' => ['maker' => $maker, 'serial' => $serial]])['test'];
}
$tone = $result['found'] ? 'success' : ($result['kind'] === 'error' ? 'error' : 'warning');
flashAlert($saved . escapeHtml(warrantySays($maker, $result)) . ($result['found'] && $result['product'] !== '' ? ' - ' . escapeHtml($result['product']) : ''), $tone);
}
redirect();
}

101
admin/settings_warranty.php Normal file
View File

@@ -0,0 +1,101 @@
<?php
/*
* Admin > Warranty Lookup - the manufacturers an asset's warranty can be looked up with
* (functions/warranty.php): Dell's and HP's keys, and whether Lenovo's support site is asked.
* Each has Save and test, with a serial number to try. Saved by edit_warranty_settings, tested by
* test_warranty_lookup (admin/post/settings_warranty.php).
*/
require_once "includes/inc_all_admin.php";
$warranty_ready = true;
try {
mysqli_query($mysqli, "SELECT config_warranty_lenovo FROM settings LIMIT 1");
} catch (\Throwable $e) {
$warranty_ready = false;
}
if (!$warranty_ready) { ?>
<div class="alert alert-warning"><i class="fas fa-fw fa-exclamation-triangle me-2"></i>Warranty lookup arrives with a database update - run it in <a href="update.php">Maintenance &gt; Update</a> first.</div>
<?php
require_once "../includes/footer.php";
exit;
}
$warranty = settingsCurrent(['config_warranty_dell_client_id', 'config_warranty_dell_client_secret', 'config_warranty_hp_client_id', 'config_warranty_hp_client_secret', 'config_warranty_lenovo']);
$saved_secret = function ($stored) {
return trim((string) $stored) !== '' ? 'Saved - type a new one to replace it' : 'The secret\'s value';
};
$ready = warrantySettings()['ready'];
// Save and test, with a serial number to try - sent with the form, not saved with it
$test_field = function ($maker, $placeholder) {
return '<div class="input-group mt-3" style="max-width: 32rem;">'
. '<span class="input-group-text"><i class="fas fa-fw fa-barcode"></i></span>'
. '<input type="text" class="form-control" name="warranty_test_' . $maker . '" placeholder="' . escapeHtml($placeholder) . '" maxlength="40" data-settings-untracked aria-label="Serial number to try">'
. '<button type="submit" class="btn btn-outline-primary" name="test_warranty_lookup" value="' . $maker . '"><i class="fas fa-fw fa-vial me-1"></i>Save and test</button>'
. '</div>';
};
$state = function ($on, $off_text) {
return ($on ? '<span class="badge text-bg-success me-1">On</span>' : '<span class="badge text-bg-secondary me-1">' . escapeHtml($off_text) . '</span>') . ' ';
};
echo settingsPageStart('warranty');
?>
<form action="post.php" method="post" autocomplete="off" data-settings-form>
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<div class="card itflow-settings-card">
<div class="card-body">
<?= settingsSectionStart('how', 'How it works', 'An asset is looked up by its make - Dell, HP or Lenovo - or, with no make, by its model: Latitude, ThinkPad, EliteBook. Only empty dates are filled in: a warranty or purchase date already on an asset is never changed.') ?>
<div class="small">
<p class="mb-2"><strong>On one asset</strong> - the <i class="fas fa-search"></i> button beside <strong>Warranty expires</strong> on its Purchase tab, before you save.</p>
<p class="mb-2"><strong>On many</strong> - select them on Assets, then <strong>Bulk Action &gt; Look Up Warranty</strong>.</p>
<p class="mb-0 text-body-secondary">The warranty date is when the last of the manufacturer's coverage for it ends; the purchase date, when its warranty began - for Dell, the day it shipped.</p>
</div>
<?= settingsSectionEnd() ?>
<?= settingsSectionStart('dell', 'Dell', $state($ready['dell'], 'Not set up') . 'TechDirect\'s Warranty API, by service tag. Ask for a key at <a href="https://techdirect.dell.com" target="_blank" rel="noopener">techdirect.dell.com<i class="fas fa-external-link-alt small ms-1"></i></a> under Services &gt; APIs - Dell approves it, usually within a few days.') ?>
<div class="row g-3">
<div class="col-lg-6">
<?= settingsInput('config_warranty_dell_client_id', $warranty['config_warranty_dell_client_id'], ['icon' => 'fa-id-badge', 'label' => 'Client ID', 'maxlength' => 200,
'help' => 'Empty switches Dell lookups off, and forgets its secret.']) ?>
</div>
<div class="col-lg-6">
<?= settingsInput('config_warranty_dell_client_secret', '', ['icon' => 'fa-key', 'type' => 'password', 'label' => 'Client secret', 'maxlength' => 500,
'autocomplete' => 'new-password', 'placeholder' => $saved_secret($warranty['config_warranty_dell_client_secret'])]) ?>
</div>
</div>
<?= $test_field('dell', 'A service tag to try') ?>
<?= settingsSectionEnd() ?>
<?= settingsSectionStart('lenovo', 'Lenovo', $state($ready['lenovo'], 'Off') . 'Lenovo\'s support site, asked the way its own pages ask it - no key needed. It isn\'t an API Lenovo offers, so it can stop working when Lenovo changes the site.') ?>
<?= settingsSwitch('config_warranty_lenovo', $warranty['config_warranty_lenovo'], ['label' => 'Look up Lenovo serial numbers on Lenovo\'s support site']) ?>
<?= $test_field('lenovo', 'A serial number to try') ?>
<?= settingsSectionEnd() ?>
<?= settingsSectionStart('hp', 'HP', $state($ready['hp'], 'Not set up') . 'HP Inc.\'s Warranty API, by serial number. Register at <a href="https://developers.hp.com" target="_blank" rel="noopener">developers.hp.com<i class="fas fa-external-link-alt small ms-1"></i></a>, then email warrantyapi.customers@hp.com for access - HP approves each by hand and doesn\'t give every IT company one. Not for HP Enterprise (HPE) servers, which have no such API.') ?>
<div class="row g-3">
<div class="col-lg-6">
<?= settingsInput('config_warranty_hp_client_id', $warranty['config_warranty_hp_client_id'], ['icon' => 'fa-id-badge', 'label' => 'API key', 'maxlength' => 200,
'help' => 'Empty switches HP lookups off, and forgets its secret.']) ?>
</div>
<div class="col-lg-6">
<?= settingsInput('config_warranty_hp_client_secret', '', ['icon' => 'fa-key', 'type' => 'password', 'label' => 'API secret', 'maxlength' => 500,
'autocomplete' => 'new-password', 'placeholder' => $saved_secret($warranty['config_warranty_hp_client_secret']),
'help' => 'HP works through each lookup as a job, so its answers can take a few minutes.']) ?>
</div>
</div>
<?= $test_field('hp', 'A serial number to try') ?>
<?= settingsSectionEnd() ?>
<?= settingsSaveBar('edit_warranty_settings') ?>
</div>
</div>
</form>
<?php
require_once "../includes/footer.php";

View File

@@ -2384,6 +2384,51 @@ if (isset($_GET['asset_duplicate_check'])) {
exit;
}
/*
* Warranty lookup (functions/warranty.php, js/warranty_lookup.js). warranty_lookup: asset_ids[] -
* up to 25 assets, looked up and their empty dates filled, for Assets' bulk window; or make, model
* and serial - what the asset form has typed, looked up for the form to fill in. warranty_hp_check:
* an HP job asked after, with the same asset_ids[] or serial. Answers {results} or {answer}, an HP
* job not finished {done: false}, and anything refused {error}.
*/
if (isset($_POST['warranty_lookup']) || isset($_POST['warranty_hp_check'])) {
validateCSRFToken();
header('Content-Type: application/json');
if (!moduleOn('itdoc')) {
exit(json_encode(['error' => moduleOffText('itdoc')]));
}
if (lookupUserPermission('module_support') < 2) {
exit(json_encode(['error' => 'Looking up warranties takes Support at Modify in your role.']));
}
if (!warrantyAnyReady()) {
exit(json_encode(['error' => 'Warranty lookup isn\'t set up - Admin > Warranty Lookup.']));
}
session_write_close(); // a lookup can take a while - other pages needn't wait on it
$asset_ids = array_slice(array_map('intval', (array) ($_POST['asset_ids'] ?? [])), 0, 25);
if (isset($_POST['warranty_hp_check'])) {
$job = (string) $_POST['warranty_hp_check'];
if ($asset_ids) {
$check = warrantyAssetsHpCheck($job, $asset_ids);
exit(json_encode($check['done'] ? ['done' => true, 'results' => $check['results']] : ['done' => false]));
}
$serial = strtoupper(trim((string) ($_POST['serial'] ?? '')));
$check = warrantyHpCheck($job, [$serial]);
if (!$check['done']) {
exit(json_encode(['done' => false]));
}
$result = $check['error'] !== '' ? warrantyNotFound($check['error'], 'error') : ($check['results'][$serial] ?? warrantyNotFound("doesn't know serial number $serial"));
exit(json_encode(['done' => true, 'answer' => warrantyFormAnswer('hp', $result)]));
}
if ($asset_ids) {
exit(json_encode(['results' => warrantyAssetsLookup($asset_ids)]));
}
$maker = warrantyMaker($_POST['make'] ?? '', $_POST['model'] ?? '');
$result = warrantyLookup(['form' => ['maker' => $maker, 'serial' => mb_substr((string) ($_POST['serial'] ?? ''), 0, 60)]])['form'];
exit(json_encode(['answer' => warrantyFormAnswer($maker, $result)]));
}
if (isset($_GET['client_duplicate_check'])) {
header('Content-Type: application/json');

View File

@@ -437,6 +437,14 @@ $search_noun = $type_filter ? $asset_type_tabs[$type_filter]['label'] : 'assets'
data-bulk="true">
<i class="fas fa-fw fa-info-circle me-2"></i>Set Status
</a>
<?php if (warrantyAnyReady()) { // Their empty warranty and purchase dates from Dell, HP and Lenovo (functions/warranty.php) ?>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/asset/asset_bulk_warranty.php"
data-modal-size="lg"
data-bulk="true">
<i class="fas fa-fw fa-shield-alt me-2"></i>Look Up Warranty
</a>
<?php } ?>
<a class="dropdown-item" href="#" data-tag-picker data-tag-entity="asset" data-tag-bulk data-csrf="<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-tags me-2"></i>Tags
</a>

View File

@@ -0,0 +1,72 @@
<?php
/*
* Assets > Bulk Action > Look Up Warranty - the selected assets looked up with their manufacturers
* by serial number, a few at a time, each one's empty warranty and purchase dates filled in
* (js/warranty_lookup.js warrantyLookupBulk(), agent/ajax.php warranty_lookup, functions/warranty.php).
* Up to 500 at once. Each row says what was found; dates already there aren't changed.
*/
require_once '../../../includes/modal_header.php';
$assets = warrantyAssets(array_slice(array_map('intval', $_GET['asset_ids'] ?? []), 0, 500));
$count = count($assets);
$can = moduleOn('itdoc') && lookupUserPermission('module_support') >= 2;
$makers = warrantyMakers();
$ready = warrantySettings()['ready'];
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-shield-alt me-2"></i>Look Up Warranty for <strong><?= $count ?></strong> asset<?= $count === 1 ? '' : 's' ?></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" id="warrantyBulk" data-csrf="<?= $_SESSION['csrf_token'] ?>">
<?php if (!$can) { ?>
<div class="alert alert-warning mb-0"><i class="fas fa-fw fa-lock me-2"></i>Looking up warranties takes Support at Modify in your role.</div>
<?php } elseif (!warrantyAnyReady()) { ?>
<div class="alert alert-warning mb-0"><i class="fas fa-fw fa-exclamation-triangle me-2"></i>Warranty lookup isn't set up - an admin sets it up in Admin &gt; Warranty Lookup.</div>
<?php } elseif (!$count) { ?>
<div class="alert alert-secondary mb-0">None of these assets can be looked up.</div>
<?php } else { ?>
<p class="text-body-secondary small">Each one's empty warranty and purchase dates are filled in from its manufacturer, by its serial number. Dates already there aren't changed. Keep this open until it's done - closing it stops the lookup.</p>
<div class="mb-2 small fw-semibold" data-warranty-progress></div>
<div class="table-responsive" style="max-height: 55vh;">
<table class="table table-sm table-borderless align-middle mb-0">
<thead class="text-nowrap small text-body-secondary">
<tr><th>Asset</th><th>Serial</th><th>Result</th></tr>
</thead>
<tbody>
<?php foreach ($assets as $asset) {
$maker = warrantyMaker($asset['asset_make'], $asset['asset_model']); ?>
<tr data-warranty-asset="<?= intval($asset['asset_id']) ?>">
<td>
<div class="fw-semibold text-nowrap"><?= escapeHtml($asset['asset_name']) ?></div>
<div class="small text-body-secondary"><?= escapeHtml(trim($asset['asset_make'] . ' ' . $asset['asset_model'])) ?: '-' ?></div>
</td>
<td class="font-monospace small text-nowrap"><?= escapeHtml($asset['asset_serial']) ?: '-' ?></td>
<td class="small" data-warranty-result>
<span class="text-body-secondary"><?= $maker !== '' ? escapeHtml($makers[$maker]) . ($ready[$maker] ? ' - waiting' : ' - not set up') : 'Not a Dell, HP or Lenovo' ?></span>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<script>
itflowReady(function () {
window.warrantyLookupBulk(document.getElementById('warrantyBulk'));
});
</script>
<?php } ?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Close</button>
</div>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -509,8 +509,14 @@ $asset_form_icons = [
<div class="input-group">
<span class="input-group-text"><i class="fas fa-shield-alt fa-fw"></i></span>
<input type="date" class="form-control" name="warranty_expire" max="2999-12-31" value="<?= $asset_warranty_expire ?>">
<?php if (warrantyAnyReady()) { // From its manufacturer, by its serial number (js/warranty_lookup.js) ?>
<button type="button" class="btn btn-outline-secondary" data-warranty-lookup title="Look up its warranty with its manufacturer - Dell, HP or Lenovo - by its serial number" aria-label="Look up its warranty"><i class="fas fa-fw fa-search"></i></button>
<?php } ?>
</div>
</div>
<?php if (warrantyAnyReady()) { ?>
<div class="col-12 small" data-warranty-note></div>
<?php } ?>
</div>
</div>

5
db.sql
View File

@@ -4345,6 +4345,11 @@ CREATE TABLE `settings` (
`config_log_forward_tls_verify` tinyint(1) NOT NULL DEFAULT 1,
`config_ticket_pictures_ticket_id` int(11) NOT NULL DEFAULT 0,
`config_ticket_pictures_reply_id` int(11) NOT NULL DEFAULT 0,
`config_warranty_dell_client_id` varchar(200) DEFAULT NULL,
`config_warranty_dell_client_secret` text DEFAULT NULL,
`config_warranty_hp_client_id` varchar(200) DEFAULT NULL,
`config_warranty_hp_client_secret` text DEFAULT NULL,
`config_warranty_lenovo` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

View File

@@ -29,6 +29,7 @@ require_once __DIR__ . '/functions/api_keys.php';
require_once __DIR__ . '/functions/asset_interface.php';
require_once __DIR__ . '/functions/rack.php';
require_once __DIR__ . '/functions/asset.php';
require_once __DIR__ . '/functions/warranty.php';
require_once __DIR__ . '/functions/asset_type.php';
require_once __DIR__ . '/functions/asset_type_custom.php';
require_once __DIR__ . '/functions/archived.php';

View File

@@ -69,6 +69,8 @@ function settingsPages() {
'about' => 'The parts of ITFlow in use - IT documentation, ticketing, invoicing, the calendar, the Knowledge Base and the client portal, and the parts that come with them - and white-labelling.'],
'logs' => ['group' => 'system', 'title' => 'Log Settings', 'icon' => 'fa-scroll', 'url' => 'settings_logs.php', 'under' => 'logs',
'about' => 'How long the audit log and app logs are kept, and sending them on to a syslog server or SIEM.'],
'warranty' => ['group' => 'system', 'title' => 'Warranty Lookup', 'icon' => 'fa-shield-alt', 'url' => 'settings_warranty.php', 'under' => 'warranty', 'module' => 'itdoc',
'about' => 'An asset\'s warranty and purchase dates filled in from its serial number - asked of Dell, HP and Lenovo.'],
'telemetry' => ['group' => 'system', 'title' => 'Telemetry', 'icon' => 'fa-satellite-dish', 'url' => 'settings_telemetry.php',
'about' => 'Whether ITFlow tells the ITFlow project, each night, how it is being used.'],
];
@@ -152,7 +154,7 @@ function modulePaths() {
'agent/modals/asset/', 'agent/modals/credential/', 'agent/modals/network/', 'agent/modals/rack/', 'agent/modals/certificate/', 'agent/modals/domain/',
'agent/modals/software/', 'agent/modals/service/', 'agent/modals/document/', 'agent/modals/file/', 'agent/modals/folder/',
'admin/asset_types.php', 'admin/document_templates.php', 'admin/document_template.php', 'admin/software_templates.php', 'admin/software_template.php',
'admin/vendor_templates.php', 'admin/vendor_template.php', 'admin/network_platforms.php',
'admin/vendor_templates.php', 'admin/vendor_template.php', 'admin/network_platforms.php', 'admin/settings_warranty.php',
'admin/modals/asset_type/', 'admin/modals/document_template/', 'admin/modals/software_template/', 'admin/modals/vendor_template/',
'client/assets.php', 'client/asset.php', 'client/licenses.php', 'client/domains.php', 'client/certificates.php', 'client/documents.php',
'client/document.php', 'client/document_add.php', 'client/file.php',
@@ -346,6 +348,9 @@ function adminNavGroups() {
$itdoc ? ['file' => 'software_templates.php', 'icon' => 'fa-box-open', 'label' => 'Licenses', 'also' => ['software_template.php']] : null,
$itdoc ? ['file' => 'document_templates.php', 'icon' => 'fa-file-alt', 'label' => 'Documents', 'also' => ['document_template.php']] : null,
]))],
'warranty' => ['label' => 'Warranty Lookup', 'icon' => 'fa-shield-alt', 'pages' => $itdoc ? [
['file' => 'settings_warranty.php', 'icon' => 'fa-shield-alt', 'label' => 'Warranty Lookup'],
] : []],
'text' => ['label' => 'Text Messaging', 'icon' => 'fa-sms', 'pages' => array_values(array_filter([
['file' => 'text_messaging.php', 'icon' => 'fa-sms', 'label' => 'Setup'],
smsProvider() ? ['file' => 'text_messages.php', 'icon' => 'fa-comment-dots', 'label' => 'Messages', 'count' => smsFailedRecently(), 'title' => 'Failed to send in the last week', 'tone' => 'text-bg-danger'] : null,
@@ -641,6 +646,12 @@ function settingsFields() {
'config_module_enable_kb' => ['page' => 'module', 'section' => 'Modules', 'label' => 'Knowledge Base', 'words' => 'module knowledge base kb articles how-to help'] + $on_off,
'config_client_portal_enable' => ['page' => 'module', 'section' => 'Modules', 'label' => 'Client portal', 'words' => 'module portal clients'] + $on_off,
'config_whitelabel_key' => ['page' => 'module', 'section' => 'White-label', 'label' => 'White-label key', 'kind' => 'secret', 'words' => 'whitelabel white label powered by banner'],
// Warranty lookup
'config_warranty_dell_client_id' => ['page' => 'warranty', 'section' => 'Dell', 'label' => 'Dell client ID', 'words' => 'dell techdirect warranty api key service tag'],
'config_warranty_dell_client_secret' => ['page' => 'warranty', 'section' => 'Dell', 'label' => 'Dell client secret', 'kind' => 'secret', 'words' => 'dell techdirect warranty api secret'],
'config_warranty_hp_client_id' => ['page' => 'warranty', 'section' => 'HP', 'label' => 'HP client ID', 'words' => 'hp hewlett packard warranty api key'],
'config_warranty_hp_client_secret' => ['page' => 'warranty', 'section' => 'HP', 'label' => 'HP client secret', 'kind' => 'secret', 'words' => 'hp hewlett packard warranty api secret'],
'config_warranty_lenovo' => ['page' => 'warranty', 'section' => 'Lenovo', 'label' => 'Lenovo lookups', 'kind' => 'switch', 'words' => 'lenovo thinkpad warranty lookup support site'],
'config_whitelabel_enabled' => ['page' => 'module', 'section' => 'White-label', 'label' => 'White-label', 'search' => false] + $on_off,
// Logs

557
functions/warranty.php Normal file
View File

@@ -0,0 +1,557 @@
<?php
/*
* Warranty lookup - when an asset's warranty runs out, and when it shipped, from its serial number,
* asked of its manufacturer (Admin > Warranty Lookup, admin/settings_warranty.php):
*
* Dell - TechDirect's Warranty API, with a key from techdirect.dell.com; up to 100 service tags a
* request (warrantyDell()).
* HP - HP Inc.'s Warranty API, with a key from developers.hp.com. HP answers as a job it works
* through, so a lookup starts one and is asked back until it's done (warrantyHpStart(),
* warrantyHpCheck()). Not HP Enterprise (HPE) - it has no such API.
* Lenovo - Lenovo's support site, asked as its own pages ask it: no key, but not an API Lenovo
* offers, so it can stop working when Lenovo changes the site (warrantyLenovo()).
*
* Which manufacturer is the asset's make, or with none its model's family - Latitude, ThinkPad,
* EliteBook (warrantyMaker()). A lookup fills what is empty and changes nothing that's there
* (warrantyApply()): the warranty date, from the latest end of the coverage the manufacturer has
* for it, and the purchase date, from when its warranty began - Dell's ship date.
*
* The Look up button on the asset form and Assets' bulk Look up Warranty window (js/warranty_lookup.js)
* ask agent/ajax.php. WARRANTY_*_URL are where each is asked - for tests.
*/
defined('WARRANTY_DELL_URL') || define('WARRANTY_DELL_URL', 'https://apigtwb2c.us.dell.com/');
defined('WARRANTY_HP_URL') || define('WARRANTY_HP_URL', 'https://warranty.api.hp.com/');
defined('WARRANTY_LENOVO_URL') || define('WARRANTY_LENOVO_URL', 'https://pcsupport.lenovo.com/');
/* The manufacturers a warranty can be looked up with - key => name. */
function warrantyMakers() {
return ['dell' => 'Dell', 'hp' => 'HP', 'lenovo' => 'Lenovo'];
}
/*
* Which manufacturer an asset is, for a lookup - 'dell', 'hp', 'lenovo' or '' - by its make, or by
* its model's family when it has no make. HP Enterprise (HPE) is '': it has no warranty API.
*/
function warrantyMaker($make, $model = '') {
$make = strtolower(trim((string) $make));
if ($make !== '') {
if (strpos($make, 'dell') !== false) {
return 'dell';
}
if (strpos($make, 'lenovo') !== false) {
return 'lenovo';
}
if (preg_match('/\bhpe\b|enterprise/', $make)) {
return '';
}
return preg_match('/^hp\b|hewlett/', $make) ? 'hp' : '';
}
$model = strtolower(trim((string) $model));
if (preg_match('/\b(latitude|optiplex|precision|inspiron|vostro|xps|poweredge|wyse)\b/', $model)) {
return 'dell';
}
if (preg_match('/\b(thinkpad|thinkcentre|thinkstation|thinkbook|thinksystem|ideapad|ideacentre)\b/', $model)) {
return 'lenovo';
}
return preg_match('/\b(elitebook|probook|zbook|elitedesk|prodesk|eliteone|proone)\b/', $model) ? 'hp' : '';
}
/*
* What's set up in Admin > Warranty Lookup - each manufacturer's key, opened - with 'ready' for
* each that can be asked. All off before the database update that brings them (4.4.4).
*/
function warrantySettings() {
global $mysqli;
static $settings = null;
if ($settings !== null) {
return $settings;
}
$row = [];
try {
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_warranty_dell_client_id, config_warranty_dell_client_secret, config_warranty_hp_client_id,
config_warranty_hp_client_secret, config_warranty_lenovo FROM settings WHERE company_id = 1")) ?: [];
} catch (\Throwable $e) {
$row = [];
}
$settings = [
'dell_id' => trim((string) ($row['config_warranty_dell_client_id'] ?? '')),
'dell_secret' => trim(secretOpen((string) ($row['config_warranty_dell_client_secret'] ?? ''), 'warranty')),
'hp_id' => trim((string) ($row['config_warranty_hp_client_id'] ?? '')),
'hp_secret' => trim(secretOpen((string) ($row['config_warranty_hp_client_secret'] ?? ''), 'warranty')),
'lenovo' => $row ? intval($row['config_warranty_lenovo'] ?? 0) === 1 : false,
];
$settings['ready'] = [
'dell' => $settings['dell_id'] !== '' && $settings['dell_secret'] !== '',
'hp' => $settings['hp_id'] !== '' && $settings['hp_secret'] !== '',
'lenovo' => $settings['lenovo'],
];
return $settings;
}
/* Whether any manufacturer can be asked - the Look up button and bulk action show only then. */
function warrantyAnyReady() {
return in_array(true, warrantySettings()['ready'], true);
}
/*
* One request - ['status', 'body', 'json', 'error']. $body: an array sent as a form, or a string
* sent as it is (JSON). A browser's name for Lenovo's site, which turns away what doesn't look like one.
*/
function warrantyHttp($method, $url, array $headers = [], $body = null, $timeout = 25) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => strtoupper($method),
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_USERAGENT => strpos($url, WARRANTY_LENOVO_URL) === 0 ? 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ITFlow' : 'ITFlow',
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
CURLOPT_ENCODING => '',
]);
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($body) ? http_build_query($body) : $body);
}
$response = curl_exec($ch);
$status = intval(curl_getinfo($ch, CURLINFO_RESPONSE_CODE));
$error = $response === false ? curl_error($ch) : '';
curl_close($ch);
$json = is_string($response) ? json_decode($response, true) : null;
return ['status' => $status, 'body' => is_string($response) ? $response : '', 'json' => is_array($json) ? $json : null, 'error' => $error];
}
/* What went wrong with a request, for people - its status and what the manufacturer said. */
function warrantyHttpError($maker, array $response) {
$name = warrantyMakers()[$maker];
if ($response['error'] !== '') {
return "$name couldn't be reached: " . $response['error'];
}
$json = $response['json'] ?? [];
$said = $json['error_description'] ?? $json['message'] ?? $json['error']['message'] ?? $json['detail'] ?? (is_string($json['error'] ?? null) ? $json['error'] : '');
$hint = in_array($response['status'], [400, 401, 403], true) && $maker !== 'lenovo' ? ' - check its key in Admin > Warranty Lookup' : '';
return "$name answered HTTP {$response['status']}" . ($said !== '' ? ': ' . mb_substr(trim((string) $said), 0, 200) : '') . $hint;
}
/* A date as Y-m-d from what a manufacturer sends ("2027-03-01T05:59:59.000001Z", "2027-03-01"), or ''. */
function warrantyDate($value) {
return preg_match('/^(\d{4}-\d{2}-\d{2})/', trim((string) $value), $m) && strtotime($m[1]) ? $m[1] : '';
}
/*
* What a manufacturer has for a serial, from the coverage it lists - ['found' => true, 'end' (the
* latest end), 'start' (the purchase date: $start, or the earliest start), 'coverage' (the name of
* the one ending last), 'product']. $coverage: [start, end, name] each.
*/
function warrantyFound(array $coverage, $product = '', $start = '') {
$end = '';
$name = '';
$first = '';
foreach ($coverage as [$from, $to, $what]) {
$from = warrantyDate($from);
$to = warrantyDate($to);
if ($to !== '' && $to >= $end) {
$end = $to;
$name = trim((string) $what);
}
if ($from !== '' && ($first === '' || $from < $first)) {
$first = $from;
}
}
if ($end === '') {
return warrantyNotFound('has no warranty for it');
}
return ['found' => true, 'kind' => 'found', 'why' => '', 'end' => $end, 'start' => warrantyDate($start) ?: $first, 'coverage' => $name, 'product' => trim((string) $product), 'pending' => ''];
}
/*
* Nothing found for a serial - $kind 'missing' (the manufacturer has nothing for it; $why is said
* after its name), 'skip' (not looked up - no make it can be, no serial) or 'error' (it couldn't be
* asked); $why is a sentence for those.
*/
function warrantyNotFound($why, $kind = 'missing') {
return ['found' => false, 'kind' => $kind, 'why' => $why, 'end' => '', 'start' => '', 'coverage' => '', 'product' => '', 'pending' => ''];
}
/*
* Dell - service tags => what Dell has for each. A token from the key, then up to 100 tags a
* request. A tag Dell doesn't know is not found; Dell not answering is an error for each.
*/
function warrantyDell(array $tags) {
$settings = warrantySettings();
$results = [];
$tags = array_values(array_unique(array_filter(array_map(function ($tag) {
return strtoupper(trim((string) $tag));
}, $tags))));
if (!$tags) {
return [];
}
// The key in the form, as TechDirect's guide has it - or as Basic, as its gateway also takes
$token_url = WARRANTY_DELL_URL . 'auth/oauth/v2/token';
$token = warrantyHttp('POST', $token_url, ['Content-Type: application/x-www-form-urlencoded', 'Accept: application/json'],
['grant_type' => 'client_credentials', 'client_id' => $settings['dell_id'], 'client_secret' => $settings['dell_secret']]);
if (empty($token['json']['access_token']) && in_array($token['status'], [400, 401], true)) {
$token = warrantyHttp('POST', $token_url, ['Content-Type: application/x-www-form-urlencoded', 'Accept: application/json',
'Authorization: Basic ' . base64_encode($settings['dell_id'] . ':' . $settings['dell_secret'])], ['grant_type' => 'client_credentials']);
}
$access = (string) ($token['json']['access_token'] ?? '');
if ($access === '') {
$error = warrantyHttpError('dell', $token);
return array_fill_keys($tags, warrantyNotFound($error, 'error'));
}
foreach (array_chunk($tags, 100) as $chunk) {
$response = warrantyHttp('GET', WARRANTY_DELL_URL . 'PROD/sbil/eapi/v5/asset-entitlements?servicetags=' . rawurlencode(implode(',', $chunk)),
['Authorization: Bearer ' . $access, 'Accept: application/json']);
if ($response['status'] !== 200 || !is_array($response['json'])) {
$error = warrantyHttpError('dell', $response);
$results += array_fill_keys($chunk, warrantyNotFound($error, 'error'));
continue;
}
foreach ($response['json'] as $item) {
$tag = strtoupper(trim((string) ($item['serviceTag'] ?? '')));
if ($tag === '' || isset($results[$tag])) {
continue;
}
if (!empty($item['invalid'])) {
$results[$tag] = warrantyNotFound("doesn't know service tag $tag");
continue;
}
$coverage = [];
foreach ((array) ($item['entitlements'] ?? []) as $entitlement) {
$coverage[] = [$entitlement['startDate'] ?? '', $entitlement['endDate'] ?? '', $entitlement['serviceLevelDescription'] ?? ''];
}
$results[$tag] = warrantyFound($coverage, $item['productLineDescription'] ?? '', $item['shipDate'] ?? '');
}
foreach ($chunk as $tag) {
$results[$tag] = $results[$tag] ?? warrantyNotFound("doesn't know service tag $tag");
}
}
return $results;
}
/* HP - a token from the key, or ['error']. */
function warrantyHpToken() {
$settings = warrantySettings();
$token = warrantyHttp('POST', WARRANTY_HP_URL . 'oauth/v1/token', ['Content-Type: application/x-www-form-urlencoded', 'Accept: application/json',
'Authorization: Basic ' . base64_encode($settings['hp_id'] . ':' . $settings['hp_secret'])], ['grant_type' => 'client_credentials']);
$access = (string) ($token['json']['access_token'] ?? '');
return $access !== '' ? ['token' => $access, 'error' => ''] : ['token' => '', 'error' => warrantyHttpError('hp', $token)];
}
/* HP - start the job that looks up these serial numbers: ['job', 'error']. */
function warrantyHpStart(array $serials) {
$serials = array_values(array_unique(array_filter(array_map(function ($serial) {
return strtoupper(trim((string) $serial));
}, $serials))));
if (!$serials) {
return ['job' => '', 'error' => 'No serial numbers to look up.'];
}
$token = warrantyHpToken();
if ($token['token'] === '') {
return ['job' => '', 'error' => $token['error']];
}
$response = warrantyHttp('POST', WARRANTY_HP_URL . 'productwarranty/v2/jobs', ['Authorization: Bearer ' . $token['token'], 'Accept: application/json', 'Content-Type: application/json'],
json_encode(array_map(function ($serial) {
return ['sn' => $serial];
}, array_slice($serials, 0, 5000))));
$job = (string) ($response['json']['jobId'] ?? '');
return $job !== '' ? ['job' => $job, 'error' => ''] : ['job' => '', 'error' => warrantyHttpError('hp', $response)];
}
/*
* HP - where a job stands: ['done', 'results' (serial => what HP has, once done), 'error']. A
* serial HP sent back an error for, or left out, is not found.
*/
function warrantyHpCheck($job, array $serials = []) {
$job = trim((string) $job);
if (!preg_match('/^[A-Za-z0-9._:-]{1,100}$/', $job)) {
return ['done' => true, 'results' => [], 'error' => "That isn't an HP job."];
}
$token = warrantyHpToken();
if ($token['token'] === '') {
return ['done' => true, 'results' => [], 'error' => $token['error']];
}
$headers = ['Authorization: Bearer ' . $token['token'], 'Accept: application/json'];
$status = warrantyHttp('GET', WARRANTY_HP_URL . 'productwarranty/v2/jobs/' . rawurlencode($job), $headers);
$state = strtolower((string) ($status['json']['status'] ?? ''));
if ($status['status'] !== 200) {
return ['done' => true, 'results' => [], 'error' => warrantyHttpError('hp', $status)];
}
if (in_array($state, ['error', 'failed'], true)) {
return ['done' => true, 'results' => [], 'error' => "HP couldn't finish looking them up (its job says $state)."];
}
if ($state !== 'completed') {
return ['done' => false, 'results' => [], 'error' => ''];
}
$response = warrantyHttp('GET', WARRANTY_HP_URL . 'productwarranty/v2/jobs/' . rawurlencode($job) . '/results', $headers, null, 40);
if ($response['status'] !== 200 || !is_array($response['json'])) {
return ['done' => true, 'results' => [], 'error' => warrantyHttpError('hp', $response)];
}
$results = [];
foreach ($response['json'] as $item) {
$serial = strtoupper(trim((string) ($item['product']['serialNumber'] ?? $item['sn'] ?? '')));
if ($serial === '' || isset($results[$serial])) {
continue;
}
if (!empty($item['error']) || empty($item['offers'])) {
$results[$serial] = warrantyNotFound("doesn't know serial number $serial" . (!empty($item['error']) ? ' - it may need the product number' : ''));
continue;
}
$coverage = [];
foreach ((array) $item['offers'] as $offer) {
$coverage[] = [$offer['serviceObligationLineItemStartDate'] ?? '', $offer['serviceObligationLineItemEndDate'] ?? '', $offer['offerDescription'] ?? ''];
}
$results[$serial] = warrantyFound($coverage, $item['product']['productDescription'] ?? '');
}
foreach ($serials as $serial) {
$serial = strtoupper(trim((string) $serial));
if ($serial !== '') {
$results[$serial] = $results[$serial] ?? warrantyNotFound("doesn't know serial number $serial");
}
}
return ['done' => true, 'results' => $results, 'error' => ''];
}
/*
* Lenovo - what its support site has for a serial number: the product it is, then that product's
* warranty page, whose coverage is in its ds_warranties. Contract coverage counts only while active.
*/
function warrantyLenovo($serial) {
$serial = strtoupper(trim((string) $serial));
if (!preg_match('/^[A-Z0-9-]{4,30}$/', $serial)) {
return warrantyNotFound("doesn't take serial number $serial");
}
$product = warrantyHttp('GET', WARRANTY_LENOVO_URL . 'us/en/api/v4/mse/getproducts?productId=' . rawurlencode($serial), ['Accept: application/json', 'Accept-Language: en-US,en;q=0.9']);
if ($product['status'] !== 200 || $product['json'] === null) {
return warrantyNotFound(warrantyHttpError('lenovo', $product), 'error');
}
$found = isset($product['json']['Id']) ? $product['json'] : ($product['json'][0] ?? []);
$id = trim((string) ($found['Id'] ?? ''));
if ($id === '' || !preg_match('#^[A-Za-z0-9/_.-]+$#', $id)) {
return warrantyNotFound("doesn't know serial number $serial");
}
$page = warrantyHttp('GET', WARRANTY_LENOVO_URL . 'us/en/products/' . strtolower($id) . '/warranty', ['Accept: text/html', 'Accept-Language: en-US,en;q=0.9']);
if ($page['status'] !== 200) {
return warrantyNotFound(warrantyHttpError('lenovo', $page), 'error');
}
if (!preg_match('/var\s+ds_warranties\s*=\s*(?:window\.ds_warranties\s*\|\|\s*)?(\{.*\})\s*;?\s*$/m', $page['body'], $m) || !is_array($data = json_decode($m[1], true))) {
return warrantyNotFound("Lenovo's warranty page has changed - ITFlow can't read it", 'error');
}
$coverage = [];
$base = [];
foreach (['ContractWarranties', 'BaseWarranties', 'UpmaWarranties', 'AodWarranties', 'InstantWarranties', 'SaeWarranties'] as $kind) {
foreach ((array) ($data[$kind] ?? []) as $warranty) {
if ($kind === 'ContractWarranties' && !in_array((string) ($warranty['Status'] ?? ''), ['Active', '1'], true)) {
continue;
}
$coverage[] = [$warranty['Start'] ?? '', $warranty['End'] ?? '', $warranty['Name'] ?? ''];
if ($kind === 'BaseWarranties' && warrantyDate($warranty['Start'] ?? '') !== '') {
$base[] = warrantyDate($warranty['Start']);
}
}
}
$result = warrantyFound($coverage, preg_replace('/\s*\(.*$/', '', (string) ($data['ProductName'] ?? $found['Name'] ?? '')), $base ? min($base) : '');
if (!$result['found']) {
$result['why'] = "has no warranty for serial number $serial";
}
return $result;
}
/*
* Look up serial numbers - $items: key => ['maker', 'serial'] - key => what the manufacturer has.
* Dell's together, Lenovo's one by one; HP's start one job, each answered 'pending' with its id
* for warrantyHpCheck(). A manufacturer not set up says so.
*/
function warrantyLookup(array $items) {
$settings = warrantySettings();
$results = [];
$by = ['dell' => [], 'hp' => [], 'lenovo' => []];
foreach ($items as $key => $item) {
$maker = (string) ($item['maker'] ?? '');
$serial = strtoupper(trim((string) ($item['serial'] ?? '')));
if (!isset($by[$maker])) {
$results[$key] = warrantyNotFound("Its make isn't Dell, HP or Lenovo - set the make to look it up", 'skip');
continue;
}
if (!$settings['ready'][$maker]) {
$results[$key] = warrantyNotFound(warrantyMakers()[$maker] . " lookups aren't set up - Admin > Warranty Lookup", 'skip');
continue;
}
if ($serial === '') {
$results[$key] = warrantyNotFound('It has no serial number to look up', 'skip');
continue;
}
$by[$maker][$key] = $serial;
}
if ($by['dell']) {
$dell = warrantyDell(array_values($by['dell']));
foreach ($by['dell'] as $key => $serial) {
$results[$key] = $dell[$serial] ?? warrantyNotFound("doesn't know service tag $serial");
}
}
foreach ($by['lenovo'] as $key => $serial) {
$results[$key] = warrantyLenovo($serial);
}
if ($by['hp']) {
$job = warrantyHpStart(array_values($by['hp']));
foreach ($by['hp'] as $key => $serial) {
$results[$key] = $job['job'] !== '' ? array_merge(warrantyNotFound('', 'pending'), ['pending' => $job['job']]) : warrantyNotFound($job['error'], 'error');
}
}
return $results;
}
/*
* Fill an asset's empty warranty and purchase dates from what its manufacturer has ($result, found)
* - nothing there is changed. ['warranty' => 'filled'|'kept'|'', 'purchase' => the same]; logged,
* and on its history, when anything is filled.
*/
function warrantyApply($asset_id, $maker, array $result) {
global $mysqli, $session_name;
$asset_id = intval($asset_id);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT asset_name, asset_status, asset_client_id, asset_warranty_expire, asset_purchase_date FROM assets WHERE asset_id = $asset_id"));
$did = ['warranty' => '', 'purchase' => ''];
if (!$row || empty($result['found'])) {
return $did;
}
$empty = function ($date) {
$date = trim((string) $date);
return $date === '' || strpos($date, '0000-00-00') === 0;
};
$set = [];
$said = [];
$name = warrantyMakers()[$maker] ?? 'The manufacturer';
if ($result['end'] !== '') {
if ($empty($row['asset_warranty_expire'])) {
$set[] = "asset_warranty_expire = '" . escapeSql($result['end']) . "'";
$said[] = 'warranty expires ' . $result['end'];
$did['warranty'] = 'filled';
} else {
$did['warranty'] = 'kept';
}
}
if ($result['start'] !== '') {
if ($empty($row['asset_purchase_date'])) {
$set[] = "asset_purchase_date = '" . escapeSql($result['start']) . "'";
$said[] = 'purchased ' . $result['start'];
$did['purchase'] = 'filled';
} else {
$did['purchase'] = 'kept';
}
}
if ($set) {
mysqli_query($mysqli, "UPDATE assets SET " . implode(', ', $set) . " WHERE asset_id = $asset_id");
$what = escapeSql("$session_name filled in from $name's warranty lookup: " . implode(', ', $said) . ($result['coverage'] !== '' ? " ({$result['coverage']})" : ''));
logAudit("Asset", "Edit", $what . ' on ' . escapeSql($row['asset_name']), intval($row['asset_client_id']), $asset_id);
mysqli_query($mysqli, "INSERT INTO asset_history SET asset_history_status = '" . escapeSql($row['asset_status']) . "', asset_history_description = '$what', asset_history_asset_id = $asset_id");
}
return $did;
}
/* What a lookup found, for people - "Dell: covered until 2027-03-01 (ProSupport), from 2024-02-01", "Dell doesn't know service tag ABC1234". */
function warrantySays($maker, array $result) {
$name = warrantyMakers()[$maker] ?? '';
if (!empty($result['found'])) {
return "$name: covered until " . formatDate($result['end']) . ($result['coverage'] !== '' ? ' (' . $result['coverage'] . ')' : '')
. ($result['start'] !== '' ? ', from ' . formatDate($result['start']) : '');
}
if ($result['kind'] === 'pending') {
return "$name is looking it up - this can take a few minutes";
}
return $result['kind'] === 'missing' ? "$name {$result['why']}" : $result['why'];
}
/* Assets for a lookup, of clients the user can open - asset id => row (asset_id, asset_name, asset_make, asset_model, asset_serial, asset_client_id). */
function warrantyAssets(array $asset_ids) {
global $mysqli;
$ids = array_values(array_unique(array_filter(array_map('intval', $asset_ids))));
if (!$ids) {
return [];
}
$assets = [];
$sql = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_make, asset_model, asset_serial, asset_client_id FROM assets WHERE asset_id IN (" . implode(',', $ids) . ")");
while ($row = mysqli_fetch_assoc($sql)) {
if (hasClientAccess($row['asset_client_id'])) {
$assets[intval($row['asset_id'])] = $row;
}
}
return $assets;
}
/* What a lookup did to an asset's dates, for people - "warranty and purchase dates filled in". */
function warrantyDidSays(array $did) {
$filled = array_keys(array_filter($did, function ($what) {
return $what === 'filled';
}));
$kept = array_keys(array_filter($did, function ($what) {
return $what === 'kept';
}));
if (!$filled) {
return $kept ? 'its dates were already set - nothing changed' : 'nothing to fill in';
}
$names = ['warranty' => 'warranty', 'purchase' => 'purchase'];
$said = implode(' and ', array_map(function ($what) use ($names) {
return $names[$what];
}, $filled)) . (count($filled) > 1 ? ' dates' : ' date') . ' filled in';
return $said . ($kept ? ' - its ' . $names[$kept[0]] . ' date was already set' : '');
}
/*
* How a lookup went for an asset, its empty dates filled from what was found - ['asset_id',
* 'name', 'tone' (success|secondary|warning|danger|info), 'text', 'pending' (an HP job to ask after)].
*/
function warrantyAssetOutcome(array $asset, $maker, array $result) {
$outcome = ['asset_id' => intval($asset['asset_id']), 'name' => (string) $asset['asset_name'], 'tone' => 'secondary', 'text' => '', 'pending' => ''];
if ($result['found']) {
$did = warrantyApply($asset['asset_id'], $maker, $result);
$outcome['tone'] = in_array('filled', $did, true) ? 'success' : 'secondary';
$outcome['text'] = warrantySays($maker, $result) . ' - ' . warrantyDidSays($did);
return $outcome;
}
$outcome['tone'] = ['pending' => 'info', 'missing' => 'warning', 'error' => 'danger'][$result['kind']] ?? 'secondary';
$outcome['text'] = warrantySays($maker, $result);
$outcome['pending'] = (string) $result['pending'];
return $outcome;
}
/* Look assets up and fill their empty dates - the bulk window's few at a time. Each asset's outcome (warrantyAssetOutcome()). */
function warrantyAssetsLookup(array $asset_ids) {
$assets = warrantyAssets($asset_ids);
$items = [];
foreach ($assets as $id => $asset) {
$items[$id] = ['maker' => warrantyMaker($asset['asset_make'], $asset['asset_model']), 'serial' => $asset['asset_serial']];
}
$results = warrantyLookup($items);
$outcomes = [];
foreach ($assets as $id => $asset) {
$outcomes[] = warrantyAssetOutcome($asset, $items[$id]['maker'], $results[$id]);
}
return $outcomes;
}
/* Ask after an HP job for assets - ['done', 'results' (each asset's outcome, once done)]. */
function warrantyAssetsHpCheck($job, array $asset_ids) {
$assets = warrantyAssets($asset_ids);
$serials = [];
foreach ($assets as $id => $asset) {
$serials[$id] = strtoupper(trim((string) $asset['asset_serial']));
}
$check = warrantyHpCheck($job, array_values($serials));
if (!$check['done']) {
return ['done' => false, 'results' => []];
}
$outcomes = [];
foreach ($assets as $id => $asset) {
$result = $check['error'] !== '' ? warrantyNotFound($check['error'], 'error') : ($check['results'][$serials[$id]] ?? warrantyNotFound("doesn't know serial number {$serials[$id]}"));
$outcomes[] = warrantyAssetOutcome($asset, 'hp', $result);
}
return ['done' => true, 'results' => $outcomes];
}
/* A lookup for the asset form, before it's saved - by what's typed in it. What it found, for the form to fill its empty fields from. */
function warrantyFormAnswer($maker, array $result) {
return ['found' => $result['found'], 'tone' => $result['found'] ? 'success' : (['pending' => 'info', 'missing' => 'warning', 'error' => 'danger'][$result['kind']] ?? 'secondary'),
'text' => warrantySays($maker, $result), 'end' => $result['end'], 'start' => $result['start'], 'pending' => (string) $result['pending']];
}

View File

@@ -178,6 +178,7 @@ if ($itflow_pulse) { ?>
<?php if (!empty($session_user_id) && basename(dirname($_SERVER['REQUEST_URI'])) !== 'guest') { ?>
<script src="<?= staticFileUrl('/js/client_card.js') ?>"></script>
<script src="<?= staticFileUrl('/js/quick_add.js') ?>"></script>
<script src="<?= staticFileUrl('/js/warranty_lookup.js') ?>"></script>
<?php } ?>
<script src="<?= staticFileUrl('/js/ticket_timers.js') ?>"></script>
<?php

276
js/warranty_lookup.js Normal file
View File

@@ -0,0 +1,276 @@
/*
* Warranty lookup (functions/warranty.php, agent/ajax.php warranty_lookup and warranty_hp_check).
*
* The Look up button beside Warranty expires on the asset form ([data-warranty-lookup]) asks with
* what the form has typed - make, model, serial - and fills its empty warranty and purchase dates;
* for a date already there it offers the manufacturer's instead, as a button.
*
* Assets' Bulk Action > Look Up Warranty window (agent/modals/asset/asset_bulk_warranty.php) calls
* warrantyLookupBulk(): a few assets at a time, each one's result on its row, their empty dates
* filled by ITFlow. Closing the window stops it; the list is reloaded when anything was filled.
*
* HP answers as a job it works through: asked after every 10 seconds, for up to 15 minutes.
*/
(function () {
'use strict';
var HP_EVERY = 10000;
var HP_FOR = 15 * 60 * 1000;
var AT_ONCE = 5;
function ask(data, done, failed) {
itflowPost('ajax.php', data, function (text) {
var json;
try {
json = JSON.parse(text);
} catch (e) {
failed('ITFlow sent back something unexpected.');
return;
}
if (json.error) {
failed(json.error);
return;
}
done(json);
}, function () {
failed('ITFlow couldn\'t be reached.');
});
}
// HP's job, asked after until it's done - then done(json); gave_up() after HP_FOR
function waitOnHp(data, done, gave_up, failed, stopped) {
var started = Date.now();
(function again() {
setTimeout(function () {
if (stopped && stopped()) {
return;
}
ask(data, function (json) {
if (json.done) {
done(json);
} else if (Date.now() - started > HP_FOR) {
gave_up();
} else {
again();
}
}, failed);
}, HP_EVERY);
})();
}
var icons = { success: 'fa-check-circle', secondary: 'fa-minus-circle', warning: 'fa-question-circle', danger: 'fa-exclamation-triangle', info: 'fa-circle-notch fa-spin' };
function say(el, tone, text) {
el.textContent = '';
var icon = document.createElement('i');
icon.className = 'fas fa-fw me-1 ' + (icons[tone] || icons.secondary) + ' text-' + (tone === 'secondary' ? 'body-secondary' : tone);
el.appendChild(icon);
el.appendChild(document.createTextNode(text));
}
// The asset form's Look up
document.addEventListener('click', function (e) {
var button = e.target.closest('[data-warranty-lookup]');
if (!button) {
return;
}
e.preventDefault();
var form = button.closest('form');
var field = function (name) {
return form.querySelector('[name="' + name + '"]');
};
var note = form.querySelector('[data-warranty-note]');
var serial = field('serial') ? field('serial').value.trim() : '';
var csrf = field('csrf_token') ? field('csrf_token').value : '';
if (serial === '') {
say(note, 'warning', 'Put in its serial number first, on the Details tab.');
return;
}
function fill(answer) {
button.disabled = false;
say(note, answer.tone, answer.text);
if (!answer.found) {
return;
}
var filled = [];
var offers = [];
[['warranty_expire', answer.end, 'Warranty expires'], ['purchase_date', answer.start, 'Purchased']].forEach(function (pair) {
var input = field(pair[0]);
if (!input || !pair[1]) {
return;
}
if (input.value === '') {
input.value = pair[1];
input.dispatchEvent(new Event('change', { bubbles: true }));
filled.push(pair[2]);
} else if (input.value !== pair[1]) {
// A date already there stays - the manufacturer's is offered
var use = document.createElement('button');
use.type = 'button';
use.className = 'btn btn-link btn-sm p-0 ms-2 align-baseline';
use.textContent = 'Use ' + pair[1] + ' for ' + pair[2];
use.addEventListener('click', function () {
input.value = pair[1];
input.dispatchEvent(new Event('change', { bubbles: true }));
use.remove();
});
offers.push(use);
}
});
if (filled.length) {
note.appendChild(document.createTextNode(' - ' + filled.join(' and ') + ' filled in; save to keep ' + (filled.length > 1 ? 'them' : 'it') + '.'));
}
offers.forEach(function (use) {
note.appendChild(use);
});
}
button.disabled = true;
say(note, 'info', 'Looking it up...');
var failed = function (message) {
button.disabled = false;
say(note, 'danger', message);
};
ask({ csrf_token: csrf, warranty_lookup: 1, make: field('make') ? field('make').value : '', model: field('model') ? field('model').value : '', serial: serial }, function (json) {
if (!json.answer.pending) {
fill(json.answer);
return;
}
say(note, 'info', json.answer.text);
waitOnHp({ csrf_token: csrf, warranty_hp_check: json.answer.pending, serial: serial }, function (json) {
fill(json.answer);
}, function () {
failed('HP is taking too long - try again later.');
}, failed, function () {
return !document.body.contains(button);
});
}, failed);
});
// Assets' bulk window
window.warrantyLookupBulk = function (box) {
var csrf = box.dataset.csrf;
var waiting = Array.prototype.map.call(box.querySelectorAll('[data-warranty-asset]'), function (row) {
return row.dataset.warrantyAsset;
});
var total = waiting.length;
var progress = box.querySelector('[data-warranty-progress]');
var finished = 0;
var onHp = 0;
var tally = { success: 0, secondary: 0, warning: 0, danger: 0 };
var stopped = false;
var modal = box.closest('.modal');
if (modal) {
modal.addEventListener('hidden.bs.modal', function () {
stopped = true;
if (tally.success) {
window.location.reload();
}
}, { once: true });
}
function mark(result, last) {
var cell = box.querySelector('[data-warranty-asset="' + result.asset_id + '"] [data-warranty-result]');
if (cell) {
say(cell, result.tone, result.text);
}
if (last) {
tally[result.tone] = (tally[result.tone] || 0) + 1;
finished++;
}
}
function count() {
if (finished < total) {
say(progress, 'info', finished + ' of ' + total + ' looked up' + (onHp ? ' - waiting on HP for ' + onHp : ''));
return;
}
var parts = [];
if (tally.success) {
parts.push(tally.success + ' filled in');
}
if (tally.secondary) {
parts.push(tally.secondary + ' left as they were');
}
if (tally.warning) {
parts.push(tally.warning + ' not found');
}
if (tally.danger) {
parts.push(tally.danger + ' couldn\'t be looked up');
}
say(progress, tally.danger ? 'warning' : 'success', 'Done - ' + parts.join(', ') + '.');
}
function watch(job, ids) {
onHp += ids.length;
var settle = function (results) {
onHp -= ids.length;
results.forEach(function (result) {
mark(result, true);
});
count();
};
waitOnHp({ csrf_token: csrf, warranty_hp_check: job, asset_ids: ids }, function (json) {
settle(json.results);
}, function () {
settle(ids.map(function (id) {
return { asset_id: id, tone: 'danger', text: 'HP is taking too long - look it up again later' };
}));
}, function (message) {
settle(ids.map(function (id) {
return { asset_id: id, tone: 'danger', text: message };
}));
}, function () {
return stopped;
});
}
function next() {
if (stopped) {
return;
}
var batch = waiting.splice(0, AT_ONCE);
if (!batch.length) {
return;
}
batch.forEach(function (id) {
mark({ asset_id: id, tone: 'info', text: 'Looking it up...' }, false);
});
ask({ csrf_token: csrf, warranty_lookup: 1, asset_ids: batch }, function (json) {
var jobs = {};
json.results.forEach(function (result) {
if (result.pending) {
mark(result, false);
(jobs[result.pending] = jobs[result.pending] || []).push(result.asset_id);
} else {
mark(result, true);
}
});
// An asset ITFlow didn't answer for - one of a client you can't open, or gone
batch.forEach(function (id) {
var answered = json.results.some(function (result) {
return String(result.asset_id) === String(id);
});
if (!answered) {
mark({ asset_id: id, tone: 'secondary', text: 'Not looked up - it isn\'t there, or is a client\'s you can\'t open' }, true);
}
});
Object.keys(jobs).forEach(function (job) {
watch(job, jobs[job]);
});
count();
next();
}, function (message) {
batch.forEach(function (id) {
mark({ asset_id: id, tone: 'danger', text: message }, true);
});
count();
next();
});
}
count();
next();
};
})();