Files
itflow/functions/warranty.php

558 lines
27 KiB
PHP

<?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']];
}