Files
WMS/Modules/M3/Http/Controllers/API/CloseShipment.php
T
2026-09-16 17:25:53 +01:00

1081 lines
58 KiB
PHP

<?php
namespace Modules\M3\Http\Controllers\API;
use Config;
use DB;
use File;
use Http;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Log;
use Modules\M3\Helpers\Helper;
use Modules\M3\Http\Controllers\Controller;
use Modules\M3\Http\Controllers\GetContentsController;
use Str;
// use Request;
class CloseShipment extends Controller
{
// CloseShipmentCoChargeAPI : with URL PARAMS COCharge
public static function CloseShipmentCoChargeAPI(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'));
// dump($request->all());
$NODEBUG = true; // ALWAYS set TRUE in Production
$PACKAGES = [];
$JSONCoCharge = [];
$JSONCS = [];
// Get the Calling User
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
$SHSOURCE = 'CloseShipmentCoChargeAPI';
try {
// Get URL PARAMS
$urlParams = count($request->all()) > 0 ? $request->all() : '';
$WHS = isset($urlParams['WHS']) ? $urlParams['WHS'] : '';
$COMPANY = isset($urlParams['COMPANY']) ? $urlParams['COMPANY'] : '';
$MANIFEST = isset($urlParams['MANIFEST']) ? $urlParams['MANIFEST'] : '';
$TRANSTYPE = isset($urlParams['TRANSTYPE']) ? $urlParams['TRANSTYPE'] : 'M'; // M , P , Z
$TRANSTYPE = $TRANSTYPE != '' ? $TRANSTYPE : 'M'; // M , P , Z
$SHDT = isset($urlParams['SHDT']) ? $urlParams['SHDT'] : '';
$SHTIME = isset($urlParams['SHTIME']) ? $urlParams['SHTIME'] : '';
$SHTYPE = isset($urlParams['SHTYPE']) ? $urlParams['SHTYPE'] : '';
$allErrMsgs = '';
$LineAck = [];
// PDF File PATH
$pdfFilePath = Config::get('arrays.PdfPath');
$DELIVERYNO = $MANIFEST != '' ? $MANIFEST : '000000';
// Log::channel('dailyCron')->info("Close Manifest:".$MANIFEST.'-WHS: '.$WHS."-CO:".$COMPANY);
if ($urlParams != '') {
// Write to Logs : JSON
$JSONIN = json_encode([
'WHS' => $WHS,
'COMPANY' => $COMPANY,
'MANIFEST-MACPKR' => $MANIFEST,
'TRANSTYPE' => $TRANSTYPE,
]);
// dd($JSONIN);
$data = [
'SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => '',
'SHINTBOX' => '',
'SHTYPE' => 'M3-Req-out',
'SHDATA' => $JSONIN,
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
// dd($JSONIN);
// Get Token
$tokenResponse = Helper::checkReceiveTokenV2();
$tokenData = $tokenResponse->getData();
// dd($IonToken->code);
if ($tokenData->code == '200') {
$IonToken = isset($tokenData->token) ? $tokenData->token : '';
} else {
$SHDATA = isset($tokenData->message) ? $tokenData->message : '';
$DELIVERYNO = isset($AYMACPKR) ? $AYMACPKR : '000000';
// Write to Logs : Error
$data = [
'SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => 'X',
'SHINTBOX' => '',
'SHTYPE' => 'M3-Res-out',
'SHDATA' => $SHDATA,
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
return $tokenResponse;
}
// Set Endpoint URL
$endPointURL = env('ENDPOINTURL') . 'APIFLOWS/Sentinel/TransferAPI?ionapiRespStyle=sync';
$token = $IonToken;
// Read from ICM695M1
if ($TRANSTYPE == 'M') {
$ICM695M1PREP = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
->select('AYCO', 'AYWHS', 'AYMACPKR', 'AYRLNO', 'AYAPRF1551')
->distinct()
->where('AYCO', $COMPANY)
->where('AYAPRF1551', $MANIFEST)
->where('AYWHS', $WHS)
->orderBy('AYMACPKR');
} elseif ($TRANSTYPE == 'P') {
$ICM695M1PREP = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
->select('AYCO', 'AYWHS', 'AYMACPKR', 'AYRLNO', 'AYAPRF1551')
->distinct()
->where('AYCO', $COMPANY)
->where('AYMACPKR', $MANIFEST)
->where('AYWHS', $WHS)
->orderBy('AYMACPKR');
// Check Date & Time Before Updating ICM699M
if ($SHDT != '' && $SHTIME != '' && $SHTYPE != '' && $NODEBUG) {
$ICM699MU = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
->where('SHMACPKR', $MANIFEST)
->where('SHDT', $SHDT)
->where('SHTIME', $SHTIME)
->where('SHCO', $COMPANY)
->where('SHWHS', $WHS)
->where('SHSOURCE', $SHSOURCE)
->where('SHERROR', 'X')
->where('SHTYPE', $SHTYPE)
->update(['SHERROR' => 'Z', 'SHACKUSER' => $SHUSER, 'SHACKDATE' => date('Y-m-d'), 'SHACKTIME' => date('H:i:s')]);
}
// Get Acknowledged Record for M3-QtyChg PackSyst4tray
$ICM699MQtyChg = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
->select()
->where('SHMACPKR', $MANIFEST)
->where('SHCO', $COMPANY)
->where('SHWHS', $WHS)
->where('SHSOURCE', 'PackSyst4tray')
->where('SHERROR', 'Z')
->where('SHTYPE', 'M3-QtyChg')
->get();
// dd($ICM699MQtyChg);
foreach ($ICM699MQtyChg as $key => $ICM699MQtyChgR) {
$string = $ICM699MQtyChgR->SHDATA;
$start = 'PickerLine:';
$end = ' -';
$LineAck[] = Helper::getSubstringBetween($string, $start, $end);
}
// dd($LineAck);
} elseif ($TRANSTYPE == 'Z') {
$ICM695M1PREP = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->select()
->distinct()
->where('A4CO', $COMPANY)
->where('A4WHS', $WHS)
->where('A4MACPKR', $MANIFEST)
->orderBy('A4MACPKR');
}
$ICM695M1TMP = $ICM695M1PREP->get();
// dump($ICM695M1TMP);
// Log::channel('dailyCron')->info($ICM695M1TMP);
// PFC if MACKPKR already Closed : Case 671
$ICM695M1TMPCOL = collect($ICM695M1TMP);
if ($TRANSTYPE == 'Z') {
$ICM695M1TMPCOLF = $ICM695M1TMPCOL->map(function ($post) {
return trim($post->A4MACPKR);
});
} else {
$ICM695M1TMPCOLF = $ICM695M1TMPCOL->map(function ($post) {
return trim($post->AYMACPKR);
});
}
// dump($ICM695M1TMPCOLF);
$ICM695M1TMPCOLFA = $ICM695M1TMPCOLF->toArray();
// dump($ICM695M1TMPCOLFA);
$ICM699MSuccess = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
->select('SHMACPKR')
->whereIn('SHMACPKR', $ICM695M1TMPCOLFA)
->where('SHCO', $COMPANY)
->where('SHWHS', $WHS)
->where('SHSOURCE', 'CloseShipmentCoChargeAPI')
->where('SHERROR', '')
->where('SHTYPE', 'M3-Res-out')
->where('SHDATA', 'like', '%Success%')
->get();
// dump($ICM699MSuccess);
$ICM699MSuccessCol = collect($ICM699MSuccess);
$ICM699MSuccessColF = $ICM699MSuccessCol->map(function ($post) {
return $post->SHMACPKR;
});
// dump($ICM699MSuccessColF);
$ICM699MSuccessColFAr = $ICM699MSuccessColF->toArray();
if ($TRANSTYPE == 'Z') {
// Use the reject method to remove items based on the condition
$ICM695M1TMPF = $ICM695M1TMP->reject(function ($post) use ($ICM699MSuccessColFAr) {
return in_array($post->A4MACPKR, $ICM699MSuccessColFAr);
});
} else {
// Use the reject method to remove items based on the condition
$ICM695M1TMPF = $ICM695M1TMP->reject(function ($post) use ($ICM699MSuccessColFAr) {
return in_array($post->AYMACPKR, $ICM699MSuccessColFAr);
});
}
$ICM695M1TMP = $ICM695M1TMPF;
// Log::channel('dailyCron')->info($ICM695M1TMP);
// dd($ICM695M1TMP);
$FreightTermsTMP = DB::connection(config('m3.connection', 'pgsql'))->table('icm321m')
->selectRaw('TRIM(ARCODE) as FREIGHTTERMS,ARCHARGE as BILLABLE')
->get();
// Close Shipment for Manifest or Single MacPKR
if (count($ICM695M1TMP) > 0 && ($TRANSTYPE == 'M' || $TRANSTYPE == 'P')) {
// Loop the Results from $ICM595M1TMP
foreach ($ICM695M1TMP as $key => $ICM695M1R) {
$PACKAGES = [];
$AYWHS = trim($ICM695M1R->AYWHS);
$AYCO = trim($ICM695M1R->AYCO);
$AYMACPKR = trim($ICM695M1R->AYMACPKR);
$AYRLNO = trim($ICM695M1R->AYRLNO);
$MANIFEST = trim($ICM695M1R->AYAPRF1551);
// Reset Errors after each Loop
$ErrorMsgs = '';
// Set Endflag for Short pick after each Loop
$EndFlag = 0;
// Precheck All Qty are Equal before Proceeding to Close
// Get Parts And Lots from ICM688M2
$ICM688M2SL = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m2')
->select('A5PART', 'A5PACKED', 'A5PICKED', 'A5PKLN', 'A5RSVQTY')
->distinct()
->where('A5CO', $AYCO)
->where('A5WHS', $AYWHS)
->where('A5MACPKR', $AYMACPKR)
->where('A5RLNO', $AYRLNO)
->orderBy('A5PART')
->get();
// dump($ICM688M2SL);
// Get PACK/Dock from ICM799M
// $ICM799MSEL = DB::connection(config('m3.connection', 'pgsql'))->table('icm799m')
// ->groupBy('IMTOLOC')
// ->select('IMTOLOC',DB::raw('SUM(IMQTY) as IMQTYTOT') )
// ->where('IMDIV',$AYCO)
// ->where('IMWHS',$AYWHS)
// ->where('IMDELNO',$AYMACPKR)
// ->where('IMLINE',$AYRLNO)
// ->whereIn('IMTOLOC',['DOCK','PACK'])
// ->get();
// PFC : Check that Picked / Packed are all Equal
foreach ($ICM688M2SL as $key => $ICM688M2SLR) {
$A5PACKED = isset($ICM688M2SLR->A5PACKED) ? $ICM688M2SLR->A5PACKED : 0;
$A5PICKED = isset($ICM688M2SLR->A5PICKED) ? $ICM688M2SLR->A5PICKED : 0;
$A5PKLN = isset($ICM688M2SLR->A5PKLN) ? $ICM688M2SLR->A5PKLN : 0;
$A5RSVQTY = isset($ICM688M2SLR->A5RSVQTY) ? $ICM688M2SLR->A5RSVQTY : 0;
$A5ShortShipQty = (int) $A5RSVQTY - (int) $A5PICKED;
// Set EndFLag=1 for short picks
if ($A5ShortShipQty > 0) {
$EndFlag = 1;
}
}
// Get TRAILERNUMBER SELECT APTRUCKID FROM ICM705M1 WHERE APCO=110 AND APWHS=321 AND APMANIFEST=22
$TRAILERNUMBERS = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1')
->select('APTRUCKID', 'APTRACKNO', 'APMANIFEST')
->where('APCO', $COMPANY)
->where('APMANIFEST', $MANIFEST)
->where('APWHS', $WHS)
->first();
$TRAILERNUMBER = isset($TRAILERNUMBERS->APTRUCKID) ? trim($TRAILERNUMBERS->APTRUCKID) : '';
$PRONUMBER = isset($TRAILERNUMBERS->APTRACKNO) ? trim($TRAILERNUMBERS->APTRACKNO) : '';
$ICM695M1JOINTMP = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
->selectRAW('AYMACPKR,AYINTBOX,AYHEIGHT,AYWIDTH,AYDEPTH,AYTYPE,AYLNWGHT,AYID,AYSPR1A01,TRIM(AYSPR15A01) AS SCAC , TRIM(AYSPR30A01) AS TRACKING,AYTRUCK AS AGGREGATION,A4RATETCP AS FREIGHT, A4OFSTRM AS FREIGHTTERMS,A4RATEM3,A4CLOSEM3, A4SHIPTYPE, A4REFORD,A4ONO,A4SHIPVIA,A42SSVCNAM,A4SHIPVIA1')
->leftJoin('ICM688M1', function ($join) {
$join->on('AYCO', '=', 'A4CO');
$join->on('AYWHS', '=', 'A4WHS');
$join->on('AYMACPKR', '=', 'A4MACPKR');
})
->where('AYMACPKR', $AYMACPKR)
->where('AYCO', $AYCO)
->where('AYWHS', $AYWHS)
->orderBy('AYINTBOX')
->get();
// dd($ICM695M1JOINTMP);
foreach ($ICM695M1JOINTMP as $key => $ICM695M1JOINR) {
$A4SHIPVIA = isset($ICM695M1JOINR->A4SHIPVIA) ? trim(str_replace('&', '_', $ICM695M1JOINR->A4SHIPVIA)) : '';
$SHIPTYPE = trim($ICM695M1JOINR->A4SHIPTYPE);
$A42SSVCNAM = trim($ICM695M1JOINR->A42SSVCNAM);
$A4SHIPVIA1 = trim($ICM695M1JOINR->A4SHIPVIA1);
$FREIGHTTERMS = trim($ICM695M1JOINR->FREIGHTTERMS);
$A4RATEM3 = trim($ICM695M1JOINR->A4RATEM3);
$FREIGHT = trim($ICM695M1JOINR->FREIGHT);
$A4REFORD = trim($ICM695M1JOINR->A4REFORD);
$A4ONO = trim($ICM695M1JOINR->A4ONO);
$AYMACPKR = trim($ICM695M1JOINR->AYMACPKR);
$AYINTBOX = trim($ICM695M1JOINR->AYINTBOX);
$A4CLOSEM3 = trim($ICM695M1JOINR->A4CLOSEM3);
$TRACKING = trim($ICM695M1JOINR->TRACKING);
$SCAC = trim($ICM695M1JOINR->SCAC);
$CARRIER = '';
$AYTYPE = trim($ICM695M1JOINR->AYID) != '' ? trim($ICM695M1JOINR->AYID) : '';
$AYLNWGHT = trim($ICM695M1JOINR->AYLNWGHT);
$AYHEIGHT = trim($ICM695M1JOINR->AYHEIGHT);
$AYWIDTH = trim($ICM695M1JOINR->AYWIDTH);
$AYDEPTH = trim($ICM695M1JOINR->AYDEPTH);
$BILLOFLADING = isset($ICM695M1JOINR->AYSPR1A01) ? trim($ICM695M1JOINR->AYSPR1A01) : '';
$TRANSPORTMODE = $A4SHIPVIA;
$SERVICETYPE = $A4SHIPVIA;
// Get Carrier Name from ICM160M
if ($SCAC != '') {
$SCACSub = substr($SCAC, 0, 4);
$ICM160M = DB::connection(config('m3.connection', 'pgsql'))->table('icm160m')
->select('CANAM')
->where('CANUM', $SCACSub)
->where('CACO', $COMPANY)
->first();
$CARRIER = isset($ICM160M->CANAM) ? trim(str_replace('&', '_', $ICM160M->CANAM)) : '';
}
// PFC Check BOL for LTL
if ($SHIPTYPE == 'LTL') {
$ErrorMsgs = $BILLOFLADING == '' || $SCAC == '' || $TRACKING == '' ?
$ErrorMsgs . " Missing one or more of tracking number, BOL, or carrier. Please enter this data manually in 'invoicing' screen and retry this API call;" : $ErrorMsgs . '';
} else {
$ErrorMsgs = $SCAC == '' || $TRACKING == '' ?
$ErrorMsgs . " Missing one or more of tracking number, BOL, or carrier. Please enter this data manually in 'invoicing' screen and retry this API call; " : $ErrorMsgs . '';
}
if ($PRONUMBER == '' && $SCAC == 'RETR') {
$ErrorMsgs = $ErrorMsgs . ' Missing PARS info for this RETRans order. Please contact MPBA to ask them to enter the value for you, and then you can retry; ';
}
// MAK : PFC Check for GS1-Label A1SPR1A01 in ICM666M and ICM695M3
$GS1Label = '';
// First Check if GS1 Label is required in ICM666M
$ICM666MSQLSel = DB::connection(config('m3.connection', 'pgsql'))->table('icm666m')
->select('A1SPR1A01')
->where('A1CO', $AYCO)
->where('A1WHS', $AYWHS)
->where('A1DELNO', $AYMACPKR)
->first();
$GS1LabelExist = isset($ICM666MSQLSel->A1SPR1A01) ? trim($ICM666MSQLSel->A1SPR1A01) : 0;
// Case #566: BOL = PRONUMBER For SCAC=='RETR'
if ($SCAC == 'RETR') {
$BILLOFLADING = $PRONUMBER;
}
// Get Commodities
$myRequest = new Request;
$myRequest->setMethod('POST');
$myRequest->request->add([
'MACPKR' => $AYMACPKR,
]);
// Call processShipment
$controller = new GetContentsController;
$response = $controller->processShipment($myRequest);
$responseData = $response->getData();
$error = isset($responseData->error) ? $responseData->error : '';
if ($error == '') {
// $commodities = json_encode($responseData->commodities);
// Get Commodities
$commoditiesTmp = isset($responseData->commodities) ? $responseData->commodities : '';
if ($commoditiesTmp != '') {
$commodities = $commoditiesTmp; // json_encode($commoditiesTmp);
// dump( $commodities);
} else {
$commodities = '';
$ErrorMsgs = $ErrorMsgs . ' Could not find Commodities; ';
}
} else {
$commodities = '';
$ErrorMsgs = $ErrorMsgs . ' Could not find Commodities; ';
}
// End Commodities
// Check ICM699M for SHERROR=X
$ICM699MS = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
->select('SHMACPKR')
->where('SHMACPKR', $AYMACPKR)
->where('SHCO', $AYCO)
->where('SHWHS', $AYWHS)
->whereIn('SHSOURCE', ['TransferAPIURL', 'CloseShipmentCoChargeAPI', 'PackSyst4tray'])
->where('SHERROR', 'X')
->whereIn('SHTYPE', ['M3-Res-out', 'M3-QtyChg'])
->first();
$AlreadySentToM3 = isset($ICM699MS->SHMACPKR) ? trim($ICM699MS->SHMACPKR) : '';
// dump($AlreadySentToM3);
if ($AlreadySentToM3 != '') {
// Add Message
$ErrorMsgs = $ErrorMsgs . ' There are previous M3 transmissions in error for this delivery note that have not been addressed; ';
}
if ($AYTYPE == '') {
// Get AETYPE SELECT APTRUCKID FROM ICM705M1 WHERE APCO=110 AND APWHS=321 AND APMANIFEST=22
$ICM693MS = DB::connection(config('m3.connection', 'pgsql'))->table('icm693m')
->select('AEID')
->where('AESPR1A01', 'D')
->where('AETYPE', trim($ICM695M1JOINR->AYTYPE))
->first();
$AYTYPE = isset($ICM693MS->AEID) ? trim($ICM693MS->AEID) : '';
}
$CurrentFreightTerms = $FreightTermsTMP->where('FREIGHTTERMS', $FREIGHTTERMS)->first();
$BILLABLE = isset($CurrentFreightTerms->BILLABLE) ? trim($CurrentFreightTerms->BILLABLE) : 'N';
// If billable=Y and a4ratetcp(FREIGHT)>0 and a4ratem3=blank, then call the freight API CoCharge
if ($BILLABLE == 'Y' && $FREIGHT > 0 && $A4RATEM3 == '') {
$DELIVERYNO = isset($AYMACPKR) ? $AYMACPKR : '000000';
if ($SHIPTYPE == 'LTL') {
$shippingToBill = $FREIGHT * (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL')) / 100;
} else {
$shippingToBill = $FREIGHT * (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel')) / 100;
}
// Construct Json for COCharge
$JSONCoCharge = [
'QUANTITY' => round($shippingToBill, 2), // $FREIGHT with modified Params
'ORDERCATEGORY' => $A4REFORD,
'CONUMBER' => $A4ONO,
];
} else {
$JSONCoCharge = [];
}
// If billable=Y and a4ratetcp(FREIGHT)=0 and a4ratem3=blank, then we need to:
// Write a record to ICM699M to indicate that we are not calling the rate API because the $ are 0
if ($BILLABLE == 'Y' && $FREIGHT == 0 && $A4RATEM3 == '') {
// Add Message
$ErrorMsgs = $ErrorMsgs . ' Please manually add a freight charge for this Prepaid and Add order; ';
}
// Close Shipment
// If ( (billable=Y and a4RATEM3 (from array in memory)="X") OR (billable=N) ) and a4closeM3="" then call the close API
// Set PDF URLs for Labels
$CarrierLabel = '';
$ContentLabel = '';
$docTypes = ['ContentLabel', 'CarrierLabel'];
foreach ($docTypes as $key => $value) {
switch ($value) {
case 'CarrierLabel':
$DOCTYPE = 'CarrierLabel';
$DOCNUMT = $AYINTBOX;
$PDFKey = $value . '/' . $value . '_' . $AYMACPKR . '_' . $DOCNUMT . '_' . $COMPANY . '_' . $WHS;
$pdfFileName = $pdfFilePath . $PDFKey . '.pdf';
// dd($pdfFileName);
if (File::exists($pdfFileName)) {
$CarrierLabel = route('m3.M3GetPDFFromCache.index', ['MACPKR' => $AYMACPKR, 'DOCTYPE' => $DOCTYPE]);
}
break;
case 'ContentLabel':
$DOCTYPE = 'ContentLabel';
$DOCNUMT = $AYINTBOX;
$PDFKey = $value . '/' . $value . '_' . $AYMACPKR . '_' . $DOCNUMT . '_' . $COMPANY . '_' . $WHS;
$pdfFileName = $pdfFilePath . $PDFKey . '.pdf';
// dd($pdfFileName);
if (File::exists($pdfFileName)) {
$ContentLabel = route('m3.M3GetPDFFromCache.index', ['MACPKR' => $AYMACPKR, 'DOCTYPE' => $DOCTYPE]);
}
break;
}
}
// Second Check GS1 Label existence in ICM695M3
if ($GS1LabelExist == 1) {
$ICM695M3SQLSel = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m3')
->select('A2GS1LABEL')
->where('A2CO', $AYCO)
->where('A2WHS', $AYWHS)
// ->where('A2MACPKR',$AYMACPKR)
->where('A2INTBOX', $AYINTBOX)
->first();
$GS1Label = isset($ICM695M3SQLSel->A2GS1LABEL) ? trim($ICM695M3SQLSel->A2GS1LABEL) : '';
if ($GS1Label == '') {
$ErrorMsgs = $ErrorMsgs . ' Missing G1-128 Label. Please contact MPBA to ask them to enter the value for you, and then you can retry; ';
}
}
// Get Packages Array
$PACKAGES[] = [
'TRACKINGID' => $TRACKING,
'BUNDLES' => $AYTYPE,
'WEIGHT' => $AYLNWGHT,
'HEIGHT' => $AYHEIGHT,
'WIDTH' => $AYWIDTH,
'LENGTH' => $AYDEPTH,
'SSCC' => $GS1Label,
'SHIPLABELDOC' => $CarrierLabel,
'CONTENTLABELDOC' => $ContentLabel,
];
}
// dump($PACKAGES);
// Check Packages array before proceeding with CloseShipment
if (count($PACKAGES) > 0) {
// Get Packlist
$PackingList = '';
$DOCTYPE = 'PackingList';
$DOCNUMT = $AYMACPKR;
$PDFKey = $DOCTYPE . '/' . $DOCTYPE . '_' . $AYMACPKR . '_' . $DOCNUMT . '_' . $COMPANY . '_' . $WHS;
$pdfFileName = $pdfFilePath . $PDFKey . '.pdf';
// dd($pdfFileName);
if (File::exists($pdfFileName)) {
$PackingList = route('m3.M3GetPDFFromCache.index', ['MACPKR' => $AYMACPKR, 'DOCTYPE' => $DOCTYPE]);
}
// dd($PackingList);
// Add Cocharge
if (count($JSONCoCharge) > 0) {
// Construct Json for CloseShipment With PDF Files
$tempClose = [
'DIVI' => $AYCO,
'WHS' => $AYWHS,
'DELIVERYNO' => $AYMACPKR,
'PICKLISTSUFFIX' => $AYRLNO,
'TYPE' => 'CloseShipment',
'SCAC' => $SCAC,
'CARRIER' => $CARRIER,
'TRANSPORTMODE' => $TRANSPORTMODE,
'SERVICETYPE' => $SERVICETYPE,
'TRACKINGNUMBER' => $TRACKING,
'PRONUMBER' => $PRONUMBER,
'BILLOFLADING' => $BILLOFLADING,
'TRAILERNUMBER' => $TRAILERNUMBER,
'PACKAGES' => $PACKAGES,
'DELIVERYNOTEDOC' => $PackingList,
'shipType' => $SHIPTYPE,
'carrierServiceDescription' => $A42SSVCNAM,
'modeOfTransport' => $A4SHIPVIA1,
'COMMODITIES' => $commodities,
'ENDFLAG' => $EndFlag,
];
$JSONCoChargeCS = array_merge($JSONCoCharge, $tempClose);
$JSONCS = json_encode($JSONCoChargeCS);
} else {
// Construct Json for CloseShipment With PDF Files
$JSONCS = json_encode([
'DIVI' => $AYCO,
'WHS' => $AYWHS,
'DELIVERYNO' => $AYMACPKR,
'PICKLISTSUFFIX' => $AYRLNO,
'TYPE' => 'CloseShipment',
'SCAC' => $SCAC,
'CARRIER' => $CARRIER,
'TRANSPORTMODE' => $TRANSPORTMODE,
'SERVICETYPE' => $SERVICETYPE,
'TRACKINGNUMBER' => $TRACKING,
'PRONUMBER' => $PRONUMBER,
'BILLOFLADING' => $BILLOFLADING,
'TRAILERNUMBER' => $TRAILERNUMBER,
'PACKAGES' => $PACKAGES,
'DELIVERYNOTEDOC' => $PackingList,
'ServiceType' => $SHIPTYPE,
'ServiceLevelCode' => $A42SSVCNAM,
'TransportationMode' => $A4SHIPVIA1,
'COMMODITIES' => $commodities,
'ENDFLAG' => $EndFlag,
]);
}
// dump($JSONCS);
// No Errors Proceed in Calling M3 CLose API
if ($ErrorMsgs == '') {
// Write to Logs Out : Send JSON Request To M3
$DELIVERYNO = isset($AYMACPKR) ? $AYMACPKR : '000000';
// dump($DELIVERYNO);
// MAK : Log JSON Manifest # and MACKPKR #
// Log::channel('dailyCron')->info('1 >>> JSON Sent for Manifest: '.$MANIFEST.' ,Macpicker: '.$AYMACPKR);
Log::channel('dailyCron')->info('1 >>> JSON Sent for Manifest: ' . (string) (int) $MANIFEST . ' ,Macpicker: ' . $AYMACPKR);
$data = [
'SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => '',
'SHINTBOX' => '',
'SHTYPE' => 'M3-JSN-out',
'SHDATA' => $JSONCS,
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
$response = Http::withHeaders([
'accept' => 'application/json',
'Content-Type' => 'application/json',
'Connection' => 'close',
])
->withToken($token)
->withBody($JSONCS, 'application/json')
->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';
$responseJSON = $response->getBody()->getContents();
$JsonSanytized = Helper::sanityzeString($responseJSON);
$responseContents = json_decode($JsonSanytized);
// MAK : Add response Time
// $M3ResponseTimeTmp = $response->hasHeader('x-response-time') ? ltrim($response->header('x-response-time'),"-") : '';
// $M3ResponseTimeTmp2 = $M3ResponseTimeTmp /1000;
// $dateTime = new DateTime();
// $dateTime->setTimestamp($M3ResponseTimeTmp2);
// // dump( $dateTime->format('d/m/Y H:i:s.v') );
// $M3ResponseTime = $M3ResponseTimeTmp != '' ? '-M3ResponseTime:' . $dateTime->format('d/m/Y H:i:s.v') : '-M3ResponseTime';
// // dump($M3ResponseTime);
// $transferStats = $response->transferStats;
// $M3transferTime = $transferStats->getTransferTime()!=null ? "-M3transferTime:".$transferStats->getTransferTime() : "-M3transferTime";
// dd($M3transferTime);
// Log M3 response
Log::channel('dailyCron')->info('2 >>> Close API M3 Responded...');
if ($responseContents != null && $responseStatusCode == '200') {
$responseMsg = $responseContents->result->CloseShipment;
$M3APIRESULT = $responseMsg->PickingListClose->Result;
$M3APIRESULTMsg = isset($responseMsg->PickingListClose->ErrorMessage) ? $responseMsg->PickingListClose->ErrorMessage : '';
// Check M3 Response for Errors
$responseResult = $responseContents->result;
$M3Errors = Helper::checkM3Errors($responseResult);
// dd($M3Errors);
// If you get a successful response, update database file ICM688M1/A4RATEm3=X
// Update ICM688M1 : Change A4RATEM3
if (count($JSONCoCharge) > 0 && $M3APIRESULT != 'Error') {
DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->where('A4MACPKR', $AYMACPKR)
->where('A4CO', $AYCO)
->where('A4WHS', $AYWHS)
->update(['A4RATEM3' => 'X', 'A4PICKSTS' => 'A']);
} elseif (count($JSONCoCharge) == 0 && $M3APIRESULT != 'Error') {
// Update ICM688M1 : Change A4RATEM3
DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->where('A4MACPKR', $AYMACPKR)
->where('A4CO', $AYCO)
->where('A4WHS', $AYWHS)
->update(['A4PICKSTS' => 'A']);
}
} else {
$M3APIRESULT = 'Error';
$responseMsg = 'M3 API responded with null value';
$M3APIRESULTMsg = 'M3 API responded with null value';
$responseResult = '';
$M3Errors = $responseStatusCode;
}
// If you get a successful response
if ($M3APIRESULT != 'Error') {
// Write to Logs Out : Success
$DELIVERYNO = isset($AYMACPKR) ? $AYMACPKR : '000000';
$data = [
'SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => '',
'SHINTBOX' => '',
'SHTYPE' => 'M3-Res-out',
'SHDATA' => 'Success...' . json_encode($responseResult) . $M3SessionId,
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
}
// If you get a failure, write a record to ICM699M to indicate that the CLOSE API call failed
else {
// Update ICM688M1 : Change A4PICKSTS
DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->where('A4MACPKR', $AYMACPKR)
->where('A4CO', $AYCO)
->where('A4WHS', $AYWHS)
->update(['A4PICKSTS' => 'a']);
// Write to Logs Out : Error
$DELIVERYNO = isset($AYMACPKR) ? $AYMACPKR : '000000';
$data = [
'SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => 'X',
'SHINTBOX' => '',
'SHTYPE' => 'M3-Res-out',
'SHDATA' => 'Important-Error: ' . $M3Errors . json_encode($responseMsg) . $M3SessionId,
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
// Add Message
$ErrorMsgs = $ErrorMsgs . $M3Errors . ' ';
}
}
// Errors found Log to ICM699M and update A4PICKSTS
else {
// Write to Logs : Error
// Clear Duplicate messages
$ErrorMsgsC = Helper::removeDuplicateSubstrings($ErrorMsgs);
$DELIVERYNO = isset($AYMACPKR) ? $AYMACPKR : '000000';
$data = [
'SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => 'X',
'SHINTBOX' => '',
'SHTYPE' => 'M3-Res-out',
'SHDATA' => $ErrorMsgsC,
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
}
}
$allErrMsgs = $allErrMsgs . $ErrorMsgs;
}
// Update ICM699M : Look for CommTCP_read and set SHERROR to Z Case # 580
$SHACKNOTE = 'Sentinel automatically closed the error (false positive CommTCP_read)';
$ICM699MUZ = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
->where('SHMACPKR', $AYMACPKR)
->where('SHCO', $COMPANY)
->where('SHWHS', $WHS)
->where('SHSOURCE', $SHSOURCE)
->where('SHERROR', 'X')
->where('SHTYPE', 'M3-General')
->where('SHDATA', 'like', '%CommTCP_read%')
->update(['SHERROR' => 'Z', 'SHACKUSER' => $SHUSER, 'SHACKDATE' => date('Y-m-d'), 'SHACKTIME' => date('H:i:s'), 'SHACKNOTE' => $SHACKNOTE]);
// Update ICM705M1 to say that we have processed this manifest (set APSPARE2='X' )
if ($TRANSTYPE == 'M') {
$ICM705M1U = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1')
->where('APMANIFEST', $MANIFEST)
->where('APCO', $COMPANY)
->where('APWHS', $WHS)
->update(['APSPARE2' => 'X']);
}
// Send Response
if ($allErrMsgs == '') {
return response()->json([
'code' => '200',
'status' => 'Success',
'message' => 'All Operations Successful',
]);
} else {
$allErrMsgsC = Helper::removeDuplicateSubstrings($allErrMsgs);
return response()->json([
'code' => '206',
'status' => 'Success With Warnings',
'message' => $allErrMsgsC . '; Check Transaction Logs for Errors or Warnings.',
]);
}
}
// Close Shipment for Zero Picks
elseif (count($ICM695M1TMP) > 0 && $TRANSTYPE == 'Z') {
// dd($ICM695M1TMP);
$ErrorMsgs = '';
foreach ($ICM695M1TMP as $key => $ICM695M1JOINR) {
$SHIPTYPE = trim($ICM695M1JOINR->A4SHIPTYPE);
$FREIGHTTERMS = trim($ICM695M1JOINR->A4OFSTRM);
$A4RATEM3 = trim($ICM695M1JOINR->A4RATEM3);
$FREIGHT = trim($ICM695M1JOINR->A4RATETCP);
$A4REFORD = trim($ICM695M1JOINR->A4REFORD);
$A4ONO = trim($ICM695M1JOINR->A4ONO);
$AYMACPKR = trim($ICM695M1JOINR->A4MACPKR);
$A4CLOSEM3 = trim($ICM695M1JOINR->A4CLOSEM3);
$AYWHS = trim($ICM695M1JOINR->A4WHS);
$AYCO = trim($ICM695M1JOINR->A4CO);
// dump($AYMACPKR);
// Construct Json for CloseShipment Without PDF Files
$JSONCS = json_encode([
'DIVI' => $AYCO,
'WHS' => $AYWHS,
'DELIVERYNO' => $AYMACPKR,
'TYPE' => 'CloseShipment',
'PICKLISTSUFFIX' => '1',
'ENDFLAG' => '1',
]);
// Write to Logs Out : JSON Request To M3
$DELIVERYNO = isset($AYMACPKR) ? $AYMACPKR : '000000';
$data = [
'SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => '',
'SHINTBOX' => '',
'SHTYPE' => 'M3-JSN-out',
'SHDATA' => $JSONCS,
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
$response = Http::withHeaders([
'accept' => 'application/json',
'Content-Type' => 'application/json',
'Connection' => 'close',
])
->withToken($token)
->withBody($JSONCS, 'application/json')
->timeout(Config::get('arrays.curlTimeOut'))
->retry(2, 100)
->post($endPointURL);
$responseContents = json_decode($response->getBody()->getContents());
$M3SessionId = $response->hasHeader('x-transaction-id') ? '-sessionID:' . $response->header('x-transaction-id') : '-sessionID';
$M3Errors = '';
if ($responseContents != null) {
$responseMsg = $responseContents->result->CloseShipment;
$M3APIRESULT = $responseMsg->PickingListClose->Result;
$M3APIRESULTMsg = isset($responseMsg->PickingListClose->ErrorMessage) ? $responseMsg->PickingListClose->ErrorMessage : '';
// Check M3 Response for Errors
$responseResult = $responseContents->result;
$M3Errors = Helper::checkM3Errors($responseResult);
// If you get a successful response, update database file ICM688M1/A4PICKSTS=A
if ($M3APIRESULT != 'Error') {
// Update ICM688M1 : Change A4RATEM3
DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->where('A4MACPKR', $AYMACPKR)
->where('A4CO', $AYCO)
->where('A4WHS', $AYWHS)
->where('A4PICKSTS', '!=', 'X')
->update(['A4PICKSTS' => 'A']);
}
} else {
$M3APIRESULT = 'Error';
$responseMsg = 'M3 API responded with null value';
$M3APIRESULTMsg = 'M3 API responded with null value';
}
// If you get a successful response
if ($M3APIRESULT != 'Error') {
// Write to Logs Out : Success
$DELIVERYNO = isset($AYMACPKR) ? $AYMACPKR : '000000';
$data = [
'SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => '',
'SHINTBOX' => '',
'SHTYPE' => 'M3-Res-out',
'SHDATA' => 'Success' . $M3SessionId,
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
}
// If you get a failure, write a record to ICM699M to indicate that the CLOSE API call failed
else {
// Update ICM688M1 : Change A4PICKSTS
DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->where('A4MACPKR', $AYMACPKR)
->where('A4CO', $AYCO)
->where('A4WHS', $AYWHS)
->where('A4PICKSTS', '!=', 'X')
->update(['A4PICKSTS' => 'a']);
// Write to Logs Out : Error
$DELIVERYNO = isset($AYMACPKR) ? $AYMACPKR : '000000';
$data = [
'SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => 'X',
'SHINTBOX' => '',
'SHTYPE' => 'M3-Res-out',
'SHDATA' => 'Important-Error: ' . $M3Errors . json_encode($responseMsg) . $M3SessionId,
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
// dump($data);
Helper::logToICM699M($data);
// Add Message
$ErrorMsgs = $ErrorMsgs . $M3Errors . '-';
}
// Update ICM699M : Look for CommTCP_read and set SHERROR to Z Case # 580
$SHACKNOTE = 'Sentinel automatically closed the error (false positive CommTCP_read)';
$ICM699MUZ = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
->where('SHMACPKR', $AYMACPKR)
->where('SHCO', $COMPANY)
->where('SHWHS', $WHS)
->where('SHSOURCE', $SHSOURCE)
->where('SHERROR', 'X')
->where('SHTYPE', 'M3-General')
->where('SHDATA', 'like', '%CommTCP_read%')
->update(['SHERROR' => 'Z', 'SHACKUSER' => $SHUSER, 'SHACKDATE' => date('Y-m-d'), 'SHACKTIME' => date('H:i:s'), 'SHACKNOTE' => $SHACKNOTE]);
}
// Send Response
if ($ErrorMsgs == '') {
return response()->json([
'code' => '200',
'status' => 'Success',
'message' => 'All Operations Successful',
]);
} else {
return response()->json([
'code' => '206',
'status' => 'Success With Warnings',
'message' => $ErrorMsgs . '; Check The Logs for Errors or Warnings.',
]);
}
}
// ## End Zero Pick
else {
$DELIVERYNO = isset($MANIFEST) ? $MANIFEST : '000000';
// # Set SHDATA Message
$SHDATAMSG = 'No records found in ICM695M1,or URL parameters incomplete';
// count($ICM695M1TMP)==0 ? 'MacPkr already closed' :
$SHERROR = 'X';
// count($ICM695M1TMP)==0 ? 'Z' :
// Write to Logs Out : Error
$data = [
'SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => $SHERROR,
'SHINTBOX' => '',
'SHTYPE' => 'M3-Req-out',
'SHDATA' => $SHDATAMSG,
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
// Return Error
return response()->json([
'code' => '405',
'status' => 'Error',
'message' => 'No records found in ICM695M1,or URL parameters incomplete For MacPkr/Manifest:' . $DELIVERYNO,
]);
}
} else {
// Write to Logs Out : Error
$DELIVERYNO = isset($AYMACPKR) ? $AYMACPKR : '000000';
$data = [
'SHMACPKR' => $DELIVERYNO,
'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' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
// Return Error
return response()->json([
'code' => '405',
'status' => 'Error',
'message' => 'No URL Parameters Sent',
]);
}
} catch (\Throwable $th) {
// Log::error($th);
$getCurlErrors = str_contains($th->getMessage(), 'cURL error');
if ($getCurlErrors) {
// dd($getCurlErrors);
// Write to Logs Out : Failed
$data = [
'SHMACPKR' => $DELIVERYNO,
'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' . $JSONIN,
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
return response()->json([
'code' => '405',
'status' => 'error',
'message' => 'Curl Error: Communication with M3 Timed Out.',
]);
} else {
// Write to Logs Out : Error
$DELIVERYNO = isset($AYMACPKR) ? $AYMACPKR : '000000';
$data = [
'SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => 'X',
'SHINTBOX' => '',
'SHTYPE' => 'M3-Res-out',
'SHDATA' => 'An Error Occured - ' . substr($th, 0, 300),
'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE,
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
Log::error($th);
return response()->json([
'code' => '405',
'status' => 'error',
'message' => 'Catched Error: ' . $th,
]);
}
}
}
// End CloseShipmentCoChargeAPI
}