M3 Integration fixes

This commit is contained in:
Mark Gregory
2026-09-21 14:57:06 +01:00
parent 3e714e9568
commit e4213d1fd6
4 changed files with 161 additions and 252 deletions
@@ -59,7 +59,7 @@
<div class="hd-select-wrap shrink-0 md:w-72">
<select
class="hd-select"
aria-label="Select Kanban board"
aria-label="Kanban board"
onchange="window.location.href = '{{ route('helpdesk.kanban') }}?board_id=' + encodeURIComponent(this.value)"
>
@foreach ($boards as $availableBoard)
+159 -249
View File
@@ -6,8 +6,6 @@ use Config;
use DB;
use Http;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Log;
use Modules\M3\Helpers\Helper;
use Modules\M3\Http\Controllers\Controller;
use Str;
@@ -15,262 +13,174 @@ use Str;
class ReplenAPI extends Controller
{
private const ZERO_PAD = '000000';
private const JSON_CONTENT_TYPE = 'application/json';
private const SOURCE = 'M3InventoryReportReplen';
// M3Replenishement with URL Params
public function M3InventoryReportReplen(Request $request)
{
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
// dd($request->all());
// Log::info( $request->all() );
// Get The Calling User
$sHUSER = m3User() !== '' ? Str::upper(m3User()) : 'WebUser';
$mACPKR = isset($mACPKR) ? $mACPKR : self::ZERO_PAD;
$sHSOURCE = 'M3InventoryReportReplen';
$m3Errors = '';
$this->configureTimeouts();
$context = $this->requestContext($request);
try {
// Get Json Contents
$urlParams = count($request->all()) > 0 ? $request->all() : '';
$cO = isset($urlParams['CO']) ? $urlParams['CO'] : '';
$wHS = isset($urlParams['WHS']) ? $urlParams['WHS'] : '';
$pARTNO = isset($urlParams['PARTNO']) ? $urlParams['PARTNO'] : '';
$pKLN = isset($urlParams['PKLN']) ? $urlParams['PKLN'] : '';
$rEQPKWS = isset($urlParams['REQPKWS']) ? $urlParams['REQPKWS'] : '';
$rEQKPKUS = isset($urlParams['REQKPKUS']) ? $urlParams['REQKPKUS'] : 'WebUser';
if ($urlParams != '') {
$incomingParams = ['CO' => $cO, 'WHS' => $wHS, 'PARTNO' => $pARTNO, 'PKLN' => $pKLN, 'REQPKWS' => $rEQPKWS, 'REQKPKUS' => $rEQKPKUS];
$incomingParams = json_encode($incomingParams);
// Write to Logs : Params In
$data = ['SHMACPKR' => $mACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => '', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Req-out',
'SHDATA' => $incomingParams, 'SHUSER' => $sHUSER, 'SHSOURCE' => $sHSOURCE, 'SHCO' => $cO, 'SHWHS' => $wHS];
Helper::logToICM699M($data);
$pART = explode(',', $pARTNO);
foreach ($pART as $value) {
$pARTS[] = ['PART' => $value, 'LOT' => ''];
}
$jSON = json_encode(['WHS' => $wHS, 'PARTS' => $pARTS]);
// Write to Logs : Params Sent To M3
$data = ['SHMACPKR' => $mACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => '', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Req-out',
'SHDATA' => 'Sent To M3-' . $jSON, 'SHUSER' => $sHUSER, 'SHSOURCE' => $sHSOURCE, 'SHCO' => $cO, 'SHWHS' => $wHS];
Helper::logToICM699M($data);
// Get Token
$tokenResponse = Helper::checkReceiveTokenV2();
$tokenData = $tokenResponse->getData();
if ($tokenData->code == '200') {
$ionToken = isset($tokenData->token) ? $tokenData->token : '';
} else {
$sHDATA = isset($tokenData->message) ? $tokenData->message : '';
// Write to Logs : Error
$data = ['SHMACPKR' => $mACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
'SHDATA' => $sHDATA, 'SHUSER' => $sHUSER, 'SHSOURCE' => $sHSOURCE, 'SHCO' => $cO, 'SHWHS' => $wHS];
Helper::logToICM699M($data);
return $tokenResponse;
}
// Call ionapi with Params
$endPointURL = env('ENDPOINTURL') . 'APIFLOWS/Sentinel/M3InventoryReportList?ionapiRespStyle=sync';
$token = $ionToken;
$response = Http::withHeaders([
'accept' => self::JSON_CONTENT_TYPE,
'Content-Type' => self::JSON_CONTENT_TYPE,
])
->withToken($token)
->withBody($jSON, self::JSON_CONTENT_TYPE)
->timeout(Config::get('arrays.curlTimeOut'))
->retry(3, 100)
->post($endPointURL);
$responseStatusCode = $response->getStatusCode();
$m3SessionId = $response->hasHeader('x-transaction-id') ? '-sessionID:' . $response->header('x-transaction-id') : '-sessionID';
if ($responseStatusCode == '200') {
// Check M3 Response for Errors
$m3Errors = '';
$responseJSON = $response->getBody()->getContents();
$jsonSanytized = Helper::sanityzeString($responseJSON);
// Array
$responseArray = json_decode($jsonSanytized, true);
$responseTMP = $responseArray['result'];
} else {
$m3Errors = 'Error: No Response from M3';
}
// Validate response From M3
if ($m3Errors != '') {
// Write to Logs : Error
$data = ['SHMACPKR' => $mACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
'SHDATA' => $responseStatusCode . '-' . $m3Errors . $m3SessionId, 'SHUSER' => $sHUSER, 'SHSOURCE' => $sHSOURCE, 'SHCO' => $cO, 'SHWHS' => $wHS];
Helper::logToICM699M($data);
// Send Response
return response()->json([
'code' => '405',
'status' => 'error',
'message' => 'Error: No Response from M3',
]);
} else {
// Write to Logs : JSON
$data = ['SHMACPKR' => $mACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => '', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
'SHDATA' => $responseStatusCode . '-' . $jsonSanytized . $m3SessionId, 'SHUSER' => $sHUSER, 'SHSOURCE' => $sHSOURCE, 'SHCO' => $cO, 'SHWHS' => $wHS];
Helper::logToICM699M($data);
}
$dataToWrite2 = [];
foreach ($responseTMP as $value) {
$dataToWrite = [];
foreach ($value as $key2 => $content) {
if ($key2 != 'Locations') {
$dataToWrite[$key2] = $content;
} else {
foreach ($content as $content2) {
$dataToWrite2[] = array_merge($dataToWrite, $content2);
}
}
}
}
// Delete Old Records from IC630M
foreach ($dataToWrite2 as $value) {
DB::connection(config('m3.connection', 'pgsql'))->table('ic630m')
->where('LLCO', $cO)
->where('LLWHNO', $wHS)
->where('LLPPN', trim($value['PartNumber']))
->delete();
}
foreach ($dataToWrite2 as $value) {
// Check if Location exist in DE640M $value['Location']
$dE640MSQLSEL = DB::connection(config('m3.connection', 'pgsql'))->table('de640m')
->where('LVCO', $cO)
->where('WSELOC', $value['Warehouse'])
->where('VLOCID', $value['Location'])
->first();
$locationExist = isset($dE640MSQLSEL->VLOCID) ? trim($dE640MSQLSEL->VLOCID) : '';
$wHExist = isset($dE640MSQLSEL->WSELOC) ? trim($dE640MSQLSEL->WSELOC) : '';
$cOExist = isset($dE640MSQLSEL->LVCO) ? trim($dE640MSQLSEL->LVCO) : '';
// if No records Founds insert New Record
if ($locationExist == '' && $wHExist == '' && $cOExist == '') {
$sQLInsertPrep640M['LVCO'] = $cO; // Company
$sQLInsertPrep640M['WSELOC'] = $value['Warehouse'];
// $sQLInsertPrep640M['LVUSD3'] = $value['']; // Pallet Size : Not Found in M3 JSON
$sQLInsertPrep640M['VLOCID'] = $value['Location']; // Stock location
$sQLInsertPrep640M['LVSEQN'] = $value['LocationSeq'];
$sQLInsertPrep640M['LVUSD2'] = $value['LocationType'];
$sQLInsertPrep640M['LVZONE'] = $value['Zone']; // Warehouse zone
$sQLInsertPrep640M['LVMAINTTS'] = now(); // Last maintained time stamp
DB::connection(config('m3.connection', 'pgsql'))->table('de640m')->insert($sQLInsertPrep640M);
}
// Update
else {
$sQLUpdatePrep640M['LVSEQN'] = $value['LocationSeq'];
$sQLUpdatePrep640M['LVUSD2'] = $value['LocationType'];
$sQLUpdatePrep640M['LVZONE'] = $value['Zone'];
$sQLUpdatePrep640M['LVMAINTTS'] = now();
DB::connection(config('m3.connection', 'pgsql'))->table('de640m')
->where('LVCO', $cO)
->where('WSELOC', $value['Warehouse'])
->where('VLOCID', $value['Location'])
->update($sQLUpdatePrep640M);
}
// Insert New Records to IC630M
$sQLInsertPrep630M = [];
$sQLInsertPrep630M['LLCO'] = $cO; // Company
$sQLInsertPrep630M['LLWHNO'] = $value['Warehouse']; // Warehouse
$sQLInsertPrep630M['LLPPN'] = $value['PartNumber']; // Part Number
$sQLInsertPrep630M['LLBALANCE'] = $value['Quantity']; // Quantity
$sQLInsertPrep630M['LLSTLC'] = $value['Location']; // Stock location
$sQLInsertPrep630M['LLLTNO'] = $value['LotNumber']; // Lot Number
$sQLInsertPrep630M['LLMAINTTS'] = now(); // Request time timestamp
$sQLInsertPrep630M['LLIZLCF'] = trim($value['LotNumber']) != '' ? '1' : ''; // Lot control flag
$sQLInsertPrep630M['LLSPR10A01'] = $value['Allocation']; // Allocation
$sQLInsertPrep630M['LLSPR15A01'] = $value['AllocatedTo']; // AllocatedTo
$descSanytized = Helper::sanityzeString($value['Description']);
// $descSanytized = str_replace(['–','\u20131'], '-',$value['Description']);
$sQLInsertPrep630M['LLCMDESC'] = $descSanytized; // Description
DB::connection(config('m3.connection', 'pgsql'))->table('ic630m')->insert($sQLInsertPrep630M);
}
// Send Response
return response()->json([
'code' => '200',
'status' => 'Success',
]);
} else {
// Write to Logs Out : Error
$mACPKR = isset($mACPKR) ? $mACPKR : self::ZERO_PAD;
$data = ['SHMACPKR' => $mACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
'SHDATA' => 'No URL Parameters Sent', 'SHUSER' => $sHUSER, 'SHSOURCE' => $sHSOURCE, 'SHCO' => $cO, 'SHWHS' => $wHS];
Helper::logToICM699M($data);
// Return Error
return response()->json([
'code' => '405',
'status' => 'Error',
'message' => 'No URL Parameters Sent',
]);
if ($context['params'] === []) {
return $this->missingParametersResponse($context);
}
} catch (\Throwable $th) {
// Write to Logs Out : Error
$mACPKR = isset($mACPKR) ? $mACPKR : self::ZERO_PAD;
$getCurlErrors = str_contains($th->getMessage(), 'cURL error');
if ($getCurlErrors) {
// dd($getCurlErrors);
// Write to Logs Out : Failed
$data = ['SHMACPKR' => $mACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
'SHDATA' => 'Curl Error: Communication with M3 Timed Out' . ' M3-JSN-out' . $incomingParams, 'SHUSER' => $sHUSER, 'SHSOURCE' => $sHSOURCE, 'SHCO' => $cO, 'SHWHS' => $wHS];
Helper::logToICM699M($data);
return response()->json([
'code' => '405',
'status' => 'error',
'message' => 'Curl Error: Communication with M3 Timed Out.',
]);
} else {
// Set SHERROR To Z if Duplicate Key Detected $th
// Read The substring from SHDATA after M3-JSN-out
$sHERROR = 'X';
$word = 'Duplicate key value specified';
$position = strpos($th, $word);
if ($position !== false) {
$sHERROR = 'Z';
}
$data = ['SHMACPKR' => $mACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => $sHERROR, 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
'SHDATA' => 'An Error Occured - ' . substr($th, 0, 300), 'SHUSER' => $sHUSER, 'SHSOURCE' => $sHSOURCE, 'SHCO' => $cO, 'SHWHS' => $wHS];
Helper::logToICM699M($data);
return response()->json([
'code' => '405',
'status' => 'error',
'message' => 'Catched Error: ' . $th,
]);
$this->logRequest($context);
$tokenResponse = Helper::checkReceiveTokenV2();
$tokenData = $tokenResponse->getData();
if ((string) ($tokenData->code ?? '') !== '200') {
$this->log($context, (string) ($tokenData->message ?? ''), 'X', 'M3-Res-out');
return $tokenResponse;
}
$result = $this->fetchInventory($context, (string) ($tokenData->token ?? ''));
if ($result['error'] !== '') {
$this->log($context, $result['status'] . '-' . $result['error'] . $result['session'], 'X', 'M3-Res-out');
return response()->json(['code' => '405', 'status' => 'error', 'message' => $result['error']]);
}
$this->log($context, $result['status'] . '-' . $result['json'] . $result['session'], '', 'M3-Res-out');
$rows = $this->flattenInventory($result['result']);
$this->replaceInventory($context, $rows);
return response()->json(['code' => '200', 'status' => 'Success']);
} catch (\Throwable $throwable) {
return $this->exceptionResponse($context, $throwable);
}
}
// End M3InventoryReportReplen
private function configureTimeouts(): void
{
$timeout = Config::get('arrays.PHPTimeOut');
ini_set('max_execution_time', $timeout);
ini_set('max_input_time', $timeout);
ini_set('default_socket_timeout', $timeout);
}
private function requestContext(Request $request): array
{
$params = $request->all();
return [
'params' => $params,
'co' => (string) ($params['CO'] ?? ''),
'whs' => (string) ($params['WHS'] ?? ''),
'partNo' => (string) ($params['PARTNO'] ?? ''),
'pkln' => (string) ($params['PKLN'] ?? ''),
'reqPkws' => (string) ($params['REQPKWS'] ?? ''),
'reqKpkus' => (string) ($params['REQKPKUS'] ?? 'WebUser'),
'user' => m3User() !== '' ? Str::upper(m3User()) : 'WebUser',
'macpkr' => self::ZERO_PAD,
];
}
private function logRequest(array $context): void
{
$incoming = json_encode([
'CO' => $context['co'], 'WHS' => $context['whs'], 'PARTNO' => $context['partNo'],
'PKLN' => $context['pkln'], 'REQPKWS' => $context['reqPkws'], 'REQKPKUS' => $context['reqKpkus'],
]);
$this->log($context, (string) $incoming, '', 'M3-Req-out');
$this->log($context, 'Sent To M3-' . $this->inventoryRequestJson($context), '', 'M3-Req-out');
}
private function inventoryRequestJson(array $context): string
{
$parts = array_map(static fn (string $part): array => ['PART' => $part, 'LOT' => ''], explode(',', $context['partNo']));
return (string) json_encode(['WHS' => $context['whs'], 'PARTS' => $parts]);
}
private function fetchInventory(array $context, string $token): array
{
$response = Http::withHeaders(['accept' => self::JSON_CONTENT_TYPE, 'Content-Type' => self::JSON_CONTENT_TYPE])
->withToken($token)
->withBody($this->inventoryRequestJson($context), self::JSON_CONTENT_TYPE)
->timeout(Config::get('arrays.curlTimeOut'))->retry(3, 100)
->post(env('ENDPOINTURL') . 'APIFLOWS/Sentinel/M3InventoryReportList?ionapiRespStyle=sync');
$status = $response->getStatusCode();
$session = $response->hasHeader('x-transaction-id') ? '-sessionID:' . $response->header('x-transaction-id') : '-sessionID';
if ((string) $status !== '200') {
return ['status' => $status, 'session' => $session, 'error' => 'Error: No Response from M3', 'json' => '', 'result' => []];
}
$json = Helper::sanityzeString($response->getBody()->getContents());
$decoded = json_decode($json, true);
return ['status' => $status, 'session' => $session, 'error' => '', 'json' => $json, 'result' => $decoded['result'] ?? []];
}
private function flattenInventory(array $result): array
{
$rows = [];
foreach ($result as $item) {
$base = array_diff_key($item, ['Locations' => true]);
foreach (($item['Locations'] ?? []) as $location) {
$rows[] = array_merge($base, $location);
}
}
return $rows;
}
private function replaceInventory(array $context, array $rows): void
{
foreach ($rows as $row) {
DB::connection(config('m3.connection', 'pgsql'))->table('ic630m')
->where('LLCO', $context['co'])->where('LLWHNO', $context['whs'])
->where('LLPPN', trim((string) ($row['PartNumber'] ?? '')))->delete();
}
foreach ($rows as $row) {
$this->upsertLocation($context, $row);
$this->insertInventory($context, $row);
}
}
private function upsertLocation(array $context, array $row): void
{
$connection = DB::connection(config('m3.connection', 'pgsql'));
$query = $connection->table('de640m')->where('LVCO', $context['co'])
->where('WSELOC', $row['Warehouse'] ?? '')->where('VLOCID', $row['Location'] ?? '');
$values = ['LVSEQN' => $row['LocationSeq'] ?? '', 'LVUSD2' => $row['LocationType'] ?? '', 'LVZONE' => $row['Zone'] ?? '', 'LVMAINTTS' => now()];
if ($query->exists()) {
$query->update($values);
return;
}
$connection->table('de640m')->insert(array_merge($values, ['LVCO' => $context['co'], 'WSELOC' => $row['Warehouse'] ?? '', 'VLOCID' => $row['Location'] ?? '']));
}
private function insertInventory(array $context, array $row): void
{
DB::connection(config('m3.connection', 'pgsql'))->table('ic630m')->insert([
'LLCO' => $context['co'], 'LLWHNO' => $row['Warehouse'] ?? '', 'LLPPN' => $row['PartNumber'] ?? '',
'LLBALANCE' => $row['Quantity'] ?? 0, 'LLSTLC' => $row['Location'] ?? '', 'LLLTNO' => $row['LotNumber'] ?? '',
'LLMAINTTS' => now(), 'LLIZLCF' => trim((string) ($row['LotNumber'] ?? '')) !== '' ? '1' : '',
'LLSPR10A01' => $row['Allocation'] ?? '', 'LLSPR15A01' => $row['AllocatedTo'] ?? '',
'LLCMDESC' => Helper::sanityzeString((string) ($row['Description'] ?? '')),
]);
}
private function missingParametersResponse(array $context)
{
$this->log($context, 'No URL Parameters Sent', 'X', 'M3-Res-out');
return response()->json(['code' => '405', 'status' => 'Error', 'message' => 'No URL Parameters Sent']);
}
private function exceptionResponse(array $context, \Throwable $throwable)
{
if (str_contains($throwable->getMessage(), 'cURL error')) {
$this->log($context, 'Curl Error: Communication with M3 Timed Out', 'X', 'M3-Res-out');
return response()->json(['code' => '405', 'status' => 'error', 'message' => 'Curl Error: Communication with M3 Timed Out.']);
}
$error = str_contains($throwable->getMessage(), 'Duplicate key value specified') ? 'Z' : 'X';
$this->log($context, 'An Error Occured - ' . substr($throwable->getMessage(), 0, 300), $error, 'M3-Res-out');
return response()->json(['code' => '405', 'status' => 'error', 'message' => 'Catched Error: ' . $throwable->getMessage()]);
}
private function log(array $context, string $message, string $error, string $type): void
{
Helper::logToICM699M([
'SHMACPKR' => $context['macpkr'], 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => $error,
'SHINTBOX' => '', 'SHTYPE' => $type, 'SHDATA' => $message, 'SHUSER' => $context['user'], 'SHSOURCE' => self::SOURCE,
'SHCO' => $context['co'], 'SHWHS' => $context['whs'],
]);
}
}
@@ -68,7 +68,6 @@
</div>
</div>
</div>
<!-- <div class="row g-2 align-items-center mb-2"> -->
</div>
</div>
</div>
+1 -1
View File
@@ -102,7 +102,7 @@
align-items: center;
background: linear-gradient(135deg, rgba(15, 118, 110, 0.14), rgba(37, 99, 235, 0.12));
border-radius: 18px;
color: #064e49;
color: #052f2c;
display: flex;
font-size: 1.35rem;
height: 56px;