| Server IP : 13.126.101.145 / Your IP : 216.73.217.37 Web Server : Apache/2.4.52 (Ubuntu) System : Linux ip-11-115-0-196 6.8.0-1039-aws #41~22.04.1-Ubuntu SMP Thu Sep 11 10:54:48 UTC 2025 x86_64 User : www-data ( 33) PHP Version : 8.3.17 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /var/www/html/rentals_updated/wp-content/plugins/Vision Link/ |
Upload File : |
<?php
/**
* Fault Report Page with Button Triggered API Call, Token Generation, and Cursor Pagination
*/
if (!defined('ABSPATH')) {
exit;
}
// ✅ WooCommerce Serial Numbers
// function fault_get_woocommerce_serial_numbers() {
// global $wpdb;
// $query = "
// SELECT pm.meta_value AS serial_number
// FROM {$wpdb->postmeta} pm
// INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
// WHERE pm.meta_key = 'equipment_serial_number'
// AND p.post_status = 'publish'
// ";
// return array_unique($wpdb->get_col($query));
// }
// ✅ Generate a New Token on Every API Call
function generate_api_token() {
$token_url = 'https://fedlogin.cat.com/as/token.oauth2'; // Updated token URL
$response = wp_remote_post($token_url, [
'body' => [
'grant_type' => 'client_credentials',
'client_id' => 'visionlink_dlr_J090_2_cc_client',
'client_secret' => 'xPeEMbWFFZ9UjKiBVkcsftksauDH3MqT2lgKtRaUcbG7PAkgD9LdPIj2I1oRk1im'
],
'timeout' => 60,
]);
if (is_wp_error($response)) {
error_log('Token Fetch Error: ' . $response->get_error_message());
return null;
}
$status_code = wp_remote_retrieve_response_code($response);
$body = json_decode(wp_remote_retrieve_body($response), true);
if ($status_code !== 200) {
error_log("Token Error: HTTP $status_code - " . json_encode($body));
return null;
}
return $body['access_token'] ?? null;
}
// ✅ Fetch Fault Data from API with Pagination
function fetch_fault_data_from_api_ajax() {
check_ajax_referer('fetch_fault_nonce', 'nonce');
// Local
// $custom_db = new wpdb('root', '', 'visionlink_db', 'localhost');
// Production
$custom_db = new wpdb('vision', 'Passrms!123', 'visionlink_db', 'localhost');
$api_url = 'https://services.cat.com/catDigital/faultsHistory/v1/faults';
$next_cursor = null;
$fetched_records = 0;
do {
$token = generate_api_token();
if (!$token) {
wp_send_json_error(['message' => 'Failed to generate token']);
}
$url = $api_url;
if ($next_cursor) {
$url .= "?cursor=" . urlencode($next_cursor);
}
$response = wp_remote_get($url, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'timeout' => 60,
]);
if (is_wp_error($response)) {
wp_send_json_error(['message' => 'API Fetch Error: ' . $response->get_error_message()]);
}
$api_data = json_decode(wp_remote_retrieve_body($response), true);
if (empty($api_data['faults'])) {
break;
}
// ✅ Loop Through Faults and Save Only Latest Records
foreach ($api_data['faults'] as $fault) {
$equipment = $fault['equipmentHeader'] ?? [];
$fault_block = $fault['faultBlock'] ?? [];
$serial_number = $equipment['serialNumber'] ?? null;
$make = $equipment['make'] ?? null;
$model = $equipment['model'] ?? null;
$product_family = $equipment['productFamily'] ?? null;
$fault_type = $fault_block['faultType'] ?? null;
$fault_description = $fault_block['faultDescription'] ?? null;
$source_description = $fault_block['sourceDescription'] ?? null;
$fault_received_time = date('Y-m-d H:i:s', strtotime($fault_block['faultReceivedTime'] ?? ''));
$fault_occurred_time = date('Y-m-d H:i:s', strtotime($fault_block['faultOccurredTime'] ?? ''));
$hour_meter = isset($fault['hourMeter']) ? (float)$fault['hourMeter'] : null;
$odometer = isset($fault['odometerInKilometer']) ? (float)$fault['odometerInKilometer'] : null;
// ✅ Check for existing records and insert only latest
$existing_time = $custom_db->get_var($custom_db->prepare(
"SELECT MAX(faultReceivedTime) FROM wp_fault_report WHERE serial_number = %s",
$serial_number
));
if (!$existing_time || $fault_received_time > $existing_time) {
$custom_db->insert('wp_fault_report', [
'serial_number' => $serial_number,
'make' => $make,
'model' => $model,
'product_family' => $product_family,
'faultType' => $fault_type,
'faultDescription' => $fault_description,
'sourceDescription' => $source_description,
'faultReceivedTime' => $fault_received_time,
'faultOccurredTime' => $fault_occurred_time,
'hourMeter' => $hour_meter,
'odometerInKilometer' => $odometer
]);
$fetched_records++;
}
}
$next_cursor = $api_data['nextCursor'] ?? null;
} while ($next_cursor);
wp_send_json_success(['message' => 'Data fetched successfully', 'records' => $fetched_records]);
}
// ✅ Display the Fault Report Page with Button and Latest Data on Load
function fault_report_display_page() {
?>
<div class="wrap table-responsive">
<h1>Fault Report</h1>
<button id="fetch-fault-data" style="margin: 10px; padding: 10px; background: #000; color: #FFBD2B; border: 1px solid #FFBD2B;">
Fetch Fault Data
</button>
<span id="api-response"></span>
<table id="fault-report-table" class="table table-striped table-bordered table-data" style="width:100%">
<thead style="background-color:#FFBD2B;" class="table-dark">
<tr>
<th>Serial Number</th>
<th>Make</th>
<th>Model</th>
<th>Fault Type</th>
<th>Fault Description</th>
<th>Received Date</th>
<th>Occurred Date</th>
</tr>
</thead>
<tbody id="fault-data-tbody">
<?php
global $wpdb;
// Local
// $custom_db = new wpdb('root', '', 'visionlink_db', 'localhost');
// Production
$custom_db = new wpdb('vision', 'Passrms!123', 'visionlink_db', 'localhost');
// ✅ Fetch and display latest data
$results = $custom_db->get_results("SELECT * FROM wp_fault_report ORDER BY faultReceivedTime DESC");
if (!empty($results)) {
foreach ($results as $fault) {
echo '<tr>';
echo '<td>' . esc_html($fault->serial_number ?? '') . '</td>';
echo '<td>' . esc_html($fault->make ?? '') . '</td>';
echo '<td>' . esc_html($fault->model ?? '') . '</td>';
echo '<td>' . esc_html($fault->faultType ?? '') . '</td>';
echo '<td>' . esc_html($fault->faultDescription ?? '') . '</td>';
echo '<td>' . ($fault->faultReceivedTime ? date('d-m-Y', strtotime($fault->faultReceivedTime)) : '') . '</td>';
echo '<td>' . ($fault->faultOccurredTime ? date('d-m-Y', strtotime($fault->faultOccurredTime)) : '') . '</td>';
echo '</tr>';
}
} else {
echo '<tr><td colspan="7" style="text-align:center;">No fault data available</td></tr>';
}
?>
</tbody>
</table>
</div>
<script>
jQuery(document).ready(function($) {
$('#fetch-fault-data').click(function() {
$('#api-response').html('<span style="color:blue; font-weight:bold;">Fetching data... Please wait.</span>');
$.post('<?php echo admin_url('admin-ajax.php'); ?>', {
action: 'fetch_fault_data',
nonce: '<?php echo wp_create_nonce('fetch_fault_nonce'); ?>'
}, function(response) {
if (response.success) {
$('#api-response').html('<span style="color:green; font-weight:bold;">✔ Data fetched successfully</span>');
setTimeout(() => location.reload(), 2000); // Reload after 2 seconds
} else {
$('#api-response').html('<span style="color:red; font-weight:bold;">✖ Error: Api server down ' + response.data.message + '</span>');
}
}).fail(function() {
$('#api-response').html('<span style="color:red; font-weight:bold;">✖ API request failed. Please try again.</span>');
});
});
$('#fault-report-table').DataTable({
"order": [[5, "desc"]], // Sort by "Received Date"
"pageLength": 10
});
});
</script>
<?php
}
// ✅ Register AJAX Actions
add_action('wp_ajax_fetch_fault_data', 'fetch_fault_data_from_api_ajax');
?>