m3 Security Fixes

This commit is contained in:
Mark Gregory
2026-09-16 17:16:25 +01:00
parent d68687f062
commit 8f37245e13
64 changed files with 4247 additions and 4426 deletions
+71 -72
View File
@@ -2,96 +2,95 @@
// M3 now uses Core's PostgreSQL connection. No per-user DB credentials are required. // M3 now uses Core's PostgreSQL connection. No per-user DB credentials are required.
return [ return [
#'nonWorkingHourCode' => ['73,85,89,90,91,92,86,99'], // 'nonWorkingHourCode' => ['73,85,89,90,91,92,86,99'],
'autorefresh_all' => ['00:15'], 'autorefresh_all' => ['00:15'],
'autorefresh_notall' => ['00:15'], 'autorefresh_notall' => ['00:15'],
'payrollCodes' => ['33,49,75,94,98,102,171'], 'payrollCodes' => ['33,49,75,94,98,102,171'],
'min_work_hours_for_break' => ['4'], 'min_work_hours_for_break' => ['4'],
'ignore_picks_that_last_longer_than_this_many_hours' => ['8'], 'ignore_picks_that_last_longer_than_this_many_hours' => ['8'],
'env_ports' => ['test'=>'10004','live'=>'10005'], 'env_ports' => ['test' => '10004', 'live' => '10005'],
'hold_code_array' => ['A'=>'Admin Hold', 'hold_code_array' => ['A' => 'Admin Hold',
'C'=>'AR Past Due', 'C' => 'AR Past Due',
'D'=>'Over Credit Limit', 'D' => 'Over Credit Limit',
'E'=>'Over Order Limit', 'E' => 'Over Order Limit',
'F'=>'Address Check Fail', 'F' => 'Address Check Fail',
'Q'=>'Quote Hold', 'Q' => 'Quote Hold',
'H'=>'A/R Cust Hold', 'H' => 'A/R Cust Hold',
'I'=>'EDI Hold', 'I' => 'EDI Hold',
'P'=>'EDI Price Hold', 'P' => 'EDI Price Hold',
'Z'=>'Haz Hold', 'Z' => 'Haz Hold',
'X'=>'CID Hold', 'X' => 'CID Hold',
'W'=>'Web Hold', 'W' => 'Web Hold',
'T'=>'Duplicate Hold'], 'T' => 'Duplicate Hold'],
'user_array' => '', //$user_array, 'user_array' => '', // $user_array,
'misc' => [ 'misc' => [
'discountCarrierRateForCustomerPriceLTL'=>0.00, # This is the percent off list that we want to charge customers 'discountCarrierRateForCustomerPriceLTL' => 0.00, // This is the percent off list that we want to charge customers
'discountCarrierRateForCustomerPriceParcel'=>0.00, # This is the percent off list that we want to charge customers - to use in ship confirm 'discountCarrierRateForCustomerPriceParcel' => 0.00, // This is the percent off list that we want to charge customers - to use in ship confirm
], ],
'transxTypes' =>[ 'transxTypes' => [
'ICM710E' => 'Splitting delivery orders', 'ICM710E' => 'Splitting delivery orders',
'ICM710E13' => 'Pre-Splitting interco delivery orders', 'ICM710E13' => 'Pre-Splitting interco delivery orders',
'ICM710E12' => 'Pre-Splitting customer delivery orders', 'ICM710E12' => 'Pre-Splitting customer delivery orders',
'M3InventoryReportListURL' => 'Retrieve inventory on hand', 'M3InventoryReportListURL' => 'Retrieve inventory on hand',
'M3InventoryReportReplen' => 'Retrieve Replenishments', 'M3InventoryReportReplen' => 'Retrieve Replenishments',
'M3ReceiverAPI' => 'Post Splitting delivery orders', 'M3ReceiverAPI' => 'Post Splitting delivery orders',
'PdfStorageAPI' => 'PDF document storage', 'PdfStorageAPI' => 'PDF document storage',
'PackSyst4tray' => 'Change of qty picked after picking', 'PackSyst4tray' => 'Change of qty picked after picking',
'CloseShipmentCoChargeAPI' => 'Closing delivery orders', 'CloseShipmentCoChargeAPI' => 'Closing delivery orders',
'TransferAPIURL' => 'Move goods to Pack/Dock locations', 'TransferAPIURL' => 'Move goods to Pack/Dock locations',
'OP705API' => 'Closing a manifest', 'OP705API' => 'Closing a manifest',
'CloseShipmentCoChargeAPIMfest' => 'Batch closing for M3 manifests at night', 'CloseShipmentCoChargeAPIMfest' => 'Batch closing for M3 manifests at night',
'M3-General' => 'General - contact MPBA', 'M3-General' => 'General - contact MPBA',
'UpdateShipmentNumber' => 'Update Shipment Number', 'UpdateShipmentNumber' => 'Update Shipment Number',
], ],
'curlTimeOut' => 30, 'curlTimeOut' => 30,
'PHPTimeOut' => 600, 'PHPTimeOut' => 600,
'PHPTimeOutCL'=> 1000, 'PHPTimeOutCL' => 1000,
'maxRecDL' => 20000, 'maxRecDL' => 20000,
'maxRecCL' => 55000, 'maxRecCL' => 55000,
'BadChars' => ['–','\t','\n','\u20134807','\u20131','\u201333','\u2013671' ,'Ÿ','á', 'é', 'í', 'ó' ,'ú','“','”'], 'BadChars' => ['–', '\t', '\n', '\u20134807', '\u20131', '\u201333', '\u2013671', 'Ÿ', 'á', 'é', 'í', 'ó', 'ú', '“', '”'],
'PdfPath' => env('M3_LABELS_PATH', storage_path('app/m3/labels') . DIRECTORY_SEPARATOR), # Warning : The path for PDF storage is shared by all Instances and should not be altered 'PdfPath' => env('M3_LABELS_PATH', storage_path('app/m3/labels') . DIRECTORY_SEPARATOR), // Warning : The path for PDF storage is shared by all Instances and should not be altered
'DUMMYPDF' => '', 'DUMMYPDF' => '',
'uom_size' => ['110-142-303'=>'mm', 'uom_size' => ['110-142-303' => 'mm',
'110-143-321'=>'mm', '110-143-321' => 'mm',
'110-143-322'=>'in'], # unit of mesure for boxes lengths mm or in '110-143-322' => 'in'], // unit of mesure for boxes lengths mm or in
'uom_wt' => ['110-142-303'=>'kg', 'uom_wt' => ['110-142-303' => 'kg',
'110-143-321'=>'kg', '110-143-321' => 'kg',
'110-143-322'=>'lbs'], # unit of mesure for boxes weight kg or lbs '110-143-322' => 'lbs'], // unit of mesure for boxes weight kg or lbs
#STATUS ARRAY FOR ICM688M1 // STATUS ARRAY FOR ICM688M1
'status_ICM688M1_array' => [ 'status_ICM688M1_array' => [
"P"=>"Pending error checking by splitting (OP510E2)", 'P' => 'Pending error checking by splitting (OP510E2)',
"H"=>"Hold as error found (OP510E3)", 'H' => 'Hold as error found (OP510E3)',
"L"=>"Ready to pick", 'L' => 'Ready to pick',
"I"=>"In picking", 'I' => 'In picking',
"F"=>"In packing", 'F' => 'In packing',
"X"=>"Cancelled", 'X' => 'Cancelled',
"C"=>"Packed", 'C' => 'Packed',
"B"=>"Loaded", 'B' => 'Loaded',
"a"=>"Manually removed from Sentinel ship confirm screen", 'a' => 'Manually removed from Sentinel ship confirm screen',
"A"=>"ShipConfirmed" ], 'A' => 'ShipConfirmed'],
'whsePerf_targets' => [ 'whsePerf_targets' => [
'all_notes'=>'90', 'all_dollars'=>'85', 'all_weight'=>'90', 'all_notes' => '90', 'all_dollars' => '85', 'all_weight' => '90',
'ltl_notes'=>'90', 'ltl_dollars'=>'95', 'ltl_weight'=>'99', 'ltl_notes' => '90', 'ltl_dollars' => '95', 'ltl_weight' => '99',
'parcel_notes'=>'90', 'parcel_dollars'=>'75', 'parcel_weight'=>'80' 'parcel_notes' => '90', 'parcel_dollars' => '75', 'parcel_weight' => '80',
], ],
'2Ship' => [ '2Ship' => [
# 2Ship WS_Key // 2Ship WS_Key
# live $TwoShip_Key="FED945D1-5DC7-415E-BDAB-16347E7C1304"; // live $TwoShip_Key="FED945D1-5DC7-415E-BDAB-16347E7C1304";
# test $TwoShip_Key="45027F2A-EDA6-4C16-8AD4-9BC70CE94AB8"; // test $TwoShip_Key="45027F2A-EDA6-4C16-8AD4-9BC70CE94AB8";
'TwoShip_Key' => "45027F2A-EDA6-4C16-8AD4-9BC70CE94AB8", 'TwoShip_Key' => '45027F2A-EDA6-4C16-8AD4-9BC70CE94AB8',
'end_point' =>"https://euroapi.2ship.com/api/", 'end_point' => 'https://euroapi.2ship.com/api/',
'hold_update' =>"UpdateOnHoldOrder_V1", 'hold_update' => 'UpdateOnHoldOrder_V1',
], ],
]; ];
+29 -32
View File
@@ -1,40 +1,37 @@
<?php <?php
# PayRollCodes are the keys (left) to read LBPF, lines per hours (right) // PayRollCodes are the keys (left) to read LBPF, lines per hours (right)
return [ return [
'lph_per_code_array' => ['16'=>'30', 'lph_per_code_array' => ['16' => '30',
'33'=>'12', '33' => '12',
'49'=>'25', '49' => '25',
'66'=>'60', '66' => '60',
'75'=>'15', '75' => '15',
'94'=>'40', '94' => '40',
'98'=>'8', '98' => '8',
'102'=>'10', '102' => '10',
'171'=>'17' '171' => '17',
] ],
]; ];
# '75'=>'26', // '75'=>'26',
# '75'=>'23', // '75'=>'23',
# '33'=>'13', #2025-08-04 // '33'=>'13', #2025-08-04
# Found in BLDPERFST rpg pgm in EWRPGSRC / EWSRCTST // Found in BLDPERFST rpg pgm in EWRPGSRC / EWSRCTST
# PICKING stats // PICKING stats
# when a5sentview in ('7','9') then 33 // when a5sentview in ('7','9') then 33
# when a5sentview = 5 then 49 // when a5sentview = 5 then 49
# when a5sentview = 12 then 98 // when a5sentview = 12 then 98
# when a5sentview in ('2','10') then 75 // when a5sentview in ('2','10') then 75
# when a5sentview in ('1','3','4','11') then 94 // when a5sentview in ('1','3','4','11') then 94
# when a5sentview = 8 then 102 // when a5sentview = 8 then 102
# when a5sentview = 6 then 171 // when a5sentview = 6 then 171
# else 999 // else 999
# PACKING stats // PACKING stats
# case when (select AYTYPE from ICM695M1 // case when (select AYTYPE from ICM695M1
# where AYINTBOX=AZINTBOX // where AYINTBOX=AZINTBOX
# and AYSENTPKR=AZSENTPKR FETCH FIRST ROW ONLY) // and AYSENTPKR=AZSENTPKR FETCH FIRST ROW ONLY)
# in ('','BX') then '16' else '66' end as AYTYPE, // in ('','BX') then '16' else '66' end as AYTYPE,
?>
+56 -60
View File
@@ -2,17 +2,13 @@
namespace Modules\M3\Console; namespace Modules\M3\Console;
use Illuminate\Console\Command;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use DB;
use Illuminate\Console\Command;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Log; use Log;
use Str;
use Modules\M3\Http\Controllers\API\CloseShipment; use Modules\M3\Http\Controllers\API\CloseShipment;
use Str;
class CallCloseAPI extends Command class CallCloseAPI extends Command
{ {
@@ -32,100 +28,101 @@ class CallCloseAPI extends Command
public function handle() public function handle()
{ {
//$this->info('Start CallCloseAPI...'); // $this->info('Start CallCloseAPI...');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut')); ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
try { try {
# Get the Calling User // Get the Calling User
$userId = $this->argument('user'); $userId = $this->argument('user');
$SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : ''); $SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : '');
# Get the Manifest Number // Get the Manifest Number
$manifest = $this->argument('manifest'); $manifest = $this->argument('manifest');
$MANIFESTNum = isset($manifest) ? $manifest : ''; $MANIFESTNum = isset($manifest) ? $manifest : '';
$co = $this->argument('co'); $co = $this->argument('co');
$APCO = isset($co) ? $co : ''; $APCO = isset($co) ? $co : '';
$whs = $this->argument('whs'); $whs = $this->argument('whs');
$APWHS = isset($whs) ? $whs : ''; $APWHS = isset($whs) ? $whs : '';
// if ($SHUSER!='') { // if ($SHUSER!='') {
// Log::channel('dailyCron')->info("Cron...Start CallCloseAPI...For Manifest#: ".$MANIFESTNum); // ".$SHUSER." // Log::channel('dailyCron')->info("Cron...Start CallCloseAPI...For Manifest#: ".$MANIFESTNum); // ".$SHUSER."
if( $MANIFESTNum==''){ if ($MANIFESTNum == '') {
# Get Macpickers from ICM705M1 // Get Macpickers from ICM705M1
$ICM705M1 = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1') $ICM705M1 = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1')
->select('APMANIFEST','APCO','APWHS') ->select('APMANIFEST', 'APCO', 'APWHS')
->where('APSPARE2','') ->where('APSPARE2', '')
->where('APMANIFEST','!=','0') ->where('APMANIFEST', '!=', '0')
->whereRaw('EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - APLDCLOZ)) / 60 > 15') ->whereRaw('EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - APLDCLOZ)) / 60 > 15')
->orderBy('APMANIFEST','desc') ->orderBy('APMANIFEST', 'desc')
->get(); ->get();
// dump($ICM705M1); // dump($ICM705M1);
if (count($ICM705M1)>0) { if (count($ICM705M1) > 0) {
# Loop the Results from $ICM705M1 // Loop the Results from $ICM705M1
foreach ($ICM705M1 as $key => $ICM705M1R) { foreach ($ICM705M1 as $key => $ICM705M1R) {
$MANIFESTNum = $ICM705M1R->APMANIFEST; $MANIFESTNum = $ICM705M1R->APMANIFEST;
$USERCO = isset($ICM705M1R->APCO) ? $ICM705M1R->APCO : ''; $USERCO = isset($ICM705M1R->APCO) ? $ICM705M1R->APCO : '';
$USERWH = isset($ICM705M1R->APWHS) ? $ICM705M1R->APWHS : ''; $USERWH = isset($ICM705M1R->APWHS) ? $ICM705M1R->APWHS : '';
# Update ICM705M1 and set APSPARE2 to P // Update ICM705M1 and set APSPARE2 to P
$ICM705M1U = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1') $ICM705M1U = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1')
->where('APMANIFEST',$MANIFESTNum) ->where('APMANIFEST', $MANIFESTNum)
->where('APCO',$USERCO) ->where('APCO', $USERCO)
->where('APWHS',$USERWH) ->where('APWHS', $USERWH)
->update(["APSPARE2"=>"P"]); ->update(['APSPARE2' => 'P']);
$myRequest = new Request(); $myRequest = new Request;
$myRequest->setMethod('POST'); $myRequest->setMethod('POST');
$myRequest->request->add([ $myRequest->request->add([
'WHS' => $USERWH, 'WHS' => $USERWH,
'COMPANY' => $USERCO, 'COMPANY' => $USERCO,
'TRANSTYPE' => 'M', 'TRANSTYPE' => 'M',
'MANIFEST' => $MANIFESTNum 'MANIFEST' => $MANIFESTNum,
]); ]);
$callCloseShipment = CloseShipment::CloseShipmentCoChargeAPI($myRequest); $callCloseShipment = CloseShipment::CloseShipmentCoChargeAPI($myRequest);
$responseData = $callCloseShipment->getData(); $responseData = $callCloseShipment->getData();
$jsonData = json_encode($responseData); $jsonData = json_encode($responseData);
Log::channel('dailyCron')->info("Close Shipment API Response for Manifest:".(string)(int)$MANIFESTNum.'-'.$jsonData); Log::channel('dailyCron')->info('Close Shipment API Response for Manifest:' . (string) (int) $MANIFESTNum . '-' . $jsonData);
} }
} }
} }
# Call Closing for a specific Manifest // Call Closing for a specific Manifest
else{ else {
# Get Macpickers from ICM705M1 // Get Macpickers from ICM705M1
$ICM705M1 = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1') $ICM705M1 = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1')
->select('APMANIFEST','APCO','APWHS') ->select('APMANIFEST', 'APCO', 'APWHS')
->where('APSPARE2','') ->where('APSPARE2', '')
->where('APCO',$APCO) ->where('APCO', $APCO)
->where('APWHS',$APWHS) ->where('APWHS', $APWHS)
->where('APMANIFEST','=',$MANIFESTNum) ->where('APMANIFEST', '=', $MANIFESTNum)
->first(); ->first();
# Update ICM705M1 and set APSPARE2 to P // Update ICM705M1 and set APSPARE2 to P
$ICM705M1U = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1') $ICM705M1U = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1')
->where('APMANIFEST',$MANIFESTNum) ->where('APMANIFEST', $MANIFESTNum)
->where('APCO',$APCO) ->where('APCO', $APCO)
->where('APWHS',$APWHS) ->where('APWHS', $APWHS)
->update(["APSPARE2"=>"P"]); ->update(['APSPARE2' => 'P']);
$myRequest = new Request(); $myRequest = new Request;
$myRequest->setMethod('POST'); $myRequest->setMethod('POST');
$myRequest->request->add([ $myRequest->request->add([
'WHS' => $APWHS , 'WHS' => $APWHS,
'COMPANY' => $APCO, 'COMPANY' => $APCO,
'TRANSTYPE' => 'M', 'TRANSTYPE' => 'M',
'MANIFEST' => $MANIFESTNum 'MANIFEST' => $MANIFESTNum,
]); ]);
$callCloseShipment = CloseShipment::CloseShipmentCoChargeAPI($myRequest); $callCloseShipment = CloseShipment::CloseShipmentCoChargeAPI($myRequest);
$responseData = $callCloseShipment->getData(); $responseData = $callCloseShipment->getData();
$jsonData = json_encode($responseData); $jsonData = json_encode($responseData);
Log::channel('dailyCron')->info("Close Shipment API Response for Manifest:".$MANIFESTNum.'-'.$jsonData); Log::channel('dailyCron')->info('Close Shipment API Response for Manifest:' . $MANIFESTNum . '-' . $jsonData);
return 1; return 1;
} }
// } // }
@@ -135,8 +132,7 @@ class CallCloseAPI extends Command
// $this->error('A user must be defined...'); // $this->error('A user must be defined...');
// } // }
} } catch (\Throwable $th) {
catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
Log::channel('dailyCron')->error($th); Log::channel('dailyCron')->error($th);
} }
+93 -104
View File
@@ -2,18 +2,14 @@
namespace Modules\M3\Console; namespace Modules\M3\Console;
use Illuminate\Console\Command;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use Illuminate\Http\Request; use DB;
use Symfony\Component\HttpFoundation\Response;
use Log;
use Str;
use Excel; use Excel;
use Illuminate\Console\Command;
use Log;
use Modules\M3\Services\SpreadsheetExport;
use Storage; use Storage;
use Str;
class ClosedOrderSaveXls extends Command class ClosedOrderSaveXls extends Command
{ {
@@ -48,53 +44,52 @@ class ClosedOrderSaveXls extends Command
*/ */
public function handle() public function handle()
{ {
//$this->info('Start CallCloseAPI...'); // $this->info('Start CallCloseAPI...');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
try { try {
Log::channel('dailyCron')->info("Cron...Start Save Orders Closed Lines to Excel"); Log::channel('dailyCron')->info('Cron...Start Save Orders Closed Lines to Excel');
# Get the Calling User // Get the Calling User
$userId = $this->argument('user'); $userId = $this->argument('user');
$SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : ''); $SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : '');
$CO = $this->argument('co'); $CO = $this->argument('co');
$COMPANY = isset($CO) ? trim($CO) : ''; $COMPANY = isset($CO) ? trim($CO) : '';
$PWHS = $this->argument('whs'); $PWHS = $this->argument('whs');
$WHS = isset($PWHS) ? trim($PWHS) : ''; $WHS = isset($PWHS) ? trim($PWHS) : '';
$PPL = $this->argument('pl'); $PPL = $this->argument('pl');
$PLANT = isset($PPL) ? trim($PPL) : ''; $PLANT = isset($PPL) ? trim($PPL) : '';
# Generate last Month Report // Generate last Month Report
$date = new \DateTime('FIRST DAY OF THIS MONTH'); $date = new \DateTime('FIRST DAY OF THIS MONTH');
$date->modify('-1 month'); $date->modify('-1 month');
$fromPreviousMonth = $date->format('Y-m-d'); $fromPreviousMonth = $date->format('Y-m-d');
$toPreviousMonth = $date->modify('last day of this month')->format('Y-m-d'); $toPreviousMonth = $date->modify('last day of this month')->format('Y-m-d');
$reportDate = \DateTime::createFromFormat('Y-m-d', $fromPreviousMonth )->format('Ymd'); $reportDate = \DateTime::createFromFormat('Y-m-d', $fromPreviousMonth)->format('Ymd');
$toreportDate = \DateTime::createFromFormat('Y-m-d', $toPreviousMonth )->format('Ymd'); $toreportDate = \DateTime::createFromFormat('Y-m-d', $toPreviousMonth)->format('Ymd');
$reportDateWD = $fromPreviousMonth; $reportDateWD = $fromPreviousMonth;
$toreportDateWD = $toPreviousMonth; $toreportDateWD = $toPreviousMonth;
if ($WHS == '321') { if ($WHS == '321') {
$prevMonthFile = 'Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'.xlsx'; $prevMonthFile = 'Closedorderlinesreport_' . $reportDateWD . '-' . $toreportDateWD . '.xlsx';
} } else {
else { $prevMonthFile = $WHS . '/Closedorderlinesreport_' . $reportDateWD . '-' . $toreportDateWD . '-' . $WHS . '.xlsx';
$prevMonthFile = $WHS.'/Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'-'.$WHS.'.xlsx';
} }
$this->info("Generate Last Month Report..."); $this->info('Generate Last Month Report...');
$this->info("From Date: ".$reportDate); $this->info('From Date: ' . $reportDate);
$this->info("To Date: ".$toreportDate); $this->info('To Date: ' . $toreportDate);
# Check that the Excel file Exist // Check that the Excel file Exist
$prevMonthFileExist = Storage::disk('publicCL')->exists($prevMonthFile) ? false: true ; $prevMonthFileExist = Storage::disk('publicCL')->exists($prevMonthFile) ? false : true;
$this->info("Prev Month File Exist: " .$prevMonthFileExist); $this->info('Prev Month File Exist: ' . $prevMonthFileExist);
if($reportDate!='' && $COMPANY!='' && $WHS!='' && $PLANT!='' && $prevMonthFileExist ){ if ($reportDate != '' && $COMPANY != '' && $WHS != '' && $PLANT != '' && $prevMonthFileExist) {
# Case 729: Add Currency code A1SHCURR FROM ICM666M // Case 729: Add Currency code A1SHCURR FROM ICM666M
$ICM688M2 = DB::connection(config('m3.connection', 'pgsql')) $ICM688M2 = DB::connection(config('m3.connection', 'pgsql'))
->select(" ->select("
SELECT (SHDT || ' ' || SHTIME) AS DATECLOSED, A5MACPKR, A5ONO, SELECT (SHDT || ' ' || SHTIME) AS DATECLOSED, A5MACPKR, A5ONO,
@@ -110,8 +105,8 @@ class ClosedOrderSaveXls extends Command
A1SHCURR, A1SHCURR,
CASE CASE
WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL' WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL'
THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL'))/100 ." THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * " . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL')) / 100 . '
ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel') )/100 ." ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ' . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel')) / 100 . "
END AS FREIGHT END AS FREIGHT
FROM ICM688M2 FROM ICM688M2
LEFT JOIN ICM699M ON SHMACPKR=A5MACPKR AND SHTYPE='M3-Res-out' AND SHDATA LIKE 'Success%' AND SHSOURCE='CloseShipmentCoChargeAPI' LEFT JOIN ICM699M ON SHMACPKR=A5MACPKR AND SHTYPE='M3-Res-out' AND SHDATA LIKE 'Success%' AND SHSOURCE='CloseShipmentCoChargeAPI'
@@ -129,61 +124,58 @@ class ClosedOrderSaveXls extends Command
// "A5PACKED" => 'Packed',"CALCULATED_COLUMN" => 'Back Order Qty',"ANOTHER_CALCULATED_COLUMN" => 'Value Packed $',"A4SHSHNM" => 'Customer name', // "A5PACKED" => 'Packed',"CALCULATED_COLUMN" => 'Back Order Qty',"ANOTHER_CALCULATED_COLUMN" => 'Value Packed $',"A4SHSHNM" => 'Customer name',
// "SHDT" => 'Date',"SHTIME" => 'Time',"REASON" => 'Failure Reason','A1SHCURR'=> 'Currency Code','FREIGHT'=> 'Freight']; // "SHDT" => 'Date',"SHTIME" => 'Time',"REASON" => 'Failure Reason','A1SHCURR'=> 'Currency Code','FREIGHT'=> 'Freight'];
$newItem = ["DATECLOSED" => 'Close Date',"A5MACPKR" => 'Delivery #', "A5ONO" => 'Order #', $newItem = ['DATECLOSED' => 'Close Date', 'A5MACPKR' => 'Delivery #', 'A5ONO' => 'Order #',
"A4OFSTRM" => 'Terms',"WEIGHT" => 'Weight',"A4SCAC" => 'Carrier',"A4SHIPTYPE" => 'Mode (Parcel, Air, TL or LTL)', 'A4OFSTRM' => 'Terms', 'WEIGHT' => 'Weight', 'A4SCAC' => 'Carrier', 'A4SHIPTYPE' => 'Mode (Parcel, Air, TL or LTL)',
"A4REFORD" => 'Order Type',"A5PART" => 'Part #',"A5RSVQTY" => 'Reserved', 'A4REFORD' => 'Order Type', 'A5PART' => 'Part #', 'A5RSVQTY' => 'Reserved',
"A5PACKED" => 'Packed',"CALCULATED_COLUMN" => 'Back Order Qty',"ANOTHER_CALCULATED_COLUMN" => 'Value Packed $',"A4SHSHNM" => 'Customer name', 'A5PACKED' => 'Packed', 'CALCULATED_COLUMN' => 'Back Order Qty', 'ANOTHER_CALCULATED_COLUMN' => 'Value Packed $', 'A4SHSHNM' => 'Customer name',
"REASON" => 'Failure Reason','A1SHCURR'=> 'Currency Code','FREIGHT'=> 'Freight']; 'REASON' => 'Failure Reason', 'A1SHCURR' => 'Currency Code', 'FREIGHT' => 'Freight'];
$ICM688M2Col = collect($ICM688M2); $ICM688M2Col = collect($ICM688M2);
$ICM688M2Col->prepend($newItem); $ICM688M2Col->prepend($newItem);
# Count records before exporting to excel : Max 55K records are allowed // Count records before exporting to excel : Max 55K records are allowed
$ICM688M2Count = $ICM688M2Col->count(); $ICM688M2Count = $ICM688M2Col->count();
# Set Max allowed records // Set Max allowed records
$maxRecords = Config::get('arrays.maxRecCL'); $maxRecords = Config::get('arrays.maxRecCL');
if ($ICM688M2Count>$maxRecords) { if ($ICM688M2Count > $maxRecords) {
Log::channel('dailyCron')->info('Maximum allowed records for Excel export is: '.number_format($maxRecords).' current records: '.number_format($ICM688M2Count)); Log::channel('dailyCron')->info('Maximum allowed records for Excel export is: ' . number_format($maxRecords) . ' current records: ' . number_format($ICM688M2Count));
} }
} } else {
else{
$ICM688M2Col = collect(); $ICM688M2Col = collect();
} }
if ($ICM688M2Col->count()>0) { if ($ICM688M2Col->count() > 0) {
$this->info("Saving Last Month Excel Report to Disk"); $this->info('Saving Last Month Excel Report to Disk');
Log::channel('dailyCron')->info("Saving Last Month Excel Report to Disk"); Log::channel('dailyCron')->info('Saving Last Month Excel Report to Disk');
# Store the File to Storage // Store the File to Storage
app(\Modules\M3\Services\SpreadsheetExport::class)->store($ICM688M2Col, $prevMonthFile, 'publicCL'); app(SpreadsheetExport::class)->store($ICM688M2Col, $prevMonthFile, 'publicCL');
# Other File Formats : \Maatwebsite\Excel\Excel::CSV , ,\Maatwebsite\Excel\Excel::ODS // Other File Formats : \Maatwebsite\Excel\Excel::CSV , ,\Maatwebsite\Excel\Excel::ODS
} } else {
else{ Log::channel('dailyCron')->info('Monthly report, no records found: Nothing to save...');
Log::channel('dailyCron')->info("Monthly report, no records found: Nothing to save...");
} }
# Generate current Month Report // Generate current Month Report
$now = new \DateTime(); $now = new \DateTime;
$first_day_of_month = $now->format('Y-m-01'); $first_day_of_month = $now->format('Y-m-01');
$current_date = $now->format('Y-m-d'); $current_date = $now->format('Y-m-d');
$reportDate2 = \DateTime::createFromFormat('Y-m-d', $first_day_of_month )->format('Ymd'); $reportDate2 = \DateTime::createFromFormat('Y-m-d', $first_day_of_month)->format('Ymd');
$toreportDate2 = \DateTime::createFromFormat('Y-m-d', $current_date )->format('Ymd'); $toreportDate2 = \DateTime::createFromFormat('Y-m-d', $current_date)->format('Ymd');
if ($WHS == '321') { if ($WHS == '321') {
$currentMonthFile = 'first_of_month_to_current_date.xlsx'; $currentMonthFile = 'first_of_month_to_current_date.xlsx';
} } else {
else{ $currentMonthFile = $WHS . '/first_of_month_to_current_date_' . $WHS . '.xlsx';
$currentMonthFile = $WHS.'/first_of_month_to_current_date_'.$WHS.'.xlsx';
} }
$this->info("Generate Current Month Report..."); $this->info('Generate Current Month Report...');
$this->info("From Date: ".$reportDate2); $this->info('From Date: ' . $reportDate2);
$this->info("To Date : ".$toreportDate2); $this->info('To Date : ' . $toreportDate2);
if($reportDate2!='' && $COMPANY!='' && $WHS!='' && $PLANT!=''){ if ($reportDate2 != '' && $COMPANY != '' && $WHS != '' && $PLANT != '') {
$this->info(">>> Proceed..."); $this->info('>>> Proceed...');
# Case 729: Add Currency code A1SHCURR FROM ICM666M // Case 729: Add Currency code A1SHCURR FROM ICM666M
$ICM688M2 = DB::connection(config('m3.connection', 'pgsql')) $ICM688M2 = DB::connection(config('m3.connection', 'pgsql'))
->select(" ->select("
SELECT (SHDT || ' ' || SHTIME) AS DATECLOSED, A5MACPKR, A5ONO, SELECT (SHDT || ' ' || SHTIME) AS DATECLOSED, A5MACPKR, A5ONO,
@@ -199,8 +191,8 @@ class ClosedOrderSaveXls extends Command
A1SHCURR, A1SHCURR,
CASE CASE
WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL' WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL'
THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL'))/100 ." THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * " . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL')) / 100 . '
ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel') )/100 ." ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ' . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel')) / 100 . "
END AS FREIGHT END AS FREIGHT
FROM ICM688M2 FROM ICM688M2
LEFT JOIN ICM699M ON SHMACPKR=A5MACPKR AND SHTYPE='M3-Res-out' AND SHDATA LIKE 'Success%' AND SHSOURCE='CloseShipmentCoChargeAPI' LEFT JOIN ICM699M ON SHMACPKR=A5MACPKR AND SHTYPE='M3-Res-out' AND SHDATA LIKE 'Success%' AND SHSOURCE='CloseShipmentCoChargeAPI'
@@ -218,42 +210,39 @@ class ClosedOrderSaveXls extends Command
// "A5PACKED" => 'Packed',"CALCULATED_COLUMN" => 'Back Order Qty',"ANOTHER_CALCULATED_COLUMN" => 'Value Packed $',"A4SHSHNM" => 'Customer name', // "A5PACKED" => 'Packed',"CALCULATED_COLUMN" => 'Back Order Qty',"ANOTHER_CALCULATED_COLUMN" => 'Value Packed $',"A4SHSHNM" => 'Customer name',
// "SHDT" => 'Date',"SHTIME" => 'Time',"REASON" => 'Failure Reason','A1SHCURR'=> 'Currency Code','FREIGHT'=> 'Freight']; // "SHDT" => 'Date',"SHTIME" => 'Time',"REASON" => 'Failure Reason','A1SHCURR'=> 'Currency Code','FREIGHT'=> 'Freight'];
$newItem2 = ["DATECLOSED" => 'Close Date',"A5MACPKR" => 'Delivery #', "A5ONO" => 'Order #', $newItem2 = ['DATECLOSED' => 'Close Date', 'A5MACPKR' => 'Delivery #', 'A5ONO' => 'Order #',
"A4OFSTRM" => 'Terms',"WEIGHT" => 'Weight',"A4SCAC" => 'Carrier',"A4SHIPTYPE" => 'Mode (Parcel, Air, TL or LTL)', 'A4OFSTRM' => 'Terms', 'WEIGHT' => 'Weight', 'A4SCAC' => 'Carrier', 'A4SHIPTYPE' => 'Mode (Parcel, Air, TL or LTL)',
"A4REFORD" => 'Order Type',"A5PART" => 'Part #',"A5RSVQTY" => 'Reserved', 'A4REFORD' => 'Order Type', 'A5PART' => 'Part #', 'A5RSVQTY' => 'Reserved',
"A5PACKED" => 'Packed',"CALCULATED_COLUMN" => 'Back Order Qty',"ANOTHER_CALCULATED_COLUMN" => 'Value Packed $',"A4SHSHNM" => 'Customer name', 'A5PACKED' => 'Packed', 'CALCULATED_COLUMN' => 'Back Order Qty', 'ANOTHER_CALCULATED_COLUMN' => 'Value Packed $', 'A4SHSHNM' => 'Customer name',
"REASON" => 'Failure Reason','A1SHCURR'=> 'Currency Code','FREIGHT'=> 'Freight']; 'REASON' => 'Failure Reason', 'A1SHCURR' => 'Currency Code', 'FREIGHT' => 'Freight'];
$ICM688M2Col2 = collect($ICM688M2); $ICM688M2Col2 = collect($ICM688M2);
$ICM688M2Col2->prepend($newItem2); $ICM688M2Col2->prepend($newItem2);
# Count records before exporting to excel : Max 55K records are allowed // Count records before exporting to excel : Max 55K records are allowed
$ICM688M2Count = $ICM688M2Col2->count(); $ICM688M2Count = $ICM688M2Col2->count();
# Set Max allowed records // Set Max allowed records
$maxRecords = Config::get('arrays.maxRecCL'); $maxRecords = Config::get('arrays.maxRecCL');
if ($ICM688M2Count>$maxRecords) { if ($ICM688M2Count > $maxRecords) {
Log::channel('dailyCron')->info('Maximum allowed records for Excel export is: '.number_format($maxRecords).' current records: '.number_format($ICM688M2Count)); Log::channel('dailyCron')->info('Maximum allowed records for Excel export is: ' . number_format($maxRecords) . ' current records: ' . number_format($ICM688M2Count));
} }
} } else {
else{
$ICM688M2Col2 = collect(); $ICM688M2Col2 = collect();
} }
if ($ICM688M2Col2->count()>0) { if ($ICM688M2Col2->count() > 0) {
$this->info("Saving Current Month Excel Report to Disk"); $this->info('Saving Current Month Excel Report to Disk');
Log::channel('dailyCron')->info("Saving Current Month Excel Report to Disk"); Log::channel('dailyCron')->info('Saving Current Month Excel Report to Disk');
# Store the File to Storage // Store the File to Storage
app(\Modules\M3\Services\SpreadsheetExport::class)->store($ICM688M2Col2, $currentMonthFile, 'publicCL'); app(SpreadsheetExport::class)->store($ICM688M2Col2, $currentMonthFile, 'publicCL');
} } else {
else{ Log::channel('dailyCron')->info('Daily Report, no records found: Nothing to save...');
Log::channel('dailyCron')->info("Daily Report, no records found: Nothing to save...");
} }
Log::channel('dailyCron')->info("Cron...End Save Orders Closed Lines to Excel"); Log::channel('dailyCron')->info('Cron...End Save Orders Closed Lines to Excel');
$this->info("Cron...End Save Orders Closed Lines to Excel"); $this->info('Cron...End Save Orders Closed Lines to Excel');
} } catch (\Throwable $th) {
catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
Log::channel('dailyCron')->error($th); Log::channel('dailyCron')->error($th);
} }
+24 -33
View File
@@ -2,18 +2,10 @@
namespace Modules\M3\Console; namespace Modules\M3\Console;
use Illuminate\Console\Command;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Log;
use Str;
use Storage;
use File; use File;
use Illuminate\Console\Command;
use Log;
class DeleteOldLabels extends Command class DeleteOldLabels extends Command
{ {
@@ -48,44 +40,44 @@ class DeleteOldLabels extends Command
*/ */
public function handle(): void public function handle(): void
{ {
//$this->info('Start CallCloseAPI...'); // $this->info('Start CallCloseAPI...');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
try { try {
$this->info("Start Delete Old Labels Command..."); $this->info('Start Delete Old Labels Command...');
Log::channel('dailyCron')->info("Cron...Start Delete Old Labels Command..."); Log::channel('dailyCron')->info('Cron...Start Delete Old Labels Command...');
$labelsDirectoryTmp = '/www/sentm3live/htdocs/labels/'; $labelsDirectoryTmp = '/www/sentm3live/htdocs/labels/';
$subFolders = ['CarrierLabel/','ContentLabel/','PackingList/']; // ,'CarrierLabel/','ContentLabel','PackingList','' $subFolders = ['CarrierLabel/', 'ContentLabel/', 'PackingList/']; // ,'CarrierLabel/','ContentLabel','PackingList',''
$daysOld = 180; // Number of days to consider a file old : 180 =Six Months $daysOld = 180; // Number of days to consider a file old : 180 =Six Months
$filesToDeleteArr = []; $filesToDeleteArr = [];
foreach ($subFolders as $key => $subFolder) { foreach ($subFolders as $key => $subFolder) {
$labelsDirectory = $labelsDirectoryTmp.$subFolder; $labelsDirectory = $labelsDirectoryTmp . $subFolder;
$this->info("Getting Files From Directory: ".$labelsDirectory); $this->info('Getting Files From Directory: ' . $labelsDirectory);
Log::channel('dailyCron')->info("Getting Files From Directory: ".$labelsDirectory); Log::channel('dailyCron')->info('Getting Files From Directory: ' . $labelsDirectory);
exec('find '.$labelsDirectory.' -ctime +180 -type f -exec rm {} \;'); exec('find ' . $labelsDirectory . ' -ctime +180 -type f -exec rm {} \;');
# exec('find '.$labelsDirectory.' -ctime +190 -type f -print | wc -l'); // exec('find '.$labelsDirectory.' -ctime +190 -type f -print | wc -l');
} }
$labelsFolder = $labelsDirectoryTmp; $labelsFolder = $labelsDirectoryTmp;
# Get Files from the specified Directory // Get Files from the specified Directory
$filesToDelete = File::allFiles($labelsFolder); $filesToDelete = File::allFiles($labelsFolder);
foreach ($filesToDelete as $file) { foreach ($filesToDelete as $file) {
$lastAccessTime = new \DateTime("@".$file->getATime()); $lastAccessTime = new \DateTime('@' . $file->getATime());
$now = new \DateTime(); $now = new \DateTime;
$diff = $now->diff($lastAccessTime)->days; $diff = $now->diff($lastAccessTime)->days;
if ($diff >= $daysOld) { if ($diff >= $daysOld) {
$this->info("File: ".$file." is Days Old: ".$diff); $this->info('File: ' . $file . ' is Days Old: ' . $diff);
// Log::channel('dailyCron')->info("File: ".$file." is Days Old: ".$diff); // Log::channel('dailyCron')->info("File: ".$file." is Days Old: ".$diff);
# Add the File to Array // Add the File to Array
$filesToDeleteArr[] = $file; $filesToDeleteArr[] = $file;
} }
} }
@@ -93,14 +85,13 @@ class DeleteOldLabels extends Command
// $this->info("Files to Delete..."); // $this->info("Files to Delete...");
// dump($filesToDeleteArr); // dump($filesToDeleteArr);
# Delete Old Files // Delete Old Files
File::delete($filesToDeleteArr); File::delete($filesToDeleteArr);
Log::channel('dailyCron')->info("Cron...End Delete Old Labels Command..."); Log::channel('dailyCron')->info('Cron...End Delete Old Labels Command...');
$this->info("End Delete Old Labels Command..."); $this->info('End Delete Old Labels Command...');
} } catch (\Throwable $th) {
catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
Log::channel('dailyCron')->error($th); Log::channel('dailyCron')->error($th);
} }
+98 -114
View File
@@ -2,32 +2,18 @@
namespace Modules\M3\Console; namespace Modules\M3\Console;
use Illuminate\Console\Command;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Log;
use Str;
use File;
use DateTime;
use Storage;
use Cache;
use Picqer\Barcode\BarcodeGeneratorPNG;
use Dompdf\Dompdf;
use Ayeo\Barcode;
use PDF;
use App; use App;
use Ayeo\Barcode;
use Zebra\Client; use Cache;
use Zebra\Zpl\Image; use Config;
use Zebra\Zpl\Builder; use DB;
use Zebra\Zpl\GdDecoder; use Dompdf\Dompdf;
use File;
use Illuminate\Console\Command;
use Log;
use PDF;
use Picqer\Barcode\BarcodeGeneratorPNG;
use Str;
class GenerateGS1Cmd extends Command class GenerateGS1Cmd extends Command
{ {
@@ -62,7 +48,7 @@ class GenerateGS1Cmd extends Command
*/ */
public function handle() public function handle()
{ {
//$this->info('Start CallCloseAPI...'); // $this->info('Start CallCloseAPI...');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
@@ -70,44 +56,43 @@ class GenerateGS1Cmd extends Command
try { try {
$this->info('>>> Run GS1 Label creation Command...'); $this->info('>>> Run GS1 Label creation Command...');
Log::channel('LabelCron')->info(">>> Run GS1 Label creation Command..."); Log::channel('LabelCron')->info('>>> Run GS1 Label creation Command...');
# Get the Calling User // Get the Calling User
$userId = $this->argument('user'); $userId = $this->argument('user');
$SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : 'TWOSHIP'); $SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : 'TWOSHIP');
$this->info('User: '.$SHUSER); $this->info('User: ' . $SHUSER);
# Get Manifest Array // Get Manifest Array
$GSArray1 = $this->option('gsarray'); $GSArray1 = $this->option('gsarray');
$GSArray = json_decode($GSArray1, true); $GSArray = json_decode($GSArray1, true);
// dump($GSArray); // dump($GSArray);
# MAK : Used for debug only // MAK : Used for debug only
$GSArray = ["Macpkr"=> "55555","Recipient_Address1"=>"9571 Pan American DR", "Recipient_Address2"=>"C/O AEE Solar","Recipient_City"=>"El Paso", $GSArray = ['Macpkr' => '55555', 'Recipient_Address1' => '9571 Pan American DR', 'Recipient_Address2' => 'C/O AEE Solar', 'Recipient_City' => 'El Paso',
"Recipient_CompanyName"=>"SNAPRACK EL PASO PRODUCTION","Recipient_CountryCode"=>"US","Recipient_PostalCode"=>"79927","Recipient_State"=>"TX", 'Recipient_CompanyName' => 'SNAPRACK EL PASO PRODUCTION', 'Recipient_CountryCode' => 'US', 'Recipient_PostalCode' => '79927', 'Recipient_State' => 'TX',
"Sender_Address1"=>"6800 Arnold Miller Pkwy","Sender_Address2"=>"","Sender_City"=>"Solon", 'Sender_Address1' => '6800 Arnold Miller Pkwy', 'Sender_Address2' => '', 'Sender_City' => 'Solon',
"Sender_CompanyName"=>"Erico International","Sender_Country"=>"US","Sender_PostalCode"=>"44139","Sender_State"=>"OH", 'Sender_CompanyName' => 'Erico International', 'Sender_Country' => 'US', 'Sender_PostalCode' => '44139', 'Sender_State' => 'OH',
"CarrierName"=>"R&L Carriers","trackingno"=>"306539838","BOLnumber"=>"693103848064454","ShipmentPONumber"=>"4523039092", 'CarrierName' => 'R&L Carriers', 'trackingno' => '306539838', 'BOLnumber' => '693103848064454', 'ShipmentPONumber' => '4523039092',
"PackagesArray"=> ["package 1" , "package 2"] 'PackagesArray' => ['package 1', 'package 2'],
]; ];
if ($SHUSER != '') {
if ($SHUSER!='') { // Get User CO & WH from Table ICM428M
# Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH','R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US','=',$SHUSER) ->where('R428US', '=', $SHUSER)
->first(); ->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; # User $R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; // User
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; # Company $COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; # Plant $PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; # WareHouse $WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; // WareHouse
$Macpkr = $GSArray['Macpkr']; $Macpkr = $GSArray['Macpkr'];
$packageType = '0'; $packageType = '0';
$manufactID = '0826528'; # MAK : get ID from Nvent and save to Config File $manufactID = '0826528'; // MAK : get ID from Nvent and save to Config File
$total_length = 9; $total_length = 9;
$html = ' $html = '
<html> <html>
@@ -137,74 +122,74 @@ class GenerateGS1Cmd extends Command
</head> </head>
<body style="font-family: Arial, sans-serif;">'; <body style="font-family: Arial, sans-serif;">';
# Get number of Pallets // Get number of Pallets
$packageCount = count($GSArray['PackagesArray']); $packageCount = count($GSArray['PackagesArray']);
$packageNum = 1; $packageNum = 1;
foreach ($GSArray['PackagesArray'] as $key => $value) { foreach ($GSArray['PackagesArray'] as $key => $value) {
$table_style = $packageNum < $packageCount ? ' style="page-break-after: always;" ' : ''; $table_style = $packageNum < $packageCount ? ' style="page-break-after: always;" ' : '';
if (Cache::has('GS1SEQUENCE')) { if (Cache::has('GS1SEQUENCE')) {
$GS1SEQUENCE = Cache::get('GS1SEQUENCE'); $GS1SEQUENCE = Cache::get('GS1SEQUENCE');
$GS1SEQUENCE++; $GS1SEQUENCE++;
$GS1SEQUENCEID = str_pad($GS1SEQUENCE, $total_length, "0", STR_PAD_LEFT); $GS1SEQUENCEID = str_pad($GS1SEQUENCE, $total_length, '0', STR_PAD_LEFT);
} }
# Box Number Not Found Get it from DB // Box Number Not Found Get it from DB
else{ else {
$GS1SEQUENCE = 1; $GS1SEQUENCE = 1;
$GS1SEQUENCEID = str_pad($GS1SEQUENCE, $total_length, "0", STR_PAD_LEFT); $GS1SEQUENCEID = str_pad($GS1SEQUENCE, $total_length, '0', STR_PAD_LEFT);
} }
Cache::forever('GS1SEQUENCE', $GS1SEQUENCEID); Cache::forever('GS1SEQUENCE', $GS1SEQUENCEID);
$this->info(">>> GS1 sequence Id: ".$GS1SEQUENCEID); $this->info('>>> GS1 sequence Id: ' . $GS1SEQUENCEID);
$gs1_128_bc_1 = '00' .$packageType . $manufactID . $GS1SEQUENCEID; $gs1_128_bc_1 = '00' . $packageType . $manufactID . $GS1SEQUENCEID;
# Calculate Check Digit // Calculate Check Digit
$digits = str_split($gs1_128_bc_1); $digits = str_split($gs1_128_bc_1);
$sum = 0; $sum = 0;
$length = count($digits); $length = count($digits);
# Loop through each digit starting from the right // Loop through each digit starting from the right
for ($i = 0; $i < $length; $i++) { for ($i = 0; $i < $length; $i++) {
$digit = $digits[$length - $i - 1]; $digit = $digits[$length - $i - 1];
# Assign a weight of 3 or 1 alternately // Assign a weight of 3 or 1 alternately
$weight = ($i % 2 == 0) ? 3 : 1; $weight = ($i % 2 == 0) ? 3 : 1;
# Add the product of the digit and its weight to the sum // Add the product of the digit and its weight to the sum
$sum += $digit * $weight; $sum += $digit * $weight;
} }
# Calculate the remainder when sum is divided by 10 // Calculate the remainder when sum is divided by 10
$remainder = $sum % 10; $remainder = $sum % 10;
# If remainder is 0, check digit is 0; otherwise, subtract remainder from 10 // If remainder is 0, check digit is 0; otherwise, subtract remainder from 10
$checkDigit = ($remainder == 0) ? 0 : 10 - $remainder; $checkDigit = ($remainder == 0) ? 0 : 10 - $remainder;
$gs1_128_bc = $gs1_128_bc_1 . $checkDigit; $gs1_128_bc = $gs1_128_bc_1 . $checkDigit;
$gs1_128_bc_desc = '(00)' .$packageType . $manufactID . $GS1SEQUENCEID .$checkDigit; $gs1_128_bc_desc = '(00)' . $packageType . $manufactID . $GS1SEQUENCEID . $checkDigit;
$data = [ $data = [
'ship_to' => $GSArray["Recipient_CompanyName"].'<br>'.$GSArray["Recipient_Address1"].'<br>'. 'ship_to' => $GSArray['Recipient_CompanyName'] . '<br>' . $GSArray['Recipient_Address1'] . '<br>' .
$GSArray["Recipient_City"].','. $GSArray["Recipient_State"] $GSArray['Recipient_City'] . ',' . $GSArray['Recipient_State']
.'<br>'.$GSArray["Recipient_PostalCode"] , . '<br>' . $GSArray['Recipient_PostalCode'],
'from' => $GSArray["Sender_CompanyName"].'<br>'.$GSArray["Sender_Address1"].'<br>'. 'from' => $GSArray['Sender_CompanyName'] . '<br>' . $GSArray['Sender_Address1'] . '<br>' .
$GSArray["Sender_City"].','. $GSArray["Sender_State"] $GSArray['Sender_City'] . ',' . $GSArray['Sender_State']
.'<br>'.$GSArray["Sender_PostalCode"] , . '<br>' . $GSArray['Sender_PostalCode'],
'ship_to_lbl' => '420'.$GSArray["Recipient_PostalCode"], 'ship_to_lbl' => '420' . $GSArray['Recipient_PostalCode'],
'ship_to_desc' => '(420)'.$GSArray["Recipient_PostalCode"], 'ship_to_desc' => '(420)' . $GSArray['Recipient_PostalCode'],
'pro' => '190071217845706', 'pro' => '190071217845706',
'item_number' => '10000B', 'item_number' => '10000B',
'upc' => '098506095310', 'upc' => '098506095310',
'quantity' => '1', 'quantity' => '1',
'serial_shipping_container' => $gs1_128_bc_desc 'serial_shipping_container' => $gs1_128_bc_desc,
]; ];
# Initialize barcode generator // Initialize barcode generator
$generator = new BarcodeGeneratorPNG(); $generator = new BarcodeGeneratorPNG;
# Generate barcodes // Generate barcodes
$shipToPostalCodeBarcode = $generator->getBarcode($data['ship_to_lbl'], $generator::TYPE_CODE_128); $shipToPostalCodeBarcode = $generator->getBarcode($data['ship_to_lbl'], $generator::TYPE_CODE_128);
$serialShippingContainerBarcode = $generator->getBarcode($data['serial_shipping_container'], $generator::TYPE_CODE_128, 2 ,50); $serialShippingContainerBarcode = $generator->getBarcode($data['serial_shipping_container'], $generator::TYPE_CODE_128, 2, 50);
# HTML content for the label // HTML content for the label
$html .= ' $html .= '
<table '.$table_style.'> <table ' . $table_style . '>
<tr> <tr>
<td colspan="2" class="border_btm border_rght align_lft"> <td colspan="2" class="border_btm border_rght align_lft">
FROM:<br>' . $data['from'] . ' FROM:<br>' . $data['from'] . '
@@ -219,18 +204,18 @@ class GenerateGS1Cmd extends Command
' . $data['ship_to_desc'] . ' ' . $data['ship_to_desc'] . '
</td> </td>
<td class="border_btm margin_t align_lft"> <td class="border_btm margin_t align_lft">
Carrier: '.$GSArray["CarrierName"].' <br> Carrier: ' . $GSArray['CarrierName'] . ' <br>
PRO #: '.$GSArray["ShipmentPONumber"].' <br> PRO #: ' . $GSArray['ShipmentPONumber'] . ' <br>
B/L #: '.$GSArray["BOLnumber"].' B/L #: ' . $GSArray['BOLnumber'] . '
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2" class="border_btm margin_t align_lft border_rght"> <td colspan="2" class="border_btm margin_t align_lft border_rght">
PURCHASE ORDER: '.$GSArray["Macpkr"].' <br> PURCHASE ORDER: ' . $GSArray['Macpkr'] . ' <br>
Vendor: ' . $manufactID . ' Vendor: ' . $manufactID . '
</td> </td>
<td colspan="2" class="border_btm margin_t align_center"> <td colspan="2" class="border_btm margin_t align_center">
Pallet # : '.$packageNum.' of '.$packageCount.' Pallet # : ' . $packageNum . ' of ' . $packageCount . '
</td> </td>
</tr> </tr>
<tr> <tr>
@@ -244,32 +229,32 @@ class GenerateGS1Cmd extends Command
$packageNum++; $packageNum++;
} }
$html .='</body> </html>'; $html .= '</body> </html>';
// dump($html); // dump($html);
// App::call('App\Http\Controllers\utilitiesContoller@generateGS128'); // App::call('App\Http\Controllers\utilitiesContoller@generateGS128');
ob_start(); ob_start();
# Initialize Dompdf // Initialize Dompdf
$dompdf = new Dompdf(); $dompdf = new Dompdf;
$dompdf->loadHtml($html); $dompdf->loadHtml($html);
$dompdf->setPaper('a6', 'portrait'); $dompdf->setPaper('a6', 'portrait');
# Render the HTML as PDF // Render the HTML as PDF
$dompdf->render(); $dompdf->render();
# Output the generated PDF to Browser // Output the generated PDF to Browser
// $dompdf->stream(); // $dompdf->stream();
$pdfContent = $dompdf->output(); $pdfContent = $dompdf->output();
// dump($pdfContent); // dump($pdfContent);
$labelsPath = Config::get('arrays.PdfPath'); $labelsPath = Config::get('arrays.PdfPath');
# Put the PDF in labels/CarrierLabel // Put the PDF in labels/CarrierLabel
$GSFolder = "GSLabel"; $GSFolder = 'GSLabel';
$carrierFileName = $GSFolder.'_'.$Macpkr.'_'.$COMPANY.'_'.$WHS; $carrierFileName = $GSFolder . '_' . $Macpkr . '_' . $COMPANY . '_' . $WHS;
file_put_contents($labelsPath.$GSFolder.'/'.$carrierFileName.'.pdf',$pdfContent); file_put_contents($labelsPath . $GSFolder . '/' . $carrierFileName . '.pdf', $pdfContent);
# Check if the PDF was generated correctly // Check if the PDF was generated correctly
// if (!file_exists($tempPdfPath) || filesize($tempPdfPath) === 0) { // if (!file_exists($tempPdfPath) || filesize($tempPdfPath) === 0) {
// throw new Exception('PDF generation failed.'); // throw new Exception('PDF generation failed.');
// } // }
@@ -277,11 +262,10 @@ class GenerateGS1Cmd extends Command
ob_end_clean(); ob_end_clean();
} }
Log::channel('LabelCron')->info("<<< GS1-128...End of Label Creation"); Log::channel('LabelCron')->info('<<< GS1-128...End of Label Creation');
$this->info("<<< GS1-128...End of Label Creation"); $this->info('<<< GS1-128...End of Label Creation');
} } catch (\Throwable $th) {
catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
Log::channel('LabelCron')->error($th); Log::channel('LabelCron')->error($th);
} }
+6 -13
View File
@@ -2,16 +2,10 @@
namespace Modules\M3\Console; namespace Modules\M3\Console;
use Illuminate\Console\Command;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use Illuminate\Console\Command;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Log; use Log;
use Str;
use Modules\M3\Http\Controllers\utilitiesContoller; use Modules\M3\Http\Controllers\utilitiesContoller;
class UtilitiesCmd extends Command class UtilitiesCmd extends Command
@@ -47,24 +41,23 @@ class UtilitiesCmd extends Command
*/ */
public function handle(): void public function handle(): void
{ {
//$this->info('Start CallCloseAPI...'); // $this->info('Start CallCloseAPI...');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
try { try {
$this->info("Start Utilities Command..."); $this->info('Start Utilities Command...');
// $this->info('User: '.$SHUSER); // $this->info('User: '.$SHUSER);
$myRequest = new Request(); $myRequest = new Request;
utilitiesContoller::fixICM799MSentPKR($myRequest); utilitiesContoller::fixICM799MSentPKR($myRequest);
// Log::channel('dailyCron')->info("Cron...End Save Orders Closed Lines to Excel"); // Log::channel('dailyCron')->info("Cron...End Save Orders Closed Lines to Excel");
$this->info("End Utilities Command..."); $this->info('End Utilities Command...');
} } catch (\Throwable $th) {
catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
Log::channel('dailyCron')->error($th); Log::channel('dailyCron')->error($th);
} }
+52 -60
View File
@@ -2,19 +2,13 @@
namespace Modules\M3\Console; namespace Modules\M3\Console;
use Illuminate\Console\Command;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use Illuminate\Http\Request; use DB;
use Symfony\Component\HttpFoundation\Response; use Illuminate\Console\Command;
use Log; use Log;
use Modules\M3\Services\SpreadsheetExport;
use Str; use Str;
use Storage;
class WHSMetricsSaveXls extends Command class WHSMetricsSaveXls extends Command
{ {
/** /**
@@ -48,41 +42,41 @@ class WHSMetricsSaveXls extends Command
*/ */
public function handle() public function handle()
{ {
//$this->info('Start CallCloseAPI...'); // $this->info('Start CallCloseAPI...');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
try { try {
Log::channel('dailyCron')->info("Cron...Start Save WHS Metrics to Excel"); Log::channel('dailyCron')->info('Cron...Start Save WHS Metrics to Excel');
# Get the Calling User // Get the Calling User
$userId = $this->argument('user'); $userId = $this->argument('user');
$SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : ''); $SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : '');
$CO = $this->argument('co'); $CO = $this->argument('co');
// $COMPANY = isset($CO) ? trim($CO) : '110'; // $COMPANY = isset($CO) ? trim($CO) : '110';
$COMPANY = '110'; $COMPANY = '110';
$PWHS = $this->argument('whs'); $PWHS = $this->argument('whs');
// $WHS = isset($PWHS) ? trim($PWHS) : '321'; // $WHS = isset($PWHS) ? trim($PWHS) : '321';
$WHS = '321'; $WHS = '321';
$PPL = $this->argument('pl'); $PPL = $this->argument('pl');
// $PLANT = isset($PPL) ? trim($PPL) : '143'; // $PLANT = isset($PPL) ? trim($PPL) : '143';
$PLANT = '143'; $PLANT = '143';
$date = new \DateTime(); $date = new \DateTime;
$DateToday = $date->format('Y-m-d'); $DateToday = $date->format('Y-m-d');
# Define File Name // Define File Name
$whsPerfFile = 'WhsPerf/'.$WHS.'/WhsPerfMetrics_'.$DateToday.'-'.$WHS.'.xlsx'; $whsPerfFile = 'WhsPerf/' . $WHS . '/WhsPerfMetrics_' . $DateToday . '-' . $WHS . '.xlsx';
Log::channel('dailyCron')->info(">>> File Name:"); Log::channel('dailyCron')->info('>>> File Name:');
Log::channel('dailyCron')->info($whsPerfFile); Log::channel('dailyCron')->info($whsPerfFile);
$this->info("Generate Today WHS Performance Report..."); $this->info('Generate Today WHS Performance Report...');
if( $COMPANY!='' && $WHS!='' && $PLANT!='' ){ if ($COMPANY != '' && $WHS != '' && $PLANT != '') {
# Get Header Content // Get Header Content
$ICM700MHeadSel = DB::connection(config('m3.connection', 'pgsql')) $ICM700MHeadSel = DB::connection(config('m3.connection', 'pgsql'))
->select(" ->select("
WITH TEMPFILE AS ( WITH TEMPFILE AS (
@@ -100,31 +94,32 @@ class WHSMetricsSaveXls extends Command
"); ");
// dd($ICM700MHeadSel); // dd($ICM700MHeadSel);
$newItem = ["A4SHIPTYPE" => 'Method', "STATUS" => 'Status', "SOURCE" => 'Source', "PICKERS" => 'Pickers', $newItem = ['A4SHIPTYPE' => 'Method', 'STATUS' => 'Status', 'SOURCE' => 'Source', 'PICKERS' => 'Pickers',
"WEIGHT" => 'Weight', "LINES" => 'Lines', "DOLLARS" => 'Dollars']; 'WEIGHT' => 'Weight', 'LINES' => 'Lines', 'DOLLARS' => 'Dollars'];
# Trim All values // Trim All values
$ICM700MHeadCol = collect($ICM700MHeadSel)->map(function ($item) { $ICM700MHeadCol = collect($ICM700MHeadSel)->map(function ($item) {
foreach ($item as $key => $value) { foreach ($item as $key => $value) {
if (is_string($value)) { if (is_string($value)) {
$item->{$key} = trim($value); $item->{$key} = trim($value);
} }
} }
return $item; return $item;
}); });
# Prepend Header to Collection // Prepend Header to Collection
$ICM700MHeadCol->prepend($newItem); $ICM700MHeadCol->prepend($newItem);
// $this->info($ICM700MHeadCol); // $this->info($ICM700MHeadCol);
// Log::channel('dailyCron')->info(">>> Header Content"); // Log::channel('dailyCron')->info(">>> Header Content");
// Log::channel('dailyCron')->info($ICM700MHeadCol); // Log::channel('dailyCron')->info($ICM700MHeadCol);
# Count records before exporting to excel // Count records before exporting to excel
$ICM700MHeadCount = $ICM700MHeadCol->count(); $ICM700MHeadCount = $ICM700MHeadCol->count();
# Get Details Content // Get Details Content
$ICM700MDetailsSel = DB::connection(config('m3.connection', 'pgsql')) $ICM700MDetailsSel = DB::connection(config('m3.connection', 'pgsql'))
->select(" ->select("
WITH TEMPFILE AS ( WITH TEMPFILE AS (
SELECT A3CO,A3WHS,A3PLT,A3MACPKR,A4PICKCRTS,SOURCE, SELECT A3CO,A3WHS,A3PLT,A3MACPKR,A4PICKCRTS,SOURCE,
(SELECT TO_TIMESTAMP(CAST(SHDT AS TEXT) || ' ' || CAST(SHTIME AS TEXT), 'YYYY-MM-DD HH24:MI:SS') FROM ICM699M WHERE SHMACPKR=A4MACPKR AND SHTYPE='Lisnr-Hold' ORDER BY SHDT DESC, SHTIME DESC FETCH FIRST 1 ROWS ONLY) AS CARRIERASSIGNED, (SELECT TO_TIMESTAMP(CAST(SHDT AS TEXT) || ' ' || CAST(SHTIME AS TEXT), 'YYYY-MM-DD HH24:MI:SS') FROM ICM699M WHERE SHMACPKR=A4MACPKR AND SHTYPE='Lisnr-Hold' ORDER BY SHDT DESC, SHTIME DESC FETCH FIRST 1 ROWS ONLY) AS CARRIERASSIGNED,
@@ -140,54 +135,51 @@ class WHSMetricsSaveXls extends Command
SELECT * FROM TEMPFILE SELECT * FROM TEMPFILE
"); ");
$newItem2 = ["A3CO" => 'Co', "A3WHS" => 'Whs', "A3PLT" => 'Plt', "A3MACPKR" => 'Delivery No', "A4PICKCRTS" => 'Date Time Arrived in Sentinel', $newItem2 = ['A3CO' => 'Co', 'A3WHS' => 'Whs', 'A3PLT' => 'Plt', 'A3MACPKR' => 'Delivery No', 'A4PICKCRTS' => 'Date Time Arrived in Sentinel',
"SOURCE" => 'Source', "CARRIERASSIGNED" => 'Date carrier Assigned', "A4ONO" => 'Order No', "A4SHSHNM" => 'Customer name',"A4SCAC" => 'Carrier', 'SOURCE' => 'Source', 'CARRIERASSIGNED' => 'Date carrier Assigned', 'A4ONO' => 'Order No', 'A4SHSHNM' => 'Customer name', 'A4SCAC' => 'Carrier',
"A42SSVCNAM" => 'Service', "A4PICKSTS" => 'Picker Status', "STATUS" => 'Open or Closed', "A4SHIPTYPE" => 'Method', 'A42SSVCNAM' => 'Service', 'A4PICKSTS' => 'Picker Status', 'STATUS' => 'Open or Closed', 'A4SHIPTYPE' => 'Method',
"A4TPCKWGHT" => 'Weight', "A4NOPICLNS" => 'Lines' , "DOLLARS" => 'Dollars' ]; 'A4TPCKWGHT' => 'Weight', 'A4NOPICLNS' => 'Lines', 'DOLLARS' => 'Dollars'];
# Trim all values // Trim all values
$ICM700MDetailsCol = collect($ICM700MDetailsSel)->map(function ($item) { $ICM700MDetailsCol = collect($ICM700MDetailsSel)->map(function ($item) {
foreach ($item as $key => $value) { foreach ($item as $key => $value) {
if (is_string($value)) { if (is_string($value)) {
$item->{$key} = trim($value); $item->{$key} = trim($value);
} }
} }
return $item; return $item;
}); });
# Prepend Header // Prepend Header
$ICM700MDetailsCol->prepend($newItem2); $ICM700MDetailsCol->prepend($newItem2);
# Count records before exporting to excel // Count records before exporting to excel
$ICM700MDetailsCount = $ICM700MDetailsCol->count(); $ICM700MDetailsCount = $ICM700MDetailsCol->count();
} } else {
else{
$ICM700MDetailsCol = collect(); $ICM700MDetailsCol = collect();
} }
// Log::channel('dailyCron')->info(">>> Detail Content"); // Log::channel('dailyCron')->info(">>> Detail Content");
// Log::channel('dailyCron')->info($ICM700MDetailsCol); // Log::channel('dailyCron')->info($ICM700MDetailsCol);
# Save Head and Details to XLS file // Save Head and Details to XLS file
if ($ICM700MHeadCount>0 && $ICM700MDetailsCount>0) { if ($ICM700MHeadCount > 0 && $ICM700MDetailsCount > 0) {
$this->info("Saving Today WHS Performance Report to Disk..."); $this->info('Saving Today WHS Performance Report to Disk...');
Log::channel('dailyCron')->info("Saving Today WHS Performance Report to Disk..."); Log::channel('dailyCron')->info('Saving Today WHS Performance Report to Disk...');
# Store both collections in one XLSX workbook using Core's PhpSpreadsheet dependency. // Store both collections in one XLSX workbook using Core's PhpSpreadsheet dependency.
app(\Modules\M3\Services\SpreadsheetExport::class)->storeSheets([ app(SpreadsheetExport::class)->storeSheets([
'Summary' => $ICM700MHeadCol, 'Summary' => $ICM700MHeadCol,
'Details' => $ICM700MDetailsCol, 'Details' => $ICM700MDetailsCol,
], $whsPerfFile, 'publicLabels'); ], $whsPerfFile, 'publicLabels');
} else {
} Log::channel('dailyCron')->info('Today WHS Performance Report, no records found: Nothing to save...');
else{
Log::channel('dailyCron')->info("Today WHS Performance Report, no records found: Nothing to save...");
} }
Log::channel('dailyCron')->info("Cron...End Save Today WHS Performance Report to Excel"); Log::channel('dailyCron')->info('Cron...End Save Today WHS Performance Report to Excel');
$this->info("Cron...End Save Today WHS Performance Report to Excel"); $this->info('Cron...End Save Today WHS Performance Report to Excel');
} } catch (\Throwable $th) {
catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
Log::channel('dailyCron')->error($th); Log::channel('dailyCron')->error($th);
} }
@@ -2,8 +2,8 @@
namespace Modules\M3\Database\Seeders; namespace Modules\M3\Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
class M3DatabaseSeeder extends Seeder class M3DatabaseSeeder extends Seeder
{ {
+4 -2
View File
@@ -1,11 +1,13 @@
<?php <?php
// app/Helpers/USStates.php // app/Helpers/USStates.php
namespace Modules\M3\Helpers; namespace Modules\M3\Helpers;
class CAProvinces class CAProvinces
{ {
public static function all() { public static function all()
{
return [ return [
'AB' => 'Alberta', 'AB' => 'Alberta',
'BC' => 'British Columbia', 'BC' => 'British Columbia',
@@ -19,7 +21,7 @@ class CAProvinces
'PE' => 'Prince Edward Island', 'PE' => 'Prince Edward Island',
'QC' => 'Quebec', 'QC' => 'Quebec',
'SK' => 'Saskatchewan', 'SK' => 'Saskatchewan',
'YT' => 'Yukon' 'YT' => 'Yukon',
]; ];
} }
} }
+177 -184
View File
@@ -2,79 +2,71 @@
namespace Modules\M3\Helpers; namespace Modules\M3\Helpers;
use Gate;
use DB;
use Config;
use Form;
use Auth;
use Redirect;
use Mail;
use Log;
use Cache; use Cache;
use Str; use Config;
use File; use DB;
use Illuminate\Support\Facades\Schema;
use Log;
class Helper class Helper
{ {
# Check M3 API Token // Check M3 API Token
public static function checkReceiveToken(){ public static function checkReceiveToken()
{
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
# Clear Cache // Clear Cache
// Cache::forget('token'); // Cache::forget('token');
# Check if cached Token is still Valid // Check if cached Token is still Valid
$token = Cache::get('token'); $token = Cache::get('token');
if (isset($token)) { if (isset($token)) {
$IonToken = $token; $IonToken = $token;
// Log::info("Cached Token: ".$IonToken); // Log::info("Cached Token: ".$IonToken);
} } else {
else{ // ## CURL
### CURL // ## Generate Token
### Generate Token
$curl = curl_init(); $curl = curl_init();
curl_setopt_array($curl, array( curl_setopt_array($curl, [
CURLOPT_URL => env('ENDPOINTURLSSO').env('URLTOKEN'), CURLOPT_URL => env('ENDPOINTURLSSO') . env('URLTOKEN'),
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '', CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10, CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0, CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true, CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'grant_type='.env('GRANT_TYPE').'&password='.env('PASSWORD').'&username='.env('USERNAME').'&client_secret='.env('CLIENT_SECRET'). CURLOPT_POSTFIELDS => 'grant_type=' . env('GRANT_TYPE') . '&password=' . env('PASSWORD') . '&username=' . env('USERNAME') . '&client_secret=' . env('CLIENT_SECRET') .
'&client_id='.env('CLIENT_ID'), '&client_id=' . env('CLIENT_ID'),
CURLOPT_HTTPHEADER => array( CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded', 'Content-Type: application/x-www-form-urlencoded',
'charset:UTF-8', 'charset:UTF-8',
'Accept: application/json' 'Accept: application/json',
), ],
)); ]);
$response = curl_exec($curl); $response = curl_exec($curl);
// dd($response); // dd($response);
$responseJ = json_decode($response); $responseJ = json_decode($response);
if($response === false ){ if ($response === false) {
return response()->json([ return response()->json([
'code' =>'400', 'code' => '400',
'status' =>'Failed', 'status' => 'Failed',
'message' =>'Token Verification Error...'.curl_error($curl) 'message' => 'Token Verification Error...' . curl_error($curl),
]); ]);
} } elseif (isset($responseJ->access_token)) {
else if(isset($responseJ->access_token) ){ $IonToken = $responseJ->access_token;
$IonToken = $responseJ->access_token;
// Log::info("New Token: " . $IonToken); // Log::info("New Token: " . $IonToken);
Cache::put('token', $IonToken, now()->addMinutes(59)); Cache::put('token', $IonToken, now()->addMinutes(59));
} } else {
else{
// dd($response); // dd($response);
return response()->json([ return response()->json([
'code' =>'400', 'code' => '400',
'status' =>'Failed', 'status' => 'Failed',
'message' =>'Token Verification Error...M3 response:'.$response 'message' => 'Token Verification Error...M3 response:' . $response,
]); ]);
} }
@@ -88,158 +80,158 @@ class Helper
// ]); // ]);
} }
# Check M3 API Token V2 // Check M3 API Token V2
public static function checkReceiveTokenV2(){ public static function checkReceiveTokenV2()
{
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
# Clear Cache // Clear Cache
// Cache::forget('token'); // Cache::forget('token');
# Check if cached Token is still Valid // Check if cached Token is still Valid
$token = Cache::get('token'); $token = Cache::get('token');
if (isset($token)) { if (isset($token)) {
$IonToken = $token; $IonToken = $token;
// Log::info("Cached Token: ".$IonToken); // Log::info("Cached Token: ".$IonToken);
} } else {
else{ // ## CURL
### CURL // ## Generate Token
### Generate Token
$curl = curl_init(); $curl = curl_init();
curl_setopt_array($curl, array( curl_setopt_array($curl, [
CURLOPT_URL => env('ENDPOINTURLSSO').env('URLTOKEN'), CURLOPT_URL => env('ENDPOINTURLSSO') . env('URLTOKEN'),
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '', CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10, CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0, CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true, CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'grant_type='.env('GRANT_TYPE').'&password='.env('PASSWORD').'&username='.env('USERNAME').'&client_secret='.env('CLIENT_SECRET'). CURLOPT_POSTFIELDS => 'grant_type=' . env('GRANT_TYPE') . '&password=' . env('PASSWORD') . '&username=' . env('USERNAME') . '&client_secret=' . env('CLIENT_SECRET') .
'&client_id='.env('CLIENT_ID'), '&client_id=' . env('CLIENT_ID'),
CURLOPT_HTTPHEADER => array( CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded', 'Content-Type: application/x-www-form-urlencoded',
'charset:UTF-8', 'charset:UTF-8',
'Accept: application/json' 'Accept: application/json',
), ],
)); ]);
$response = curl_exec($curl); $response = curl_exec($curl);
// dd($response); // dd($response);
$responseJ = json_decode($response); $responseJ = json_decode($response);
curl_close($curl); curl_close($curl);
if($response === false ){ if ($response === false) {
# Clear Cache // Clear Cache
Cache::forget('token'); Cache::forget('token');
# Return Error
// Return Error
return response()->json([ return response()->json([
'code' =>'400', 'code' => '400',
'status' =>'Failed', 'status' => 'Failed',
'message' =>'Token Verification Error...'.curl_error($curl) 'message' => 'Token Verification Error...' . curl_error($curl),
]); ]);
} } elseif (isset($responseJ->access_token)) {
else if(isset($responseJ->access_token) ){ $IonToken = $responseJ->access_token;
$IonToken = $responseJ->access_token;
// Log::info("New Token: " . $IonToken); // Log::info("New Token: " . $IonToken);
Cache::put('token', $IonToken, now()->addMinutes(59)); Cache::put('token', $IonToken, now()->addMinutes(59));
} } else {
else{ // Clear Cache
# Clear Cache
Cache::forget('token'); Cache::forget('token');
return response()->json([ return response()->json([
'code' =>'400', 'code' => '400',
'status' =>'Failed', 'status' => 'Failed',
'message' =>'Token Verification Error...M3 response:'.$response 'message' => 'Token Verification Error...M3 response:' . $response,
]); ]);
} }
} }
// return $IonToken; // return $IonToken;
return response()->json([ return response()->json([
'code' => '200', 'code' => '200',
'token' => $IonToken 'token' => $IonToken,
]); ]);
} }
# Read M3 JSON and Analyse it for Errors // Read M3 JSON and Analyse it for Errors
public static function checkM3Errors($responseResult){ public static function checkM3Errors($responseResult)
{
// dd($responseResult); // dd($responseResult);
# M3 Response Types // M3 Response Types
$M3TypesResponse = ['CloseShipment','Move','COCharge','Replenish','MoveDock']; $M3TypesResponse = ['CloseShipment', 'Move', 'COCharge', 'Replenish', 'MoveDock'];
# CloseShipment Types And Contents // CloseShipment Types And Contents
$M3CloseShipmentResp = ['AddPackage','PickingListClose','TrailerNo','TrackingNo','ContentLabel', 'DeliveryNote','ShipLabel']; $M3CloseShipmentResp = ['AddPackage', 'PickingListClose', 'TrailerNo', 'TrackingNo', 'ContentLabel', 'DeliveryNote', 'ShipLabel'];
// 'ContentLabel', 'DeliveryNote','ShipLabel' // 'ContentLabel', 'DeliveryNote','ShipLabel'
$ErrorMessages = ''; $ErrorMessages = '';
$typesErrors =0; $typesErrors = 0;
foreach ($M3TypesResponse as $key => $Type) { foreach ($M3TypesResponse as $key => $Type) {
// dump($responseResult->$Type); // dump($responseResult->$Type);
if ($Type=='CloseShipment') { if ($Type == 'CloseShipment') {
// dump($Type); // dump($Type);
$CloseShipmentErr = 0; $CloseShipmentErr = 0;
$M3RespClose = $responseResult->$Type; $M3RespClose = $responseResult->$Type;
foreach ($M3CloseShipmentResp as $key => $closeType) { foreach ($M3CloseShipmentResp as $key => $closeType) {
$ErrorMessage = $M3RespClose->$closeType->ErrorMessage; $ErrorMessage = $M3RespClose->$closeType->ErrorMessage;
$ErrorMessage = $ErrorMessage=="" ? "" : $ErrorMessage; $ErrorMessage = $ErrorMessage == '' ? '' : $ErrorMessage;
$Result = $M3RespClose->$closeType->Result; $Result = $M3RespClose->$closeType->Result;
$ResultT = $M3RespClose->$closeType->Result; $ResultT = $M3RespClose->$closeType->Result;
$Result = $Result=="N/A" || $Result=="OK" ? "" : $Result; $Result = $Result == 'N/A' || $Result == 'OK' ? '' : $Result;
if ($ErrorMessage!='' || $Result!='') { if ($ErrorMessage != '' || $Result != '') {
$ErrorMessages .= $closeType.'-'.$Result.'-'.$ErrorMessage.' '; $ErrorMessages .= $closeType . '-' . $Result . '-' . $ErrorMessage . ' ';
} }
// dump($closeType);// dump($ErrorMessage);// dump($Result); // dump($closeType);// dump($ErrorMessage);// dump($Result);
if ($ResultT=="N/A") { if ($ResultT == 'N/A') {
$CloseShipmentErr++; $CloseShipmentErr++;
} }
} }
} } elseif ($Type == 'MoveDock') {
else if($Type=='MoveDock'){ $MoveDockRes = isset($responseResult->$Type->Move) ? $responseResult->$Type->Move : '';
$MoveDockRes = isset($responseResult->$Type->Move) ? $responseResult->$Type->Move : ''; $ErrorMessage = isset($MoveDockRes->ErrorMessage) ? $MoveDockRes->ErrorMessage : '';
$ErrorMessage = isset($MoveDockRes->ErrorMessage) ? $MoveDockRes->ErrorMessage :''; $ErrorMessage = $ErrorMessage == '' ? '' : $ErrorMessage;
$ErrorMessage = $ErrorMessage=="" ? "" : $ErrorMessage; $Result = isset($MoveDockRes->Result) ? $MoveDockRes->Result : '';
$Result = isset($MoveDockRes->Result) ? $MoveDockRes->Result : ""; $ResultT = $Result;
$ResultT = $Result; $Result = $Result == 'N/A' || $Result == 'OK' ? '' : $Result;
$Result = $Result=="N/A" || $Result=="OK" ? "" : $Result; if ($ErrorMessage != '' || $Result != '') {
if ($ErrorMessage!='' || $Result!='') { $ErrorMessages .= $Type . '-' . $Result . '-' . $ErrorMessage . ' ';
$ErrorMessages .= $Type.'-'.$Result.'-'.$ErrorMessage.' ';
} }
// dump($Type);// dump($ErrorMessage);// dump($Result);// dump($responseResult->$Type); // dump($Type);// dump($ErrorMessage);// dump($Result);// dump($responseResult->$Type);
if ($ResultT=="N/A") { if ($ResultT == 'N/A') {
$typesErrors++; $typesErrors++;
} }
} } else {
else{ $ErrorMessage = isset($responseResult->$Type->ErrorMessage) ? $responseResult->$Type->ErrorMessage : '';
$ErrorMessage = isset($responseResult->$Type->ErrorMessage) ? $responseResult->$Type->ErrorMessage :''; $ErrorMessage = $ErrorMessage == '' ? '' : $ErrorMessage;
$ErrorMessage = $ErrorMessage=="" ? "" : $ErrorMessage; $Result = isset($responseResult->$Type->Result) ? $responseResult->$Type->Result : '';
$Result = isset($responseResult->$Type->Result) ? $responseResult->$Type->Result : ""; $ResultT = $Result;
$ResultT = $Result; $Result = $Result == 'N/A' || $Result == 'OK' ? '' : $Result;
$Result = $Result=="N/A" || $Result=="OK" ? "" : $Result; if ($ErrorMessage != '' || $Result != '') {
if ($ErrorMessage!='' || $Result!='') { $ErrorMessages .= $Type . '-' . $Result . '-' . $ErrorMessage . ' ';
$ErrorMessages .= $Type.'-'.$Result.'-'.$ErrorMessage.' ';
} }
// dump($Type); // dump($ErrorMessage); // dump($Result); // dump($responseResult->$Type); // dump($Type); // dump($ErrorMessage); // dump($Result); // dump($responseResult->$Type);
if ($ResultT=="N/A") { if ($ResultT == 'N/A') {
$typesErrors++; $typesErrors++;
} }
} }
} }
// dd($ErrorMessages); // dd($ErrorMessages);
if ($CloseShipmentErr == count($M3CloseShipmentResp) && $typesErrors == count($M3TypesResponse)-1) { if ($CloseShipmentErr == count($M3CloseShipmentResp) && $typesErrors == count($M3TypesResponse) - 1) {
$ErrorMessages .= '-M3 did not call any method or type '; $ErrorMessages .= '-M3 did not call any method or type ';
} }
return $ErrorMessages; return $ErrorMessages;
} }
# Log All Success And Error to ICM699M // Log All Success And Error to ICM699M
public static function logToICM699M($data){ public static function logToICM699M($data)
{
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
$insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('ICM699M')->insert($data); $insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('ICM699M')->insert($data);
@@ -247,8 +239,9 @@ class Helper
// dump($insertSQL); // dump($insertSQL);
} }
# Get Substring in string between 2 Substrings // Get Substring in string between 2 Substrings
public static function getSubstringBetween($string, $start, $end) { public static function getSubstringBetween($string, $start, $end)
{
$startPos = strpos($string, $start); $startPos = strpos($string, $start);
if ($startPos === false) { if ($startPos === false) {
return ''; return '';
@@ -258,12 +251,13 @@ class Helper
return ''; return '';
} }
$substring = substr($string, $startPos + strlen($start), $endPos - ($startPos + strlen($start))); $substring = substr($string, $startPos + strlen($start), $endPos - ($startPos + strlen($start)));
return $substring; return $substring;
} }
public static function checkLength($JSONL,$DBL,$TYPE) public static function checkLength($JSONL, $DBL, $TYPE)
{ {
# Check type // Check type
$JSONType = gettype($JSONL); $JSONType = gettype($JSONL);
switch ($JSONType) { switch ($JSONType) {
@@ -285,11 +279,11 @@ class Helper
// Log::info( $JSONL .' L: '. strlen($JSONL) .' DBL: '. $DBL .' Type:'.$JSONType.':'.$TYPE ); // Log::info( $JSONL .' L: '. strlen($JSONL) .' DBL: '. $DBL .' Type:'.$JSONType.':'.$TYPE );
// Check Json Field should be < DB Field // Check Json Field should be < DB Field
$LengthOK[413] = ( strlen($JSONL) <= $DBL ) ? true : false ; $LengthOK[413] = (strlen($JSONL) <= $DBL) ? true : false;
// Empty Fields // Empty Fields
$LengthOK[411] = true; //!empty($JSONL) ? true : false ; $LengthOK[411] = true; // !empty($JSONL) ? true : false ;
// Wrong Types // Wrong Types
$LengthOK[417] = true; //$JSONTypeConv == $TYPE ? true : false ; $LengthOK[417] = true; // $JSONTypeConv == $TYPE ? true : false ;
// Log::info($LengthOK); // Log::info($LengthOK);
return $LengthOK; return $LengthOK;
@@ -297,22 +291,22 @@ class Helper
public static function sanityzeString($StrTosanityze) public static function sanityzeString($StrTosanityze)
{ {
$badChars = Config::get('arrays.BadChars'); $badChars = Config::get('arrays.BadChars');
$goodString = trim($StrTosanityze); $goodString = trim($StrTosanityze);
$goodString = str_replace("'", "",$goodString); $goodString = str_replace("'", '', $goodString);
$goodString = preg_replace('/\x{f0e0}/u', '', $goodString); $goodString = preg_replace('/\x{f0e0}/u', '', $goodString);
$goodString = preg_replace('/\\\\u201[0-9A-F]+/i', '', $goodString); $goodString = preg_replace('/\\\\u201[0-9A-F]+/i', '', $goodString);
$goodString = str_replace($badChars, '',$goodString); $goodString = str_replace($badChars, '', $goodString);
$goodString = iconv("UTF-8", "ISO-8859-1//IGNORE", $goodString); $goodString = iconv('UTF-8', 'ISO-8859-1//IGNORE', $goodString);
$goodString = iconv("ISO-8859-1", "UTF-8", $goodString); $goodString = iconv('ISO-8859-1', 'UTF-8', $goodString);
# MAK : New Automatic Detection for encoding and conversion // MAK : New Automatic Detection for encoding and conversion
# Detect the encoding // Detect the encoding
// $encoding = mb_detect_encoding($goodString, mb_list_encodings(), true); // $encoding = mb_detect_encoding($goodString, mb_list_encodings(), true);
// Log::info($goodString); // Log::info($goodString);
# If encoding is detected, convert the string // If encoding is detected, convert the string
// if ($encoding !== false) { // if ($encoding !== false) {
// // Log::info($encoding); // // Log::info($encoding);
// // Log::info($goodString); // // Log::info($goodString);
@@ -326,14 +320,15 @@ class Helper
return $goodString; return $goodString;
} }
# Remove Duplicate SubString // Remove Duplicate SubString
public static function removeDuplicateSubstrings($str) { public static function removeDuplicateSubstrings($str)
{
$result = ''; $result = '';
$seenPhrases = []; $seenPhrases = [];
$phrases = explode(' ', $str); $phrases = explode(' ', $str);
foreach ($phrases as $phrase) { foreach ($phrases as $phrase) {
if (!in_array($phrase, $seenPhrases)) { if (! in_array($phrase, $seenPhrases)) {
$result .= $phrase . ' '; $result .= $phrase . ' ';
$seenPhrases[] = $phrase; $seenPhrases[] = $phrase;
} }
@@ -342,44 +337,42 @@ class Helper
return trim($result); return trim($result);
} }
public static function getUserCOWHSPLT(){ public static function getUserCOWHSPLT()
$defaults = [ {
'UserCO' => '', $defaults = [
'UserWHS' => '', 'UserCO' => '',
'UserPL' => '', 'UserWHS' => '',
]; 'UserPL' => '',
$loggedUser = strtoupper(trim((string) m3_user()));
if ($loggedUser === '') {
return $defaults;
}
try {
if (!\Illuminate\Support\Facades\Schema::connection(config('m3.connection', 'pgsql'))->hasTable('icm428m')) {
return $defaults;
}
$user = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US', 'R428ADMUSR', 'R428PWRUSR', 'R428CO', 'R428PL', 'R428WH', 'R42811A', 'R42821A')
->where('R428US', $loggedUser)
->first();
if (!$user) {
return $defaults;
}
return [
'UserCO' => trim((string) ($user->R428CO ?? '')),
'UserWHS' => trim((string) ($user->R428WH ?? '')),
'UserPL' => trim((string) ($user->R428PL ?? '')),
]; ];
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::warning('M3 user context unavailable', ['exception' => $e->getMessage()]); $loggedUser = strtoupper(trim((string) m3_user()));
return $defaults; if ($loggedUser === '') {
return $defaults;
}
try {
if (! Schema::connection(config('m3.connection', 'pgsql'))->hasTable('icm428m')) {
return $defaults;
}
$user = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US', 'R428ADMUSR', 'R428PWRUSR', 'R428CO', 'R428PL', 'R428WH', 'R42811A', 'R42821A')
->where('R428US', $loggedUser)
->first();
if (! $user) {
return $defaults;
}
return [
'UserCO' => trim((string) ($user->R428CO ?? '')),
'UserWHS' => trim((string) ($user->R428WH ?? '')),
'UserPL' => trim((string) ($user->R428PL ?? '')),
];
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::warning('M3 user context unavailable', ['exception' => $e->getMessage()]);
return $defaults;
}
} }
} }
}
@@ -1,11 +1,14 @@
<?php <?php
if (! function_exists('subdirAsset')) { if (! function_exists('subdirAsset')) {
function subdirAsset($path){ function subdirAsset($path)
return asset( (App::environment('production') ? env('APP_DIR') : '')."/".$path); {
} return asset((App::environment('production') ? env('APP_DIR') : '') . '/' . $path);
}
} }
if (! function_exists('subdirMix')) { if (! function_exists('subdirMix')) {
function subdirMix($path){ function subdirMix($path)
return mix( (App::environment('production') ? env('APP_DIR') : '')."/".$path); {
} return mix((App::environment('production') ? env('APP_DIR') : '') . '/' . $path);
}
} }
+2 -1
View File
@@ -1,4 +1,5 @@
<?php <?php
// app/Helpers/USStates.php // app/Helpers/USStates.php
namespace Modules\M3\Helpers; namespace Modules\M3\Helpers;
@@ -58,7 +59,7 @@ class USStates
'WV' => 'West Virginia', 'WV' => 'West Virginia',
'WI' => 'Wisconsin', 'WI' => 'Wisconsin',
'WY' => 'Wyoming', 'WY' => 'Wyoming',
'DC' => 'District of Columbia' 'DC' => 'District of Columbia',
]; ];
} }
} }
File diff suppressed because it is too large Load Diff
+288 -286
View File
@@ -2,18 +2,18 @@
namespace Modules\M3\Http\Controllers\API; namespace Modules\M3\Http\Controllers\API;
use Modules\M3\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use DB;
use Config; use Config;
use Str; use DB;
use Illuminate\Http\Request;
use Log; use Log;
use Modules\M3\Helpers\Helper; use Modules\M3\Helpers\Helper;
use Modules\M3\Http\Controllers\Controller;
use Modules\M3\Services\PostgresProgramBridge;
use Str;
class M3Controller extends Controller class M3Controller extends Controller
{ {
# Split Data and Write to ICM666M2 // Split Data and Write to ICM666M2
public function insertToICM666M2($dataSplit, $commentData) public function insertToICM666M2($dataSplit, $commentData)
{ {
// dump($commentData); // dump($commentData);
@@ -22,7 +22,7 @@ class M3Controller extends Controller
$commentDataSS = explode("\n", $dataSplit); $commentDataSS = explode("\n", $dataSplit);
$AXLINENO = 1; $AXLINENO = 1;
foreach ($commentDataSS as $substring) { foreach ($commentDataSS as $substring) {
# Process each substring // Process each substring
$fullData = $commentData; $fullData = $commentData;
$fullData['AXCOMMENT'] = $substring; $fullData['AXCOMMENT'] = $substring;
$fullData['AXLINENO'] = $AXLINENO; $fullData['AXLINENO'] = $AXLINENO;
@@ -31,17 +31,21 @@ class M3Controller extends Controller
$AXLINENO++; $AXLINENO++;
# AXCO ICM666M2 CHARACTER 3 // AXCO ICM666M2 CHARACTER 3
# AXWHS ICM666M2 CHARACTER 3 // AXWHS ICM666M2 CHARACTER 3
# AXPLANT ICM666M2 CHARACTER 3 // AXPLANT ICM666M2 CHARACTER 3
# AXDOCUMENT ICM666M2 CHARACTER 15 // AXDOCUMENT ICM666M2 CHARACTER 15
# AXCOMMENT ICM666M2 CHARACTER 60 // AXCOMMENT ICM666M2 CHARACTER 60
# AXLINENO DECIMAL(3,0) // AXLINENO DECIMAL(3,0)
} }
} }
public function index(){ dd("Index"); } public function index()
public function create(){} {
dd('Index');
}
public function create() {}
public function store(Request $request) public function store(Request $request)
{ {
@@ -53,240 +57,240 @@ class M3Controller extends Controller
$SHSOURCE = 'M3ReceiverAPI'; $SHSOURCE = 'M3ReceiverAPI';
$ICM666MFields = [ $ICM666MFields = [
'Company' =>[ 'A1CO' ,3 , 'string' ], 'Company' => ['A1CO', 3, 'string'],
'Warehouse' =>[ 'A1WHS', 3, 'string'], 'Warehouse' => ['A1WHS', 3, 'string'],
'Plant' =>[ 'A1PLANT', 3, 'string'], 'Plant' => ['A1PLANT', 3, 'string'],
'PickerNumber' =>[ 'A1DELNO',11,'integer'], 'PickerNumber' => ['A1DELNO', 11, 'integer'],
'OrderNumber' =>[ 'A1ONO' ,10, 'string'], 'OrderNumber' => ['A1ONO', 10, 'string'],
'ReleaseNumber' =>[ 'A1RLNO' , 3,'string'], # Pick list suffix in ICM666M 'ReleaseNumber' => ['A1RLNO', 3, 'string'], // Pick list suffix in ICM666M
'ShipmentNumber' =>[ 'A1SHNO' ,7,'string'], 'ShipmentNumber' => ['A1SHNO', 7, 'string'],
'OrderLine' =>[ 'A1PKLN',6,'integer'], 'OrderLine' => ['A1PKLN', 6, 'integer'],
'PartNumber' =>[ 'A1PART', 15,'string'], 'PartNumber' => ['A1PART', 15, 'string'],
'Description' =>[ 'A1PARTDES', 120,'string'], 'Description' => ['A1PARTDES', 120, 'string'],
'Quantity' =>[ 'A1RSVQTY', 22,'DEC'], 'Quantity' => ['A1RSVQTY', 22, 'DEC'],
'BaseUnitPrice' =>[ 'A1SLUNPR', 22,'DEC'], 'BaseUnitPrice' => ['A1SLUNPR', 22, 'DEC'],
'Currency' =>[ 'A1SHCURR',3,'string'], 'Currency' => ['A1SHCURR', 3, 'string'],
'Zone' =>[ 'A1LVZONE', 2,'string'], 'Zone' => ['A1LVZONE', 2, 'string'],
'PromDate' =>[ 'A1PROMDTE',8,'integer'], 'PromDate' => ['A1PROMDTE', 8, 'integer'],
'RouteCode' =>[ 'A1SHSRT' ,6,'string'], 'RouteCode' => ['A1SHSRT', 6, 'string'],
'BillToId' =>[ 'A1BILLTO' ,10,'string'], 'BillToId' => ['A1BILLTO', 10, 'string'],
'ShipToId' =>[ 'A1SHIPTO',10,'string'], 'ShipToId' => ['A1SHIPTO', 10, 'string'],
'CompanyName' =>[ 'A1SHSHNM',36,'string'], 'CompanyName' => ['A1SHSHNM', 36, 'string'],
'Address1' =>[ 'A1SHSHA1', 36,'string'], 'Address1' => ['A1SHSHA1', 36, 'string'],
'Address2' =>[ 'A1SHSHA2', 36,'string'], 'Address2' => ['A1SHSHA2', 36, 'string'],
'Address3' =>[ 'A1SHSHA3', 36,'string'], 'Address3' => ['A1SHSHA3', 36, 'string'],
'Address4' =>[ 'A1SHSHA4', 36,'string'], 'Address4' => ['A1SHSHA4', 36, 'string'],
'City' =>[ 'A1SHSHCI', 20,'string'], 'City' => ['A1SHSHCI', 20, 'string'],
'State' =>[ 'A1SHSHST', 2,'string'], 'State' => ['A1SHSHST', 2, 'string'],
'PostalCode' =>[ 'A1SHSHZP', 10,'string'], 'PostalCode' => ['A1SHSHZP', 10, 'string'],
'Country' =>[ 'A1SHSHCT',3,'string'], 'Country' => ['A1SHSHCT', 3, 'string'],
'CountryName' =>[ 'A1SHP2CNTY', 40,'string'], 'CountryName' => ['A1SHP2CNTY', 40, 'string'],
'PartWeight' =>[ 'A1PRTWGT', 15,'integer'], 'PartWeight' => ['A1PRTWGT', 15, 'integer'],
'SellUOM' =>[ 'A1SLUOM', 3,'string'], 'SellUOM' => ['A1SLUOM', 3, 'string'],
'PartConv' =>[ 'A1PARTCONV', 25,'DEC'], 'PartConv' => ['A1PARTCONV', 25, 'DEC'],
'CarrierCode' =>[ 'A1CARRIER', 6,'string'], 'CarrierCode' => ['A1CARRIER', 6, 'string'],
'ShipVia' =>[ 'A1SHPVIA', 3,'string'], 'ShipVia' => ['A1SHPVIA', 3, 'string'],
'PrimaryLocation' =>[ 'A1PRIMLOC', 10,'string'], 'PrimaryLocation' => ['A1PRIMLOC', 10, 'string'],
'Allocation' =>[ 'A1SPR10A01', 10,'string'], 'Allocation' => ['A1SPR10A01', 10, 'string'],
'AllocatedTo' =>[ 'A1SPR15A01', 10,'string'], 'AllocatedTo' => ['A1SPR15A01', 10, 'string'],
'LocationSeq' =>[ 'A1LOCSEQ', 10,'string'], 'LocationSeq' => ['A1LOCSEQ', 10, 'string'],
'UOM' =>[ 'A1UOM' , 3,'string'], 'UOM' => ['A1UOM', 3, 'string'],
'HazMat' =>[ 'A1MATWRN', 4,'string'], 'HazMat' => ['A1MATWRN', 4, 'string'],
'PartUPC' =>[ 'A1UPC', 30,'string'], 'PartUPC' => ['A1UPC', 30, 'string'],
'PartEAN' =>[ 'A1EAN', 30,'string'], 'PartEAN' => ['A1EAN', 30, 'string'],
'LotFlag' =>[ 'A1IZLCF', 1,'string'], 'LotFlag' => ['A1IZLCF', 1, 'string'],
'ManOrd' =>[ 'A1MONUM', 30,'string'], 'ManOrd' => ['A1MONUM', 30, 'string'],
'LotNumber' =>[ 'A1LOTNUM', 30,'string'], 'LotNumber' => ['A1LOTNUM', 30, 'string'],
'ProductArea' =>[ 'A1LVUSD1', 15,'string'], 'ProductArea' => ['A1LVUSD1', 15, 'string'],
'FreightClass' =>[ 'A1WBFRCT' , 10,'string'], 'FreightClass' => ['A1WBFRCT', 10, 'string'],
'ShipmentPONumber' =>[ 'A1SOPONO', 20,'string'], 'ShipmentPONumber' => ['A1SOPONO', 20, 'string'],
'ShipmentPOLine' =>[ 'A1SOPOLN' , 7,'integer'], 'ShipmentPOLine' => ['A1SOPOLN', 7, 'integer'],
'ShipTerms' =>[ 'A1OFSTRM', 3,'string'], 'ShipTerms' => ['A1OFSTRM', 3, 'string'],
// 'ExchangeRate' =>[ 'A1EXGRATE', 18,'DEC'], // 'ExchangeRate' =>[ 'A1EXGRATE', 18,'DEC'],
'OrderClass' =>[ 'A1SHORCL', 3,'string'], 'OrderClass' => ['A1SHORCL', 3, 'string'],
'LocationType' =>[ 'A1LVUSD2', 2,'string'], 'LocationType' => ['A1LVUSD2', 2, 'string'],
'PallSize' =>[ 'A1LVUSD3', 10,'string'], 'PallSize' => ['A1LVUSD3', 10, 'string'],
'MasterCarton' =>[ 'A1USRLD1', 30,'string'], 'MasterCarton' => ['A1USRLD1', 30, 'string'],
'MasterQty' =>[ 'A1WBSHQY', 25,'DEC'], 'MasterQty' => ['A1WBSHQY', 25, 'DEC'],
'InnerQty' =>[ 'A1WBPKQY', 25,'DEC'], 'InnerQty' => ['A1WBPKQY', 25, 'DEC'],
'PalletQty' =>[ 'A1USRN01', 24,'DEC'], 'PalletQty' => ['A1USRN01', 24, 'DEC'],
'CartonQty' =>[ 'A1USRN31', 25,'DEC'], 'CartonQty' => ['A1USRN31', 25, 'DEC'],
'PersonName' =>[ 'A1PERNAME', 30,'string'], 'PersonName' => ['A1PERNAME', 30, 'string'],
'AccountNo' =>[ 'A1ACCNUM', 20,'string'], 'AccountNo' => ['A1ACCNUM', 20, 'string'],
'Email' =>[ 'A1EMAIL', 100,'string'], 'Email' => ['A1EMAIL', 100, 'string'],
'OrderCategory' =>[ 'A1REFORD', 1,'string'], 'OrderCategory' => ['A1REFORD', 1, 'string'],
'A1DATEADD' =>[ 'A1DATEADD', 12,'string'], 'A1DATEADD' => ['A1DATEADD', 12, 'string'],
'A1TIMEADD' =>[ 'A1TIMEADD', 12,'string'], 'A1TIMEADD' => ['A1TIMEADD', 12, 'string'],
'KitPartNumber' =>[ 'A1KITPART', 15,'string'], 'KitPartNumber' => ['A1KITPART', 15, 'string'],
'OrderLineSuffix' =>[ 'A1PKSFX', 6,'DEC'], 'OrderLineSuffix' => ['A1PKSFX', 6, 'DEC'],
'CustomerPartNumber'=>[ 'A1CUSTPART', 20,'string'], 'CustomerPartNumber' => ['A1CUSTPART', 20, 'string'],
'GS1Label' => ['A1SPR1A01', 1, 'string'], 'GS1Label' => ['A1SPR1A01', 1, 'string'],
'CurrencyExchangeRate' =>[ 'A1EXGRATE', 18,'DEC'], 'CurrencyExchangeRate' => ['A1EXGRATE', 18, 'DEC'],
]; ];
try { try {
$jsonFile = count($request->json()->all()) > 0 ? $request->json()->all() : ''; $jsonFile = count($request->json()->all()) > 0 ? $request->json()->all() : '';
# Root // Root
$Company = isset($jsonFile["Company"]) ? $jsonFile["Company"] : ''; $Company = isset($jsonFile['Company']) ? $jsonFile['Company'] : '';
$Plant = isset($jsonFile["Plant"]) ? $jsonFile["Plant"] : ''; $Plant = isset($jsonFile['Plant']) ? $jsonFile['Plant'] : '';
$Warehouse = isset($jsonFile["Warehouse"]) ? $jsonFile["Warehouse"] : ''; $Warehouse = isset($jsonFile['Warehouse']) ? $jsonFile['Warehouse'] : '';
$OrderNumber = isset($jsonFile["OrderNumber"]) ? $jsonFile["OrderNumber"] : ''; $OrderNumber = isset($jsonFile['OrderNumber']) ? $jsonFile['OrderNumber'] : '';
$PickerNumber = isset($jsonFile["PickerNumber"]) ? $jsonFile["PickerNumber"] : ''; $PickerNumber = isset($jsonFile['PickerNumber']) ? $jsonFile['PickerNumber'] : '';
$PromDate = isset($jsonFile["PromDate"]) ? $jsonFile["PromDate"] : ''; $PromDate = isset($jsonFile['PromDate']) ? $jsonFile['PromDate'] : '';
$RouteCode = isset($jsonFile["RouteCode"]) ? $jsonFile["RouteCode"] : ''; $RouteCode = isset($jsonFile['RouteCode']) ? $jsonFile['RouteCode'] : '';
$OrderCategory = isset($jsonFile["OrderCategory"]) ? $jsonFile["OrderCategory"] : ''; $OrderCategory = isset($jsonFile['OrderCategory']) ? $jsonFile['OrderCategory'] : '';
$ReleaseNumber = isset($jsonFile["ReleaseNumber"]) ? $jsonFile["ReleaseNumber"] : ''; $ReleaseNumber = isset($jsonFile['ReleaseNumber']) ? $jsonFile['ReleaseNumber'] : '';
$ShipmentNumber = isset($jsonFile["ShipmentNumber"]) ? $jsonFile["ShipmentNumber"] : ''; $ShipmentNumber = isset($jsonFile['ShipmentNumber']) ? $jsonFile['ShipmentNumber'] : '';
$Currency = isset($jsonFile["Currency"]) ? $jsonFile["Currency"] : ''; $Currency = isset($jsonFile['Currency']) ? $jsonFile['Currency'] : '';
$CarrierCode = isset($jsonFile["CarrierCode"]) ? $jsonFile["CarrierCode"] : ''; $CarrierCode = isset($jsonFile['CarrierCode']) ? $jsonFile['CarrierCode'] : '';
$ShipmentPONumber = isset($jsonFile["ShipmentPONumber"]) ? $jsonFile["ShipmentPONumber"] : ''; // CustPo $ShipmentPONumber = isset($jsonFile['ShipmentPONumber']) ? $jsonFile['ShipmentPONumber'] : ''; // CustPo
$ShipTerms = isset($jsonFile["ShipTerms"]) ? $jsonFile["ShipTerms"] : ''; $ShipTerms = isset($jsonFile['ShipTerms']) ? $jsonFile['ShipTerms'] : '';
// $ExchangeRate = isset($jsonFile["ExchangeRate"]) ? $jsonFile["ExchangeRate"] : ''; // $ExchangeRate = isset($jsonFile["ExchangeRate"]) ? $jsonFile["ExchangeRate"] : '';
$OrderClass = isset($jsonFile["OrderClass"]) ? $jsonFile["OrderClass"] : ''; $OrderClass = isset($jsonFile['OrderClass']) ? $jsonFile['OrderClass'] : '';
$GS1Label = isset($jsonFile["GS1-128Label"]) ? $jsonFile["GS1-128Label"] : '0'; $GS1Label = isset($jsonFile['GS1-128Label']) ? $jsonFile['GS1-128Label'] : '0';
$CurrencyExchangeRate = isset($jsonFile["CurrencyExchangeRate"]) ? $jsonFile["CurrencyExchangeRate"] : ''; $CurrencyExchangeRate = isset($jsonFile['CurrencyExchangeRate']) ? $jsonFile['CurrencyExchangeRate'] : '';
# Set Carrier BWAY if it's empty for Tilburg only // Set Carrier BWAY if it's empty for Tilburg only
if (($CarrierCode=='' || $CarrierCode==null) && $Warehouse=='111' && $Company=='410' && $Plant=='410' ) { if (($CarrierCode == '' || $CarrierCode == null) && $Warehouse == '111' && $Company == '410' && $Plant == '410') {
$CarrierCode = 'BWAY'; $CarrierCode = 'BWAY';
} }
$SHMACPKR = $PickerNumber!='' ? $PickerNumber : '000000'; $SHMACPKR = $PickerNumber != '' ? $PickerNumber : '000000';
if($jsonFile!=''){ if ($jsonFile != '') {
# Order Category // Order Category
/* /*
1 = Material to manufacturing order 1 = Material to manufacturing order
3 = Customer Order 3 = Customer Order
4 = Requisition Order 4 = Requisition Order
5 = Distribution Order 5 = Distribution Order
9 = Move order / Replenishment 9 = Move order / Replenishment
*/ */
# Recipient // Recipient
$recipient = $jsonFile["Recipient"]; $recipient = $jsonFile['Recipient'];
$CompanyName = isset($recipient["CompanyName"]) ? $recipient["CompanyName"] : ''; $CompanyName = isset($recipient['CompanyName']) ? $recipient['CompanyName'] : '';
$Address1 = isset($recipient["Address1"]) ? $recipient["Address1"]: ''; $Address1 = isset($recipient['Address1']) ? $recipient['Address1'] : '';
$Address2 = isset($recipient["Address2"]) ? $recipient["Address2"] : ''; $Address2 = isset($recipient['Address2']) ? $recipient['Address2'] : '';
$City = isset($recipient["City"]) ? $recipient["City"] : ''; $City = isset($recipient['City']) ? $recipient['City'] : '';
$State = isset($recipient["State"]) ? $recipient["State"] : ''; $State = isset($recipient['State']) ? $recipient['State'] : '';
$PostalCode = isset($recipient["PostalCode"]) ? $recipient["PostalCode"]: ''; $PostalCode = isset($recipient['PostalCode']) ? $recipient['PostalCode'] : '';
$Country = isset($recipient["Country"]) ? $recipient["Country"]: ''; $Country = isset($recipient['Country']) ? $recipient['Country'] : '';
$PostalCode = isset($recipient["PostalCode"]) ? $recipient["PostalCode"]: ''; $PostalCode = isset($recipient['PostalCode']) ? $recipient['PostalCode'] : '';
$BillToId = isset($recipient["BillToId"]) ? $recipient["BillToId"]: ''; $BillToId = isset($recipient['BillToId']) ? $recipient['BillToId'] : '';
$ShipToId = isset($recipient["ShipToId"]) ? $recipient["ShipToId"]: ''; $ShipToId = isset($recipient['ShipToId']) ? $recipient['ShipToId'] : '';
$Address3 = isset($recipient["Address3"]) ? $recipient["Address3"] : ''; $Address3 = isset($recipient['Address3']) ? $recipient['Address3'] : '';
$Address4 = isset($recipient["Address4"]) ? $recipient["Address4"] : ''; $Address4 = isset($recipient['Address4']) ? $recipient['Address4'] : '';
$CountryName = isset($recipient["CountryName"]) ? $recipient["CountryName"] : ''; $CountryName = isset($recipient['CountryName']) ? $recipient['CountryName'] : '';
$PersonName = isset($recipient["PersonName"]) ? $recipient["PersonName"] : ''; $PersonName = isset($recipient['PersonName']) ? $recipient['PersonName'] : '';
$AccountNo = isset($recipient["AccountNo"]) ? $recipient["AccountNo"] : ''; $AccountNo = isset($recipient['AccountNo']) ? $recipient['AccountNo'] : '';
$Email = isset($recipient["Email"]) ? $recipient["Email"] : ''; $Email = isset($recipient['Email']) ? $recipient['Email'] : '';
$A1DATEADD = date("Ymd"); $A1DATEADD = date('Ymd');
$A1TIMEADD = date("His"); $A1TIMEADD = date('His');
# MycarrierDetails // MycarrierDetails
$ShipVia = isset($jsonFile["ShipVia"]) ? $jsonFile["ShipVia"]: ''; $ShipVia = isset($jsonFile['ShipVia']) ? $jsonFile['ShipVia'] : '';
# Comments // Comments
$Picker = $Packer = $Carrier = $Other =''; $Picker = $Packer = $Carrier = $Other = '';
$AXCO = $Company; $AXCO = $Company;
$AXPLANT = $Plant; $AXPLANT = $Plant;
$AXWHS = $Warehouse; $AXWHS = $Warehouse;
$AXDELNO = $PickerNumber; $AXDELNO = $PickerNumber;
$AXONO = $OrderNumber; $AXONO = $OrderNumber;
$AXRLNO = $ReleaseNumber; $AXRLNO = $ReleaseNumber;
$AXSHNO = $ShipmentNumber; $AXSHNO = $ShipmentNumber;
$comments = isset($jsonFile["Comments"]) ? $jsonFile["Comments"] : ''; $comments = isset($jsonFile['Comments']) ? $jsonFile['Comments'] : '';
if ($comments!='') { if ($comments != '') {
foreach($comments as $key => $comment) { foreach ($comments as $key => $comment) {
$commentData = []; $commentData = [];
$AXDOCUMENT = Helper::sanityzeString($key); $AXDOCUMENT = Helper::sanityzeString($key);
$commentData=["AXCO"=>$AXCO,"AXPLANT"=>$AXPLANT,"AXWHS"=>$AXWHS,"AXDELNO"=>$AXDELNO,"AXONO"=>$AXONO, $commentData = ['AXCO' => $AXCO, 'AXPLANT' => $AXPLANT, 'AXWHS' => $AXWHS, 'AXDELNO' => $AXDELNO, 'AXONO' => $AXONO,
"AXRLNO"=>$AXRLNO,"AXSHNO"=>$AXSHNO,"AXDOCUMENT"=>$AXDOCUMENT]; 'AXRLNO' => $AXRLNO, 'AXSHNO' => $AXSHNO, 'AXDOCUMENT' => $AXDOCUMENT];
// dump($commentData); // dump($commentData);
switch ($AXDOCUMENT) { switch ($AXDOCUMENT) {
case 'Picker': case 'Picker':
$Picker = isset($comment) ? Helper::sanityzeString($comment) : 'null'; $Picker = isset($comment) ? Helper::sanityzeString($comment) : 'null';
// dump($Picker); // dump($Picker);
if ($Picker!='null') { if ($Picker != 'null') {
$this->insertToICM666M2($Picker,$commentData); $this->insertToICM666M2($Picker, $commentData);
} }
break; break;
case 'Packer': case 'Packer':
$Packer = isset($comment) ? Helper::sanityzeString($comment) : 'null'; $Packer = isset($comment) ? Helper::sanityzeString($comment) : 'null';
// dump($Packer); // dump($Packer);
if ($Packer!='null') { if ($Packer != 'null') {
$this->insertToICM666M2($Packer,$commentData); $this->insertToICM666M2($Packer, $commentData);
} }
break; break;
case 'Carrier': case 'Carrier':
$Carrier = isset($comment) ? Helper::sanityzeString($comment) : 'null'; $Carrier = isset($comment) ? Helper::sanityzeString($comment) : 'null';
// dump($Carrier); // dump($Carrier);
if ($Carrier!='null') { if ($Carrier != 'null') {
$this->insertToICM666M2($Carrier,$commentData); $this->insertToICM666M2($Carrier, $commentData);
} }
break; break;
case 'Other': case 'Other':
$Other = isset($comment) ? Helper::sanityzeString($comment) : 'null'; $Other = isset($comment) ? Helper::sanityzeString($comment) : 'null';
// dump($Other); // dump($Other);
if ($Other!='null') { if ($Other != 'null') {
$this->insertToICM666M2($Other,$commentData); $this->insertToICM666M2($Other, $commentData);
} }
break; break;
} }
} }
} }
# Get Products : commodities And Write ICM666M // Get Products : commodities And Write ICM666M
$tmpProd = ""; $tmpProd = '';
$products = $jsonFile["Contents"]["Commodities"]; $products = $jsonFile['Contents']['Commodities'];
foreach($products as $key => $product) { foreach ($products as $key => $product) {
$Quantity = isset($product['Quantity']) ? $product['Quantity'] : ''; $Quantity = isset($product['Quantity']) ? $product['Quantity'] : '';
$Description = isset($product['Description']) ? Str::limit($product['Description'],25,'') : ''; $Description = isset($product['Description']) ? Str::limit($product['Description'], 25, '') : '';
$PartNumber = isset($product['PartNumber']) ? $product['PartNumber']: ''; $PartNumber = isset($product['PartNumber']) ? $product['PartNumber'] : '';
$OrderLine = isset($product['OrderLine']) ? $product['OrderLine']: ''; $OrderLine = isset($product['OrderLine']) ? $product['OrderLine'] : '';
$PartWeight = isset($product['PartWeight']) ? $product['PartWeight']: ''; $PartWeight = isset($product['PartWeight']) ? $product['PartWeight'] : '';
$PickerLine = isset($product['PickerLine']) ? $product['PickerLine']: ''; $PickerLine = isset($product['PickerLine']) ? $product['PickerLine'] : '';
$PrimaryLocation = isset($product['PrimaryLocation']) ? $product['PrimaryLocation']: ''; $PrimaryLocation = isset($product['PrimaryLocation']) ? $product['PrimaryLocation'] : '';
$Allocation = isset($product['Allocation']) ? $product['Allocation']: ''; $Allocation = isset($product['Allocation']) ? $product['Allocation'] : '';
$AllocatedTo = isset($product['AllocatedTo']) ? $product['AllocatedTo']: ''; $AllocatedTo = isset($product['AllocatedTo']) ? $product['AllocatedTo'] : '';
$LocationSeq = isset($product['LocationSeq']) ? $product['LocationSeq']: ''; $LocationSeq = isset($product['LocationSeq']) ? $product['LocationSeq'] : '';
$Zone = isset($product['Zone']) ? $product['Zone']: ''; $Zone = isset($product['Zone']) ? $product['Zone'] : '';
$BaseUnitPrice = isset($product['BaseUnitPrice']) ? $product['BaseUnitPrice'] : ''; $BaseUnitPrice = isset($product['BaseUnitPrice']) ? $product['BaseUnitPrice'] : '';
$FrgnUnitPrice = isset($product['FrgnUnitPrice']) ? $product['FrgnUnitPrice'] : ''; $FrgnUnitPrice = isset($product['FrgnUnitPrice']) ? $product['FrgnUnitPrice'] : '';
$SellUOM = isset($product['SellUOM']) ? $product['SellUOM'] : ''; $SellUOM = isset($product['SellUOM']) ? $product['SellUOM'] : '';
$PartConv = isset($product['PartConv']) ? $product['PartConv'] : ''; $PartConv = isset($product['PartConv']) ? $product['PartConv'] : '';
$UOM = isset($product['UOM']) ? $product['UOM']: ''; $UOM = isset($product['UOM']) ? $product['UOM'] : '';
$HazMat = isset($product['HazMat']) ? $product['HazMat']: ''; $HazMat = isset($product['HazMat']) ? $product['HazMat'] : '';
$PartUPC = isset($product['PartUPC']) ? $product['PartUPC']: ''; $PartUPC = isset($product['PartUPC']) ? $product['PartUPC'] : '';
$PartEAN = isset($product['PartEAN']) ? $product['PartEAN']: ''; $PartEAN = isset($product['PartEAN']) ? $product['PartEAN'] : '';
$LotFlag = isset($product['LotFlag']) ? $product['LotFlag']: ''; $LotFlag = isset($product['LotFlag']) ? $product['LotFlag'] : '';
$ManOrd = isset($product['ManOrd']) ? $product['ManOrd']: ''; $ManOrd = isset($product['ManOrd']) ? $product['ManOrd'] : '';
$LotNumber = isset($product['LotNumber']) ? $product['LotNumber']: ''; $LotNumber = isset($product['LotNumber']) ? $product['LotNumber'] : '';
$ProductArea = isset($product['ProductArea']) ? $product['ProductArea']: ''; $ProductArea = isset($product['ProductArea']) ? $product['ProductArea'] : '';
$FreightClass = isset($product['FreightClass']) ? $product['FreightClass']: ''; $FreightClass = isset($product['FreightClass']) ? $product['FreightClass'] : '';
$ShipmentPOLine = isset($product['ShipmentPOLine']) ? $product['ShipmentPOLine']: ''; $ShipmentPOLine = isset($product['ShipmentPOLine']) ? $product['ShipmentPOLine'] : '';
$LocationType = isset($product['LocationType']) ? $product['LocationType']: ''; $LocationType = isset($product['LocationType']) ? $product['LocationType'] : '';
$PallSize = isset($product['PallSize']) ? $product['PallSize']: ''; $PallSize = isset($product['PallSize']) ? $product['PallSize'] : '';
$MasterCarton = isset($product['MasterCarton']) ? $product['MasterCarton']: ''; $MasterCarton = isset($product['MasterCarton']) ? $product['MasterCarton'] : '';
$MasterQty = isset($product['MasterQty']) ? $product['MasterQty']: ''; $MasterQty = isset($product['MasterQty']) ? $product['MasterQty'] : '';
$InnerQty = isset($product['InnerQty']) ? $product['InnerQty']: ''; $InnerQty = isset($product['InnerQty']) ? $product['InnerQty'] : '';
$PalletQty = isset($product['PalletQty']) ? $product['PalletQty']: ''; $PalletQty = isset($product['PalletQty']) ? $product['PalletQty'] : '';
$CartonQty = isset($product['CartonQty']) ? $product['CartonQty']: ''; $CartonQty = isset($product['CartonQty']) ? $product['CartonQty'] : '';
$KitPartNumber = isset($product['KitPartNumber']) ? $product['KitPartNumber']: ''; $KitPartNumber = isset($product['KitPartNumber']) ? $product['KitPartNumber'] : '';
$OrderLineSuffix = isset($product['OrderLineSuffix']) ? $product['OrderLineSuffix']: ''; $OrderLineSuffix = isset($product['OrderLineSuffix']) ? $product['OrderLineSuffix'] : '';
$CustomerPartNumber = isset($product['CustomerPartNumber']) ? substr($product['CustomerPartNumber'], 0, 20): ''; # Limit to 20 Chars $CustomerPartNumber = isset($product['CustomerPartNumber']) ? substr($product['CustomerPartNumber'], 0, 20) : ''; // Limit to 20 Chars
# Initialise Table Fields to be filled // Initialise Table Fields to be filled
$InsertArray = []; $InsertArray = [];
$fieldValues = [ $fieldValues = [
'Company' => $Company, 'Company' => $Company,
@@ -360,51 +364,51 @@ class M3Controller extends Controller
'CurrencyExchangeRate' => $CurrencyExchangeRate, 'CurrencyExchangeRate' => $CurrencyExchangeRate,
]; ];
# Check JSON fields if empty or > DB Fields // Check JSON fields if empty or > DB Fields
foreach ($ICM666MFields as $key => $value) { foreach ($ICM666MFields as $key => $value) {
# Sanitize String // Sanitize String
$fieldValue = Helper::sanityzeString($fieldValues[$key] ?? ''); $fieldValue = Helper::sanityzeString($fieldValues[$key] ?? '');
# Check Var Types & Length // Check Var Types & Length
$LengthTest = Helper::checkLength($fieldValue, $value[1], $value[2]); $LengthTest = Helper::checkLength($fieldValue, $value[1], $value[2]);
if (!$LengthTest[413] || !$LengthTest[411] || !$LengthTest[417]) { if (! $LengthTest[413] || ! $LengthTest[411] || ! $LengthTest[417]) {
// Log::error($key .' :: '. $value[0].' :: '. $value[1] .' JSONF: '.$$keyVar .' Type: '.$value[2] ); // Log::error($key .' :: '. $value[0].' :: '. $value[1] .' JSONF: '.$$keyVar .' Type: '.$value[2] );
if(!$LengthTest[413]){ if (! $LengthTest[413]) {
$message[] = [ 'code'=>'413', 'status'=>'error', 'message'=>'Field: '.$key.' is larger then expected']; $message[] = ['code' => '413', 'status' => 'error', 'message' => 'Field: ' . $key . ' is larger then expected'];
} }
if(!$LengthTest[411]){ if (! $LengthTest[411]) {
$message[] = [ 'code'=>'411', 'status'=>'error', 'message'=>'Field: '.$key.' is empty']; $message[] = ['code' => '411', 'status' => 'error', 'message' => 'Field: ' . $key . ' is empty'];
} }
if(!$LengthTest[417]){ if (! $LengthTest[417]) {
$message[] = [ 'code'=>'417', 'status'=>'error', 'message'=>'Field: '.$key.'type is different then Expected type: '.$value[2]]; $message[] = ['code' => '417', 'status' => 'error', 'message' => 'Field: ' . $key . 'type is different then Expected type: ' . $value[2]];
} }
# Write to Logs Out : Error & JSON // Write to Logs Out : Error & JSON
$data = ['SHMACPKR'=>$SHMACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> '','SHTYPE'=> 'M3-Lis-spl' , $data = ['SHMACPKR' => $SHMACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Lis-spl',
'SHDATA'=> json_encode($message).' M3-Lis-JSN'.json_encode($jsonFile) ,'SHUSER'=> $REQKPKUS,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$Company,'SHWHS'=>$Warehouse ]; 'SHDATA' => json_encode($message) . ' M3-Lis-JSN' . json_encode($jsonFile), 'SHUSER' => $REQKPKUS, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $Company, 'SHWHS' => $Warehouse];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json($message); return response()->json($message);
} else if ($fieldValue != '') { } elseif ($fieldValue != '') {
$InsertArray[$value[0]] = $fieldValue; $InsertArray[$value[0]] = $fieldValue;
} }
} }
// Log::info($InsertArray); // Log::info($InsertArray);
# Check ICM709M // Check ICM709M
$ICM709MSEL = DB::connection(config('m3.connection', 'pgsql'))->table('icm709m') $ICM709MSEL = DB::connection(config('m3.connection', 'pgsql'))->table('icm709m')
->select() ->select()
->where('AT9CO',$AXCO) ->where('AT9CO', $AXCO)
->where('AT9PLT',$AXPLANT) ->where('AT9PLT', $AXPLANT)
->where('AT9WHS',$AXWHS) ->where('AT9WHS', $AXWHS)
->where('AT9PART',$PartNumber) ->where('AT9PART', $PartNumber)
->first(); ->first();
$palletQty = isset($ICM709MSEL->AT9QTY) ? $ICM709MSEL->AT9QTY : 0; $palletQty = isset($ICM709MSEL->AT9QTY) ? $ICM709MSEL->AT9QTY : 0;
// dd($palletQty); // dd($palletQty);
# Get Pallet Qty // Get Pallet Qty
$InsertArray['A1USRN01'] = $palletQty; $InsertArray['A1USRN01'] = $palletQty;
# Hazard Material // Hazard Material
$HazMat = isset($ICM709MSEL->AT9WRN) ? $ICM709MSEL->AT9WRN : ''; $HazMat = isset($ICM709MSEL->AT9WRN) ? $ICM709MSEL->AT9WRN : '';
$InsertArray['A1MATWRN'] = $HazMat; $InsertArray['A1MATWRN'] = $HazMat;
@@ -412,28 +416,28 @@ class M3Controller extends Controller
// $InsertArray['A1USRN01']=$palletQty; // $InsertArray['A1USRN01']=$palletQty;
// } // }
# SQL Insert to ICM666M // SQL Insert to ICM666M
$insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('icm666m')->insert($InsertArray); $insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('icm666m')->insert($InsertArray);
} }
# Call PGM ICM700CSBM // Call PGM ICM700CSBM
if ($Warehouse!='' && $PickerNumber!='' && $Company!='') { if ($Warehouse != '' && $PickerNumber != '' && $Company != '') {
$PGMERRORS = ''; $PGMERRORS = '';
$AWREQN = ''; $AWREQN = '';
# connect to toolkit using DB2 credentials (can also leave blank for default authority) // connect to toolkit using DB2 credentials (can also leave blank for default authority)
try { try {
$conn = app(\Modules\M3\Services\PostgresProgramBridge::class); $conn = app(PostgresProgramBridge::class);
} catch (\Exception $e) { } catch (\Exception $e) {
# Determine reason for failure. // Determine reason for failure.
# Probably database authentication error or invalid or unreachable database. // Probably database authentication error or invalid or unreachable database.
$code = $e->getCode(); $code = $e->getCode();
$msg = $e->getMessage(); $msg = $e->getMessage();
switch ($code) { switch ($code) {
case 8001: case 8001:
# "Authorization failure on distributed database connection attempt" // "Authorization failure on distributed database connection attempt"
# Usually means a wrong DB2 user or password // Usually means a wrong DB2 user or password
$PGMERRORS = 'Could not connect due to wrong user or password.'; $PGMERRORS = 'Could not connect due to wrong user or password.';
break; break;
case 42705: case 42705:
@@ -444,91 +448,89 @@ class M3Controller extends Controller
break; break;
} }
} }
$conn->setOptions(array('persistent' => false, 'stateless' => true, 'debug' => true,'debugLogFile' => env('TOOLKIT_DEBUG_LOG'))); $conn->setOptions(['persistent' => false, 'stateless' => true, 'debug' => true, 'debugLogFile' => env('TOOLKIT_DEBUG_LOG')]);
# Add LIB // Add LIB
# $result = $conn->CLCommand('ADDLIBLE LIB(MPDAT10)'); // $result = $conn->CLCommand('ADDLIBLE LIB(MPDAT10)');
# define several input/output params // define several input/output params
$params = []; $params = [];
# $params[] = $conn->AddParameterChar('out',7,'eqNumber'); // $params[] = $conn->AddParameterChar('out',7,'eqNumber');
# AddParameterChar($io, $size, $comment, $varName, $value, $varying, $dimension) // AddParameterChar($io, $size, $comment, $varName, $value, $varying, $dimension)
# Add Warehouse Param // Add Warehouse Param
$params[] = $conn->AddParameterChar('in',3,'Company','',$Company); $params[] = $conn->AddParameterChar('in', 3, 'Company', '', $Company);
$params[] = $conn->AddParameterChar('in',3,'Warehouse','',$Warehouse); $params[] = $conn->AddParameterChar('in', 3, 'Warehouse', '', $Warehouse);
# AddParameterPackDec($io, $length, $scale, $comment, $varName, $value,$dimension) // AddParameterPackDec($io, $length, $scale, $comment, $varName, $value,$dimension)
# Add Delivery Note Param // Add Delivery Note Param
$PickerNumberNoZero = ltrim(strval($PickerNumber), '0'); $PickerNumberNoZero = ltrim(strval($PickerNumber), '0');
$params[] = $conn->AddParameterChar('in', 11, 'PickerNumber','',$PickerNumberNoZero); $params[] = $conn->AddParameterChar('in', 11, 'PickerNumber', '', $PickerNumberNoZero);
// $params[] = $conn->AddParameterZoned('in', 11, 0, 'ParamIn'); // $params[] = $conn->AddParameterZoned('in', 11, 0, 'ParamIn');
# Start Time Tracking // Start Time Tracking
$start = microtime(true); $start = microtime(true);
# ICM700C EWOBJTST ICM700C ICM700CSBM // ICM700C EWOBJTST ICM700C ICM700CSBM
$result = $conn->PgmCall('ICM700CSBM', env('OBJLIB'), $params, array(), array()); $result = $conn->PgmCall('ICM700CSBM', env('OBJLIB'), $params, [], []);
if (!$result) { if (! $result) {
$PGMERRORS = 'Error calling program. Code: ' . $conn->getErrorCode() . ' - Msg: ' . $conn->getErrorMsg(); $PGMERRORS = 'Error calling program. Code: ' . $conn->getErrorCode() . ' - Msg: ' . $conn->getErrorMsg();
} }
if ($PGMERRORS != '') { if ($PGMERRORS != '') {
# Write to Logs Out : Error & JSON // Write to Logs Out : Error & JSON
$data = ['SHMACPKR'=>$SHMACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> '','SHTYPE'=> 'M3-Lis-spl' , $data = ['SHMACPKR' => $SHMACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Lis-spl',
'SHDATA'=>$PGMERRORS .' M3-Lis-JSN'.json_encode($jsonFile) ,'SHUSER'=> $REQKPKUS,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$Company,'SHWHS'=>$Warehouse ]; 'SHDATA' => $PGMERRORS . ' M3-Lis-JSN' . json_encode($jsonFile), 'SHUSER' => $REQKPKUS, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $Company, 'SHWHS' => $Warehouse];
Helper::logToICM699M($data); Helper::logToICM699M($data);
} }
} }
# Write to Logs Out : Success // Write to Logs Out : Success
$data = ['SHMACPKR'=>$SHMACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> '','SHINTBOX'=> '','SHTYPE'=> 'M3-Lis-in' , $data = ['SHMACPKR' => $SHMACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => '', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Lis-in',
'SHDATA'=>json_encode($jsonFile) ,'SHUSER'=> $REQKPKUS,'SHSOURCE'=> $SHSOURCE ,'SHCO'=>$Company,'SHWHS'=>$Warehouse]; 'SHDATA' => json_encode($jsonFile), 'SHUSER' => $REQKPKUS, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $Company, 'SHWHS' => $Warehouse];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code'=>'200', 'code' => '200',
'status'=>'success', 'status' => 'success',
'message'=>'File Received, DB Updated' 'message' => 'File Received, DB Updated',
]); ]);
} } else {
else{ // Write to Logs Out : Error & JSON
# Write to Logs Out : Error & JSON
$SHACKNOTE = 'Sentinel automatically closed the error related to this empty data set sent by M3'; $SHACKNOTE = 'Sentinel automatically closed the error related to this empty data set sent by M3';
$data = ['SHMACPKR'=>$SHMACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'Z','SHINTBOX'=> '','SHTYPE'=> 'M3-Lis-in' , $data = ['SHMACPKR' => $SHMACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'Z', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Lis-in',
'SHDATA'=>'No Json File Found...' ,'SHUSER'=> $REQKPKUS,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$Company,'SHWHS'=>$Warehouse,"SHACKNOTE"=> $SHACKNOTE ]; 'SHDATA' => 'No Json File Found...', 'SHUSER' => $REQKPKUS, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $Company, 'SHWHS' => $Warehouse, 'SHACKNOTE' => $SHACKNOTE];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code'=>'415', 'code' => '415',
'status'=>'error', 'status' => 'error',
'message'=>'No Json File Found' 'message' => 'No Json File Found',
]); ]);
} }
} } catch (\Throwable $th) {
catch (\Throwable $th) { // Write to Logs Out : Error & JSON
# Write to Logs Out : Error & JSON $data = ['SHMACPKR' => $SHMACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Lis-in',
$data = ['SHMACPKR'=>$SHMACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> '','SHTYPE'=> 'M3-Lis-in' , 'SHDATA' => 'General Catchable Error - ' . substr($th, 0, 300) . ' M3-Lis-JSN' . json_encode($jsonFile), 'SHUSER' => $REQKPKUS, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $Company, 'SHWHS' => $Warehouse];
'SHDATA'=>'General Catchable Error - '.substr($th,0,300).' M3-Lis-JSN'.json_encode($jsonFile) ,'SHUSER'=> $REQKPKUS,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$Company,'SHWHS'=>$Warehouse ]; Helper::logToICM699M($data);
Helper::logToICM699M($data);
// Log::error($th); // Log::error($th);
return response()->json([ return response()->json([
'code'=>'405', 'code' => '405',
'status'=>'error', 'status' => 'error',
'message'=>'An Error Occured...' 'message' => 'An Error Occured...',
]); ]);
} }
} }
public function show($id){} public function show($id) {}
public function edit($id){} public function edit($id) {}
public function update(Request $request, $id){} public function update(Request $request, $id) {}
public function destroy($id){} public function destroy($id) {}
} }
@@ -2,282 +2,272 @@
namespace Modules\M3\Http\Controllers\API; namespace Modules\M3\Http\Controllers\API;
use Modules\M3\Http\Controllers\Controller; use Config;
use DB;
use Http;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use DB;
use Config;
use Str;
use Log;
use Http;
use Cache;
use DateTime;
use Smalot\PdfParser\Parser;
use File;
use Modules\M3\Helpers\Helper;
use Json; use Json;
use Log;
use Modules\M3\Helpers\Helper;
use Modules\M3\Http\Controllers\Controller;
use Str;
class M3InventoryReport extends Controller class M3InventoryReport extends Controller
{ {
# M3InventoryReport for Single Part // M3InventoryReport for Single Part
public function M3InventoryReport(Request $request){ public function M3InventoryReport(Request $request)
{
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut')); ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
// dd($request->json()->all()); // dd($request->json()->all());
# Get the Calling User // Get the Calling User
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WEBUSER'; $SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WEBUSER';
# Set SHSOURCE // Set SHSOURCE
$SHSOURCE = 'M3InventoryReport'; $SHSOURCE = 'M3InventoryReport';
$M3Errors = ''; $M3Errors = '';
$DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000'; $DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000';
try { try {
# Get Json Contents // Get Json Contents
$jsonFile = count($request->json()->all())>0 ? $request->json()->all() : ''; $jsonFile = count($request->json()->all()) > 0 ? $request->json()->all() : '';
if($jsonFile!=''){ if ($jsonFile != '') {
$WHS = isset($jsonFile["WHS"]) ? $jsonFile["WHS"] : ''; $WHS = isset($jsonFile['WHS']) ? $jsonFile['WHS'] : '';
$PART = isset($jsonFile["PART"]) ? $jsonFile["PART"] : ''; $PART = isset($jsonFile['PART']) ? $jsonFile['PART'] : '';
$LOT = isset($jsonFile["LOT"]) ? $jsonFile["LOT"] : ''; $LOT = isset($jsonFile['LOT']) ? $jsonFile['LOT'] : '';
} } else {
else { // code...
# code...
} }
# Get Token // Get Token
$tokenResponse = Helper::checkReceiveTokenV2(); $tokenResponse = Helper::checkReceiveTokenV2();
$tokenData = $tokenResponse->getData(); $tokenData = $tokenResponse->getData();
if($tokenData->code=='200'){ if ($tokenData->code == '200') {
$IonToken = isset($tokenData->token) ? $tokenData->token : ''; $IonToken = isset($tokenData->token) ? $tokenData->token : '';
} } else {
else{
$SHDATA = isset($tokenData->message) ? $tokenData->message : ''; $SHDATA = isset($tokenData->message) ? $tokenData->message : '';
# Write to Logs : Error // Write to Logs : Error
$data = ['SHMACPKR'=>'000000','SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> '','SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , $data = ['SHMACPKR' => '000000', 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => '', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
'SHDATA'=> $SHDATA ,'SHUSER'=> $SHUSER,'SHSOURCE'=> $SHSOURCE,'SHCO'=>'','SHWHS'=>$WHS]; 'SHDATA' => $SHDATA, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => '', 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return $tokenResponse; return $tokenResponse;
} }
# Call ionapi with Params // Call ionapi with Params
$endPointURL = env('ENDPOINTURL').'APIFLOWS/Sentinel/M3InventoryReport?ionapiRespStyle=sync'; $endPointURL = env('ENDPOINTURL') . 'APIFLOWS/Sentinel/M3InventoryReport?ionapiRespStyle=sync';
$token = $IonToken; $token = $IonToken;
$JSON = [ $JSON = [
"WHS" => $WHS, 'WHS' => $WHS,
"PART"=> $PART, 'PART' => $PART,
"LOT" => $LOT 'LOT' => $LOT,
]; ];
$response = Http::withHeaders([ $response = Http::withHeaders([
'accept' => 'application/json', 'accept' => 'application/json',
'Content-Type' => 'application/json' 'Content-Type' => 'application/json',
]) ])
->withToken($token) ->withToken($token)
->timeout(Config::get('arrays.curlTimeOut')) ->timeout(Config::get('arrays.curlTimeOut'))
->post($endPointURL, $JSON); ->post($endPointURL, $JSON);
$responseStatusCode = $response->getStatusCode(); $responseStatusCode = $response->getStatusCode();
$M3SessionId = $response->hasHeader('x-transaction-id') ? "-sessionID:". $response->header('x-transaction-id') : '-sessionID'; $M3SessionId = $response->hasHeader('x-transaction-id') ? '-sessionID:' . $response->header('x-transaction-id') : '-sessionID';
if ($responseStatusCode =='200') { if ($responseStatusCode == '200') {
# Check M3 Response for Errors // Check M3 Response for Errors
$M3Errors = ''; $M3Errors = '';
$responseJSON = $response->getBody()->getContents(); $responseJSON = $response->getBody()->getContents();
$JsonSanytized = Helper::sanityzeString($responseJSON); $JsonSanytized = Helper::sanityzeString($responseJSON);
} } else {
else{
$M3Errors = 'Error: No Response from M3'; $M3Errors = 'Error: No Response from M3';
} }
if ($M3Errors!='') { if ($M3Errors != '') {
# Write to Logs : Error // Write to Logs : Error
$data = ['SHMACPKR'=>$DELIVERYNO,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , $data = ['SHMACPKR' => $DELIVERYNO, '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'=>'','SHWHS'=>$WHS ]; 'SHDATA' => $responseStatusCode . $M3Errors . $M3SessionId, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => '', 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Send Response // Send Response
return response()->json([ return response()->json([
'code'=>'405', 'code' => '405',
'status'=>'error', 'status' => 'error',
'message'=>$M3Errors 'message' => $M3Errors,
]); ]);
} } else {
else{ // Write to Logs Out : Success
# Write to Logs Out : Success $data = ['SHMACPKR' => $DELIVERYNO, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => '', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
$data = ['SHMACPKR'=>$DELIVERYNO,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> '','SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , 'SHDATA' => $responseStatusCode . $JsonSanytized . '-' . json_encode($JSON) . $M3SessionId, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE,
'SHDATA'=>$responseStatusCode.$JsonSanytized.'-'.json_encode($JSON).$M3SessionId ,'SHUSER'=> $SHUSER,'SHSOURCE'=> $SHSOURCE, 'SHCO' => '', 'SHWHS' => $WHS];
'SHCO'=>'','SHWHS'=>$WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code'=>$responseStatusCode, 'code' => $responseStatusCode,
'status'=>'Success', 'status' => 'Success',
'message'=>json_decode($JsonSanytized) 'message' => json_decode($JsonSanytized),
]); ]);
} }
} } catch (\Throwable $th) {
catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
$getCurlErrors = str_contains($th->getMessage(), 'cURL error'); $getCurlErrors = str_contains($th->getMessage(), 'cURL error');
if($getCurlErrors){ if ($getCurlErrors) {
# Write to Logs Out : Failed // 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' , $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'.$JSON ,'SHUSER'=> $SHUSER,'SHSOURCE'=> $SHSOURCE,'SHCO'=>'','SHWHS'=>$WHS]; 'SHDATA' => 'Curl Error: Communication with M3 Timed Out' . ' M3-JSN-out' . $JSON, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => '', 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code'=>'405', 'code' => '405',
'status'=>'error', 'status' => 'error',
'message'=>'Curl Error: Communication with M3 Timed Out.' 'message' => 'Curl Error: Communication with M3 Timed Out.',
]); ]);
} } else {
else { // Write to Logs Out : Error
# Write to Logs Out : Error $data = ['SHMACPKR' => $DELIVERYNO, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
$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];
'SHDATA'=>'An Error Occured - '.substr($th,0,300) ,'SHUSER'=> $SHUSER,'SHSOURCE'=> $SHSOURCE];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code'=>'405', 'code' => '405',
'status'=>'error', 'status' => 'error',
'message'=>'Catched Error: '.$th 'message' => 'Catched Error: ' . $th,
]); ]);
} }
} }
} }
# End M3InventoryReport // End M3InventoryReport
# M3InventoryReportList with URL Params // M3InventoryReportList with URL Params
public function M3InventoryReportListURL(Request $request){ public function M3InventoryReportListURL(Request $request)
{
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut')); ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
# Set API Name // Set API Name
$SHSOURCE = 'M3InventoryReportListURL'; $SHSOURCE = 'M3InventoryReportListURL';
# Get The Calling User // Get The Calling User
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser'; $SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
$M3Errors = ''; $M3Errors = '';
try { try {
# Get Json Contents // Get Json Contents
$urlParams = count($request->all())>0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
$REQPKWS = isset($urlParams["REQPKWS"]) ? $urlParams["REQPKWS"] : ''; $REQPKWS = isset($urlParams['REQPKWS']) ? $urlParams['REQPKWS'] : '';
$REQKPKUS = isset($urlParams["REQKPKUS"]) ? $urlParams["REQKPKUS"] : 'WebUser'; $REQKPKUS = isset($urlParams['REQKPKUS']) ? $urlParams['REQKPKUS'] : 'WebUser';
$CO = isset($urlParams["CO"]) ? $urlParams["CO"] : ''; $CO = isset($urlParams['CO']) ? $urlParams['CO'] : '';
$WHS = isset($urlParams["WHS"]) ? $urlParams["WHS"] : ''; $WHS = isset($urlParams['WHS']) ? $urlParams['WHS'] : '';
$MACPKR = isset($urlParams["MACPKR"]) ? $urlParams["MACPKR"] : '000000'; # Delivery Number $MACPKR = isset($urlParams['MACPKR']) ? $urlParams['MACPKR'] : '000000'; // Delivery Number
$PKLN = isset($urlParams["PKLN"]) ? $urlParams["PKLN"] : ''; $PKLN = isset($urlParams['PKLN']) ? $urlParams['PKLN'] : '';
if($urlParams!=''){ if ($urlParams != '') {
$IncomingParams = ['CO'=> $CO,'WHS'=> $WHS,'MACPKR'=> $MACPKR,'PKLN'=> $PKLN,'REQPKWS'=> $REQPKWS,'REQKPKUS'=> $REQKPKUS]; $IncomingParams = ['CO' => $CO, 'WHS' => $WHS, 'MACPKR' => $MACPKR, 'PKLN' => $PKLN, 'REQPKWS' => $REQPKWS, 'REQKPKUS' => $REQKPKUS];
$IncomingParams = json_encode($IncomingParams); $IncomingParams = json_encode($IncomingParams);
# Write to Logs : Params In // Write to Logs : Params In
$data = ['SHMACPKR'=>$MACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> '','SHINTBOX'=> '','SHTYPE'=> 'M3-Req-out' , $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 ]; 'SHDATA' => $IncomingParams, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Get Parts And Lots from ICM688M2 // Get Parts And Lots from ICM688M2
$ICM688M2SLTMP = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m2') $ICM688M2SLTMP = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m2')
->select('A5WHS', 'A5PART','A5LOTNUM','A5SENTPKR') ->select('A5WHS', 'A5PART', 'A5LOTNUM', 'A5SENTPKR')
->distinct() ->distinct()
->where('A5CO',$CO) ->where('A5CO', $CO)
->where('A5WHS',$WHS) ->where('A5WHS', $WHS)
->where('A5MACPKR',$MACPKR); ->where('A5MACPKR', $MACPKR);
# Get Pack Lines // Get Pack Lines
if($PKLN!=''){ if ($PKLN != '') {
$ICM688M2SLTMP->where('A5PKLN',$PKLN); $ICM688M2SLTMP->where('A5PKLN', $PKLN);
} }
$ICM688M2SL = $ICM688M2SLTMP->get(); $ICM688M2SL = $ICM688M2SLTMP->get();
// dd($ICM688M2SL); // dd($ICM688M2SL);
if( count($ICM688M2SL)>0 ){ if (count($ICM688M2SL) > 0) {
# Update ICM688M1 : Add Timestamp // Update ICM688M1 : Add Timestamp
$ICM688M1TS = now(); $ICM688M1TS = now();
DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1') DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->where('A4MACPKR',$MACPKR) ->where('A4MACPKR', $MACPKR)
->update(['A4INRFSHTS'=>$ICM688M1TS]); ->update(['A4INRFSHTS' => $ICM688M1TS]);
$PICKERARR = []; $PICKERARR = [];
foreach ($ICM688M2SL as $key => $ICM688M2) { foreach ($ICM688M2SL as $key => $ICM688M2) {
$PART = trim($ICM688M2->A5PART); $PART = trim($ICM688M2->A5PART);
$LOT = trim($ICM688M2->A5LOTNUM); $LOT = trim($ICM688M2->A5LOTNUM);
$PARTS[] = ["PART"=> $PART , "LOT"=>$LOT]; $PARTS[] = ['PART' => $PART, 'LOT' => $LOT];
$PICKERARR[$PART] = $ICM688M2->A5SENTPKR; $PICKERARR[$PART] = $ICM688M2->A5SENTPKR;
} }
// Log::info($PARTS); // Log::info($PARTS);
// dump($PARTS); // dump($PARTS);
$JSON = json_encode( ["WHS" => $WHS,"PARTS"=> $PARTS ] ); $JSON = json_encode(['WHS' => $WHS, 'PARTS' => $PARTS]);
// Log::info($JSON); // Log::info($JSON);
# Get Token // Get Token
$tokenResponse = Helper::checkReceiveTokenV2(); $tokenResponse = Helper::checkReceiveTokenV2();
$tokenData = $tokenResponse->getData(); $tokenData = $tokenResponse->getData();
if($tokenData->code=='200'){ if ($tokenData->code == '200') {
$IonToken = isset($tokenData->token) ? $tokenData->token : ''; $IonToken = isset($tokenData->token) ? $tokenData->token : '';
} } else {
else{
$SHDATA = isset($tokenData->message) ? $tokenData->message : ''; $SHDATA = isset($tokenData->message) ? $tokenData->message : '';
# Write to Logs : Error // Write to Logs : Error
$data = ['SHMACPKR'=>$MACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , $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 ]; 'SHDATA' => $SHDATA, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return $tokenResponse; return $tokenResponse;
} }
# Call ionapi with Params // Call ionapi with Params
$endPointURL = env('ENDPOINTURL').'APIFLOWS/Sentinel/M3InventoryReportList?ionapiRespStyle=sync'; $endPointURL = env('ENDPOINTURL') . 'APIFLOWS/Sentinel/M3InventoryReportList?ionapiRespStyle=sync';
$token = $IonToken; $token = $IonToken;
$response = Http::withHeaders([ $response = Http::withHeaders([
'accept' => 'application/json', 'accept' => 'application/json',
'Content-Type' => 'application/json' 'Content-Type' => 'application/json',
]) ])
->withToken($token) ->withToken($token)
->withBody($JSON, 'application/json') ->withBody($JSON, 'application/json')
->timeout(Config::get('arrays.curlTimeOut')) ->timeout(Config::get('arrays.curlTimeOut'))
->post($endPointURL); ->post($endPointURL);
$M3SessionId = $response->hasHeader('x-transaction-id') ? "-sessionID:". $response->header('x-transaction-id') : '-sessionID'; $M3SessionId = $response->hasHeader('x-transaction-id') ? '-sessionID:' . $response->header('x-transaction-id') : '-sessionID';
$responseStatusCode = $response->getStatusCode(); $responseStatusCode = $response->getStatusCode();
if ($responseStatusCode =='200') { if ($responseStatusCode == '200') {
# Check M3 Response for Errors // Check M3 Response for Errors
$M3Errors = ''; $M3Errors = '';
$responseJSON = $response->getBody()->getContents(); $responseJSON = $response->getBody()->getContents();
$JsonSanytized = Helper::sanityzeString($responseJSON); $JsonSanytized = Helper::sanityzeString($responseJSON);
# Array // Array
$responseArray = json_decode($JsonSanytized,true); $responseArray = json_decode($JsonSanytized, true);
$responseTMP = $responseArray['result']; $responseTMP = $responseArray['result'];
} } else {
else{
$M3Errors = 'Error: No Response from M3'; $M3Errors = 'Error: No Response from M3';
} }
# Validate response From M3 // Validate response From M3
if ($M3Errors!='') { if ($M3Errors != '') {
# Write to Logs : Error // Write to Logs : Error
$data = ['SHMACPKR'=>$MACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , $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 ]; 'SHDATA' => $responseStatusCode . '-' . $M3Errors . $M3SessionId, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Send Response // Send Response
return response()->json([ return response()->json([
'code'=>'405', 'code' => '405',
'status'=>'error', 'status' => 'error',
'message'=>'Error: No Response from M3' 'message' => 'Error: No Response from M3',
]); ]);
} } else {
else{ // Write to Logs : JSON
# Write to Logs : JSON $data = ['SHMACPKR' => $MACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => '', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
$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];
'SHDATA'=>$responseStatusCode.'-'.$JsonSanytized.$M3SessionId ,'SHUSER'=> $SHUSER,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$CO,'SHWHS'=>$WHS ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
} }
@@ -287,167 +277,163 @@ class M3InventoryReport extends Controller
$dataToWrite = []; $dataToWrite = [];
foreach ($value as $key2 => $content) { foreach ($value as $key2 => $content) {
if($key2!='Locations'){ if ($key2 != 'Locations') {
$dataToWrite[$key2] = $content; $dataToWrite[$key2] = $content;
} } else {
else{
foreach ($content as $key3 => $content2) { foreach ($content as $key3 => $content2) {
//dump($content2); // dump($content2);
$dataToWrite2[] = array_merge($dataToWrite,$content2); $dataToWrite2[] = array_merge($dataToWrite, $content2);
} }
} }
} }
} }
// LOG::info($dataToWrite2); // LOG::info($dataToWrite2);
# Delete Old Records from IC630M // Delete Old Records from IC630M
foreach ($dataToWrite2 as $key => $value) { foreach ($dataToWrite2 as $key => $value) {
$ICM630MDeleteSQL = DB::connection(config('m3.connection', 'pgsql'))->table('ic630m') $ICM630MDeleteSQL = DB::connection(config('m3.connection', 'pgsql'))->table('ic630m')
->where('LLCO',$CO) ->where('LLCO', $CO)
->where('LLWHNO',$WHS) ->where('LLWHNO', $WHS)
->where('LLPPN',trim($value['PartNumber'])) ->where('LLPPN', trim($value['PartNumber']))
->delete(); ->delete();
} }
foreach ($dataToWrite2 as $key => $value) { foreach ($dataToWrite2 as $key => $value) {
# Check if Location exist in DE640M ("LVCO", "WSELOC", "VLOCID") // Check if Location exist in DE640M ("LVCO", "WSELOC", "VLOCID")
$DE640MSQLSEL = DB::connection(config('m3.connection', 'pgsql'))->table('de640m') $DE640MSQLSEL = DB::connection(config('m3.connection', 'pgsql'))->table('de640m')
->where('LVCO',$CO) ->where('LVCO', $CO)
->where('WSELOC',$value['Warehouse']) ->where('WSELOC', $value['Warehouse'])
->where('VLOCID',$value['Location']) ->where('VLOCID', $value['Location'])
->first(); ->first();
// dd($DE640MSQLSEL); // dd($DE640MSQLSEL);
$LocationExist = isset($DE640MSQLSEL->VLOCID) ? trim($DE640MSQLSEL->VLOCID) : ''; $LocationExist = isset($DE640MSQLSEL->VLOCID) ? trim($DE640MSQLSEL->VLOCID) : '';
$WHExist = isset($DE640MSQLSEL->WSELOC) ? trim($DE640MSQLSEL->WSELOC) : ''; $WHExist = isset($DE640MSQLSEL->WSELOC) ? trim($DE640MSQLSEL->WSELOC) : '';
$COExist = isset($DE640MSQLSEL->LVCO) ? trim($DE640MSQLSEL->LVCO) : ''; $COExist = isset($DE640MSQLSEL->LVCO) ? trim($DE640MSQLSEL->LVCO) : '';
// dd($LocationExist .': '.$WHExist.': '.$COExist); // dd($LocationExist .': '.$WHExist.': '.$COExist);
# if No records Founds insert New Record // if No records Founds insert New Record
if ( $LocationExist=='' && $WHExist=='' && $COExist=='' ) { if ($LocationExist == '' && $WHExist == '' && $COExist == '') {
$SQLInsertPrep640M['LVCO'] = $CO; # Company $SQLInsertPrep640M['LVCO'] = $CO; // Company
$SQLInsertPrep640M['WSELOC'] = $value['Warehouse']; $SQLInsertPrep640M['WSELOC'] = $value['Warehouse'];
// $SQLInsertPrep640M['LVDELNO'] = $MACPKR; # M3 Delivery note number DELETED // $SQLInsertPrep640M['LVDELNO'] = $MACPKR; # M3 Delivery note number DELETED
// $SQLInsertPrep640M['LVUSD3'] = $value['']; # Pallet Size : Not Found in M3 JSON // $SQLInsertPrep640M['LVUSD3'] = $value['']; # Pallet Size : Not Found in M3 JSON
$SQLInsertPrep640M['VLOCID'] = $value['Location']; # Stock location $SQLInsertPrep640M['VLOCID'] = $value['Location']; // Stock location
$SQLInsertPrep640M['LVSEQN'] = $value['LocationSeq']; $SQLInsertPrep640M['LVSEQN'] = $value['LocationSeq'];
$SQLInsertPrep640M['LVUSD2'] = $value['LocationType']; $SQLInsertPrep640M['LVUSD2'] = $value['LocationType'];
$SQLInsertPrep640M['LVZONE'] = $value['Zone']; # Warehouse zone $SQLInsertPrep640M['LVZONE'] = $value['Zone']; // Warehouse zone
$SQLInsertPrep640M['LVMAINTTS'] = now(); # Last maintained time stamp $SQLInsertPrep640M['LVMAINTTS'] = now(); // Last maintained time stamp
DB::connection(config('m3.connection', 'pgsql'))->table('de640m')->insert($SQLInsertPrep640M); DB::connection(config('m3.connection', 'pgsql'))->table('de640m')->insert($SQLInsertPrep640M);
} }
# Update // Update
else { else {
$SQLUpdatePrep640M['LVSEQN'] = $value['LocationSeq']; $SQLUpdatePrep640M['LVSEQN'] = $value['LocationSeq'];
$SQLUpdatePrep640M['LVUSD2'] = $value['LocationType']; $SQLUpdatePrep640M['LVUSD2'] = $value['LocationType'];
$SQLUpdatePrep640M['LVZONE'] = $value['Zone']; $SQLUpdatePrep640M['LVZONE'] = $value['Zone'];
$SQLUpdatePrep640M['LVMAINTTS'] = now(); $SQLUpdatePrep640M['LVMAINTTS'] = now();
DB::connection(config('m3.connection', 'pgsql'))->table('de640m') DB::connection(config('m3.connection', 'pgsql'))->table('de640m')
->where('LVCO',$CO) ->where('LVCO', $CO)
->where('WSELOC',$value['Warehouse']) ->where('WSELOC', $value['Warehouse'])
->where('VLOCID',$value['Location']) ->where('VLOCID', $value['Location'])
->update($SQLUpdatePrep640M); ->update($SQLUpdatePrep640M);
} }
# Insert New Records to IC630M // Insert New Records to IC630M
$SQLInsertPrep630M = []; $SQLInsertPrep630M = [];
$SQLInsertPrep630M['LLCO'] = $CO; # Company $SQLInsertPrep630M['LLCO'] = $CO; // Company
$SQLInsertPrep630M['LLWHNO'] = $value['Warehouse']; # Warehouse $SQLInsertPrep630M['LLWHNO'] = $value['Warehouse']; // Warehouse
// $SQLInsertPrep630M['LLDELNO'] = $MACPKR; # M3 Delivery note number DELETED // $SQLInsertPrep630M['LLDELNO'] = $MACPKR; # M3 Delivery note number DELETED
$SQLInsertPrep630M['LLPPN'] = $value['PartNumber']; # Part Number $SQLInsertPrep630M['LLPPN'] = $value['PartNumber']; // Part Number
$SQLInsertPrep630M['LLBALANCE'] = $value['Quantity']; # Quantity $SQLInsertPrep630M['LLBALANCE'] = $value['Quantity']; // Quantity
$SQLInsertPrep630M['LLSTLC'] = $value['Location']; # Stock location $SQLInsertPrep630M['LLSTLC'] = $value['Location']; // Stock location
$SQLInsertPrep630M['LLLTNO'] = $value['LotNumber']; # Lot Number $SQLInsertPrep630M['LLLTNO'] = $value['LotNumber']; // Lot Number
$SQLInsertPrep630M['LLMAINTTS'] = now(); # Request time timestamp $SQLInsertPrep630M['LLMAINTTS'] = now(); // Request time timestamp
$SQLInsertPrep630M['LLIZLCF'] = trim($value['LotNumber'])!='' ? '1' : ''; # Lot control flag $SQLInsertPrep630M['LLIZLCF'] = trim($value['LotNumber']) != '' ? '1' : ''; // Lot control flag
$SQLInsertPrep630M['LLCMDESC'] = $value['Description']; # Description $SQLInsertPrep630M['LLCMDESC'] = $value['Description']; // Description
$SQLInsertPrep630M['LLSPR10A01'] = isset($value['Allocation']) ? $value['Allocation'] : ''; # Allocation $SQLInsertPrep630M['LLSPR10A01'] = isset($value['Allocation']) ? $value['Allocation'] : ''; // Allocation
$SQLInsertPrep630M['LLSPR15A01'] = isset($value['AllocatedTo']) ? $value['AllocatedTo'] : ''; # AllocatedTo $SQLInsertPrep630M['LLSPR15A01'] = isset($value['AllocatedTo']) ? $value['AllocatedTo'] : ''; // AllocatedTo
DB::connection(config('m3.connection', 'pgsql'))->table('ic630m')->insert($SQLInsertPrep630M); DB::connection(config('m3.connection', 'pgsql'))->table('ic630m')->insert($SQLInsertPrep630M);
} }
// dump($SQLInsertPrep); // dump($SQLInsertPrep);
#Send Response // Send Response
return response()->json([ return response()->json([
'code' => '200', 'code' => '200',
'status' => 'Success' 'status' => 'Success',
]); ]);
} } else {
else{ // Write to Logs Out : Error
# Write to Logs Out : Error
$MACPKR = isset($MACPKR) ? $MACPKR : '000000'; $MACPKR = isset($MACPKR) ? $MACPKR : '000000';
$data = ['SHMACPKR'=>$MACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , $data = ['SHMACPKR' => $MACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
'SHDATA'=>'No Records Found in ICM688M2' ,'SHUSER'=> $REQKPKUS,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$CO,'SHWHS'=>$WHS ]; 'SHDATA' => 'No Records Found in ICM688M2', 'SHUSER' => $REQKPKUS, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Return Error // Return Error
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'Error', 'status' => 'Error',
'message'=> 'No Records Found in ICM688M2' 'message' => 'No Records Found in ICM688M2',
]); ]);
} }
} } else {
else { // Write to Logs Out : Error
# Write to Logs Out : Error $MACPKR = isset($MACPKR) ? $MACPKR : '000000';
$MACPKR = isset($MACPKR) ? $MACPKR : '000000'; $data = ['SHMACPKR' => $MACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
$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' => $REQKPKUS, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
'SHDATA'=>'No URL Parameters Sent','SHUSER'=> $REQKPKUS,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$CO,'SHWHS'=>$WHS ]; Helper::logToICM699M($data);
Helper::logToICM699M($data);
# Return Error // Return Error
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'Error', 'status' => 'Error',
'message'=> 'No URL Parameters Sent' 'message' => 'No URL Parameters Sent',
]); ]);
} }
} } catch (\Throwable $th) {
catch (\Throwable $th) { // Write to Logs Out : Error
# Write to Logs Out : Error
$MACPKR = isset($MACPKR) ? $MACPKR : '000000'; $MACPKR = isset($MACPKR) ? $MACPKR : '000000';
$getCurlErrors = str_contains($th->getMessage(), 'cURL error'); $getCurlErrors = str_contains($th->getMessage(), 'cURL error');
if($getCurlErrors){ if ($getCurlErrors) {
// dd($getCurlErrors); // dd($getCurlErrors);
# Write to Logs Out : Failed // 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' , $data = ['SHMACPKR' => $MACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
'SHDATA'=>$th->getMessage().' M3-JSN-out'.$IncomingParams , 'SHDATA' => $th->getMessage() . ' M3-JSN-out' . $IncomingParams,
'SHUSER'=> $SHUSER,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$CO,'SHWHS'=>$WHS]; 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code'=>'405', 'code' => '405',
'status'=>'error', 'status' => 'error',
'message'=>'Curl Error: Communication with M3 Timed Out.' 'message' => 'Curl Error: Communication with M3 Timed Out.',
]); ]);
} } else {
else { // Set SHERROR To Z if Duplicate Key Detected $th
# Set SHERROR To Z if Duplicate Key Detected $th // Read The substring from SHDATA after M3-JSN-out
# Read The substring from SHDATA after M3-JSN-out $SHERROR = 'X';
$SHERROR = 'X'; $word = 'Duplicate key value specified';
$word = 'Duplicate key value specified'; $position = strpos($th, $word);
$position = strpos($th, $word);
if ($position !== false) { if ($position !== false) {
$SHERROR = 'Z'; $SHERROR = 'Z';
} }
$data = ['SHMACPKR'=>$MACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> $SHERROR,'SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , $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'=> $REQKPKUS,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$CO,'SHWHS'=>$WHS]; 'SHDATA' => 'An Error Occured-' . substr($th, 0, 300), 'SHUSER' => $REQKPKUS, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
Log::error($th); Log::error($th);
return response()->json([ return response()->json([
'code'=>'405', 'code' => '405',
'status'=>'error', 'status' => 'error',
'message'=>'Catched Error: '.$th 'message' => 'Catched Error: ' . $th,
]); ]);
} }
} }
} }
# End M3InventoryReportListURL // End M3InventoryReportListURL
} }
+71 -78
View File
@@ -2,73 +2,69 @@
namespace Modules\M3\Http\Controllers\API; namespace Modules\M3\Http\Controllers\API;
use Modules\M3\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use DB;
use Config;
use Str;
use Log;
use Http;
use Cache; use Cache;
use DateTime; use Config;
use Smalot\PdfParser\Parser;
use File; use File;
use Illuminate\Http\Request;
use Log;
use Modules\M3\Helpers\Helper; use Modules\M3\Helpers\Helper;
use Modules\M3\Http\Controllers\Controller;
use Smalot\PdfParser\Parser;
use Str;
class PdfStorage extends Controller class PdfStorage extends Controller
{ {
# PdfStorageAPI : PDF file read and save to Cache // PdfStorageAPI : PDF file read and save to Cache
public function PdfStorageAPI(Request $request){ public function PdfStorageAPI(Request $request)
{
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut')); ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
// dd($request->all()); // dd($request->all());
# Get the Calling User // Get the Calling User
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser'; $SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
$SHSOURCE = 'PdfStorageAPI'; $SHSOURCE = 'PdfStorageAPI';
# PDF File PATH // PDF File PATH
$pdfFilePath = Config::get('arrays.PdfPath'); $pdfFilePath = Config::get('arrays.PdfPath');
try { try {
# Get URL PARAMS // Get URL PARAMS
$urlParams = count($request->all())>0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
// dd($urlParams); // dd($urlParams);
$COMPANY = isset($urlParams["COMPANY"]) ? trim($urlParams["COMPANY"]) : ''; # Company $COMPANY = isset($urlParams['COMPANY']) ? trim($urlParams['COMPANY']) : ''; // Company
$WHS = isset($urlParams["WHS"]) ? trim($urlParams["WHS"]) : ''; # WareHouse $WHS = isset($urlParams['WHS']) ? trim($urlParams['WHS']) : ''; // WareHouse
$DOCTYPE = isset($urlParams["DOCTYPE"]) ? trim($urlParams["DOCTYPE"]) : ''; # document type (PackingList, CarrierLabel, ContentLabel) $DOCTYPE = isset($urlParams['DOCTYPE']) ? trim($urlParams['DOCTYPE']) : ''; // document type (PackingList, CarrierLabel, ContentLabel)
$FILENAME = isset($urlParams["FILENAME"]) ? trim($urlParams["FILENAME"]) : ''; # PDF File name $FILENAME = isset($urlParams['FILENAME']) ? trim($urlParams['FILENAME']) : ''; // PDF File name
$DOCNUM = isset($urlParams["DOCNUM"]) ? trim($urlParams["DOCNUM"]) : ''; # document number (ie the internal box number, the pick list number) $DOCNUM = isset($urlParams['DOCNUM']) ? trim($urlParams['DOCNUM']) : ''; // document number (ie the internal box number, the pick list number)
$A4MACPKR = isset($urlParams["A4MACPKR"]) ? trim($urlParams["A4MACPKR"]) : ''; # Delivery note number $A4MACPKR = isset($urlParams['A4MACPKR']) ? trim($urlParams['A4MACPKR']) : ''; // Delivery note number
if($urlParams!=''){ if ($urlParams != '') {
# Key Combination : COMPANY WHS A4MACPKR DOCTYPE DOCNUM // Key Combination : COMPANY WHS A4MACPKR DOCTYPE DOCNUM
# Document type (PackingList, CarrierLabel, ContentLabel) // Document type (PackingList, CarrierLabel, ContentLabel)
$DELIVERYNO = isset($A4MACPKR) ? $A4MACPKR : '000000'; $DELIVERYNO = isset($A4MACPKR) ? $A4MACPKR : '000000';
$DELIVERYNO = $DELIVERYNO!="" && $DELIVERYNO!=null ? $DELIVERYNO : '000000'; $DELIVERYNO = $DELIVERYNO != '' && $DELIVERYNO != null ? $DELIVERYNO : '000000';
# Write to Logs : Params In // Write to Logs : Params In
$IncomingParams = ['COMPANY'=> $COMPANY,'WHS'=> $WHS,'DOCTYPE'=> $DOCTYPE,'FILENAME'=> $FILENAME,'A4MACPKR'=> $A4MACPKR,'DOCNUM' => $DOCNUM]; $IncomingParams = ['COMPANY' => $COMPANY, 'WHS' => $WHS, 'DOCTYPE' => $DOCTYPE, 'FILENAME' => $FILENAME, 'A4MACPKR' => $A4MACPKR, 'DOCNUM' => $DOCNUM];
$data = ['SHMACPKR'=>$DELIVERYNO,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> '','SHINTBOX'=> $DOCNUM,'SHTYPE'=> 'M3-Req-out' , $data = ['SHMACPKR' => $DELIVERYNO, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => '', 'SHINTBOX' => $DOCNUM, 'SHTYPE' => 'M3-Req-out',
'SHDATA'=>json_encode($IncomingParams) ,'SHUSER'=> $SHUSER,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$COMPANY,'SHWHS'=>$WHS ]; 'SHDATA' => json_encode($IncomingParams), 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $COMPANY, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Make Key and Test Validity // Make Key and Test Validity
if ($A4MACPKR!='' && $DOCTYPE!='' && $DOCNUM!='' && $COMPANY!='' && $WHS!=''){ if ($A4MACPKR != '' && $DOCTYPE != '' && $DOCNUM != '' && $COMPANY != '' && $WHS != '') {
$cacheKey = $A4MACPKR.$DOCTYPE.$DOCNUM.$COMPANY.$WHS; $cacheKey = $A4MACPKR . $DOCTYPE . $DOCNUM . $COMPANY . $WHS;
} } else {
else{ $cacheKey = '';
$cacheKey ='';
} }
# Read PDF File and Encode to Base64 // Read PDF File and Encode to Base64
$pdfFileName = $pdfFilePath.$FILENAME.'.pdf'; $pdfFileName = $pdfFilePath . $FILENAME . '.pdf';
// dd($pdfFileName); // dd($pdfFileName);
// dd(File::exists($pdfFileName)); // dd(File::exists($pdfFileName));
if (File::exists($pdfFileName) && $cacheKey!='') { if (File::exists($pdfFileName) && $cacheKey != '') {
// dd(File::exists($pdfFileName)); // dd(File::exists($pdfFileName));
// Parse PDF file and build necessary objects. // Parse PDF file and build necessary objects.
$parser = new \Smalot\PdfParser\Parser(); $parser = new Parser;
// $pdf = $parser->parseFile('/www/sentm3test/htdocs/labels/E1232824-10826596.pdf'); // $pdf = $parser->parseFile('/www/sentm3test/htdocs/labels/E1232824-10826596.pdf');
// dump($pdf); // dump($pdf);
@@ -83,84 +79,81 @@ class PdfStorage extends Controller
// Output base64 string // Output base64 string
// dump($base64PDF); // dump($base64PDF);
# Save Cache // Save Cache
Cache::forever($cacheKey, $base64PDF); Cache::forever($cacheKey, $base64PDF);
// Cache::put($cacheKey, $base64PDF, now()->addMinutes(60)); // Cache::put($cacheKey, $base64PDF, now()->addMinutes(60));
# Retrieve Cache // Retrieve Cache
// $cachedPdfFile = Cache::get($cacheKey); // $cachedPdfFile = Cache::get($cacheKey);
// dump("Retrieve Base64 Encoded PDF saved in Cache:"); // dump("Retrieve Base64 Encoded PDF saved in Cache:");
// dump($cachedPdfFile); // dump($cachedPdfFile);
// $pdfData = substr($cachedPdfFile,0,50); // $pdfData = substr($cachedPdfFile,0,50);
# remove File from Cache // remove File from Cache
// Cache::put(pdfFileName, 'value', -5); // Cache::put(pdfFileName, 'value', -5);
// Cache::forget($pdfFileName); // Cache::forget($pdfFileName);
# Base64 Decode and Display // Base64 Decode and Display
// $pdf = $parser->parseContent(base64_decode($base64PDF)); // $pdf = $parser->parseContent(base64_decode($base64PDF));
// $text = $pdf->getText(); // $text = $pdf->getText();
// dump($text); // dump($text);
# Write to Logs Out : Success // Write to Logs Out : Success
$data = ['SHMACPKR'=>$DELIVERYNO,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> '','SHINTBOX'=> $DOCNUM,'SHTYPE'=> 'M3-Res-out' , $data = ['SHMACPKR' => $DELIVERYNO, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => '', 'SHINTBOX' => $DOCNUM, 'SHTYPE' => 'M3-Res-out',
'SHDATA'=>'PDF File converted to Base64 and Saved to Cache.Key: '.$cacheKey,'SHUSER'=> $SHUSER,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$COMPANY,'SHWHS'=>$WHS]; 'SHDATA' => 'PDF File converted to Base64 and Saved to Cache.Key: ' . $cacheKey, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $COMPANY, 'SHWHS' => $WHS];
// dd($data); // dd($data);
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code' => '200', 'code' => '200',
'status' => 'Success', 'status' => 'Success',
'cacheKey'=> $cacheKey 'cacheKey' => $cacheKey,
// 'PDFData' => $pdfData // 'PDFData' => $pdfData
]); ]);
} } else {
else {
$SHDATA = File::exists($pdfFileName) ? '' : 'PDF File Not Found-'; $SHDATA = File::exists($pdfFileName) ? '' : 'PDF File Not Found-';
$SHDATA = $cacheKey!='' ? $SHDATA.'' : $SHDATA.'Cache Key is missing Params'; $SHDATA = $cacheKey != '' ? $SHDATA . '' : $SHDATA . 'Cache Key is missing Params';
# Write to Logs Out : Error // Write to Logs Out : Error
$data = ['SHMACPKR'=>$DELIVERYNO,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> $DOCNUM,'SHTYPE'=> 'M3-Res-out' , $data = ['SHMACPKR' => $DELIVERYNO, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => $DOCNUM, 'SHTYPE' => 'M3-Res-out',
'SHDATA'=>'An Error Occured -'.$SHDATA,'SHUSER'=> $SHUSER,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$COMPANY,'SHWHS'=>$WHS]; 'SHDATA' => 'An Error Occured -' . $SHDATA, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $COMPANY, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Return Error // Return Error
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'Error', 'status' => 'Error',
'message'=> $SHDATA 'message' => $SHDATA,
]); ]);
} }
} } else {
else { // Write to Logs Out : Error
# Write to Logs Out : Error
$DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000'; $DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000';
$data = ['SHMACPKR'=>$DELIVERYNO,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , $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]; 'SHDATA' => 'No URL Parameters Sent.', 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $COMPANY, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Return Error // Return Error
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'Error', 'status' => 'Error',
'message'=> 'No URL Parameters Sent' 'message' => 'No URL Parameters Sent',
]); ]);
} }
} } catch (\Throwable $th) {
catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
# Write to Logs Out : Error // Write to Logs Out : Error
$DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000'; $DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000';
$data = ['SHMACPKR'=>$DELIVERYNO,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , $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]; 'SHDATA' => 'An Error Occured - ' . substr($th, 0, 300), 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $COMPANY, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code'=>'405', 'code' => '405',
'status'=>'error', 'status' => 'error',
'message'=>'Catched Error: '.$th 'message' => 'Catched Error: ' . $th,
]); ]);
} }
} }
# End PdfStorageAPI // End PdfStorageAPI
} }
+143 -154
View File
@@ -2,94 +2,89 @@
namespace Modules\M3\Http\Controllers\API; namespace Modules\M3\Http\Controllers\API;
use Modules\M3\Http\Controllers\Controller; use Config;
use DB;
use Http;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use DB;
use Config;
use Str;
use Log; use Log;
use Http;
use Cache;
use DateTime;
use Smalot\PdfParser\Parser;
use File;
use Modules\M3\Helpers\Helper; use Modules\M3\Helpers\Helper;
use Modules\M3\Http\Controllers\Controller;
use Str;
class ReplenAPI extends Controller class ReplenAPI extends Controller
{ {
# M3Replenishement with URL Params // M3Replenishement with URL Params
public function M3InventoryReportReplen(Request $request){ public function M3InventoryReportReplen(Request $request)
{
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut')); ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
// dd($request->all()); // dd($request->all());
// Log::info( $request->all() ); // Log::info( $request->all() );
# Get The Calling User // Get The Calling User
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser'; $SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
$MACPKR = isset($MACPKR) ? $MACPKR : '000000'; $MACPKR = isset($MACPKR) ? $MACPKR : '000000';
$SHSOURCE = 'M3InventoryReportReplen'; $SHSOURCE = 'M3InventoryReportReplen';
$M3Errors = ''; $M3Errors = '';
try { try {
# Get Json Contents // Get Json Contents
$urlParams = count($request->all())>0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
$CO = isset($urlParams["CO"]) ? $urlParams["CO"] : ''; $CO = isset($urlParams['CO']) ? $urlParams['CO'] : '';
$WHS = isset($urlParams["WHS"]) ? $urlParams["WHS"] : ''; $WHS = isset($urlParams['WHS']) ? $urlParams['WHS'] : '';
$PARTNO = isset($urlParams["PARTNO"]) ? $urlParams["PARTNO"] : ''; $PARTNO = isset($urlParams['PARTNO']) ? $urlParams['PARTNO'] : '';
$PKLN = isset($urlParams["PKLN"]) ? $urlParams["PKLN"] : ''; $PKLN = isset($urlParams['PKLN']) ? $urlParams['PKLN'] : '';
$REQPKWS = isset($urlParams["REQPKWS"]) ? $urlParams["REQPKWS"] : ''; $REQPKWS = isset($urlParams['REQPKWS']) ? $urlParams['REQPKWS'] : '';
$REQKPKUS = isset($urlParams["REQKPKUS"]) ? $urlParams["REQKPKUS"] : 'WebUser'; $REQKPKUS = isset($urlParams['REQKPKUS']) ? $urlParams['REQKPKUS'] : 'WebUser';
if($urlParams!=''){ if ($urlParams != '') {
$IncomingParams = ['CO'=> $CO,'WHS'=> $WHS,'PARTNO'=> $PARTNO,'PKLN'=> $PKLN,'REQPKWS'=> $REQPKWS,'REQKPKUS'=> $REQKPKUS]; $IncomingParams = ['CO' => $CO, 'WHS' => $WHS, 'PARTNO' => $PARTNO, 'PKLN' => $PKLN, 'REQPKWS' => $REQPKWS, 'REQKPKUS' => $REQKPKUS];
$IncomingParams = json_encode($IncomingParams); $IncomingParams = json_encode($IncomingParams);
# Write to Logs : Params In // Write to Logs : Params In
$data = ['SHMACPKR'=>$MACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> '','SHINTBOX'=> '','SHTYPE'=> 'M3-Req-out' , $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 ]; 'SHDATA' => $IncomingParams, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
$PART = explode( ',',$PARTNO); $PART = explode(',', $PARTNO);
foreach( $PART as $key => $value){ foreach ($PART as $key => $value) {
$PARTS[] = ["PART"=> $value,"LOT"=>""]; $PARTS[] = ['PART' => $value, 'LOT' => ''];
} }
// dump($PARTS); // dump($PARTS);
$JSON = json_encode( ["WHS" => $WHS,"PARTS"=> $PARTS ] ); $JSON = json_encode(['WHS' => $WHS, 'PARTS' => $PARTS]);
# Write to Logs : Params Sent To M3 // 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' , $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 ]; 'SHDATA' => 'Sent To M3-' . $JSON, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Get Token // Get Token
$tokenResponse = Helper::checkReceiveTokenV2(); $tokenResponse = Helper::checkReceiveTokenV2();
$tokenData = $tokenResponse->getData(); $tokenData = $tokenResponse->getData();
// dd($IonToken->code); // dd($IonToken->code);
if($tokenData->code=='200'){ if ($tokenData->code == '200') {
$IonToken = isset($tokenData->token) ? $tokenData->token : ''; $IonToken = isset($tokenData->token) ? $tokenData->token : '';
} } else {
else{
$SHDATA = isset($tokenData->message) ? $tokenData->message : ''; $SHDATA = isset($tokenData->message) ? $tokenData->message : '';
# Write to Logs : Error // Write to Logs : Error
$data = ['SHMACPKR'=>$MACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , $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 ]; 'SHDATA' => $SHDATA, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return $tokenResponse; return $tokenResponse;
} }
# Call ionapi with Params // Call ionapi with Params
$endPointURL = env('ENDPOINTURL').'APIFLOWS/Sentinel/M3InventoryReportList?ionapiRespStyle=sync'; $endPointURL = env('ENDPOINTURL') . 'APIFLOWS/Sentinel/M3InventoryReportList?ionapiRespStyle=sync';
$token = $IonToken; $token = $IonToken;
$response = Http:: $response = Http::withHeaders([
withHeaders([ 'accept' => 'application/json',
'accept' => 'application/json', 'Content-Type' => 'application/json',
'Content-Type' => 'application/json'
]) ])
->withToken($token) ->withToken($token)
->withBody($JSON, 'application/json') ->withBody($JSON, 'application/json')
@@ -99,41 +94,39 @@ class ReplenAPI extends Controller
$responseStatusCode = $response->getStatusCode(); $responseStatusCode = $response->getStatusCode();
$M3SessionId = $response->hasHeader('x-transaction-id') ? "-sessionID:". $response->header('x-transaction-id') : '-sessionID'; $M3SessionId = $response->hasHeader('x-transaction-id') ? '-sessionID:' . $response->header('x-transaction-id') : '-sessionID';
if ($responseStatusCode =='200') { if ($responseStatusCode == '200') {
# Check M3 Response for Errors // Check M3 Response for Errors
$M3Errors = ''; $M3Errors = '';
$responseJSON = $response->getBody()->getContents(); $responseJSON = $response->getBody()->getContents();
$JsonSanytized = Helper::sanityzeString($responseJSON); $JsonSanytized = Helper::sanityzeString($responseJSON);
# Array // Array
$responseArray = json_decode($JsonSanytized,true); $responseArray = json_decode($JsonSanytized, true);
// LOG::info( $responseArray); // LOG::info( $responseArray);
$responseTMP = $responseArray['result']; $responseTMP = $responseArray['result'];
// LOG::info($responseTMP); // LOG::info($responseTMP);
} } else {
else{
$M3Errors = 'Error: No Response from M3'; $M3Errors = 'Error: No Response from M3';
} }
# Validate response From M3 // Validate response From M3
if ($M3Errors!='') { if ($M3Errors != '') {
# Write to Logs : Error // Write to Logs : Error
$data = ['SHMACPKR'=>$MACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> 'X','SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , $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 ]; 'SHDATA' => $responseStatusCode . '-' . $M3Errors . $M3SessionId, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Send Response // Send Response
return response()->json([ return response()->json([
'code'=>'405', 'code' => '405',
'status'=>'error', 'status' => 'error',
'message'=>'Error: No Response from M3' 'message' => 'Error: No Response from M3',
]); ]);
} } else {
else{ // Write to Logs : JSON
# Write to Logs : JSON $data = ['SHMACPKR' => $MACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => '', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
$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];
'SHDATA'=>$responseStatusCode.'-'.$JsonSanytized.$M3SessionId ,'SHUSER'=> $SHUSER,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$CO,'SHWHS'=>$WHS ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
} }
@@ -143,152 +136,148 @@ class ReplenAPI extends Controller
$dataToWrite = []; $dataToWrite = [];
foreach ($value as $key2 => $content) { foreach ($value as $key2 => $content) {
if($key2!='Locations'){ if ($key2 != 'Locations') {
$dataToWrite[$key2] = $content; $dataToWrite[$key2] = $content;
} } else {
else{
foreach ($content as $key3 => $content2) { foreach ($content as $key3 => $content2) {
//dump($content2); // dump($content2);
$dataToWrite2[] = array_merge($dataToWrite,$content2); $dataToWrite2[] = array_merge($dataToWrite, $content2);
} }
} }
} }
} }
// LOG::info($dataToWrite2); // LOG::info($dataToWrite2);
# Delete Old Records from IC630M // Delete Old Records from IC630M
foreach ($dataToWrite2 as $key => $value) { foreach ($dataToWrite2 as $key => $value) {
$ICM630MDeleteSQL = DB::connection(config('m3.connection', 'pgsql'))->table('ic630m') $ICM630MDeleteSQL = DB::connection(config('m3.connection', 'pgsql'))->table('ic630m')
->where('LLCO',$CO) ->where('LLCO', $CO)
->where('LLWHNO',$WHS) ->where('LLWHNO', $WHS)
->where('LLPPN',trim($value['PartNumber'])) ->where('LLPPN', trim($value['PartNumber']))
->delete(); ->delete();
} }
foreach ($dataToWrite2 as $key => $value) { foreach ($dataToWrite2 as $key => $value) {
# Check if Location exist in DE640M $value['Location'] // Check if Location exist in DE640M $value['Location']
$DE640MSQLSEL = DB::connection(config('m3.connection', 'pgsql'))->table('de640m') $DE640MSQLSEL = DB::connection(config('m3.connection', 'pgsql'))->table('de640m')
->where('LVCO',$CO) ->where('LVCO', $CO)
->where('WSELOC',$value['Warehouse']) ->where('WSELOC', $value['Warehouse'])
->where('VLOCID',$value['Location']) ->where('VLOCID', $value['Location'])
->first(); ->first();
// dd($DE640MSQLSEL); // dd($DE640MSQLSEL);
$LocationExist = isset($DE640MSQLSEL->VLOCID) ? trim($DE640MSQLSEL->VLOCID) : ''; $LocationExist = isset($DE640MSQLSEL->VLOCID) ? trim($DE640MSQLSEL->VLOCID) : '';
$WHExist = isset($DE640MSQLSEL->WSELOC) ? trim($DE640MSQLSEL->WSELOC) : ''; $WHExist = isset($DE640MSQLSEL->WSELOC) ? trim($DE640MSQLSEL->WSELOC) : '';
$COExist = isset($DE640MSQLSEL->LVCO) ? trim($DE640MSQLSEL->LVCO) : ''; $COExist = isset($DE640MSQLSEL->LVCO) ? trim($DE640MSQLSEL->LVCO) : '';
// dd($LocationExist .': '.$WHExist.': '.$COExist); // dd($LocationExist .': '.$WHExist.': '.$COExist);
# if No records Founds insert New Record // if No records Founds insert New Record
if ( $LocationExist=='' && $WHExist=='' && $COExist=='' ) { if ($LocationExist == '' && $WHExist == '' && $COExist == '') {
$SQLInsertPrep640M['LVCO'] = $CO; // Company $SQLInsertPrep640M['LVCO'] = $CO; // Company
$SQLInsertPrep640M['WSELOC'] = $value['Warehouse']; $SQLInsertPrep640M['WSELOC'] = $value['Warehouse'];
// $SQLInsertPrep640M['LVUSD3'] = $value['']; // Pallet Size : Not Found in M3 JSON // $SQLInsertPrep640M['LVUSD3'] = $value['']; // Pallet Size : Not Found in M3 JSON
$SQLInsertPrep640M['VLOCID'] = $value['Location']; // Stock location $SQLInsertPrep640M['VLOCID'] = $value['Location']; // Stock location
$SQLInsertPrep640M['LVSEQN'] = $value['LocationSeq']; $SQLInsertPrep640M['LVSEQN'] = $value['LocationSeq'];
$SQLInsertPrep640M['LVUSD2'] = $value['LocationType']; $SQLInsertPrep640M['LVUSD2'] = $value['LocationType'];
$SQLInsertPrep640M['LVZONE'] = $value['Zone']; // Warehouse zone $SQLInsertPrep640M['LVZONE'] = $value['Zone']; // Warehouse zone
$SQLInsertPrep640M['LVMAINTTS'] = now(); // Last maintained time stamp $SQLInsertPrep640M['LVMAINTTS'] = now(); // Last maintained time stamp
DB::connection(config('m3.connection', 'pgsql'))->table('de640m')->insert($SQLInsertPrep640M); DB::connection(config('m3.connection', 'pgsql'))->table('de640m')->insert($SQLInsertPrep640M);
} }
# Update // Update
else { else {
$SQLUpdatePrep640M['LVSEQN'] = $value['LocationSeq']; $SQLUpdatePrep640M['LVSEQN'] = $value['LocationSeq'];
$SQLUpdatePrep640M['LVUSD2'] = $value['LocationType']; $SQLUpdatePrep640M['LVUSD2'] = $value['LocationType'];
$SQLUpdatePrep640M['LVZONE'] = $value['Zone']; $SQLUpdatePrep640M['LVZONE'] = $value['Zone'];
$SQLUpdatePrep640M['LVMAINTTS'] = now(); $SQLUpdatePrep640M['LVMAINTTS'] = now();
DB::connection(config('m3.connection', 'pgsql'))->table('de640m') DB::connection(config('m3.connection', 'pgsql'))->table('de640m')
->where('LVCO',$CO) ->where('LVCO', $CO)
->where('WSELOC',$value['Warehouse']) ->where('WSELOC', $value['Warehouse'])
->where('VLOCID',$value['Location']) ->where('VLOCID', $value['Location'])
->update($SQLUpdatePrep640M); ->update($SQLUpdatePrep640M);
} }
# Insert New Records to IC630M // Insert New Records to IC630M
$SQLInsertPrep630M = []; $SQLInsertPrep630M = [];
$SQLInsertPrep630M['LLCO'] = $CO; # Company $SQLInsertPrep630M['LLCO'] = $CO; // Company
$SQLInsertPrep630M['LLWHNO'] = $value['Warehouse']; # Warehouse $SQLInsertPrep630M['LLWHNO'] = $value['Warehouse']; // Warehouse
$SQLInsertPrep630M['LLPPN'] = $value['PartNumber']; # Part Number $SQLInsertPrep630M['LLPPN'] = $value['PartNumber']; // Part Number
$SQLInsertPrep630M['LLBALANCE'] = $value['Quantity']; # Quantity $SQLInsertPrep630M['LLBALANCE'] = $value['Quantity']; // Quantity
$SQLInsertPrep630M['LLSTLC'] = $value['Location']; # Stock location $SQLInsertPrep630M['LLSTLC'] = $value['Location']; // Stock location
$SQLInsertPrep630M['LLLTNO'] = $value['LotNumber']; # Lot Number $SQLInsertPrep630M['LLLTNO'] = $value['LotNumber']; // Lot Number
$SQLInsertPrep630M['LLMAINTTS'] = now(); # Request time timestamp $SQLInsertPrep630M['LLMAINTTS'] = now(); // Request time timestamp
$SQLInsertPrep630M['LLIZLCF'] = trim($value['LotNumber'])!='' ? '1' : ''; # Lot control flag $SQLInsertPrep630M['LLIZLCF'] = trim($value['LotNumber']) != '' ? '1' : ''; // Lot control flag
$SQLInsertPrep630M['LLSPR10A01'] = $value['Allocation']; # Allocation $SQLInsertPrep630M['LLSPR10A01'] = $value['Allocation']; // Allocation
$SQLInsertPrep630M['LLSPR15A01'] = $value['AllocatedTo']; # AllocatedTo $SQLInsertPrep630M['LLSPR15A01'] = $value['AllocatedTo']; // AllocatedTo
$DescSanytized = Helper::sanityzeString($value['Description']); $DescSanytized = Helper::sanityzeString($value['Description']);
// $DescSanytized = str_replace(['–','\u20131'], '-',$value['Description']); // $DescSanytized = str_replace(['–','\u20131'], '-',$value['Description']);
$SQLInsertPrep630M['LLCMDESC'] = $DescSanytized; // Description $SQLInsertPrep630M['LLCMDESC'] = $DescSanytized; // Description
DB::connection(config('m3.connection', 'pgsql'))->table('ic630m')->insert($SQLInsertPrep630M); DB::connection(config('m3.connection', 'pgsql'))->table('ic630m')->insert($SQLInsertPrep630M);
} }
// dump($SQLInsertPrep); // dump($SQLInsertPrep);
#Send Response // Send Response
return response()->json([ return response()->json([
'code' => '200', 'code' => '200',
'status' => 'Success' 'status' => 'Success',
]); ]);
} } else {
else { // Write to Logs Out : Error
# Write to Logs Out : Error $MACPKR = isset($MACPKR) ? $MACPKR : '000000';
$MACPKR = isset($MACPKR) ? $MACPKR : '000000'; $data = ['SHMACPKR' => $MACPKR, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => 'X', 'SHINTBOX' => '', 'SHTYPE' => 'M3-Res-out',
$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];
'SHDATA'=>'No URL Parameters Sent','SHUSER'=> $SHUSER,'SHSOURCE'=> $SHSOURCE,'SHCO'=>$CO,'SHWHS'=>$WHS ]; Helper::logToICM699M($data);
Helper::logToICM699M($data);
# Return Error // Return Error
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'Error', 'status' => 'Error',
'message'=> 'No URL Parameters Sent' 'message' => 'No URL Parameters Sent',
]); ]);
} }
} } catch (\Throwable $th) {
catch (\Throwable $th) { // Write to Logs Out : Error
# Write to Logs Out : Error
$MACPKR = isset($MACPKR) ? $MACPKR : '000000'; $MACPKR = isset($MACPKR) ? $MACPKR : '000000';
$getCurlErrors = str_contains($th->getMessage(), 'cURL error'); $getCurlErrors = str_contains($th->getMessage(), 'cURL error');
if($getCurlErrors){ if ($getCurlErrors) {
// dd($getCurlErrors); // dd($getCurlErrors);
# Write to Logs Out : Failed // 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' , $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]; 'SHDATA' => 'Curl Error: Communication with M3 Timed Out' . ' M3-JSN-out' . $IncomingParams, 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code'=>'405', 'code' => '405',
'status'=>'error', 'status' => 'error',
'message'=>'Curl Error: Communication with M3 Timed Out.' 'message' => 'Curl Error: Communication with M3 Timed Out.',
]); ]);
} } else {
else { // Set SHERROR To Z if Duplicate Key Detected $th
# Set SHERROR To Z if Duplicate Key Detected $th // Read The substring from SHDATA after M3-JSN-out
# Read The substring from SHDATA after M3-JSN-out $SHERROR = 'X';
$SHERROR = 'X'; $word = 'Duplicate key value specified';
$word = 'Duplicate key value specified'; $position = strpos($th, $word);
$position = strpos($th, $word);
if ($position !== false) { if ($position !== false) {
$SHERROR = 'Z'; $SHERROR = 'Z';
} }
$data = ['SHMACPKR'=>$MACPKR,'SHDT'=> date('Y-m-d'),'SHTIME'=> date('H:i:s') ,'SHERROR'=> $SHERROR,'SHINTBOX'=> '','SHTYPE'=> 'M3-Res-out' , $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]; 'SHDATA' => 'An Error Occured - ' . substr($th, 0, 300), 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data); Helper::logToICM699M($data);
// Log::error($th); // Log::error($th);
return response()->json([ return response()->json([
'code'=>'405', 'code' => '405',
'status'=>'error', 'status' => 'error',
'message'=>'Catched Error: '.$th 'message' => 'Catched Error: ' . $th,
]); ]);
} }
} }
} }
# End M3InventoryReportReplen // End M3InventoryReportReplen
} }
+199 -205
View File
@@ -2,23 +2,20 @@
namespace Modules\M3\Http\Controllers\API; namespace Modules\M3\Http\Controllers\API;
use Modules\M3\Http\Controllers\Controller; use Config;
use DateTime;
use DB;
use Http;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use DB;
use Config;
use Str;
use Log; use Log;
use Http;
use Cache;
use DateTime;
use Smalot\PdfParser\Parser;
use File;
use Modules\M3\Helpers\Helper; use Modules\M3\Helpers\Helper;
use Modules\M3\Http\Controllers\Controller;
use Str;
class TransferAPI extends Controller class TransferAPI extends Controller
{ {
# TransferAPIURL : with URL PARAMS // TransferAPIURL : with URL PARAMS
public function TransferAPIURL(Request $request) public function TransferAPIURL(Request $request)
{ {
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
@@ -26,68 +23,67 @@ class TransferAPI extends Controller
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
// dd($request->all()); // dd($request->all());
# Get the Calling User // Get the Calling User
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser'; $SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
# Set SHSOURCE // Set SHSOURCE
$SHSOURCE = 'TransferAPIURL'; $SHSOURCE = 'TransferAPIURL';
$M3Errors = ''; $M3Errors = '';
# Get URL PARAMS // Get URL PARAMS
$urlParams = count($request->all()) > 0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
$DIVI = isset($urlParams["COMPANY"]) ? $urlParams["COMPANY"] : ''; $DIVI = isset($urlParams['COMPANY']) ? $urlParams['COMPANY'] : '';
$WHS = isset($urlParams["WHS"]) ? $urlParams["WHS"] : ''; $WHS = isset($urlParams['WHS']) ? $urlParams['WHS'] : '';
try { try {
if ($urlParams != '') { if ($urlParams != '') {
$PART = isset($urlParams["PART"]) ? $urlParams["PART"] : ''; $PART = isset($urlParams['PART']) ? $urlParams['PART'] : '';
$LOCATIONFROM = isset($urlParams["LOCATIONFROM"]) ? $urlParams["LOCATIONFROM"] : ''; $LOCATIONFROM = isset($urlParams['LOCATIONFROM']) ? $urlParams['LOCATIONFROM'] : '';
$LOCATIONTO = isset($urlParams["LOCATIONTO"]) ? $urlParams["LOCATIONTO"] : ''; $LOCATIONTO = isset($urlParams['LOCATIONTO']) ? $urlParams['LOCATIONTO'] : '';
$QUANTITY = isset($urlParams["QUANTITY"]) ? $urlParams["QUANTITY"] : ''; $QUANTITY = isset($urlParams['QUANTITY']) ? $urlParams['QUANTITY'] : '';
$ORDERCATEGORY = isset($urlParams["ORDERCATEGORY"]) ? $urlParams["ORDERCATEGORY"] : ''; $ORDERCATEGORY = isset($urlParams['ORDERCATEGORY']) ? $urlParams['ORDERCATEGORY'] : '';
$LOTNUMBER = isset($urlParams["LOTNUMBER"]) ? $urlParams["LOTNUMBER"] : ""; $LOTNUMBER = isset($urlParams['LOTNUMBER']) ? $urlParams['LOTNUMBER'] : '';
$CONUMBER = isset($urlParams["CONUMBER"]) ? $urlParams["CONUMBER"] : ''; $CONUMBER = isset($urlParams['CONUMBER']) ? $urlParams['CONUMBER'] : '';
$COLINENO = isset($urlParams["COLINENO"]) ? $urlParams["COLINENO"] : ''; $COLINENO = isset($urlParams['COLINENO']) ? $urlParams['COLINENO'] : '';
$DELIVERYNO = isset($urlParams["DELIVERYNO"]) ? $urlParams["DELIVERYNO"] : '000000'; $DELIVERYNO = isset($urlParams['DELIVERYNO']) ? $urlParams['DELIVERYNO'] : '000000';
$PICKLISTSUFFIX = isset($urlParams["PICKLISTSUFFIX"]) ? $urlParams["PICKLISTSUFFIX"] : ''; $PICKLISTSUFFIX = isset($urlParams['PICKLISTSUFFIX']) ? $urlParams['PICKLISTSUFFIX'] : '';
$ENDFLAG = isset($urlParams["ENDFLAG"]) ? $urlParams["ENDFLAG"] : ''; $ENDFLAG = isset($urlParams['ENDFLAG']) ? $urlParams['ENDFLAG'] : '';
$TYPE = isset($urlParams["TYPE"]) ? $urlParams["TYPE"] : ''; $TYPE = isset($urlParams['TYPE']) ? $urlParams['TYPE'] : '';
$COLINESUFFIX = isset($urlParams["COLINESUFFIX"]) ? $urlParams["COLINESUFFIX"] : ''; $COLINESUFFIX = isset($urlParams['COLINESUFFIX']) ? $urlParams['COLINESUFFIX'] : '';
# TYPE : // TYPE :
# DeliveryNote // DeliveryNote
# S15 // S15
# CloseShipment // CloseShipment
# COCharge // COCharge
# Replenishment // Replenishment
# Move // Move
# ORDERCATEGORY : Order Category
# 1 = Material to manufacturing order
# 3 = Customer Order
# 4 = Requisition Order
# 5 = Distribution Order
# 9 = Move order
// ORDERCATEGORY : Order Category
// 1 = Material to manufacturing order
// 3 = Customer Order
// 4 = Requisition Order
// 5 = Distribution Order
// 9 = Move order
$DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000'; $DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000';
$TRANSTYPE = isset($urlParams["TRANSTYPE"]) ? $urlParams["TRANSTYPE"] : ''; # R for Retry $TRANSTYPE = isset($urlParams['TRANSTYPE']) ? $urlParams['TRANSTYPE'] : ''; // R for Retry
$SHDT = isset($urlParams["SHDT"]) ? $urlParams["SHDT"] : ''; $SHDT = isset($urlParams['SHDT']) ? $urlParams['SHDT'] : '';
$SHTIME = isset($urlParams["SHTIME"]) ? $urlParams["SHTIME"] : ''; $SHTIME = isset($urlParams['SHTIME']) ? $urlParams['SHTIME'] : '';
$SHTYPE = isset($urlParams["SHTYPE"]) ? $urlParams["SHTYPE"] : ''; $SHTYPE = isset($urlParams['SHTYPE']) ? $urlParams['SHTYPE'] : '';
# Retry Transfer // Retry Transfer
if ($TRANSTYPE == 'R') { if ($TRANSTYPE == 'R') {
# $t = strtotime($SHTIME); // $t = strtotime($SHTIME);
# $SHTIMEHM = date('H:i',$t); // $SHTIMEHM = date('H:i',$t);
# dd($SHTIMEHM); // dd($SHTIMEHM);
# Get the record that contain the payload // Get the record that contain the payload
$ICM699MS = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m') $ICM699MS = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
->select('SHDATA') ->select('SHDATA')
->where('SHMACPKR', $DELIVERYNO) ->where('SHMACPKR', $DELIVERYNO)
->where('SHDT', $SHDT) ->where('SHDT', $SHDT)
->where('SHTIME', $SHTIME) ->where('SHTIME', $SHTIME)
# ->whereRaw("VARCHAR_FORMAT (TIMESTAMP (CURRENT DATE) + MIDNIGHT_SECONDS (SHTIME) SECONDS, 'HH24:MI') = ?", [$SHTIMEHM]) // ->whereRaw("VARCHAR_FORMAT (TIMESTAMP (CURRENT DATE) + MIDNIGHT_SECONDS (SHTIME) SECONDS, 'HH24:MI') = ?", [$SHTIMEHM])
->where('SHCO', $DIVI) ->where('SHCO', $DIVI)
->where('SHWHS', $WHS) ->where('SHWHS', $WHS)
->where('SHSOURCE', $SHSOURCE) ->where('SHSOURCE', $SHSOURCE)
@@ -96,28 +92,28 @@ class TransferAPI extends Controller
->first(); ->first();
// dump($ICM699MS->SHDATA); // dump($ICM699MS->SHDATA);
# Read The substring from SHDATA after M3-JSN-out // Read The substring from SHDATA after M3-JSN-out
$word = 'M3-JSN-out'; $word = 'M3-JSN-out';
$SHDATA = isset($ICM699MS->SHDATA) ? $ICM699MS->SHDATA : ''; $SHDATA = isset($ICM699MS->SHDATA) ? $ICM699MS->SHDATA : '';
$SHDATAJSON = ""; $SHDATAJSON = '';
$position = strpos($SHDATA, $word); $position = strpos($SHDATA, $word);
# Also Read CommTCP_read // Also Read CommTCP_read
$word2 = 'url:http://127.0.0.1:10005/api/TransferAPIURL?'; $word2 = 'url:http://127.0.0.1:10005/api/TransferAPIURL?';
$SHDATA2 = isset($ICM699MS->SHDATA) ? $ICM699MS->SHDATA : ''; $SHDATA2 = isset($ICM699MS->SHDATA) ? $ICM699MS->SHDATA : '';
$position2 = strpos($SHDATA2, $word2); $position2 = strpos($SHDATA2, $word2);
if ($position !== false) { if ($position !== false) {
$SHDATAJSON = substr($SHDATA, $position + strlen($word)); $SHDATAJSON = substr($SHDATA, $position + strlen($word));
} else if ($position2 !== false) { } elseif ($position2 !== false) {
$SHDATAJSONS = substr($SHDATA2, $position2 + strlen($word2)); $SHDATAJSONS = substr($SHDATA2, $position2 + strlen($word2));
$SHDATAJSONA = []; $SHDATAJSONA = [];
parse_str($SHDATAJSONS, $SHDATAJSONA); parse_str($SHDATAJSONS, $SHDATAJSONA);
$SHDATAJSON = json_encode($SHDATAJSONA); $SHDATAJSON = json_encode($SHDATAJSONA);
} }
# Find the position of the opening and closing curly braces // Find the position of the opening and closing curly braces
$startPos = strpos($SHDATAJSON, '{'); $startPos = strpos($SHDATAJSON, '{');
$endPos = strrpos($SHDATAJSON, '}'); $endPos = strrpos($SHDATAJSON, '}');
# Extract the substring within the curly braces // Extract the substring within the curly braces
$SHDATAJSON = substr($SHDATAJSON, $startPos, $endPos - $startPos + 1); $SHDATAJSON = substr($SHDATAJSON, $startPos, $endPos - $startPos + 1);
// dd($SHDATAJSON); // dd($SHDATAJSON);
@@ -130,7 +126,7 @@ class TransferAPI extends Controller
$LOCATIONTO = isset($JSONTR->LOCATIONTO) ? $JSONTR->LOCATIONTO : ''; $LOCATIONTO = isset($JSONTR->LOCATIONTO) ? $JSONTR->LOCATIONTO : '';
$QUANTITY = isset($JSONTR->QUANTITY) ? $JSONTR->QUANTITY : ''; $QUANTITY = isset($JSONTR->QUANTITY) ? $JSONTR->QUANTITY : '';
$ORDERCATEGORY = isset($JSONTR->ORDERCATEGORY) ? $JSONTR->ORDERCATEGORY : ''; $ORDERCATEGORY = isset($JSONTR->ORDERCATEGORY) ? $JSONTR->ORDERCATEGORY : '';
$LOTNUMBER = isset($JSONTR->LOTNUMBER) ? $JSONTR->LOTNUMBER : ""; $LOTNUMBER = isset($JSONTR->LOTNUMBER) ? $JSONTR->LOTNUMBER : '';
$CONUMBER = isset($JSONTR->CONUMBER) ? $JSONTR->CONUMBER : ''; $CONUMBER = isset($JSONTR->CONUMBER) ? $JSONTR->CONUMBER : '';
$COLINENO = isset($JSONTR->COLINENO) ? $JSONTR->COLINENO : ''; $COLINENO = isset($JSONTR->COLINENO) ? $JSONTR->COLINENO : '';
$DELIVERYNO = isset($JSONTR->DELIVERYNO) ? $JSONTR->DELIVERYNO : '000000'; $DELIVERYNO = isset($JSONTR->DELIVERYNO) ? $JSONTR->DELIVERYNO : '000000';
@@ -141,7 +137,7 @@ class TransferAPI extends Controller
} }
// dd($JSONTR); // dd($JSONTR);
# Set SHERROR to Z in ICM699M // Set SHERROR to Z in ICM699M
$ICM699MU = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m') $ICM699MU = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
->where('SHMACPKR', $DELIVERYNO) ->where('SHMACPKR', $DELIVERYNO)
->where('SHDT', $SHDT) ->where('SHDT', $SHDT)
@@ -151,13 +147,13 @@ class TransferAPI extends Controller
->where('SHSOURCE', $SHSOURCE) ->where('SHSOURCE', $SHSOURCE)
->where('SHERROR', 'X') ->where('SHERROR', 'X')
->where('SHTYPE', $SHTYPE) ->where('SHTYPE', $SHTYPE)
->update(["SHERROR" => "Z", "SHACKUSER" => $SHUSER, "SHACKDATE" => date('Y-m-d'), "SHACKTIME" => date('H:i:s')]); ->update(['SHERROR' => 'Z', 'SHACKUSER' => $SHUSER, 'SHACKDATE' => date('Y-m-d'), 'SHACKTIME' => date('H:i:s')]);
} }
# Part Exists : proceed // Part Exists : proceed
if ($PART != '') { if ($PART != '') {
# Read from ICM688M2 // Read from ICM688M2
# Get Parts And Lots from ICM688M2 // Get Parts And Lots from ICM688M2
$ICM688M2SLTMP = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m2') $ICM688M2SLTMP = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m2')
->select('A5BRADLN', 'A5PKSFX', 'A5PLANT', 'A5SENTPKR') ->select('A5BRADLN', 'A5PKSFX', 'A5PLANT', 'A5SENTPKR')
->distinct() ->distinct()
@@ -165,7 +161,7 @@ class TransferAPI extends Controller
->where('A5WHS', $WHS) ->where('A5WHS', $WHS)
->where('A5MACPKR', $DELIVERYNO); ->where('A5MACPKR', $DELIVERYNO);
# Get Pack Lines // Get Pack Lines
if ($COLINENO != '') { if ($COLINENO != '') {
$ICM688M2SLTMP->where('A5PKLN', $COLINENO); $ICM688M2SLTMP->where('A5PKLN', $COLINENO);
} }
@@ -173,48 +169,48 @@ class TransferAPI extends Controller
// dd($ICM688M2SL->A5BRADLN); // dd($ICM688M2SL->A5BRADLN);
$A5BRADLINE = isset($ICM688M2SL->A5BRADLN) ? $ICM688M2SL->A5BRADLN : ''; $A5BRADLINE = isset($ICM688M2SL->A5BRADLN) ? $ICM688M2SL->A5BRADLN : '';
$COLINESUFFIX = isset($ICM688M2SL->A5PKSFX) ? $ICM688M2SL->A5PKSFX : ''; # Case 551 : $COLINESUFFIX $COLINESUFFIX = isset($ICM688M2SL->A5PKSFX) ? $ICM688M2SL->A5PKSFX : ''; // Case 551 : $COLINESUFFIX
$A5PLANT = isset($ICM688M2SL->A5PLANT) ? $ICM688M2SL->A5PLANT : ''; $A5PLANT = isset($ICM688M2SL->A5PLANT) ? $ICM688M2SL->A5PLANT : '';
$A5SENTPKR = isset($ICM688M2SL->A5SENTPKR) ? $ICM688M2SL->A5SENTPKR : ''; $A5SENTPKR = isset($ICM688M2SL->A5SENTPKR) ? $ICM688M2SL->A5SENTPKR : '';
$JSONIN = json_encode([ $JSONIN = json_encode([
"DIVI" => $DIVI, 'DIVI' => $DIVI,
"WHS" => $WHS, 'WHS' => $WHS,
"PART" => $PART, 'PART' => $PART,
"LOCATIONFROM" => $LOCATIONFROM, 'LOCATIONFROM' => $LOCATIONFROM,
"LOCATIONTO" => $LOCATIONTO, 'LOCATIONTO' => $LOCATIONTO,
"QUANTITY" => $QUANTITY, 'QUANTITY' => $QUANTITY,
"ORDERCATEGORY" => $ORDERCATEGORY, 'ORDERCATEGORY' => $ORDERCATEGORY,
"LOTNUMBER" => $LOTNUMBER, 'LOTNUMBER' => $LOTNUMBER,
"CONUMBER" => $CONUMBER, 'CONUMBER' => $CONUMBER,
"COLINENO" => $COLINENO, 'COLINENO' => $COLINENO,
"DELIVERYNO" => $DELIVERYNO, 'DELIVERYNO' => $DELIVERYNO,
"PICKLISTSUFFIX" => $PICKLISTSUFFIX, 'PICKLISTSUFFIX' => $PICKLISTSUFFIX,
"ENDFLAG" => $ENDFLAG, 'ENDFLAG' => $ENDFLAG,
"TYPE" => $TYPE, 'TYPE' => $TYPE,
"COLINESUFFIX" => $COLINESUFFIX, 'COLINESUFFIX' => $COLINESUFFIX,
], JSON_UNESCAPED_SLASHES); ], JSON_UNESCAPED_SLASHES);
$JSON = json_encode([ $JSON = json_encode([
"DIVI" => $DIVI, 'DIVI' => $DIVI,
"WHS" => $WHS, 'WHS' => $WHS,
"PART" => $PART, 'PART' => $PART,
"LOCATIONFROM" => $LOCATIONFROM, 'LOCATIONFROM' => $LOCATIONFROM,
"LOCATIONTO" => $LOCATIONTO, 'LOCATIONTO' => $LOCATIONTO,
"QUANTITY" => $QUANTITY, 'QUANTITY' => $QUANTITY,
"ORDERCATEGORY" => $ORDERCATEGORY, 'ORDERCATEGORY' => $ORDERCATEGORY,
"LOTNUMBER" => $LOTNUMBER, 'LOTNUMBER' => $LOTNUMBER,
"CONUMBER" => $CONUMBER, 'CONUMBER' => $CONUMBER,
"COLINENO" => $A5BRADLINE, 'COLINENO' => $A5BRADLINE,
"DELIVERYNO" => $DELIVERYNO, 'DELIVERYNO' => $DELIVERYNO,
"PICKLISTSUFFIX" => $PICKLISTSUFFIX, 'PICKLISTSUFFIX' => $PICKLISTSUFFIX,
"ENDFLAG" => $ENDFLAG, 'ENDFLAG' => $ENDFLAG,
"TYPE" => $TYPE, 'TYPE' => $TYPE,
"COLINESUFFIX" => $COLINESUFFIX, 'COLINESUFFIX' => $COLINESUFFIX,
], JSON_UNESCAPED_SLASHES); ], JSON_UNESCAPED_SLASHES);
// dd($JSON); // dd($JSON);
# Write JSON Params to Logs Out // Write JSON Params to Logs Out
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -225,18 +221,18 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Get Token // Get Token
$tokenResponse = Helper::checkReceiveTokenV2(); $tokenResponse = Helper::checkReceiveTokenV2();
$tokenData = $tokenResponse->getData(); $tokenData = $tokenResponse->getData();
if ($tokenData->code == '200') { if ($tokenData->code == '200') {
$IonToken = isset($tokenData->token) ? $tokenData->token : ''; $IonToken = isset($tokenData->token) ? $tokenData->token : '';
} else { } else {
$SHDATA = isset($tokenData->message) ? $tokenData->message : ''; $SHDATA = isset($tokenData->message) ? $tokenData->message : '';
# Write to Logs : Error // Write to Logs : Error
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -247,43 +243,43 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return $tokenResponse; return $tokenResponse;
} }
# Call ionapi with Params // Call ionapi with Params
$endPointURL = env('ENDPOINTURL') . 'APIFLOWS/Sentinel/TransferAPI?ionapiRespStyle=sync'; $endPointURL = env('ENDPOINTURL') . 'APIFLOWS/Sentinel/TransferAPI?ionapiRespStyle=sync';
$token = $IonToken; $token = $IonToken;
$response = Http::withHeaders([ $response = Http::withHeaders([
'accept' => 'application/json', 'accept' => 'application/json',
'Content-Type' => 'application/json' 'Content-Type' => 'application/json',
]) ])
->withToken($token) ->withToken($token)
->withBody($JSON, 'application/json') ->withBody($JSON, 'application/json')
->timeout(Config::get('arrays.curlTimeOut')) ->timeout(Config::get('arrays.curlTimeOut'))
->post($endPointURL); ->post($endPointURL);
$responseStatusCode = $response->getStatusCode(); $responseStatusCode = $response->getStatusCode();
$M3SessionId = $response->hasHeader('x-transaction-id') ? "-sessionID:" . $response->header('x-transaction-id') : '-sessionID'; $M3SessionId = $response->hasHeader('x-transaction-id') ? '-sessionID:' . $response->header('x-transaction-id') : '-sessionID';
$M3ResponseTimeTmp = $response->hasHeader('x-response-time') ? ltrim($response->header('x-response-time'), "-") : '0'; $M3ResponseTimeTmp = $response->hasHeader('x-response-time') ? ltrim($response->header('x-response-time'), '-') : '0';
$M3ResponseTimeTmp2 = floatval($M3ResponseTimeTmp) / 1000; //$M3ResponseTimeTmp / 1000; $M3ResponseTimeTmp2 = floatval($M3ResponseTimeTmp) / 1000; // $M3ResponseTimeTmp / 1000;
$dateTime = new DateTime(); $dateTime = new DateTime;
$dateTime->setTimestamp($M3ResponseTimeTmp2); $dateTime->setTimestamp($M3ResponseTimeTmp2);
// dump( $dateTime->format('d/m/Y H:i:s.v') ); // dump( $dateTime->format('d/m/Y H:i:s.v') );
$M3ResponseTime = $M3ResponseTimeTmp != '' ? '-M3ResponseTime:' . $dateTime->format('d/m/Y H:i:s.v') : '-M3ResponseTime'; $M3ResponseTime = $M3ResponseTimeTmp != '' ? '-M3ResponseTime:' . $dateTime->format('d/m/Y H:i:s.v') : '-M3ResponseTime';
// dump($M3ResponseTime); // dump($M3ResponseTime);
$transferStats = $response->transferStats; $transferStats = $response->transferStats;
$M3transferTime = $transferStats->getTransferTime() != null ? "-M3transferTime:" . $transferStats->getTransferTime() : "-M3transferTime"; $M3transferTime = $transferStats->getTransferTime() != null ? '-M3transferTime:' . $transferStats->getTransferTime() : '-M3transferTime';
// dd($M3transferTime); // dd($M3transferTime);
if ($responseStatusCode == '200') { if ($responseStatusCode == '200') {
$responseContents = json_decode($response->getBody()->getContents()); $responseContents = json_decode($response->getBody()->getContents());
$responseResult = $responseContents->result; $responseResult = $responseContents->result;
$M3JSONResponse = json_encode($responseContents); $M3JSONResponse = json_encode($responseContents);
# Check M3 Response for Errors // Check M3 Response for Errors
$M3Errors = Helper::checkM3Errors($responseResult); $M3Errors = Helper::checkM3Errors($responseResult);
} else { } else {
$M3JSONResponse = ''; $M3JSONResponse = '';
@@ -291,7 +287,7 @@ class TransferAPI extends Controller
} }
if ($M3Errors == '') { if ($M3Errors == '') {
# Write to Logs Out : Success // Write to Logs Out : Success
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -302,36 +298,36 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Log to ICM799M // Log to ICM799M
$ICM799MINS = DB::connection(config('m3.connection', 'pgsql'))->table('icm799m') $ICM799MINS = DB::connection(config('m3.connection', 'pgsql'))->table('icm799m')
->insert(["IMDIV" => $DIVI, ->insert(['IMDIV' => $DIVI,
"IMPLANT" => $A5PLANT, 'IMPLANT' => $A5PLANT,
"IMWHS" => $WHS, 'IMWHS' => $WHS,
"IMSENTPKR" => $A5SENTPKR, 'IMSENTPKR' => $A5SENTPKR,
"IMDELNO" => $DELIVERYNO, 'IMDELNO' => $DELIVERYNO,
"IMORDER" => $CONUMBER, 'IMORDER' => $CONUMBER,
"IMLINE" => $COLINENO, 'IMLINE' => $COLINENO,
"IMBRADLN" => $A5BRADLINE, 'IMBRADLN' => $A5BRADLINE,
"IMSUFFIX" => $PICKLISTSUFFIX, 'IMSUFFIX' => $PICKLISTSUFFIX,
"IMPART" => $PART, 'IMPART' => $PART,
"IMLOT" => $LOTNUMBER, 'IMLOT' => $LOTNUMBER,
"IMQTY" => $QUANTITY, 'IMQTY' => $QUANTITY,
"IMFRLOC" => $LOCATIONFROM, 'IMFRLOC' => $LOCATIONFROM,
"IMTOLOC" => $LOCATIONTO, 'IMTOLOC' => $LOCATIONTO,
"IMDATE" => date('Ymd'), 'IMDATE' => date('Ymd'),
"IMTIME" => date('His') 'IMTIME' => date('His'),
]); ]);
return response()->json([ return response()->json([
'code' => $responseStatusCode, 'code' => $responseStatusCode,
'status' => 'Success' 'status' => 'Success',
]); ]);
} else { } else {
# Write to Logs Out : Failed // Write to Logs Out : Failed
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -343,28 +339,28 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code' => '206', 'code' => '206',
'status' => 'Error', 'status' => 'Error',
'message' => $responseStatusCode . '-' . $M3Errors . '- TYPE :' . $TYPE . ' Order Category: ' . $ORDERCATEGORY . '-' . $M3JSONResponse 'message' => $responseStatusCode . '-' . $M3Errors . '- TYPE :' . $TYPE . ' Order Category: ' . $ORDERCATEGORY . '-' . $M3JSONResponse,
]); ]);
} }
} }
# Part Does not Exist : Failure // Part Does not Exist : Failure
else { else {
# Return Error // Return Error
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'Error', 'status' => 'Error',
'message' => 'Json Payload Not Valid, possible cause: Retry butto was clicked by another user.' 'message' => 'Json Payload Not Valid, possible cause: Retry butto was clicked by another user.',
]); ]);
} }
} else { } else {
# Write to Logs Out : Error // Write to Logs Out : Error
$DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000'; $DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000';
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
@@ -376,22 +372,22 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Return Error // Return Error
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'Error', 'status' => 'Error',
'message' => 'No URL Parameters Sent' 'message' => 'No URL Parameters Sent',
]); ]);
} }
} catch (\Throwable $th) { } catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
$getCurlErrors = str_contains($th->getMessage(), 'cURL error'); $getCurlErrors = str_contains($th->getMessage(), 'cURL error');
if ($getCurlErrors) { if ($getCurlErrors) {
# Write to Logs Out : Failed // Write to Logs Out : Failed
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -402,17 +398,17 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'error', 'status' => 'error',
'message' => 'Curl Error: Communication with M3 Timed Out.' 'message' => 'Curl Error: Communication with M3 Timed Out.',
]); ]);
} else { } else {
# Write to Logs Out : Error // Write to Logs Out : Error
$DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000'; $DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000';
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
@@ -424,7 +420,7 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
Log::error($th); Log::error($th);
@@ -432,15 +428,15 @@ class TransferAPI extends Controller
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'error', 'status' => 'error',
'message' => 'Uncaught Error' 'message' => 'Uncaught Error',
]); ]);
} }
} }
} }
# End TransferAPIURL // End TransferAPIURL
# UpdateShipmentNumber : with URL PARAMS // UpdateShipmentNumber : with URL PARAMS
public function UpdateShipmentNumber(Request $request) public function UpdateShipmentNumber(Request $request)
{ {
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
@@ -448,29 +444,29 @@ class TransferAPI extends Controller
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
// dd($request->all()); // dd($request->all());
# Get the Calling User // Get the Calling User
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser'; $SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
# Set SHSOURCE // Set SHSOURCE
$SHSOURCE = 'UpdateShipmentNumber'; $SHSOURCE = 'UpdateShipmentNumber';
$M3Errors = ''; $M3Errors = '';
# Get URL PARAMS // Get URL PARAMS
$urlParams = count($request->all()) > 0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
$DIVI = isset($urlParams["COMPANY"]) ? $urlParams["COMPANY"] : ''; $DIVI = isset($urlParams['COMPANY']) ? $urlParams['COMPANY'] : '';
$WHS = isset($urlParams["WHS"]) ? $urlParams["WHS"] : ''; $WHS = isset($urlParams['WHS']) ? $urlParams['WHS'] : '';
$PLANT = isset($urlParams["PLANT"]) ? $urlParams["PLANT"] : ''; $PLANT = isset($urlParams['PLANT']) ? $urlParams['PLANT'] : '';
// dump($urlParams); // dump($urlParams);
try { try {
if ($urlParams != '') { if ($urlParams != '') {
$A4SPR15A01 = isset($urlParams["A4SPR15A01"]) ? $urlParams["A4SPR15A01"] : ''; $A4SPR15A01 = isset($urlParams['A4SPR15A01']) ? $urlParams['A4SPR15A01'] : '';
$DELIVERYNO = isset($urlParams["DELIVERYNO"]) ? $urlParams["DELIVERYNO"] : ''; $DELIVERYNO = isset($urlParams['DELIVERYNO']) ? $urlParams['DELIVERYNO'] : '';
$TYPE = 'UpdateShipmentNumber'; $TYPE = 'UpdateShipmentNumber';
$allMacpkrs = []; $allMacpkrs = [];
// dd($A4SPR15A01); // dd($A4SPR15A01);
if ($A4SPR15A01 != '') { if ($A4SPR15A01 != '') {
# Read from ICM688M1 // Read from ICM688M1
$ICM688M1SLTMP = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1') $ICM688M1SLTMP = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->select('A4MACPKR') ->select('A4MACPKR')
->where('A4CO', $DIVI) ->where('A4CO', $DIVI)
@@ -478,34 +474,33 @@ class TransferAPI extends Controller
->where('A4PLANT', $PLANT) ->where('A4PLANT', $PLANT)
->where('A4SPR15A01', $A4SPR15A01); ->where('A4SPR15A01', $A4SPR15A01);
// Get Macpikers also if sent as Parameter
# Get Macpikers also if sent as Parameter
if ($DELIVERYNO != '') { if ($DELIVERYNO != '') {
$ICM688M1SLTMP->where('A4MACPKR', $DELIVERYNO); $ICM688M1SLTMP->where('A4MACPKR', $DELIVERYNO);
} }
$ICM688M1SL = $ICM688M1SLTMP->get(); $ICM688M1SL = $ICM688M1SLTMP->get();
# Loop ICM688M1 to get all A4MACPKR // Loop ICM688M1 to get all A4MACPKR
foreach ($ICM688M1SL as $key => $ICM688M1) { foreach ($ICM688M1SL as $key => $ICM688M1) {
$allMacpkrs[] = $ICM688M1->A4MACPKR; $allMacpkrs[] = $ICM688M1->A4MACPKR;
} }
} }
# A4SPR15A01 Exists : proceed // A4SPR15A01 Exists : proceed
if ($A4SPR15A01 != '' && count($allMacpkrs)>0) { if ($A4SPR15A01 != '' && count($allMacpkrs) > 0) {
$JSON = json_encode([ $JSON = json_encode([
"DIVI" => $DIVI, 'DIVI' => $DIVI,
"WHS" => $WHS, 'WHS' => $WHS,
"ShipmentNumber" => [ 'ShipmentNumber' => [
"Number" => $A4SPR15A01, 'Number' => $A4SPR15A01,
"DeliveryNumbers" => $allMacpkrs 'DeliveryNumbers' => $allMacpkrs,
], ],
"TYPE" => $TYPE, 'TYPE' => $TYPE,
"ENDFLAG" => "", 'ENDFLAG' => '',
], JSON_UNESCAPED_SLASHES); ], JSON_UNESCAPED_SLASHES);
// dd($JSON); // dd($JSON);
# Write JSON Params to Logs Out // Write JSON Params to Logs Out
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -516,18 +511,18 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Get Token // Get Token
$tokenResponse = Helper::checkReceiveTokenV2(); $tokenResponse = Helper::checkReceiveTokenV2();
$tokenData = $tokenResponse->getData(); $tokenData = $tokenResponse->getData();
if ($tokenData->code == '200') { if ($tokenData->code == '200') {
$IonToken = isset($tokenData->token) ? $tokenData->token : ''; $IonToken = isset($tokenData->token) ? $tokenData->token : '';
} else { } else {
$SHDATA = isset($tokenData->message) ? $tokenData->message : ''; $SHDATA = isset($tokenData->message) ? $tokenData->message : '';
# Write to Logs : Error // Write to Logs : Error
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -538,40 +533,40 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return $tokenResponse; return $tokenResponse;
} }
# Call ionapi with Params // Call ionapi with Params
$endPointURL = env('ENDPOINTURL') . 'APIFLOWS/Sentinel/TransferAPI?ionapiRespStyle=sync'; $endPointURL = env('ENDPOINTURL') . 'APIFLOWS/Sentinel/TransferAPI?ionapiRespStyle=sync';
$token = $IonToken; $token = $IonToken;
$response = Http::withHeaders([ $response = Http::withHeaders([
'accept' => 'application/json', 'accept' => 'application/json',
'Content-Type' => 'application/json' 'Content-Type' => 'application/json',
]) ])
->withToken($token) ->withToken($token)
->withBody($JSON, 'application/json') ->withBody($JSON, 'application/json')
->timeout(Config::get('arrays.curlTimeOut')) ->timeout(Config::get('arrays.curlTimeOut'))
->post($endPointURL); ->post($endPointURL);
$responseStatusCode = $response->getStatusCode(); $responseStatusCode = $response->getStatusCode();
$M3SessionId = $response->hasHeader('x-transaction-id') ? "-sessionID:" . $response->header('x-transaction-id') : '-sessionID'; $M3SessionId = $response->hasHeader('x-transaction-id') ? '-sessionID:' . $response->header('x-transaction-id') : '-sessionID';
$M3ResponseTimeTmp = $response->hasHeader('x-response-time') ? ltrim($response->header('x-response-time'), "-") : '0'; $M3ResponseTimeTmp = $response->hasHeader('x-response-time') ? ltrim($response->header('x-response-time'), '-') : '0';
$M3ResponseTimeTmp2 = floatval($M3ResponseTimeTmp) / 1000; //$M3ResponseTimeTmp / 1000; $M3ResponseTimeTmp2 = floatval($M3ResponseTimeTmp) / 1000; // $M3ResponseTimeTmp / 1000;
$dateTime = new DateTime(); $dateTime = new DateTime;
$dateTime->setTimestamp($M3ResponseTimeTmp2); $dateTime->setTimestamp($M3ResponseTimeTmp2);
$M3ResponseTime = $M3ResponseTimeTmp != '' ? '-M3ResponseTime:' . $dateTime->format('d/m/Y H:i:s.v') : '-M3ResponseTime'; $M3ResponseTime = $M3ResponseTimeTmp != '' ? '-M3ResponseTime:' . $dateTime->format('d/m/Y H:i:s.v') : '-M3ResponseTime';
$transferStats = $response->transferStats; $transferStats = $response->transferStats;
$M3transferTime = $transferStats->getTransferTime() != null ? "-M3transferTime:" . $transferStats->getTransferTime() : "-M3transferTime"; $M3transferTime = $transferStats->getTransferTime() != null ? '-M3transferTime:' . $transferStats->getTransferTime() : '-M3transferTime';
if ($responseStatusCode == '200') { if ($responseStatusCode == '200') {
$responseContents = json_decode($response->getBody()->getContents()); $responseContents = json_decode($response->getBody()->getContents());
$responseResult = $responseContents->result; $responseResult = $responseContents->result;
$M3JSONResponse = json_encode($responseContents); $M3JSONResponse = json_encode($responseContents);
# Check M3 Response for Errors // Check M3 Response for Errors
$M3Errors = Helper::checkM3Errors($responseResult); $M3Errors = Helper::checkM3Errors($responseResult);
} else { } else {
$M3JSONResponse = ''; $M3JSONResponse = '';
@@ -579,7 +574,7 @@ class TransferAPI extends Controller
} }
if ($M3Errors == '') { if ($M3Errors == '') {
# Write to Logs Out : Success // Write to Logs Out : Success
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -590,16 +585,16 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code' => $responseStatusCode, 'code' => $responseStatusCode,
'status' => 'Success' 'status' => 'Success',
]); ]);
} else { } else {
# Write to Logs Out : Failed // Write to Logs Out : Failed
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -611,29 +606,28 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code' => '206', 'code' => '206',
'status' => 'Error', 'status' => 'Error',
'message' => $responseStatusCode . '-' . $M3Errors . '- TYPE :' . $TYPE . '-' . $M3JSONResponse 'message' => $responseStatusCode . '-' . $M3Errors . '- TYPE :' . $TYPE . '-' . $M3JSONResponse,
]); ]);
} }
} }
# A4SPR15A01 Does not Exist : Failure // A4SPR15A01 Does not Exist : Failure
else { else {
# Return Error // Return Error
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'Error', 'status' => 'Error',
'message' => 'Json Payload Not Valid, missing Parameter or no Macpicker # found.' 'message' => 'Json Payload Not Valid, missing Parameter or no Macpicker # found.',
]); ]);
} }
} } else {
else { // Write to Logs Out : Error
# Write to Logs Out : Error
$DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000'; $DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000';
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
@@ -645,22 +639,22 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Return Error // Return Error
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'Error', 'status' => 'Error',
'message' => 'No URL Parameters Sent' 'message' => 'No URL Parameters Sent',
]); ]);
} }
} catch (\Throwable $th) { } catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
$getCurlErrors = str_contains($th->getMessage(), 'cURL error'); $getCurlErrors = str_contains($th->getMessage(), 'cURL error');
if ($getCurlErrors) { if ($getCurlErrors) {
# Write to Logs Out : Failed // Write to Logs Out : Failed
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -671,17 +665,17 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'error', 'status' => 'error',
'message' => 'Curl Error: Communication with M3 Timed Out.' 'message' => 'Curl Error: Communication with M3 Timed Out.',
]); ]);
} else { } else {
# Write to Logs Out : Error // Write to Logs Out : Error
$DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000'; $DELIVERYNO = isset($DELIVERYNO) ? $DELIVERYNO : '000000';
$data = ['SHMACPKR' => $DELIVERYNO, $data = ['SHMACPKR' => $DELIVERYNO,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
@@ -693,7 +687,7 @@ class TransferAPI extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $DIVI, 'SHCO' => $DIVI,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
Log::error($th); Log::error($th);
@@ -701,12 +695,12 @@ class TransferAPI extends Controller
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'error', 'status' => 'error',
'message' => 'Uncaught Error' 'message' => 'Uncaught Error',
]); ]);
} }
} }
} }
# End UpdateShipmentNumber // End UpdateShipmentNumber
} }
+74 -79
View File
@@ -2,23 +2,18 @@
namespace Modules\M3\Http\Controllers\API; namespace Modules\M3\Http\Controllers\API;
use Modules\M3\Http\Controllers\Controller; use Config;
use DB;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use DB;
use Config;
use Str;
use Log; use Log;
use Http;
use Cache;
use DateTime;
use Smalot\PdfParser\Parser;
use File;
use Modules\M3\Helpers\Helper; use Modules\M3\Helpers\Helper;
use Modules\M3\Http\Controllers\Controller;
use Str;
class TwoShipAPIs extends Controller class TwoShipAPIs extends Controller
{ {
# TwoShipUpdateHold with URL Params // TwoShipUpdateHold with URL Params
public function TwoShipUpdateHold(Request $request) public function TwoShipUpdateHold(Request $request)
{ {
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
@@ -28,23 +23,23 @@ class TwoShipAPIs extends Controller
// dd($request->all()); // dd($request->all());
// Log::info( $request->all() ); // Log::info( $request->all() );
# Get The Calling User // Get The Calling User
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser'; $SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
$SHSOURCE = 'TwoShipUpdateHold'; $SHSOURCE = 'TwoShipUpdateHold';
$TwoShipErrors = ''; $TwoShipErrors = '';
$urlParams = count($request->all()) > 0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
$WHS = isset($urlParams["WHS"]) ? $urlParams["WHS"] : ''; $WHS = isset($urlParams['WHS']) ? $urlParams['WHS'] : '';
$CO = isset($urlParams["COMPANY"]) ? $urlParams["COMPANY"] : ''; $CO = isset($urlParams['COMPANY']) ? $urlParams['COMPANY'] : '';
$MACPKR = isset($urlParams["MACPKR"]) ? $urlParams["MACPKR"] : ''; $MACPKR = isset($urlParams['MACPKR']) ? $urlParams['MACPKR'] : '';
try { try {
if ($urlParams != '') { if ($urlParams != '') {
$IncomingParams = ['CO' => $CO, 'WHS' => $WHS, 'MACPKR' => $MACPKR]; $IncomingParams = ['CO' => $CO, 'WHS' => $WHS, 'MACPKR' => $MACPKR];
$IncomingParams = json_encode($IncomingParams); $IncomingParams = json_encode($IncomingParams);
# Write to Logs : Params In // Write to Logs : Params In
$data = ['SHMACPKR' => $MACPKR, $data = ['SHMACPKR' => $MACPKR,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -55,37 +50,36 @@ class TwoShipAPIs extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $CO, 'SHCO' => $CO,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# First Step : Get MACPKRs list if available // First Step : Get MACPKRs list if available
# select a4macpkr from icm688m1 where a4shpaggcd in (select a4shpaggcd from icm688m1 where a4macpkr=233709) and a4shpaggcd<>0 and a4concmplt<>'y' and a4co=410 and a4whs=111 // select a4macpkr from icm688m1 where a4shpaggcd in (select a4shpaggcd from icm688m1 where a4macpkr=233709) and a4shpaggcd<>0 and a4concmplt<>'y' and a4co=410 and a4whs=111
$A4MACPKRSel = DB::connection(config('m3.connection', 'pgsql'))->select( $A4MACPKRSel = DB::connection(config('m3.connection', 'pgsql'))->select(
"select a4macpkr from icm688m1 where a4shpaggcd in (select a4shpaggcd from icm688m1 where a4macpkr={$MACPKR}) "select a4macpkr from icm688m1 where a4shpaggcd in (select a4shpaggcd from icm688m1 where a4macpkr={$MACPKR})
and a4shpaggcd<>0 and a4concmplt<>'y' and a4co='{$CO}' and a4whs='{$WHS}' " and a4shpaggcd<>0 and a4concmplt<>'y' and a4co='{$CO}' and a4whs='{$WHS}' ",
); );
// dd($A4MACPKRSel); // dd($A4MACPKRSel);
if (count($A4MACPKRSel)>0){ if (count($A4MACPKRSel) > 0) {
foreach ($A4MACPKRSel as $key => $A4MACPKRR) { foreach ($A4MACPKRSel as $key => $A4MACPKRR) {
$A4MACPKRArr[] = $A4MACPKRR->A4MACPKR; $A4MACPKRArr[] = $A4MACPKRR->A4MACPKR;
} }
} } else {
else{
$A4MACPKRArr[] = $MACPKR; $A4MACPKRArr[] = $MACPKR;
} }
// dump($A4MACPKRArr); // dump($A4MACPKRArr);
# Call 2ship API with Params // Call 2ship API with Params
$WS_key = Config::get('arrays.2Ship.TwoShip_Key'); $WS_key = Config::get('arrays.2Ship.TwoShip_Key');
$end_point = Config::get('arrays.2Ship.end_point'); $end_point = Config::get('arrays.2Ship.end_point');
$API = Config::get('arrays.2Ship.hold_update'); $API = Config::get('arrays.2Ship.hold_update');
$ShipOnHoldOrder_url = $end_point . $API; $ShipOnHoldOrder_url = $end_point . $API;
# Build Json Data // Build Json Data
$data = [ $data = [
'WS_Key' => $WS_key, 'WS_Key' => $WS_key,
'OrderNumbers' => [implode(',', $A4MACPKRArr)], 'OrderNumbers' => [implode(',', $A4MACPKRArr)],
@@ -103,82 +97,82 @@ class TwoShipAPIs extends Controller
// dump($json_string); // dump($json_string);
####### // ######
# Initialise the cURL var // Initialise the cURL var
$ch = curl_init(); $ch = curl_init();
# Get the response from cURL // Get the response from cURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_URL, $ShipOnHoldOrder_url); curl_setopt($ch, CURLOPT_URL, $ShipOnHoldOrder_url);
curl_setopt($ch, CURLOPT_VERBOSE, false); curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
#When CURLOPT_SSL_VERIFYPEER is enabled (value=1), and the verification fails to prove that the certificate is authentic, the connection fails. // When CURLOPT_SSL_VERIFYPEER is enabled (value=1), and the verification fails to prove that the certificate is authentic, the connection fails.
#When the option is zero, the peer certificate verification succeeds regardless. // When the option is zero, the peer certificate verification succeeds regardless.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
#When CURLOPT_SSL_VERIFYHOST is 2, that certificate must indicate that the server is the server to which you meant to connect, // When CURLOPT_SSL_VERIFYHOST is 2, that certificate must indicate that the server is the server to which you meant to connect,
#or the connection fails. Simply put, it means it has to have the same name in the certificate as is in the URL you operate against. // or the connection fails. Simply put, it means it has to have the same name in the certificate as is in the URL you operate against.
# Set data content type // Set data content type
curl_setopt( curl_setopt(
$ch, $ch,
CURLOPT_HTTPHEADER, CURLOPT_HTTPHEADER,
array( [
'Content-Type: application/json', 'Content-Type: application/json',
'Content-Length: ' . strlen($json_string) 'Content-Length: ' . strlen($json_string),
) ],
); );
# Post data // Post data
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string); curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string);
# Set timeout // Set timeout
curl_setopt($ch, CURLOPT_TIMEOUT, Config::get('arrays.PHPTimeOut')); curl_setopt($ch, CURLOPT_TIMEOUT, Config::get('arrays.PHPTimeOut'));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, Config::get('arrays.PHPTimeOut')); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, Config::get('arrays.PHPTimeOut'));
# if set true, cURL will follow redirects // if set true, cURL will follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
# Execute the request // Execute the request
$response = curl_exec($ch); $response = curl_exec($ch);
# Verifying error // Verifying error
$info = curl_getinfo($ch); $info = curl_getinfo($ch);
# Get status // Get status
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
# Output the error code // Output the error code
# $CurlError= curl_error($ch); // $CurlError= curl_error($ch);
$CurlError = str_replace("'", " ", curl_error($ch)); $CurlError = str_replace("'", ' ', curl_error($ch));
# Close the session // Close the session
unset($ch); unset($ch);
// dump($response); // dump($response);
// dump($status); // dump($status);
// dump($CurlError); // dump($CurlError);
if ($status == '200' && $CurlError=='') { if ($status == '200' && $CurlError == '') {
$responseJSON = json_decode($response); $responseJSON = json_decode($response);
// dump($responseJSON); // dump($responseJSON);
if($responseJSON->Success==false){ if ($responseJSON->Success == false) {
$TwoShipErrors = '2Ship Error: '.$responseJSON->GlobalError; $TwoShipErrors = '2Ship Error: ' . $responseJSON->GlobalError;
} }
} else { } else {
$TwoShipErrors = 'Error: No Response from 2Ship'; $TwoShipErrors = 'Error: No Response from 2Ship';
$TwoShipErrors .= ' -Curl Error: '.$CurlError; $TwoShipErrors .= ' -Curl Error: ' . $CurlError;
} }
# Validate response From 2Ship // Validate response From 2Ship
# Error // Error
if ($TwoShipErrors != '') { if ($TwoShipErrors != '') {
// dump($TwoShipErrors); // dump($TwoShipErrors);
# Write to Logs : Error // Write to Logs : Error
$data = ['SHMACPKR' => $MACPKR, $data = ['SHMACPKR' => $MACPKR,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -189,20 +183,20 @@ class TwoShipAPIs extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $CO, 'SHCO' => $CO,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Send Response // Send Response
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'error', 'status' => 'error',
'message' => 'Status: '.$status . '-' . $TwoShipErrors 'message' => 'Status: ' . $status . '-' . $TwoShipErrors,
]); ]);
} }
# Success // Success
else{ else {
# Write to Logs : JSON // Write to Logs : JSON
$data = ['SHMACPKR' => $MACPKR, $data = ['SHMACPKR' => $MACPKR,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -213,27 +207,28 @@ class TwoShipAPIs extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $CO, 'SHCO' => $CO,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Update ICM688M1 set a4concmplt to 'y' // Update ICM688M1 set a4concmplt to 'y'
DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1') DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->whereIn('A4MACPKR',$A4MACPKRArr) ->whereIn('A4MACPKR', $A4MACPKRArr)
->where('A4CO',$CO) ->where('A4CO', $CO)
->where('A4WHS',$WHS) ->where('A4WHS', $WHS)
->update(['A4CONCMPLT'=>'Y']); ->update(['A4CONCMPLT' => 'Y']);
} }
# Send Response
// Send Response
return response()->json([ return response()->json([
'code' => '200', 'code' => '200',
'status' => 'Success' 'status' => 'Success',
]); ]);
} }
# Error : No URL params // Error : No URL params
else { else {
# Write to Logs Out : Error // Write to Logs Out : Error
$MACPKR = isset($MACPKR) ? $MACPKR : '000000'; $MACPKR = isset($MACPKR) ? $MACPKR : '000000';
$data = ['SHMACPKR' => $MACPKR, $data = ['SHMACPKR' => $MACPKR,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
@@ -245,23 +240,23 @@ class TwoShipAPIs extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $CO, 'SHCO' => $CO,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
# Return Error // Return Error
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'Error', 'status' => 'Error',
'message' => 'No URL Parameters Sent' 'message' => 'No URL Parameters Sent',
]); ]);
} }
} catch (\Throwable $th) { } catch (\Throwable $th) {
# Write to Logs Out : Error // Write to Logs Out : Error
$getCurlErrors = str_contains($th->getMessage(), 'cURL error'); $getCurlErrors = str_contains($th->getMessage(), 'cURL error');
if ($getCurlErrors) { if ($getCurlErrors) {
// dd($getCurlErrors); // dd($getCurlErrors);
# Write to Logs Out : Failed // Write to Logs Out : Failed
$data = ['SHMACPKR' => $MACPKR, $data = ['SHMACPKR' => $MACPKR,
'SHDT' => date('Y-m-d'), 'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'), 'SHTIME' => date('H:i:s'),
@@ -272,17 +267,17 @@ class TwoShipAPIs extends Controller
'SHUSER' => $SHUSER, 'SHUSER' => $SHUSER,
'SHSOURCE' => $SHSOURCE, 'SHSOURCE' => $SHSOURCE,
'SHCO' => $CO, 'SHCO' => $CO,
'SHWHS' => $WHS 'SHWHS' => $WHS,
]; ];
Helper::logToICM699M($data); Helper::logToICM699M($data);
return response()->json([ return response()->json([
'code' => '405', 'code' => '405',
'status' => 'error', 'status' => 'error',
'message' => 'Curl Error: Communication with 2Ship Timed Out.' 'message' => 'Curl Error: Communication with 2Ship Timed Out.',
]); ]);
} }
} }
} }
# End TwoShipUpdateHold // End TwoShipUpdateHold
} }
@@ -2,22 +2,18 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB; use DB;
use Config;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Str; use Str;
class BoxPackToPalletController extends Controller class BoxPackToPalletController extends Controller
{ {
public static function index(Request $request) public static function index(Request $request)
{ {
return view('m3::liberty-theme.pages.BoxPackToPallet'); return view('m3::liberty-theme.pages.BoxPackToPallet');
} }
# Load Existing Boxes from ICM659M // Load Existing Boxes from ICM659M
public static function getBoxes(Request $request) public static function getBoxes(Request $request)
{ {
$R659PALT = $request->R659PALT ?? abort(404, 'Manifest Not Found'); $R659PALT = $request->R659PALT ?? abort(404, 'Manifest Not Found');
@@ -37,15 +33,15 @@ class BoxPackToPalletController extends Controller
'c.AYSPR15A01', 'c.AYSPR15A01',
'cv.A4APR8N001', 'cv.A4APR8N001',
'cv.A4SHSHCT', 'cv.A4SHSHCT',
'cnv.R652SORTK as CONVEYOR_NAME' 'cnv.R652SORTK as CONVEYOR_NAME',
) )
->leftJoin('ICM695M1 as c', 'p.R659BOX', '=', 'c.AYINTBOX') ->leftJoin('ICM695M1 as c', 'p.R659BOX', '=', 'c.AYINTBOX')
->leftJoin('ICM688M1 as cv', 'c.AYMACPKR', '=', 'cv.A4MACPKR') ->leftJoin('ICM688M1 as cv', 'c.AYMACPKR', '=', 'cv.A4MACPKR')
->leftJoin('ICM652M as cnv', 'cv.A4APR8N001', '=', 'cnv.R652SEQ') ->leftJoin('ICM652M as cnv', 'cv.A4APR8N001', '=', 'cnv.R652SEQ')
->where('p.R659PALT', $R659PALT) ->where('p.R659PALT', $R659PALT)
->where('p.R659CO', trim($userWhsCoPlant["USERCO"])) ->where('p.R659CO', trim($userWhsCoPlant['USERCO']))
->where('p.R659WHS', trim($userWhsCoPlant["USERWHS"])) ->where('p.R659WHS', trim($userWhsCoPlant['USERWHS']))
->where('p.R659PLANT', trim($userWhsCoPlant["USERPL"])) ->where('p.R659PLANT', trim($userWhsCoPlant['USERPL']))
->orderBy('p.R659DATE', 'desc') ->orderBy('p.R659DATE', 'desc')
->orderBy('p.R659TIME', 'desc') ->orderBy('p.R659TIME', 'desc')
->distinct() ->distinct()
@@ -67,7 +63,7 @@ class BoxPackToPalletController extends Controller
return view('m3::liberty-theme.pages.BoxPackToPalletScan', compact('boxes', 'palletHeader', 'R659PALT')); return view('m3::liberty-theme.pages.BoxPackToPalletScan', compact('boxes', 'palletHeader', 'R659PALT'));
} }
# Scan Boxes // Scan Boxes
public static function scanBoxes(Request $request) public static function scanBoxes(Request $request)
{ {
$R659PALT = $request->R659PALT ?? abort(400, 'Pallet Not Found'); $R659PALT = $request->R659PALT ?? abort(400, 'Pallet Not Found');
@@ -77,22 +73,22 @@ class BoxPackToPalletController extends Controller
$boxMessage = ''; $boxMessage = '';
# Step 1: Check for duplicate — same pallet + box combo // Step 1: Check for duplicate — same pallet + box combo
$exists = DB::connection(config('m3.connection', 'pgsql')) $exists = DB::connection(config('m3.connection', 'pgsql'))
->table('icm659m') ->table('icm659m')
->select('R659PALT') ->select('R659PALT')
->where('R659PALT', $R659PALT) ->where('R659PALT', $R659PALT)
->where('R659BOX', $R659BOX) ->where('R659BOX', $R659BOX)
->where('R659CO', trim($userWhsCoPlant["USERCO"])) ->where('R659CO', trim($userWhsCoPlant['USERCO']))
->where('R659WHS', trim($userWhsCoPlant["USERWHS"])) ->where('R659WHS', trim($userWhsCoPlant['USERWHS']))
->where('R659PLANT', trim($userWhsCoPlant["USERPL"])) ->where('R659PLANT', trim($userWhsCoPlant['USERPL']))
->first(); ->first();
if ($exists) { if ($exists) {
$boxMessage = "&bull; Box {$R659BOX} is already assigned to Pallet {$exists->R659PALT}."; $boxMessage = "&bull; Box {$R659BOX} is already assigned to Pallet {$exists->R659PALT}.";
} }
# Step 2: Check if Box exists in ICM695M1 (with carrier + conveyor joined) // Step 2: Check if Box exists in ICM695M1 (with carrier + conveyor joined)
$ICM695M1Sel = DB::connection(config('m3.connection', 'pgsql')) $ICM695M1Sel = DB::connection(config('m3.connection', 'pgsql'))
->table('ICM695M1 as c') ->table('ICM695M1 as c')
->select( ->select(
@@ -101,20 +97,20 @@ class BoxPackToPalletController extends Controller
'c.AYTYPE', 'c.AYTYPE',
'c.AYMACPKR', 'c.AYMACPKR',
'cv.A4APR8N001', 'cv.A4APR8N001',
'cnv.R652SORTK as CONVEYOR_NAME' 'cnv.R652SORTK as CONVEYOR_NAME',
) )
->leftJoin('ICM688M1 as cv', 'c.AYMACPKR', '=', 'cv.A4MACPKR') ->leftJoin('ICM688M1 as cv', 'c.AYMACPKR', '=', 'cv.A4MACPKR')
->leftJoin('ICM652M as cnv', 'cv.A4APR8N001', '=', 'cnv.R652SEQ') ->leftJoin('ICM652M as cnv', 'cv.A4APR8N001', '=', 'cnv.R652SEQ')
->where('c.AYINTBOX', $R659BOX) ->where('c.AYINTBOX', $R659BOX)
->where('c.AYCO', trim($userWhsCoPlant["USERCO"])) ->where('c.AYCO', trim($userWhsCoPlant['USERCO']))
->where('c.AYWHS', trim($userWhsCoPlant["USERWHS"])) ->where('c.AYWHS', trim($userWhsCoPlant['USERWHS']))
->where('c.AYPLANT', trim($userWhsCoPlant["USERPL"])) ->where('c.AYPLANT', trim($userWhsCoPlant['USERPL']))
->first(); ->first();
$boxExistInICM695M = isset($ICM695M1Sel->AYINTBOX); $boxExistInICM695M = isset($ICM695M1Sel->AYINTBOX);
$boxisPalletICM695M = isset($ICM695M1Sel->AYTYPE) && $ICM695M1Sel->AYTYPE != 'BX'; $boxisPalletICM695M = isset($ICM695M1Sel->AYTYPE) && $ICM695M1Sel->AYTYPE != 'BX';
if (!$boxExistInICM695M) { if (! $boxExistInICM695M) {
$br = $boxMessage == '' ? '' : '<br>'; $br = $boxMessage == '' ? '' : '<br>';
$boxMessage .= $br . "&bull; Box {$R659BOX} does not exist in ICM695M1 or it belongs to another Company."; $boxMessage .= $br . "&bull; Box {$R659BOX} does not exist in ICM695M1 or it belongs to another Company.";
} }
@@ -124,28 +120,28 @@ class BoxPackToPalletController extends Controller
$boxMessage .= $br . "&bull; Scanned barcode {$R659BOX} is not a Box."; $boxMessage .= $br . "&bull; Scanned barcode {$R659BOX} is not a Box.";
} }
# Step 3: Check that all boxes on the pallet share the same Carrier and Conveyor // Step 3: Check that all boxes on the pallet share the same Carrier and Conveyor
if ($boxExistInICM695M && !$boxisPalletICM695M && !$exists) { if ($boxExistInICM695M && ! $boxisPalletICM695M && ! $exists) {
$firstPalletBox = DB::connection(config('m3.connection', 'pgsql')) $firstPalletBox = DB::connection(config('m3.connection', 'pgsql'))
->table('ICM659M as p') ->table('ICM659M as p')
->select( ->select(
'c.AYSPR15A01', 'c.AYSPR15A01',
'cnv.R652SORTK as CONVEYOR_NAME' 'cnv.R652SORTK as CONVEYOR_NAME',
) )
->leftJoin('ICM695M1 as c', 'p.R659BOX', '=', 'c.AYINTBOX') ->leftJoin('ICM695M1 as c', 'p.R659BOX', '=', 'c.AYINTBOX')
->leftJoin('ICM688M1 as cv', 'c.AYMACPKR', '=', 'cv.A4MACPKR') ->leftJoin('ICM688M1 as cv', 'c.AYMACPKR', '=', 'cv.A4MACPKR')
->leftJoin('ICM652M as cnv', 'cv.A4APR8N001', '=', 'cnv.R652SEQ') ->leftJoin('ICM652M as cnv', 'cv.A4APR8N001', '=', 'cnv.R652SEQ')
->where('p.R659PALT', $R659PALT) ->where('p.R659PALT', $R659PALT)
->where('p.R659CO', trim($userWhsCoPlant["USERCO"])) ->where('p.R659CO', trim($userWhsCoPlant['USERCO']))
->where('p.R659WHS', trim($userWhsCoPlant["USERWHS"])) ->where('p.R659WHS', trim($userWhsCoPlant['USERWHS']))
->where('p.R659PLANT', trim($userWhsCoPlant["USERPL"])) ->where('p.R659PLANT', trim($userWhsCoPlant['USERPL']))
->first(); ->first();
if ($firstPalletBox) { if ($firstPalletBox) {
$incomingCarrier = trim($ICM695M1Sel->AYSPR15A01 ?? ''); $incomingCarrier = trim($ICM695M1Sel->AYSPR15A01 ?? '');
$incomingConveyor = trim($ICM695M1Sel->CONVEYOR_NAME ?? ''); $incomingConveyor = trim($ICM695M1Sel->CONVEYOR_NAME ?? '');
$palletCarrier = trim($firstPalletBox->AYSPR15A01 ?? ''); $palletCarrier = trim($firstPalletBox->AYSPR15A01 ?? '');
$palletConveyor = trim($firstPalletBox->CONVEYOR_NAME ?? ''); $palletConveyor = trim($firstPalletBox->CONVEYOR_NAME ?? '');
if ($incomingCarrier !== $palletCarrier) { if ($incomingCarrier !== $palletCarrier) {
$br = $boxMessage == '' ? '' : '<br>'; $br = $boxMessage == '' ? '' : '<br>';
@@ -159,29 +155,29 @@ class BoxPackToPalletController extends Controller
} }
} }
if ($exists || !$boxExistInICM695M || $boxisPalletICM695M || $boxMessage !== '') { if ($exists || ! $boxExistInICM695M || $boxisPalletICM695M || $boxMessage !== '') {
return response()->json([ return response()->json([
'success' => false, 'success' => false,
'message' => $boxMessage, 'message' => $boxMessage,
], 409); ], 409);
} }
# Step 4: Insert new box record // Step 4: Insert new box record
DB::connection(config('m3.connection', 'pgsql')) DB::connection(config('m3.connection', 'pgsql'))
->table('icm659m') ->table('icm659m')
->insert([ ->insert([
'R659PALT' => $R659PALT, 'R659PALT' => $R659PALT,
'R659BOX' => $R659BOX, 'R659BOX' => $R659BOX,
'R659LOADED' => '', 'R659LOADED' => '',
'R659USER' => $SHUSER, 'R659USER' => $SHUSER,
'R659DATE' => date('Y-m-d'), 'R659DATE' => date('Y-m-d'),
'R659TIME' => date('H:i:s'), 'R659TIME' => date('H:i:s'),
'R659CO' => trim($userWhsCoPlant["USERCO"]), 'R659CO' => trim($userWhsCoPlant['USERCO']),
'R659WHS' => trim($userWhsCoPlant["USERWHS"]), 'R659WHS' => trim($userWhsCoPlant['USERWHS']),
'R659PLANT' => trim($userWhsCoPlant["USERPL"]), 'R659PLANT' => trim($userWhsCoPlant['USERPL']),
]); ]);
# Step 5: Return the full refreshed box list // Step 5: Return the full refreshed box list
$boxes = DB::connection(config('m3.connection', 'pgsql'))->table('ICM659M as p') $boxes = DB::connection(config('m3.connection', 'pgsql'))->table('ICM659M as p')
->select( ->select(
'p.R659PALT', 'p.R659PALT',
@@ -194,15 +190,15 @@ class BoxPackToPalletController extends Controller
'c.AYSPR15A01', 'c.AYSPR15A01',
'cv.A4APR8N001', 'cv.A4APR8N001',
'cv.A4SHSHCT', 'cv.A4SHSHCT',
'cnv.R652SORTK as CONVEYOR_NAME' 'cnv.R652SORTK as CONVEYOR_NAME',
) )
->leftJoin('ICM695M1 as c', 'p.R659BOX', '=', 'c.AYINTBOX') ->leftJoin('ICM695M1 as c', 'p.R659BOX', '=', 'c.AYINTBOX')
->leftJoin('ICM688M1 as cv', 'c.AYMACPKR', '=', 'cv.A4MACPKR') ->leftJoin('ICM688M1 as cv', 'c.AYMACPKR', '=', 'cv.A4MACPKR')
->leftJoin('ICM652M as cnv', 'cv.A4APR8N001', '=', 'cnv.R652SEQ') ->leftJoin('ICM652M as cnv', 'cv.A4APR8N001', '=', 'cnv.R652SEQ')
->where('p.R659PALT', $R659PALT) ->where('p.R659PALT', $R659PALT)
->where('p.R659CO', trim($userWhsCoPlant["USERCO"])) ->where('p.R659CO', trim($userWhsCoPlant['USERCO']))
->where('p.R659WHS', trim($userWhsCoPlant["USERWHS"])) ->where('p.R659WHS', trim($userWhsCoPlant['USERWHS']))
->where('p.R659PLANT', trim($userWhsCoPlant["USERPL"])) ->where('p.R659PLANT', trim($userWhsCoPlant['USERPL']))
->orderBy('p.R659DATE', 'desc') ->orderBy('p.R659DATE', 'desc')
->orderBy('p.R659TIME', 'desc') ->orderBy('p.R659TIME', 'desc')
->distinct() ->distinct()
@@ -213,11 +209,11 @@ class BoxPackToPalletController extends Controller
return response()->json([ return response()->json([
'success' => true, 'success' => true,
'message' => "&bull; Box {$R659BOX} added to Pallet {$R659PALT}.", 'message' => "&bull; Box {$R659BOX} added to Pallet {$R659PALT}.",
'data' => $boxes, 'data' => $boxes,
]); ]);
} }
# Delete Box // Delete Box
public static function deleteBox(Request $request) public static function deleteBox(Request $request)
{ {
$R659PALT = $request->R659PALT ?? abort(400, 'Pallet Not Found'); $R659PALT = $request->R659PALT ?? abort(400, 'Pallet Not Found');
@@ -225,21 +221,21 @@ class BoxPackToPalletController extends Controller
$userWhsCoPlant = self::getUserWhsCoPlant(); $userWhsCoPlant = self::getUserWhsCoPlant();
# Guard: only allow delete if R659LOADED is empty // Guard: only allow delete if R659LOADED is empty
$record = DB::connection(config('m3.connection', 'pgsql')) $record = DB::connection(config('m3.connection', 'pgsql'))
->table('icm659m') ->table('icm659m')
->where('R659PALT', $R659PALT) ->where('R659PALT', $R659PALT)
->where('R659BOX', $R659BOX) ->where('R659BOX', $R659BOX)
->first(); ->first();
if (!$record) { if (! $record) {
return response()->json([ return response()->json([
'success' => false, 'success' => false,
'message' => "Box {$R659BOX} not found on Pallet {$R659PALT}.", 'message' => "Box {$R659BOX} not found on Pallet {$R659PALT}.",
], 404); ], 404);
} }
if (!empty(trim($record->R659LOADED))) { if (! empty(trim($record->R659LOADED))) {
return response()->json([ return response()->json([
'success' => false, 'success' => false,
'message' => "Box {$R659BOX} is already loaded and cannot be removed.", 'message' => "Box {$R659BOX} is already loaded and cannot be removed.",
@@ -252,7 +248,7 @@ class BoxPackToPalletController extends Controller
->where('R659BOX', $R659BOX) ->where('R659BOX', $R659BOX)
->delete(); ->delete();
# Return refreshed list // Return refreshed list
$boxes = DB::connection(config('m3.connection', 'pgsql'))->table('ICM659M as p') $boxes = DB::connection(config('m3.connection', 'pgsql'))->table('ICM659M as p')
->select( ->select(
'p.R659PALT', 'p.R659PALT',
@@ -265,15 +261,15 @@ class BoxPackToPalletController extends Controller
'c.AYSPR15A01', 'c.AYSPR15A01',
'cv.A4APR8N001', 'cv.A4APR8N001',
'cv.A4SHSHCT', 'cv.A4SHSHCT',
'cnv.R652SORTK as CONVEYOR_NAME' 'cnv.R652SORTK as CONVEYOR_NAME',
) )
->leftJoin('ICM695M1 as c', 'p.R659BOX', '=', 'c.AYINTBOX') ->leftJoin('ICM695M1 as c', 'p.R659BOX', '=', 'c.AYINTBOX')
->leftJoin('ICM688M1 as cv', 'c.AYMACPKR', '=', 'cv.A4MACPKR') ->leftJoin('ICM688M1 as cv', 'c.AYMACPKR', '=', 'cv.A4MACPKR')
->leftJoin('ICM652M as cnv', 'cv.A4APR8N001', '=', 'cnv.R652SEQ') ->leftJoin('ICM652M as cnv', 'cv.A4APR8N001', '=', 'cnv.R652SEQ')
->where('p.R659PALT', $R659PALT) ->where('p.R659PALT', $R659PALT)
->where('p.R659CO', trim($userWhsCoPlant["USERCO"])) ->where('p.R659CO', trim($userWhsCoPlant['USERCO']))
->where('p.R659WHS', trim($userWhsCoPlant["USERWHS"])) ->where('p.R659WHS', trim($userWhsCoPlant['USERWHS']))
->where('p.R659PLANT', trim($userWhsCoPlant["USERPL"])) ->where('p.R659PLANT', trim($userWhsCoPlant['USERPL']))
->orderBy('p.R659DATE', 'desc') ->orderBy('p.R659DATE', 'desc')
->orderBy('p.R659TIME', 'desc') ->orderBy('p.R659TIME', 'desc')
->distinct() ->distinct()
@@ -288,11 +284,11 @@ class BoxPackToPalletController extends Controller
]); ]);
} }
# Get Logged User CO/WHS/PLANT // Get Logged User CO/WHS/PLANT
public static function getUserWhsCoPlant() public static function getUserWhsCoPlant()
{ {
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : ''; $SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
# Get users from ICM428M // Get users from ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US', 'R428CO', 'R428WH', 'R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US', '=', $SHUSER) ->where('R428US', '=', $SHUSER)
@@ -304,11 +300,12 @@ class BoxPackToPalletController extends Controller
$R428PL = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; $R428PL = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '';
$userWhsCoPlant = [ $userWhsCoPlant = [
"R428US" => $R428US, 'R428US' => $R428US,
"USERCO" => $USERCO, 'USERCO' => $USERCO,
"USERWHS" => $USERWH, 'USERWHS' => $USERWH,
"USERPL" => $R428PL, 'USERPL' => $R428PL,
]; ];
return $userWhsCoPlant; return $userWhsCoPlant;
} }
} }
@@ -2,28 +2,25 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB; use DB;
use Config;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
// use Modules\M3\Models\ICM709M; // use Modules\M3\Models\ICM709M;
// //
class GetContentsController extends Controller class GetContentsController extends Controller
{ {
public function processShipment(Request $request) public function processShipment(Request $request)
{ {
# Get Mackpkr from Request // Get Mackpkr from Request
$macpacPicker = isset($request->MACPKR) ? trim($request->MACPKR) : ''; $macpacPicker = isset($request->MACPKR) ? trim($request->MACPKR) : '';
# ESN1 // ESN1
# $macpacPicker='888568'; // LTL example // $macpacPicker='888568'; // LTL example
# $macpacPicker='894337'; // another LTL example with smaller orders, therefore pallets are more mixed // $macpacPicker='894337'; // another LTL example with smaller orders, therefore pallets are more mixed
# $macpacPicker='1225311'; // parcel example // $macpacPicker='1225311'; // parcel example
# ESN2 // ESN2
# $macpacPicker='748101'; // LTL example // $macpacPicker='748101'; // LTL example
try { try {
$icm704mArray = $this->buildNMFCCodesArray(); $icm704mArray = $this->buildNMFCCodesArray();
@@ -33,25 +30,25 @@ class GetContentsController extends Controller
return response()->json(['error' => "Picker {$macpacPicker} was not found in ICM688M1"]); return response()->json(['error' => "Picker {$macpacPicker} was not found in ICM688M1"]);
} }
# Get Packages // Get Packages
$packages = $this->getPackagesData($shipmentData['macpkr_list']); $packages = $this->getPackagesData($shipmentData['macpkr_list']);
# Add NMFC to Packages // Add NMFC to Packages
$packagesWithNMFC = $this->addNMFCDataToPackages($packages, $macpacPicker, $icm704mArray); $packagesWithNMFC = $this->addNMFCDataToPackages($packages, $macpacPicker, $icm704mArray);
# Get Commodities // Get Commodities
$commodities = $this->getCommoditiesData( $commodities = $this->getCommoditiesData(
$shipmentData['company'], $shipmentData['company'],
$shipmentData['warehouse'], $shipmentData['warehouse'],
$macpacPicker, $macpacPicker,
$packages['package_595m1'], $packages['package_595m1'],
$icm704mArray $icm704mArray,
); );
return response()->json([ return response()->json([
'error' => '', 'error' => '',
'shipmentData' => $shipmentData, 'shipmentData' => $shipmentData,
'packages' => $packagesWithNMFC, 'packages' => $packagesWithNMFC,
'commodities' => $commodities 'commodities' => $commodities,
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
@@ -70,8 +67,8 @@ class GetContentsController extends Controller
'LTLClassId' => number_format(trim($row->AOFCID), 1), 'LTLClassId' => number_format(trim($row->AOFCID), 1),
'NMFCItem' => trim($row->AONMIT), 'NMFCItem' => trim($row->AONMIT),
'NMFCSub' => trim($row->AONMSB), 'NMFCSub' => trim($row->AONMSB),
'SkidDescription' => trim($row->AOSKDE) 'SkidDescription' => trim($row->AOSKDE),
] ],
]; ];
})->all(); })->all();
@@ -79,7 +76,8 @@ class GetContentsController extends Controller
protected function getShipmentData($macpacPicker) protected function getShipmentData($macpacPicker)
{ {
$result = DB::select(" $result = DB::select(
'
SELECT SELECT
SUM(A4TPCKWGHT) as total_weight, SUM(A4TPCKWGHT) as total_weight,
A4MACPKR, A4SHSHA1, A4SHSHA2, A4SHSHCI, A4SHSHNM, A4MACPKR, A4SHSHA1, A4SHSHA2, A4SHSHCI, A4SHSHNM,
@@ -93,8 +91,8 @@ class GetContentsController extends Controller
A4SHSHCT, A4SHSHZP, A4SHSHST, A4ONO, A4RLNO, A4SHNO, A4SHSHCT, A4SHSHZP, A4SHSHST, A4ONO, A4RLNO, A4SHNO,
A4STCN, A4CO, A4WHS, A4SHIPVIA, A4SLCO, A4SLWHS, A4STCN, A4CO, A4WHS, A4SHIPVIA, A4SLCO, A4SLWHS,
A4CATPID, A42SSVCCOD, A4CARRIER, A4SHPAGGCD, A4CATPID, A42SSVCCOD, A4CARRIER, A4SHPAGGCD,
A4SALESLOC, A4SHCSPO, A4OFSTRM, A4SCAC, A4PLANT", A4SALESLOC, A4SHCSPO, A4OFSTRM, A4SCAC, A4PLANT',
[$macpacPicker] [$macpacPicker],
); );
if (empty($result)) { if (empty($result)) {
@@ -121,13 +119,14 @@ class GetContentsController extends Controller
'macpkr_list' => $macpacPicker, 'macpkr_list' => $macpacPicker,
'shipment_list' => "'" . trim($row->A4ONO) . "'", 'shipment_list' => "'" . trim($row->A4ONO) . "'",
'po_list' => "'" . trim($row->A4SHCSPO) . "'", 'po_list' => "'" . trim($row->A4SHCSPO) . "'",
'order_list' => "'" . trim($row->A4ONO) . "'" 'order_list' => "'" . trim($row->A4ONO) . "'",
]; ];
} }
protected function getPackagesData($macpkrList) protected function getPackagesData($macpkrList)
{ {
$results = DB::select(" $results = DB::select(
'
SELECT SELECT
AYINTBOX, AYINTBOX,
MAX(AYHEIGHT) as height, MAX(AYHEIGHT) as height,
@@ -137,8 +136,8 @@ class GetContentsController extends Controller
FROM ICM695M1 FROM ICM695M1
WHERE AYMACPKR IN (?) WHERE AYMACPKR IN (?)
GROUP BY AYINTBOX GROUP BY AYINTBOX
ORDER BY AYINTBOX", ORDER BY AYINTBOX',
[$macpkrList] [$macpkrList],
); );
$packages = []; $packages = [];
@@ -154,7 +153,7 @@ class GetContentsController extends Controller
'HEIGHT' => $row->HEIGHT, 'HEIGHT' => $row->HEIGHT,
'WIDTH' => $row->WIDTH, 'WIDTH' => $row->WIDTH,
'DEPTH' => $row->DEPTH, 'DEPTH' => $row->DEPTH,
'WEIGHT' => $row->WEIGHT 'WEIGHT' => $row->WEIGHT,
]; ];
$packages[] = [ $packages[] = [
@@ -165,7 +164,7 @@ class GetContentsController extends Controller
'LicencePlate' => $internalBox, 'LicencePlate' => $internalBox,
'Reference1' => $internalBox, 'Reference1' => $internalBox,
'WeightType' => 0, 'WeightType' => 0,
'DimensionType' => 0 'DimensionType' => 0,
]; ];
$packagesGS1Array[] = $internalBox; $packagesGS1Array[] = $internalBox;
@@ -174,13 +173,14 @@ class GetContentsController extends Controller
return [ return [
'packages' => $packages, 'packages' => $packages,
'package_595m1' => $package595m1, 'package_595m1' => $package595m1,
'packagesGS1Array' => $packagesGS1Array 'packagesGS1Array' => $packagesGS1Array,
]; ];
} }
protected function addNMFCDataToPackages($packages, $macpkrList, $icm704mArray) protected function addNMFCDataToPackages($packages, $macpkrList, $icm704mArray)
{ {
$nmfcResults = DB::select(" $nmfcResults = DB::select(
'
WITH tempfile AS ( WITH tempfile AS (
SELECT SELECT
(SELECT A5WBFRCT FROM ICM688M2 (SELECT A5WBFRCT FROM ICM688M2
@@ -193,8 +193,8 @@ class GetContentsController extends Controller
SELECT azintbox, MIN(WBFRCT) as MIN_WBFRCT SELECT azintbox, MIN(WBFRCT) as MIN_WBFRCT
FROM tempfile FROM tempfile
GROUP BY azintbox GROUP BY azintbox
ORDER BY 1", ORDER BY 1',
[$macpkrList, $macpkrList] [$macpkrList, $macpkrList],
); );
foreach ($nmfcResults as $index => $row) { foreach ($nmfcResults as $index => $row) {
@@ -208,7 +208,8 @@ class GetContentsController extends Controller
protected function getCommoditiesData($company, $warehouse, $macpkrList, $package595m1, $icm704mArray) protected function getCommoditiesData($company, $warehouse, $macpkrList, $package595m1, $icm704mArray)
{ {
$results = DB::select(" $results = DB::select(
'
WITH tempfile1 AS ( WITH tempfile1 AS (
SELECT SELECT
A5PART, A5PART,
@@ -238,8 +239,8 @@ class GetContentsController extends Controller
A5WBFRCT, HAZARDOUS, A5SLUNPR A5WBFRCT, HAZARDOUS, A5SLUNPR
FROM tempfile1 FROM tempfile1
LEFT JOIN tempfile2 ON AZPART = A5PART LEFT JOIN tempfile2 ON AZPART = A5PART
ORDER BY A5PART", ORDER BY A5PART',
[$company, $warehouse, $macpkrList, $company, $warehouse, $macpkrList] [$company, $warehouse, $macpkrList, $company, $warehouse, $macpkrList],
); );
$commodities = []; $commodities = [];
@@ -257,7 +258,7 @@ class GetContentsController extends Controller
$nmfcData = $icm704mArray[$wbfrct] ?? [ $nmfcData = $icm704mArray[$wbfrct] ?? [
'LTLClassId' => '50', 'LTLClassId' => '50',
'NMFCItem' => '93490', 'NMFCItem' => '93490',
'NMFCSub' => '' 'NMFCSub' => '',
]; ];
$commodities[] = [ $commodities[] = [
@@ -273,14 +274,14 @@ class GetContentsController extends Controller
'NMFCItem' => $nmfcData['NMFCItem'], 'NMFCItem' => $nmfcData['NMFCItem'],
'NMFCSub' => $nmfcData['NMFCSub'], 'NMFCSub' => $nmfcData['NMFCSub'],
'DangerousGoodsInfo' => [ 'DangerousGoodsInfo' => [
'ContainsDangerousGoods' => trim($row->HAZARDOUS) === 'H4.1' 'ContainsDangerousGoods' => trim($row->HAZARDOUS) === 'H4.1',
], ],
'QuantityAssignment' => [ 'QuantityAssignment' => [
[ [
'PackageIndex' => $package595m1[trim($row->AZINTBOX)]['INDEX'], 'PackageIndex' => $package595m1[trim($row->AZINTBOX)]['INDEX'],
'Quantity' => (float) $row->AZPACKED 'Quantity' => (float) $row->AZPACKED,
] ],
] ],
]; ];
} else { } else {
$quantityIndex++; $quantityIndex++;
@@ -288,7 +289,7 @@ class GetContentsController extends Controller
$commodities[$index]['Quantity'] += (float) $row->AZPACKED; $commodities[$index]['Quantity'] += (float) $row->AZPACKED;
$commodities[$index]['QuantityAssignment'][] = [ $commodities[$index]['QuantityAssignment'][] = [
'PackageIndex' => $package595m1[trim($row->AZINTBOX)]['INDEX'], 'PackageIndex' => $package595m1[trim($row->AZINTBOX)]['INDEX'],
'Quantity' => (float) $row->AZPACKED 'Quantity' => (float) $row->AZPACKED,
]; ];
} }
@@ -297,6 +298,4 @@ class GetContentsController extends Controller
return $commodities; return $commodities;
} }
} }
@@ -2,40 +2,36 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Log;
use Str;
use Artisan; use Artisan;
use Config;
use Modules\M3\Http\Controllers\API\CloseShipment; use DB;
use Illuminate\Http\Request;
use Log;
class M3CallCloseAPIController extends Controller class M3CallCloseAPIController extends Controller
{ {
public static function index(Request $request){ public static function index(Request $request)
{
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut')); ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
try { try {
# Get the Calling User // Get the Calling User
# Get URL PARAMS // Get URL PARAMS
$urlParams = count($request->all())>0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
// dd($urlParams); // dd($urlParams);
$SHUSER = isset($urlParams["SHUSER"]) ? $urlParams["SHUSER"] : ''; $SHUSER = isset($urlParams['SHUSER']) ? $urlParams['SHUSER'] : '';
$MANIFEST = isset($urlParams["MANIFEST"]) ? $urlParams["MANIFEST"] : ''; $MANIFEST = isset($urlParams['MANIFEST']) ? $urlParams['MANIFEST'] : '';
$APCO = isset($urlParams["APCO"]) ? $urlParams["APCO"] : ''; $APCO = isset($urlParams['APCO']) ? $urlParams['APCO'] : '';
$APWHS = isset($urlParams["APWHS"]) ? $urlParams["APWHS"] : ''; $APWHS = isset($urlParams['APWHS']) ? $urlParams['APWHS'] : '';
if ($MANIFEST!='' && $APCO!='' && $APWHS!='') { // $SHUSER!='' && if ($MANIFEST != '' && $APCO != '' && $APWHS != '') { // $SHUSER!='' &&
// Log::channel('dailyCron')->info("Cron...Start CallCloseAPI...For user:".$SHUSER." Manifest#: ".$MANIFEST); // Log::channel('dailyCron')->info("Cron...Start CallCloseAPI...For user:".$SHUSER." Manifest#: ".$MANIFEST);
# Get Logged User CO & WH // Get Logged User CO & WH
# Get users from ICM428M // Get users from ICM428M
// $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') // $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
// ->select('R428US','R428CO', 'R428WH') // ->select('R428US','R428CO', 'R428WH')
// ->where('R428US','=',$SHUSER) // ->where('R428US','=',$SHUSER)
@@ -46,68 +42,64 @@ class M3CallCloseAPIController extends Controller
// $USERWH = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; // $USERWH = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '';
// dump($R428US.':'.$USERCO.':'.$USERWH); // dump($R428US.':'.$USERCO.':'.$USERWH);
# Get Macpickers from ICM705M1 // Get Macpickers from ICM705M1
# SELECT APMANIFEST FROM ICM705M1 WHERE APSPARE2='' AND APCO='110' AND APWHS='321' // SELECT APMANIFEST FROM ICM705M1 WHERE APSPARE2='' AND APCO='110' AND APWHS='321'
$ICM705M1 = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1') $ICM705M1 = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1')
->select('APMANIFEST','APCO','APWHS') ->select('APMANIFEST', 'APCO', 'APWHS')
->where('APSPARE2','') ->where('APSPARE2', '')
->where('APCO',$APCO) ->where('APCO', $APCO)
->where('APWHS',$APWHS) ->where('APWHS', $APWHS)
->where('APMANIFEST','=',$MANIFEST) ->where('APMANIFEST', '=', $MANIFEST)
->whereRaw('EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - APLDCLOZ)) / 60 > 15') ->whereRaw('EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - APLDCLOZ)) / 60 > 15')
->orderBy('APMANIFEST') ->orderBy('APMANIFEST')
->get(); ->get();
// dump($ICM705M1); // dump($ICM705M1);
if (count($ICM705M1)>0) { if (count($ICM705M1) > 0) {
# Loop the Results from $ICM705M1 // Loop the Results from $ICM705M1
foreach ($ICM705M1 as $key => $ICM705M1R) { foreach ($ICM705M1 as $key => $ICM705M1R) {
# Send CO and WHS to CallCloseAPI // Send CO and WHS to CallCloseAPI
$USERCO = isset($ICM705M1R->APCO) ? $ICM705M1R->APCO : ''; $USERCO = isset($ICM705M1R->APCO) ? $ICM705M1R->APCO : '';
$USERWH = isset($ICM705M1R->APWHS) ? $ICM705M1R->APWHS : ''; $USERWH = isset($ICM705M1R->APWHS) ? $ICM705M1R->APWHS : '';
$callCloseShipment = Artisan::call('command:CallCloseAPI', ['user'=> $SHUSER ,'manifest' => $ICM705M1R->APMANIFEST , $callCloseShipment = Artisan::call('command:CallCloseAPI', ['user' => $SHUSER, 'manifest' => $ICM705M1R->APMANIFEST,
'co' => $USERCO ,'whs' => $USERWH]); 'co' => $USERCO, 'whs' => $USERWH]);
// dump($callCloseShipment); // dump($callCloseShipment);
if ($callCloseShipment==1) { if ($callCloseShipment == 1) {
return response()->json([ return response()->json([
'code' => '200', 'code' => '200',
'status' => 'Success', 'status' => 'Success',
'message'=> 'Manifest Closing submitted' 'message' => 'Manifest Closing submitted',
]); ]);
} } else {
else{
return response()->json([ return response()->json([
'code' => '206', 'code' => '206',
'status' => 'Failure', 'status' => 'Failure',
'message'=> 'Manifest Closing Failed' 'message' => 'Manifest Closing Failed',
]); ]);
} }
} }
} } else {
else{ Log::channel('dailyCron')->info('Manifest CloseAPI: No records found in ICM705M1...');
Log::channel('dailyCron')->info("Manifest CloseAPI: No records found in ICM705M1...");
return response()->json([ return response()->json([
'code' => '206', 'code' => '206',
'status' => 'Error', 'status' => 'Error',
'message'=> "Manifest CloseAPI: No records found in ICM705M1..." 'message' => 'Manifest CloseAPI: No records found in ICM705M1...',
]); ]);
} }
} } else {
else{
Log::channel('dailyCron')->error('Manifest CloseAPI: A User and Manifest must be defined...'); Log::channel('dailyCron')->error('Manifest CloseAPI: A User and Manifest must be defined...');
return response()->json([ return response()->json([
'code' => '206', 'code' => '206',
'status' => 'Error', 'status' => 'Error',
'message'=> 'Manifest CloseAPI: A User and Manifest must be defined...' 'message' => 'Manifest CloseAPI: A User and Manifest must be defined...',
]); ]);
} }
} } catch (\Throwable $th) {
catch (\Throwable $th) {
Log::error($th); Log::error($th);
} }
} }
} }
@@ -2,50 +2,52 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB; use DB;
use Config;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response; use Illuminate\Support\Facades\Schema;
use Modules\M3\Models\ICM664M; use Modules\M3\Models\ICM664M;
class M3DeliveryController extends Controller class M3DeliveryController extends Controller
{ {
public static function index(Request $request)
public static function index(Request $request) { {
$connection = config('m3.connection', 'pgsql'); $connection = config('m3.connection', 'pgsql');
$power_user = (object) ['R428PWRUSR'=>'N','R428US'=>strtoUpper(m3_user()),'R428CO'=>'','R428PL'=>'','R428WH'=>'']; $power_user = (object) ['R428PWRUSR' => 'N', 'R428US' => strtoupper(m3_user()), 'R428CO' => '', 'R428PL' => '', 'R428WH' => ''];
if (\Illuminate\Support\Facades\Schema::connection($connection)->hasTable('icm428m')) { if (Schema::connection($connection)->hasTable('icm428m')) {
$power_user = DB::connection($connection)->table('icm428m')->select('R428PWRUSR','R428US','R428CO','R428PL','R428WH') $power_user = DB::connection($connection)->table('icm428m')->select('R428PWRUSR', 'R428US', 'R428CO', 'R428PL', 'R428WH')
->where('R428US',strtoUpper(m3_user()))->first() ?? $power_user; ->where('R428US', strtoupper(m3_user()))->first() ?? $power_user;
} }
$co=$power_user->R428CO; $plant=$power_user->R428PL; $whs=$power_user->R428WH; $co = $power_user->R428CO;
$ICM664M = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('icm664m') $plant = $power_user->R428PL;
? DB::connection($connection)->table('icm664m')->where('AVCO',$co)->where('AVPLANT',$plant)->where('AVWHS',$whs)->get() : collect(); $whs = $power_user->R428WH;
$IC670M = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('ic670m') $ICM664M = Schema::connection($connection)->hasTable('icm664m')
? DB::connection($connection)->table('ic670m')->where('WDCO',$co)->where('WDPL',$plant)->where('WDWHS',$whs)->get() : collect(); ? DB::connection($connection)->table('icm664m')->where('AVCO', $co)->where('AVPLANT', $plant)->where('AVWHS', $whs)->get() : collect();
$shipvia = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('icm319m') $IC670M = Schema::connection($connection)->hasTable('ic670m')
? DB::connection($connection)->table('icm319m')->select('AXCODE','AXDESC')->orderBy('AXCODE')->get() : collect(); ? DB::connection($connection)->table('ic670m')->where('WDCO', $co)->where('WDPL', $plant)->where('WDWHS', $whs)->get() : collect();
return view('m3::liberty-theme.pages.M3Delivery', compact('ICM664M','IC670M','power_user','shipvia')); $shipvia = Schema::connection($connection)->hasTable('icm319m')
? DB::connection($connection)->table('icm319m')->select('AXCODE', 'AXDESC')->orderBy('AXCODE')->get() : collect();
return view('m3::liberty-theme.pages.M3Delivery', compact('ICM664M', 'IC670M', 'power_user', 'shipvia'));
} }
// //
// Process data from Add modal // Process data from Add modal
// //
public static function saveM3DeliveryAdd(Request $request) { public static function saveM3DeliveryAdd(Request $request)
{
$icm664m=DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from ICM664M $icm664m = DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from ICM664M
where AVCO='$request->AVCO' and AVWHS='$request->AVWHS' and AVPLANT='$request->AVPLANT' and AVDELMETH='$request->AVDELMETH'"); where AVCO='$request->AVCO' and AVWHS='$request->AVWHS' and AVPLANT='$request->AVPLANT' and AVDELMETH='$request->AVDELMETH'");
if($icm664m[0]->COUNT1=="1") { if ($icm664m[0]->COUNT1 == '1') {
return "exists"; return 'exists';
} else { } else {
DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM664M DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM664M
(AVCO, AVPLANT, AVWHS, AVDELMETH, AVSHPVIA, AVSHSRT, AVSHORCL) (AVCO, AVPLANT, AVWHS, AVDELMETH, AVSHPVIA, AVSHSRT, AVSHORCL)
values ('$request->AVCO', '$request->AVPLANT', '$request->AVWHS', '$request->AVDELMETH', values ('$request->AVCO', '$request->AVPLANT', '$request->AVWHS', '$request->AVDELMETH',
'$request->AVSHPVIA', '$request->AVSHSRT', '$request->AVSHORCL')"); '$request->AVSHPVIA', '$request->AVSHSRT', '$request->AVSHORCL')");
return "success";
return 'success';
} }
} }
@@ -53,16 +55,16 @@ class M3DeliveryController extends Controller
// //
// Process data from Edit modal // Process data from Edit modal
// //
public static function saveM3DeliveryEdit(Request $request) { public static function saveM3DeliveryEdit(Request $request)
#dd($request); {
// dd($request);
// Update record to ICM664M // Update record to ICM664M
DB::connection(config('m3.connection', 'pgsql'))->update("update ICM664M DB::connection(config('m3.connection', 'pgsql'))->update("update ICM664M
set AVSHPVIA='$request->AVSHPVIA', AVSHSRT='$request->AVSHSRT', AVSHORCL='$request->AVSHORCL' set AVSHPVIA='$request->AVSHPVIA', AVSHSRT='$request->AVSHSRT', AVSHORCL='$request->AVSHORCL'
where AVCO='$request->AVCO' and AVPLANT='$request->AVPLANT' and AVWHS='$request->AVWHS' and AVDELMETH='$request->AVDELMETH'"); where AVCO='$request->AVCO' and AVPLANT='$request->AVPLANT' and AVWHS='$request->AVWHS' and AVDELMETH='$request->AVDELMETH'");
return "success"; return 'success';
} }
} }
@@ -2,29 +2,28 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Datatables; use Datatables;
use Str; use DB;
use Excel; use Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Modules\M3\Services\SpreadsheetExport;
use Str;
class M3ErrorsDispController extends Controller class M3ErrorsDispController extends Controller
{ {
public static function index(Request $request) public static function index(Request $request)
{ {
// dump($request->all()); // dump($request->all());
$macpkr = isset($request->macpkr) ? trim($request->macpkr) : ""; $macpkr = isset($request->macpkr) ? trim($request->macpkr) : '';
$shsource = isset($request->shsource) ? trim($request->shsource) : ""; $shsource = isset($request->shsource) ? trim($request->shsource) : '';
$showerrors = isset($request->showerrors) ? trim($request->showerrors) : "N"; $showerrors = isset($request->showerrors) ? trim($request->showerrors) : 'N';
$skipdates = isset($request->skipdates) ? trim($request->skipdates) : "N"; $skipdates = isset($request->skipdates) ? trim($request->skipdates) : 'N';
# Get users from ICM428M // Get users from ICM428M
$connection = config('m3.connection', 'pgsql'); $connection = config('m3.connection', 'pgsql');
$ICM428M = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('icm428m') $ICM428M = Schema::connection($connection)->hasTable('icm428m')
? DB::connection($connection)->table('icm428m')->select('R428US', 'R428FIRST', 'R428FAMILY')->get() ? DB::connection($connection)->table('icm428m')->select('R428US', 'R428FIRST', 'R428FAMILY')->get()
: collect(); : collect();
$ICM428MCOL = collect($ICM428M); $ICM428MCOL = collect($ICM428M);
@@ -49,16 +48,16 @@ class M3ErrorsDispController extends Controller
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
// dump($request->all()); // dump($request->all());
$SHMACPKR = null != $request->SHMACPKR ? trim($request->SHMACPKR) : ''; $SHMACPKR = $request->SHMACPKR != null ? trim($request->SHMACPKR) : '';
$SHSOURCE = null != $request->SHSOURCE ? trim($request->SHSOURCE) : ''; $SHSOURCE = $request->SHSOURCE != null ? trim($request->SHSOURCE) : '';
$STARTDATE = null != $request->STARTDATE ? trim($request->STARTDATE) : today()->subDays(1)->format('Y-m-d'); $STARTDATE = $request->STARTDATE != null ? trim($request->STARTDATE) : today()->subDays(1)->format('Y-m-d');
$ENDDATE = null != $request->ENDDATE ? trim($request->ENDDATE) : today()->format('Y-m-d'); $ENDDATE = $request->ENDDATE != null ? trim($request->ENDDATE) : today()->format('Y-m-d');
$SHOWERRORS = null != $request->SHOWERRORS ? trim($request->SHOWERRORS) : 'N'; $SHOWERRORS = $request->SHOWERRORS != null ? trim($request->SHOWERRORS) : 'N';
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : ''; $SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
$SKIPDATES = null != $request->SKIPDATES ? trim($request->SKIPDATES) : 'N'; $SKIPDATES = $request->SKIPDATES != null ? trim($request->SKIPDATES) : 'N';
# Get Logged User CO & WH // Get Logged User CO & WH
# Get users from ICM428M // Get users from ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US', 'R428CO', 'R428WH') ->select('R428US', 'R428CO', 'R428WH')
->where('R428US', '=', $SHUSER) ->where('R428US', '=', $SHUSER)
@@ -68,7 +67,7 @@ class M3ErrorsDispController extends Controller
$USERCO = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; $USERCO = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '';
$USERWH = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; $USERWH = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '';
# Merge date and time fields // Merge date and time fields
$mergedDateTime = DB::raw(" ICM699M.SHDT || ' ' || ICM699M.SHTIME AS SHDATETIME"); $mergedDateTime = DB::raw(" ICM699M.SHDT || ' ' || ICM699M.SHTIME AS SHDATETIME");
$ICM699M = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m') $ICM699M = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
@@ -83,7 +82,7 @@ class M3ErrorsDispController extends Controller
'ICM688M1.A4ONO', 'ICM688M1.A4ONO',
'ICM688M1.A4SHSHNM', 'ICM688M1.A4SHSHNM',
'ICM666M.A1ONO', 'ICM666M.A1ONO',
'ICM666M.A1SHSHNM' 'ICM666M.A1SHSHNM',
) )
->distinct() ->distinct()
->leftJoin('ICM428M', 'ICM699M.SHUSER', '=', 'ICM428M.R428US') ->leftJoin('ICM428M', 'ICM699M.SHUSER', '=', 'ICM428M.R428US')
@@ -105,7 +104,7 @@ class M3ErrorsDispController extends Controller
if ($SHSOURCE != '') { if ($SHSOURCE != '') {
$ICM699M->where('SHSOURCE', $SHSOURCE); $ICM699M->where('SHSOURCE', $SHSOURCE);
} }
# Disable PDFStorage Search // Disable PDFStorage Search
$ICM699M->where('SHSOURCE', '!=', 'PdfStorageAPI'); $ICM699M->where('SHSOURCE', '!=', 'PdfStorageAPI');
if ($SHMACPKR == '' && $SKIPDATES == 'N') { if ($SHMACPKR == '' && $SKIPDATES == 'N') {
@@ -116,7 +115,7 @@ class M3ErrorsDispController extends Controller
$ICM699M->where('SHERROR', 'X'); $ICM699M->where('SHERROR', 'X');
} }
# Get only M3 Logs // Get only M3 Logs
$ICM699M->where('SHTYPE', 'like', '%M3%'); $ICM699M->where('SHTYPE', 'like', '%M3%');
return Datatables::of($ICM699M)->addIndexColumn()->make(true); return Datatables::of($ICM699M)->addIndexColumn()->make(true);
@@ -125,16 +124,16 @@ class M3ErrorsDispController extends Controller
public static function update699M(Request $request) public static function update699M(Request $request)
{ {
// dump($request->all()); // dump($request->all());
$SHMACPKR = null != $request->SHMACPKR ? trim($request->SHMACPKR) : ''; $SHMACPKR = $request->SHMACPKR != null ? trim($request->SHMACPKR) : '';
$SHSOURCE = null != $request->SHSOURCE ? trim($request->SHSOURCE) : ''; $SHSOURCE = $request->SHSOURCE != null ? trim($request->SHSOURCE) : '';
$SHCO = null != $request->SHCO ? trim($request->SHCO) : ''; $SHCO = $request->SHCO != null ? trim($request->SHCO) : '';
$SHWHS = null != $request->SHWHS ? trim($request->SHWHS) : ''; $SHWHS = $request->SHWHS != null ? trim($request->SHWHS) : '';
$SHDT = null != $request->SHDT ? trim($request->SHDT) : ''; $SHDT = $request->SHDT != null ? trim($request->SHDT) : '';
$SHTIME = null != $request->SHTIME ? trim($request->SHTIME) : ''; $SHTIME = $request->SHTIME != null ? trim($request->SHTIME) : '';
$SHTYPE = null != $request->SHTYPE ? trim($request->SHTYPE) : ''; $SHTYPE = $request->SHTYPE != null ? trim($request->SHTYPE) : '';
$SHACKNOTE = null != $request->SHACKNOTE ? trim(substr($request->SHACKNOTE, 0, 99)) : ''; $SHACKNOTE = $request->SHACKNOTE != null ? trim(substr($request->SHACKNOTE, 0, 99)) : '';
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : ''; $SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : '';
$CLOSESIM = null != $request->CLOSESIM ? trim($request->CLOSESIM) : 'N'; $CLOSESIM = $request->CLOSESIM != null ? trim($request->CLOSESIM) : 'N';
if ($CLOSESIM == 'N') { if ($CLOSESIM == 'N') {
$ICM699MU = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m') $ICM699MU = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
@@ -146,7 +145,7 @@ class M3ErrorsDispController extends Controller
->where('SHSOURCE', $SHSOURCE) ->where('SHSOURCE', $SHSOURCE)
->where('SHERROR', 'X') ->where('SHERROR', 'X')
->where('SHTYPE', $SHTYPE) ->where('SHTYPE', $SHTYPE)
->update(["SHERROR" => "Z", "SHACKUSER" => $SHUSER, "SHACKDATE" => date('Y-m-d'), "SHACKTIME" => date('H:i:s'), "SHACKNOTE" => $SHACKNOTE]); ->update(['SHERROR' => 'Z', 'SHACKUSER' => $SHUSER, 'SHACKDATE' => date('Y-m-d'), 'SHACKTIME' => date('H:i:s'), 'SHACKNOTE' => $SHACKNOTE]);
} else { } else {
$ICM699MU = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m') $ICM699MU = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
@@ -155,12 +154,11 @@ class M3ErrorsDispController extends Controller
->where('SHSOURCE', $SHSOURCE) ->where('SHSOURCE', $SHSOURCE)
->where('SHERROR', 'X') ->where('SHERROR', 'X')
->where('SHTYPE', $SHTYPE) ->where('SHTYPE', $SHTYPE)
->update(["SHERROR" => "Z", "SHACKUSER" => $SHUSER, "SHACKDATE" => date('Y-m-d'), "SHACKTIME" => date('H:i:s'), "SHACKNOTE" => $SHACKNOTE]); ->update(['SHERROR' => 'Z', 'SHACKUSER' => $SHUSER, 'SHACKDATE' => date('Y-m-d'), 'SHACKTIME' => date('H:i:s'), 'SHACKNOTE' => $SHACKNOTE]);
} }
if ($SHSOURCE == 'CloseShipmentCoChargeAPI') {
if ($SHSOURCE == "CloseShipmentCoChargeAPI") { // Update ICM688M1 : Change A4PICKSTS
# Update ICM688M1 : Change A4PICKSTS
DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1') DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->where('A4MACPKR', $SHMACPKR) ->where('A4MACPKR', $SHMACPKR)
->where('A4CO', $SHCO) ->where('A4CO', $SHCO)
@@ -171,7 +169,7 @@ class M3ErrorsDispController extends Controller
return response()->json(['success' => true]); return response()->json(['success' => true]);
} }
# Export To Excel // Export To Excel
public static function exporttoExcel(Request $request) public static function exporttoExcel(Request $request)
{ {
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
@@ -181,15 +179,15 @@ class M3ErrorsDispController extends Controller
try { try {
// dd($request->all()); // dd($request->all());
$SHMACPKR = null != $request->SHMACPKR ? trim($request->SHMACPKR) : ''; $SHMACPKR = $request->SHMACPKR != null ? trim($request->SHMACPKR) : '';
$SHSOURCE = null != $request->SHSOURCE ? trim($request->SHSOURCE) : ''; $SHSOURCE = $request->SHSOURCE != null ? trim($request->SHSOURCE) : '';
$STARTDATE = null != $request->STARTDATE ? trim($request->STARTDATE) : today()->subDays(1)->format('Y-m-d'); $STARTDATE = $request->STARTDATE != null ? trim($request->STARTDATE) : today()->subDays(1)->format('Y-m-d');
$ENDDATE = null != $request->ENDDATE ? trim($request->ENDDATE) : today()->format('Y-m-d'); $ENDDATE = $request->ENDDATE != null ? trim($request->ENDDATE) : today()->format('Y-m-d');
$SHOWERRORS = null != $request->SHOWERRORS ? trim($request->SHOWERRORS) : 'N'; $SHOWERRORS = $request->SHOWERRORS != null ? trim($request->SHOWERRORS) : 'N';
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : ''; $SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
$SKIPDATES = null != $request->SKIPDATES ? trim($request->SKIPDATES) : 'N'; $SKIPDATES = $request->SKIPDATES != null ? trim($request->SKIPDATES) : 'N';
# Get Logged User CO & WH // Get Logged User CO & WH
# Get users from ICM428M // Get users from ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US', 'R428CO', 'R428WH') ->select('R428US', 'R428CO', 'R428WH')
->where('R428US', '=', $SHUSER) ->where('R428US', '=', $SHUSER)
@@ -199,7 +197,7 @@ class M3ErrorsDispController extends Controller
$USERCO = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; $USERCO = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '';
$USERWH = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; $USERWH = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '';
# Get users from ICM428M // Get users from ICM428M
$ICM428MAll = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428MAll = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US', 'R428FIRST', 'R428FAMILY') ->select('R428US', 'R428FIRST', 'R428FAMILY')
->get(); ->get();
@@ -214,7 +212,7 @@ class M3ErrorsDispController extends Controller
return $value->R428FAMILY = trim($value->R428FAMILY); return $value->R428FAMILY = trim($value->R428FAMILY);
}); });
# Merge date and time fields // Merge date and time fields
$mergedDateTime = DB::raw(" ICM699M.SHDT || ' ' || ICM699M.SHTIME AS SHDATETIME"); $mergedDateTime = DB::raw(" ICM699M.SHDT || ' ' || ICM699M.SHTIME AS SHDATETIME");
$ICM699M = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m') $ICM699M = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
@@ -234,14 +232,14 @@ class M3ErrorsDispController extends Controller
'ICM699M.SHACKUSER', 'ICM699M.SHACKUSER',
'ICM699M.SHINTBOX', 'ICM699M.SHINTBOX',
'ICM699M.SHACKNOTE', 'ICM699M.SHACKNOTE',
DB::raw('SUBSTR(ICM699M.SHDATA, 1, 200)') DB::raw('SUBSTR(ICM699M.SHDATA, 1, 200)'),
) )
->distinct() ->distinct()
->leftJoin('ICM428M', 'ICM699M.SHUSER', '=', 'ICM428M.R428US') ->leftJoin('ICM428M', 'ICM699M.SHUSER', '=', 'ICM428M.R428US')
->leftJoin('ICM688M1', 'ICM699M.SHMACPKR', '=', 'ICM688M1.A4MACPKR') ->leftJoin('ICM688M1', 'ICM699M.SHMACPKR', '=', 'ICM688M1.A4MACPKR')
->leftJoin('ICM666M', 'ICM699M.SHMACPKR', '=', 'ICM666M.A1DELNO'); ->leftJoin('ICM666M', 'ICM699M.SHMACPKR', '=', 'ICM666M.A1DELNO');
# Get Records Count only // Get Records Count only
$ICM699MC = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m'); $ICM699MC = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m');
if ($R428US != '') { if ($R428US != '') {
@@ -269,7 +267,7 @@ class M3ErrorsDispController extends Controller
$ICM699MC->where('SHSOURCE', $SHSOURCE); $ICM699MC->where('SHSOURCE', $SHSOURCE);
} }
# Disable PDFStorage Search // Disable PDFStorage Search
$ICM699M->where('SHSOURCE', '!=', 'PdfStorageAPI'); $ICM699M->where('SHSOURCE', '!=', 'PdfStorageAPI');
$ICM699MC->where('SHSOURCE', '!=', 'PdfStorageAPI'); $ICM699MC->where('SHSOURCE', '!=', 'PdfStorageAPI');
@@ -286,61 +284,62 @@ class M3ErrorsDispController extends Controller
$ICM699MC->where('SHERROR', 'X'); $ICM699MC->where('SHERROR', 'X');
} }
# Get only M3 Logs // Get only M3 Logs
$ICM699M->where('SHTYPE', 'like', '%M3%'); $ICM699M->where('SHTYPE', 'like', '%M3%');
$ICM699MC->where('SHTYPE', 'like', '%M3%'); $ICM699MC->where('SHTYPE', 'like', '%M3%');
# Count records before exporting to excel : Max 20K records are allowed // Count records before exporting to excel : Max 20K records are allowed
$ICM699MCount = $ICM699MC->count(); $ICM699MCount = $ICM699MC->count();
// dd($ICM699MCount); // dd($ICM699MCount);
# Set Max allowed records // Set Max allowed records
$maxRecords = Config::get('arrays.maxRecDL'); $maxRecords = Config::get('arrays.maxRecDL');
if ($ICM699MCount > $maxRecords) { if ($ICM699MCount > $maxRecords) {
return redirect()->back()->withInput()->with('message', 'Maximum allowed records for Excel Download is: ' . number_format($maxRecords) . return redirect()->back()->withInput()->with('message', 'Maximum allowed records for Excel Download is: ' . number_format($maxRecords) .
' current records: ' . number_format($ICM699MCount) . ' , change your search criteria.'); ' current records: ' . number_format($ICM699MCount) . ' , change your search criteria.');
} }
# Select Records and export them to Excel // Select Records and export them to Excel
$ICM699MSel = $ICM699M->get(); $ICM699MSel = $ICM699M->get();
$ICM699MCol = collect($ICM699MSel); $ICM699MCol = collect($ICM699MSel);
# Get Transaction Types // Get Transaction Types
$transxTypes = Config::get('arrays.transxTypes'); $transxTypes = Config::get('arrays.transxTypes');
$ICM699MCol->filter(function ($value) use ($transxTypes) { $ICM699MCol->filter(function ($value) use ($transxTypes) {
return $value->SHSOURCE = isset($transxTypes[trim($value->SHSOURCE)]) ? $transxTypes[trim($value->SHSOURCE)] : $value->SHSOURCE; return $value->SHSOURCE = isset($transxTypes[trim($value->SHSOURCE)]) ? $transxTypes[trim($value->SHSOURCE)] : $value->SHSOURCE;
}); });
# Get User Names // Get User Names
$ICM699MCol->filter(function ($value) use ($ICM428MCOL) { $ICM699MCol->filter(function ($value) use ($ICM428MCOL) {
$UserTemp = $ICM428MCOL->firstWhere('R428US', trim($value->SHACKUSER)); $UserTemp = $ICM428MCOL->firstWhere('R428US', trim($value->SHACKUSER));
$SHACKUSER = isset($UserTemp->R428FIRST) ? $UserTemp->R428FIRST . ' ' . $UserTemp->R428FAMILY : trim($value->SHACKUSER); $SHACKUSER = isset($UserTemp->R428FIRST) ? $UserTemp->R428FIRST . ' ' . $UserTemp->R428FAMILY : trim($value->SHACKUSER);
return $value->SHACKUSER = $SHACKUSER; return $value->SHACKUSER = $SHACKUSER;
}); });
# Prepend Header To Excel // Prepend Header To Excel
$newItem = ["SHMACPKR" => 'Delivery Note', $newItem = ['SHMACPKR' => 'Delivery Note',
"DELIVERY_NUM" => 'Order #', 'DELIVERY_NUM' => 'Order #',
"CUSTOMER" => 'Customer', 'CUSTOMER' => 'Customer',
"SHDATETIME" => 'Date', 'SHDATETIME' => 'Date',
"ERROR" => 'Error', 'ERROR' => 'Error',
"SHTYPE" => 'Request Type', 'SHTYPE' => 'Request Type',
"SHSOURCE" => 'Source of transaction', 'SHSOURCE' => 'Source of transaction',
"USER" => 'User', 'USER' => 'User',
"SHCODE" => 'Request or Response Data', 'SHCODE' => 'Request or Response Data',
"SHCO" => 'Division', 'SHCO' => 'Division',
"SHWHS" => 'Warehouse', 'SHWHS' => 'Warehouse',
"ACKDATE" => 'Acknowledge/Retry Date', 'ACKDATE' => 'Acknowledge/Retry Date',
"SHACKUSER" => 'Acknowledged/Retried by User', 'SHACKUSER' => 'Acknowledged/Retried by User',
"SHINTBOX" => 'Internal Box Number', 'SHINTBOX' => 'Internal Box Number',
"SHACKNOTE" => 'Note', 'SHACKNOTE' => 'Note',
"SHDATA" => 'Error description' 'SHDATA' => 'Error description',
]; ];
$ICM699MCol->prepend($newItem); $ICM699MCol->prepend($newItem);
// dd($ICM699MCol); // dd($ICM699MCol);
# Download Excel File // Download Excel File
return app(\Modules\M3\Services\SpreadsheetExport::class)->download($ICM699MCol, 'transactionLog_' . $STARTDATE . '-' . $ENDDATE . '.xlsx'); return app(SpreadsheetExport::class)->download($ICM699MCol, 'transactionLog_' . $STARTDATE . '-' . $ENDDATE . '.xlsx');
} catch (\Throwable $th) { } catch (\Throwable $th) {
Log::error($th); Log::error($th);
} }
@@ -2,166 +2,163 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use Illuminate\Http\Request; use DB;
use Symfony\Component\HttpFoundation\Response;
// use Datatables;
use Smalot\PdfParser\Parser;
use File; use File;
use Cache; // use Datatables;
use Illuminate\Http\Request;
use Smalot\PdfParser\Parser;
use Str; use Str;
class M3GetPDFFromCacheController extends Controller class M3GetPDFFromCacheController extends Controller
{ {
public static function index(Request $request){ public static function index(Request $request)
{
// Parse PDF file and build necessary objects. // Parse PDF file and build necessary objects.
$parser = new \Smalot\PdfParser\Parser(); $parser = new Parser;
$aggno = $aggmsg = ""; $aggno = $aggmsg = '';
$IC670M = $PDFArray = $carrier = $trackingno = $ICM688M1 = []; $IC670M = $PDFArray = $carrier = $trackingno = $ICM688M1 = [];
$AYMACPKR = $WHDDA = $COMPANY = $PLANT = $WHS = ''; $AYMACPKR = $WHDDA = $COMPANY = $PLANT = $WHS = '';
#$carrier = $trackingno = ""; // $carrier = $trackingno = "";
# PDF File PATH // PDF File PATH
$pdfFilePath = Config::get('arrays.PdfPath'); $pdfFilePath = Config::get('arrays.PdfPath');
try { try {
# Initialise Vars // Initialise Vars
$PDFArray = $trackingno = $carrier = $ICM688M1 = []; $PDFArray = $trackingno = $carrier = $ICM688M1 = [];
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : ''; $SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER); // dd($SHUSER);
if ($SHUSER!='') { if ($SHUSER != '') {
# Get User CO & WH // Get User CO & WH
# Get user from ICM428M // Get user from ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH','R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US','=',$SHUSER) ->where('R428US', '=', $SHUSER)
->first(); ->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; $R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : '';
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; # Company $COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; # Plant $PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; # WareHouse $WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; // WareHouse
} }
# Warehouse Table // Warehouse Table
$IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get(); $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
// ->where('WDCO',$userCO)->where('WDPL',$userPL)->where('WDWHS',$userWH) // ->where('WDCO',$userCO)->where('WDPL',$userPL)->where('WDWHS',$userWH)
# Get URL PARAMS // Get URL PARAMS
$urlParams = count($request->all())>0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
// dump($urlParams); // dump($urlParams);
$AYMACPKR = isset($urlParams["MACPKR"]) ? trim($urlParams["MACPKR"]) : ''; # Delivery note number $AYMACPKR = isset($urlParams['MACPKR']) ? trim($urlParams['MACPKR']) : ''; // Delivery note number
$DOCTYPE = isset($urlParams["DOCTYPE"]) ? trim($urlParams["DOCTYPE"]) : ''; # Document type (PackingList, CarrierLabel, ContentLabel) $DOCTYPE = isset($urlParams['DOCTYPE']) ? trim($urlParams['DOCTYPE']) : ''; // Document type (PackingList, CarrierLabel, ContentLabel)
$WHDDA = $COMPANY.$PLANT.$WHS; $WHDDA = $COMPANY . $PLANT . $WHS;
// dump($WHDDA); // dump($WHDDA);
# Check Doctype fisrt // Check Doctype fisrt
$docTypes = $DOCTYPE!='' ? [$DOCTYPE] : ['PackingList','ContentLabel', 'CarrierLabel', 'GSLabel']; # document type (PackingList, CarrierLabel, ContentLabel) $docTypes = $DOCTYPE != '' ? [$DOCTYPE] : ['PackingList', 'ContentLabel', 'CarrierLabel', 'GSLabel']; // document type (PackingList, CarrierLabel, ContentLabel)
if($urlParams!=''){ if ($urlParams != '') {
// dump($urlParams); // dump($urlParams);
# document number (ie the internal box number, the pick list number) // document number (ie the internal box number, the pick list number)
# Key Combination : COMPANY WHS A4MACPKR DOCTYPE DOCNUM // Key Combination : COMPANY WHS A4MACPKR DOCTYPE DOCNUM
# Document type (PackingList, CarrierLabel, ContentLabel) // Document type (PackingList, CarrierLabel, ContentLabel)
# Get Aggregation Number if it exists // Get Aggregation Number if it exists
$ICM695M1Agg = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1') $ICM695M1Agg = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
->select('AYTRUCK') ->select('AYTRUCK')
->where('AYCO',$COMPANY) ->where('AYCO', $COMPANY)
->where('AYWHS',$WHS) ->where('AYWHS', $WHS)
->where('AYMACPKR',$AYMACPKR) ->where('AYMACPKR', $AYMACPKR)
->first(); ->first();
// dump($ICM695M1Agg); // dump($ICM695M1Agg);
$aggno = isset($ICM695M1Agg->AYTRUCK) ? trim($ICM695M1Agg->AYTRUCK) : ''; $aggno = isset($ICM695M1Agg->AYTRUCK) ? trim($ICM695M1Agg->AYTRUCK) : '';
if($aggno!="" && $aggno!="0") { if ($aggno != '' && $aggno != '0') {
// dump($aggno); // dump($aggno);
$aggmsg="This delivery note is part of aggregation $aggno "; $aggmsg = "This delivery note is part of aggregation $aggno ";
$ICM688M1 = DB::connection(config('m3.connection', 'pgsql'))->select("select A4MACPKR from ICM688M1 where A4SHPAGGCD='$aggno'"); $ICM688M1 = DB::connection(config('m3.connection', 'pgsql'))->select("select A4MACPKR from ICM688M1 where A4SHPAGGCD='$aggno'");
#dump($ICM688M1); // dump($ICM688M1);
// foreach($ICM688M1 as $key => $ICM688M1R) { // foreach($ICM688M1 as $key => $ICM688M1R) {
// $aggmsg.=' <a href="M3GetPDFFromCache?MACPKR='.$ICM688M1R->A4MACPKR.'&COMPANY='.$COMPANY.'&PLANT='.$PLANT.'&WHS='.$WHS.'">'.$ICM688M1R->A4MACPKR.'</a>'; // $aggmsg.=' <a href="M3GetPDFFromCache?MACPKR='.$ICM688M1R->A4MACPKR.'&COMPANY='.$COMPANY.'&PLANT='.$PLANT.'&WHS='.$WHS.'">'.$ICM688M1R->A4MACPKR.'</a>';
// } // }
// $aggmsg.=" )"; // $aggmsg.=" )";
#654 add 'AYSPR15A01', 'AYSPR30A01', 'AYTRUCK' carrier and tracking# and agg# // 654 add 'AYSPR15A01', 'AYSPR30A01', 'AYTRUCK' carrier and tracking# and agg#
$ICM695M1 = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1') $ICM695M1 = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
->select('AYCO','AYWHS','AYMACPKR','AYINTBOX', 'AYSPR15A01', 'AYSPR30A01', 'AYTRUCK') ->select('AYCO', 'AYWHS', 'AYMACPKR', 'AYINTBOX', 'AYSPR15A01', 'AYSPR30A01', 'AYTRUCK')
->distinct() ->distinct()
->where('AYCO',$COMPANY) ->where('AYCO', $COMPANY)
->where('AYWHS',$WHS) ->where('AYWHS', $WHS)
// ->where('AYMACPKR',$AYMACPKR) // ->where('AYMACPKR',$AYMACPKR)
->where('AYTRUCK',$aggno) ->where('AYTRUCK', $aggno)
->orderBy('AYMACPKR')
->get();
} else {
// 654 add 'AYSPR15A01', 'AYSPR30A01', 'AYTRUCK' carrier and tracking# and agg#
$ICM695M1 = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
->select('AYCO', 'AYWHS', 'AYMACPKR', 'AYINTBOX', 'AYSPR15A01', 'AYSPR30A01', 'AYTRUCK')
->distinct()
->where('AYCO', $COMPANY)
->where('AYWHS', $WHS)
->where('AYMACPKR', $AYMACPKR)
->orderBy('AYMACPKR') ->orderBy('AYMACPKR')
->get(); ->get();
} }
else{ // dump($ICM695M1);
#654 add 'AYSPR15A01', 'AYSPR30A01', 'AYTRUCK' carrier and tracking# and agg#
$ICM695M1 = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
->select('AYCO','AYWHS','AYMACPKR','AYINTBOX', 'AYSPR15A01', 'AYSPR30A01', 'AYTRUCK')
->distinct()
->where('AYCO',$COMPANY)
->where('AYWHS',$WHS)
->where('AYMACPKR',$AYMACPKR)
->orderBy('AYMACPKR')
->get();
}
#dump($ICM695M1);
$allLabels = []; $allLabels = [];
if (count($ICM695M1)>0) { if (count($ICM695M1) > 0) {
$tmpCacheArr = $carrier = $trackingno = []; $tmpCacheArr = $carrier = $trackingno = [];
# Loop the Results from $ICM595M1TMP // Loop the Results from $ICM595M1TMP
foreach ($ICM695M1 as $key => $ICM695M1R) { foreach ($ICM695M1 as $key => $ICM695M1R) {
$WHS = trim($ICM695M1R->AYWHS); $WHS = trim($ICM695M1R->AYWHS);
$COMPANY = trim($ICM695M1R->AYCO); $COMPANY = trim($ICM695M1R->AYCO);
$AYMACPKR = trim($ICM695M1R->AYMACPKR); $AYMACPKR = trim($ICM695M1R->AYMACPKR);
$DOCNUM = trim($ICM695M1R->AYINTBOX); $DOCNUM = trim($ICM695M1R->AYINTBOX);
#654 // 654
$carrier[] = trim($ICM695M1R->AYSPR15A01); $carrier[] = trim($ICM695M1R->AYSPR15A01);
$trackingno[] = trim($ICM695M1R->AYSPR30A01); $trackingno[] = trim($ICM695M1R->AYSPR30A01);
$aggno = trim($ICM695M1R->AYTRUCK); $aggno = trim($ICM695M1R->AYTRUCK);
# Make Key and Test Validity // Make Key and Test Validity
if ($AYMACPKR!='' && $COMPANY!='' && $WHS!=''){ if ($AYMACPKR != '' && $COMPANY != '' && $WHS != '') {
//echo "<script>alert('2');</script>"; // echo "<script>alert('2');</script>";
$CarrierLabel = ''; $CarrierLabel = '';
$ContentLabel = ''; $ContentLabel = '';
$PackingList = ''; $PackingList = '';
$cacheKeyPackingList = $cacheKeyCarrierLabel = $cacheKeyContentLabel = ''; $cacheKeyPackingList = $cacheKeyCarrierLabel = $cacheKeyContentLabel = '';
# Get Unique Keys // Get Unique Keys
foreach ($docTypes as $key => $value) { foreach ($docTypes as $key => $value) {
# Check Parcel vs LTL // Check Parcel vs LTL
if( $value == 'ContentLabel' ){ if ($value == 'ContentLabel') {
$DOCNUMT = $DOCNUM; $DOCNUMT = $DOCNUM;
$ContentLabel = !is_numeric($DOCNUM) ? 'LTL' : ''; $ContentLabel = ! is_numeric($DOCNUM) ? 'LTL' : '';
} }
if( $value == 'CarrierLabel' ){ if ($value == 'CarrierLabel') {
$DOCNUMT = $DOCNUM; $DOCNUMT = $DOCNUM;
# Keep Solon Logic to read LTL // Keep Solon Logic to read LTL
$DOCNUMT2 = $ContentLabel=='LTL' ? $AYMACPKR : $DOCNUM; $DOCNUMT2 = $ContentLabel == 'LTL' ? $AYMACPKR : $DOCNUM;
if ($DOCNUMT2!=$DOCNUMT) { if ($DOCNUMT2 != $DOCNUMT) {
$PDFKey2 = $value.'/'.$value.'_'.$AYMACPKR.'_'.$DOCNUMT2.'_'.$COMPANY.'_'.$WHS; $PDFKey2 = $value . '/' . $value . '_' . $AYMACPKR . '_' . $DOCNUMT2 . '_' . $COMPANY . '_' . $WHS;
$tmpCacheArr[] = $PDFKey2; $tmpCacheArr[] = $PDFKey2;
} }
} }
if( $value == 'PackingList' ){ if ($value == 'PackingList') {
$DOCNUMT = $AYMACPKR; $DOCNUMT = $AYMACPKR;
} }
# Get GS1 Labels // Get GS1 Labels
if($value=='GSLabel' ){ if ($value == 'GSLabel') {
$PDFKey = $value.'/'.$value.'_'.$AYMACPKR.'_'.$COMPANY.'_'.$WHS.'_'.$DOCNUM; $PDFKey = $value . '/' . $value . '_' . $AYMACPKR . '_' . $COMPANY . '_' . $WHS . '_' . $DOCNUM;
// if ($ContentLabel=='LTL' ) { // if ($ContentLabel=='LTL' ) {
// $PDFKey = $value.'/'.$value.'_'.$AYMACPKR.'_'.$COMPANY.'_'.$WHS; // $PDFKey = $value.'/'.$value.'_'.$AYMACPKR.'_'.$COMPANY.'_'.$WHS;
@@ -169,9 +166,8 @@ class M3GetPDFFromCacheController extends Controller
// else{ // else{
// $PDFKey = $value.'/'.$value.'_'.$AYMACPKR.'_'.$COMPANY.'_'.$WHS.'_'.$DOCNUM; // $PDFKey = $value.'/'.$value.'_'.$AYMACPKR.'_'.$COMPANY.'_'.$WHS.'_'.$DOCNUM;
// } // }
} } else {
else{ $PDFKey = $value . '/' . $value . '_' . $AYMACPKR . '_' . $DOCNUMT . '_' . $COMPANY . '_' . $WHS;
$PDFKey = $value.'/'.$value.'_'.$AYMACPKR.'_'.$DOCNUMT.'_'.$COMPANY.'_'.$WHS;
} }
$tmpCacheArr[] = $PDFKey; $tmpCacheArr[] = $PDFKey;
} }
@@ -179,41 +175,38 @@ class M3GetPDFFromCacheController extends Controller
} }
// dump($tmpCacheArr); // dump($tmpCacheArr);
# Get unique values from array $PDFArray // Get unique values from array $PDFArray
$tmpCacheArr = collect($tmpCacheArr)->unique(); $tmpCacheArr = collect($tmpCacheArr)->unique();
// dump($tmpCacheArr); // dump($tmpCacheArr);
foreach($tmpCacheArr as $key => $value){ foreach ($tmpCacheArr as $key => $value) {
// $isCarrierLabel = Str::contains($value, 'CarrierLabel'); // $isCarrierLabel = Str::contains($value, 'CarrierLabel');
$pdfFileName = $pdfFilePath.$value.'.pdf'; $pdfFileName = $pdfFilePath . $value . '.pdf';
if(File::exists($pdfFileName)){ if (File::exists($pdfFileName)) {
// dump($pdfFileName); // dump($pdfFileName);
$pdfFile = File::get($pdfFileName); $pdfFile = File::get($pdfFileName);
# Transform content to base64 // Transform content to base64
// $base64PDF = $pdfFile; // $base64PDF = $pdfFile;
$base64PDF = base64_encode($pdfFile); $base64PDF = base64_encode($pdfFile);
// dd($base64PDF); // dd($base64PDF);
$PDFArray[] = $base64PDF; $PDFArray[] = $base64PDF;
} }
} }
// dump($PDFArray); // dump($PDFArray);
} else {
// Nothing Found
} }
else { }
# Nothing Found } catch (\Throwable $th) {
}
}
}
catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
} }
# dump($PDFArray); // dump($PDFArray);
# dump($AYMACPKR); // dump($AYMACPKR);
# dump($IC670M); // dump($IC670M);
# dump($ICM695M1); // dump($ICM695M1);
return view('m3::liberty-theme.pages.M3GetPDF',compact('IC670M','PDFArray','AYMACPKR','WHDDA','aggmsg','carrier','trackingno','ICM688M1','COMPANY','PLANT','WHS')); return view('m3::liberty-theme.pages.M3GetPDF', compact('IC670M', 'PDFArray', 'AYMACPKR', 'WHDDA', 'aggmsg', 'carrier', 'trackingno', 'ICM688M1', 'COMPANY', 'PLANT', 'WHS'));
// compact('IC670M','ViewTitle') // compact('IC670M','ViewTitle')
} }
} }
@@ -1,29 +1,29 @@
<?php <?php
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use DB;
use Config; use Config;
use DB;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
class MFOrdersController extends Controller class MFOrdersController extends Controller
{ {
public static function index(Request $request) public static function index(Request $request)
{ {
$MF = isset($request->id) ? trim($request->id) : ""; $MF = isset($request->id) ? trim($request->id) : '';
// dd("MFOrders ".$MF); // dd("MFOrders ".$MF);
# Get Users from ICM428M // Get Users from ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH', 'R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US','=',strtoUpper(m3_user())) ->where('R428US', '=', strtoupper(m3_user()))
->first(); ->first();
$user = $ICM428M->R428US; $user = $ICM428M->R428US;
$co = $ICM428M->R428CO; $co = $ICM428M->R428CO;
$whs = $ICM428M->R428WH; $whs = $ICM428M->R428WH;
$plant = $ICM428M->R428PL; $plant = $ICM428M->R428PL;
# ICM705M1 Statement // ICM705M1 Statement
$sqlstmt = "select APMANIFEST,APDOCKDOOR,APCARRIER,APTRUCKIDT,APSPARE1,APLDSTRU,APLDSTRD,APLDSTRT, $sqlstmt = "select APMANIFEST,APDOCKDOOR,APCARRIER,APTRUCKIDT,APSPARE1,APLDSTRU,APLDSTRD,APLDSTRT,
APLDCLOU,APLDCLOD,APLDCLOT,APCO,APWHS,APPLT,APSPARE2,APLDCLOZ APLDCLOU,APLDCLOD,APLDCLOT,APCO,APWHS,APPLT,APSPARE2,APLDCLOZ
from ICM705M1 from ICM705M1
@@ -31,9 +31,9 @@ class MFOrdersController extends Controller
$ICM705M1 = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt); $ICM705M1 = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt);
// dump($ICM705M1); // dump($ICM705M1);
$carrier = isset($ICM705M1[0]->APCARRIER) ? trim($ICM705M1[0]->APCARRIER) : ""; $carrier = isset($ICM705M1[0]->APCARRIER) ? trim($ICM705M1[0]->APCARRIER) : '';
if ($MF!='') { if ($MF != '') {
$status_ICM688M1_array = Config::get('arrays.status_ICM688M1_array'); $status_ICM688M1_array = Config::get('arrays.status_ICM688M1_array');
$sqlstmt = "SELECT AYCO,AYPLANT,AYMACPKR,AYONO,A4SHSHNM,A4PICKSTS,AYSPR15A01,SUM(AYLNWGHT) AS TOTWEIGHT,COUNT(*) AS BOXPAL FROM ICM695M1 $sqlstmt = "SELECT AYCO,AYPLANT,AYMACPKR,AYONO,A4SHSHNM,A4PICKSTS,AYSPR15A01,SUM(AYLNWGHT) AS TOTWEIGHT,COUNT(*) AS BOXPAL FROM ICM695M1
@@ -44,14 +44,13 @@ class MFOrdersController extends Controller
$ICM695M1 = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt); $ICM695M1 = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt);
// dump($ICM695M1); // dump($ICM695M1);
return view('m3::liberty-theme.pages.MFOrders', compact( 'ICM695M1', 'status_ICM688M1_array', 'MF', 'carrier') return view(
'm3::liberty-theme.pages.MFOrders',
compact('ICM695M1', 'status_ICM688M1_array', 'MF', 'carrier'),
); );
} } else {
else{
abort(404, 'Manifest Not Found'); abort(404, 'Manifest Not Found');
} }
} }
} }
@@ -2,52 +2,52 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use Illuminate\Http\Request; use DB;
use Symfony\Component\HttpFoundation\Response;
use Str;
use Log;
use Excel; use Excel;
use Illuminate\Http\Request;
use Log;
use Modules\M3\Services\SpreadsheetExport;
use Storage; use Storage;
use Str;
class OrderLinesOfClosedOrder extends Controller class OrderLinesOfClosedOrder extends Controller
{ {
public static function index(Request $request){ public static function index(Request $request)
{
$IC670M = $ICM688M2 = []; $IC670M = $ICM688M2 = [];
$WHDDA = $COMPANY = $PLANT = $WHS = ''; $WHDDA = $COMPANY = $PLANT = $WHS = '';
$REPORTDATEDisp = today()->format('Ymd'); $REPORTDATEDisp = today()->format('Ymd');
$allReportsUrls = []; $allReportsUrls = [];
try { try {
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : ''; $SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER); // dd($SHUSER);
if ($SHUSER!='') { if ($SHUSER != '') {
# Get User CO & WH from Table ICM428M // Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH','R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US','=',$SHUSER) ->where('R428US', '=', $SHUSER)
->first(); ->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; # User $R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; // User
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '110'; # Company $COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '110'; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '144'; # Plant $PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '144'; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '322'; # WareHouse $WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '322'; // WareHouse
} }
# Warehouse Table // Warehouse Table
$IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get(); $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
# Get URL PARAMS // Get URL PARAMS
$urlParams = count($request->all())>0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
// dump($urlParams); // dump($urlParams);
$REPORTDATEDisp = isset($urlParams["REPORTDATEDisp"]) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams["REPORTDATEDisp"]))->format('Ymd') : today()->format('Ymd'); $REPORTDATEDisp = isset($urlParams['REPORTDATEDisp']) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams['REPORTDATEDisp']))->format('Ymd') : today()->format('Ymd');
$WHDDA = $COMPANY.$PLANT.$WHS; $WHDDA = $COMPANY . $PLANT . $WHS;
// dump($WHDDA); // dump($WHDDA);
if($REPORTDATEDisp!='' && $COMPANY!='' && $WHS!='' && $PLANT!=''){ if ($REPORTDATEDisp != '' && $COMPANY != '' && $WHS != '' && $PLANT != '') {
# Case 729: Add Currency code A1SHCURR FROM ICM666M // Case 729: Add Currency code A1SHCURR FROM ICM666M
$selectContent = " $selectContent = "
SELECT A5MACPKR, A5ONO, SELECT A5MACPKR, A5ONO,
(SELECT A4REFORD FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) AS A4REFORD, (SELECT A4REFORD FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) AS A4REFORD,
@@ -60,8 +60,8 @@ class OrderLinesOfClosedOrder extends Controller
A1SHCURR, A1SHCURR,
CASE CASE
WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL' WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL'
THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL'))/100 ." THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * " . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL')) / 100 . '
ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel') )/100 ." ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ' . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel')) / 100 . "
END AS FREIGHT, END AS FREIGHT,
A4SHIPTYPE, A4SHIPTYPE,
A4SHIPVIA1, A4SHIPVIA1,
@@ -80,75 +80,73 @@ class OrderLinesOfClosedOrder extends Controller
// dump($selectContent); // dump($selectContent);
$ICM688M2 = DB::connection(config('m3.connection', 'pgsql')) $ICM688M2 = DB::connection(config('m3.connection', 'pgsql'))
->select($selectContent); ->select($selectContent);
// dd($ICM688M2); // dd($ICM688M2);
} } else {
else{
$ICM688M2 = collect(); $ICM688M2 = collect();
} }
# Get List of Files // Get List of Files
$allReportsUrls = []; $allReportsUrls = [];
if ($WHS == '321') { if ($WHS == '321') {
$files = Storage::disk('publicCL')->files(); $files = Storage::disk('publicCL')->files();
} } else {
else{
$files = Storage::disk('publicCL')->allFiles($WHS); $files = Storage::disk('publicCL')->allFiles($WHS);
} }
foreach ($files as $file) { foreach ($files as $file) {
# Get the file URL (if URL is configured in filesystems.php) // Get the file URL (if URL is configured in filesystems.php)
$url = Storage::disk('publicCL')->url($file); $url = Storage::disk('publicCL')->url($file);
$allReportsUrls[$file] = $url; $allReportsUrls[$file] = $url;
} }
} } catch (\Throwable $th) {
catch (\Throwable $th) {
Log::error($th); Log::error($th);
} }
return view('m3::liberty-theme.pages.OrderLinesOfClosed',compact('IC670M','ICM688M2','WHDDA','COMPANY','PLANT','WHS','REPORTDATEDisp','allReportsUrls')); return view('m3::liberty-theme.pages.OrderLinesOfClosed', compact('IC670M', 'ICM688M2', 'WHDDA', 'COMPANY', 'PLANT', 'WHS', 'REPORTDATEDisp', 'allReportsUrls'));
} }
public static function exporttoExcel(Request $request){ public static function exporttoExcel(Request $request)
{
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut')); ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
try { try {
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : ''; $SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER); // dd($SHUSER);
if ($SHUSER!='') { if ($SHUSER != '') {
# Get User CO & WH from Table ICM428M // Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH','R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US','=',$SHUSER) ->where('R428US', '=', $SHUSER)
->first(); ->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; # User $R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; // User
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; # Company $COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; # Plant $PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; # WareHouse $WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; // WareHouse
} }
# Warehouse Table // Warehouse Table
$IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get(); $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
# Get URL PARAMS // Get URL PARAMS
$urlParams = count($request->all())>0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
// dd($urlParams); // dd($urlParams);
$reportDate = isset($urlParams["REPORTDATE"]) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams["REPORTDATE"]))->format('Ymd') : today()->format('Ymd'); $reportDate = isset($urlParams['REPORTDATE']) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams['REPORTDATE']))->format('Ymd') : today()->format('Ymd');
$toreportDate = isset($urlParams["TOREPORTDATE"]) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams["TOREPORTDATE"]))->format('Ymd') : today()->format('Ymd'); $toreportDate = isset($urlParams['TOREPORTDATE']) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams['TOREPORTDATE']))->format('Ymd') : today()->format('Ymd');
$reportDateWD = isset($urlParams["REPORTDATE"]) ? trim($urlParams["REPORTDATE"]) : today()->format('Y-m-d'); $reportDateWD = isset($urlParams['REPORTDATE']) ? trim($urlParams['REPORTDATE']) : today()->format('Y-m-d');
$toreportDateWD = isset($urlParams["TOREPORTDATE"]) ? trim($urlParams["TOREPORTDATE"]) : today()->format('Y-m-d'); $toreportDateWD = isset($urlParams['TOREPORTDATE']) ? trim($urlParams['TOREPORTDATE']) : today()->format('Y-m-d');
$WHDDA = $COMPANY.$PLANT.$WHS; $WHDDA = $COMPANY . $PLANT . $WHS;
// dump($WHDDA); // dump($WHDDA);
if($reportDate!='' && $COMPANY!='' && $WHS!='' && $PLANT!=''){ if ($reportDate != '' && $COMPANY != '' && $WHS != '' && $PLANT != '') {
# Case 729: Add Currency code A1SHCURR FROM ICM666M // Case 729: Add Currency code A1SHCURR FROM ICM666M
$selectContent = " $selectContent = "
SELECT (SHDT || ' ' || SHTIME) AS DATECLOSED, A5MACPKR, A5ONO, SELECT (SHDT || ' ' || SHTIME) AS DATECLOSED, A5MACPKR, A5ONO,
A4OFSTRM, A4OFSTRM,
@@ -163,8 +161,8 @@ class OrderLinesOfClosedOrder extends Controller
A1SHCURR, A1SHCURR,
CASE CASE
WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL' WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL'
THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL'))/100 ." THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * " . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL')) / 100 . '
ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel'))/100 ." ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ' . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel')) / 100 . "
END AS FREIGHT END AS FREIGHT
FROM ICM688M2 FROM ICM688M2
LEFT JOIN ICM699M ON SHMACPKR=A5MACPKR AND SHTYPE='M3-Res-out' AND SHDATA LIKE 'Success%' AND SHSOURCE='CloseShipmentCoChargeAPI' LEFT JOIN ICM699M ON SHMACPKR=A5MACPKR AND SHTYPE='M3-Res-out' AND SHDATA LIKE 'Success%' AND SHSOURCE='CloseShipmentCoChargeAPI'
@@ -178,82 +176,82 @@ class OrderLinesOfClosedOrder extends Controller
AND A5CO=$COMPANY AND A5WHS=$WHS AND A5PLANT=$PLANT"; AND A5CO=$COMPANY AND A5WHS=$WHS AND A5PLANT=$PLANT";
$ICM688M2 = DB::connection(config('m3.connection', 'pgsql')) $ICM688M2 = DB::connection(config('m3.connection', 'pgsql'))
->select($selectContent); ->select($selectContent);
$newItem = ["DATECLOSED" => 'Close Date',"A5MACPKR" => 'Delivery #', "A5ONO" => 'Order #', $newItem = ['DATECLOSED' => 'Close Date', 'A5MACPKR' => 'Delivery #', 'A5ONO' => 'Order #',
"A4OFSTRM" => 'Terms',"WEIGHT" => 'Weight',"A4SCAC" => 'Carrier',"A4SHIPTYPE" => 'Mode (Parcel, Air, TL or LTL)', 'A4OFSTRM' => 'Terms', 'WEIGHT' => 'Weight', 'A4SCAC' => 'Carrier', 'A4SHIPTYPE' => 'Mode (Parcel, Air, TL or LTL)',
"A4REFORD" => 'Order Type',"A5PART" => 'Part #',"A5RSVQTY" => 'Reserved', 'A4REFORD' => 'Order Type', 'A5PART' => 'Part #', 'A5RSVQTY' => 'Reserved',
"A5PACKED" => 'Packed',"CALCULATED_COLUMN" => 'Back Order Qty',"ANOTHER_CALCULATED_COLUMN" => 'Value Packed $',"A4SHSHNM" => 'Customer name', 'A5PACKED' => 'Packed', 'CALCULATED_COLUMN' => 'Back Order Qty', 'ANOTHER_CALCULATED_COLUMN' => 'Value Packed $', 'A4SHSHNM' => 'Customer name',
"REASON" => 'Failure Reason','A1SHCURR'=> 'Currency Code','FREIGHT'=> 'Freight']; 'REASON' => 'Failure Reason', 'A1SHCURR' => 'Currency Code', 'FREIGHT' => 'Freight'];
$ICM688M2Col = collect($ICM688M2); $ICM688M2Col = collect($ICM688M2);
$ICM688M2Col->prepend($newItem); $ICM688M2Col->prepend($newItem);
// dd($ICM688M2Col); // dd($ICM688M2Col);
# Count records before exporting to excel : Max 20K records are allowed // Count records before exporting to excel : Max 20K records are allowed
$ICM688M2Count = $ICM688M2Col->count(); $ICM688M2Count = $ICM688M2Col->count();
# Set Max allowed records // Set Max allowed records
$maxRecords = Config::get('arrays.maxRecCL'); $maxRecords = Config::get('arrays.maxRecCL');
if ($ICM688M2Count>$maxRecords) { if ($ICM688M2Count > $maxRecords) {
return redirect()->back()->withInput()->with('message', 'Maximum allowed records for Excel Download is: '.number_format($maxRecords). return redirect()->back()->withInput()->with('message', 'Maximum allowed records for Excel Download is: ' . number_format($maxRecords) .
' current records: '.number_format($ICM688M2Count) . ' , change your search criteria.'); ' current records: ' . number_format($ICM688M2Count) . ' , change your search criteria.');
} }
} else {
$ICM688M2Col = '';
} }
else{
$ICM688M2Col = ""; // Download Excel
} // Add true at the end to include fields names in the Header
# Download Excel return app(SpreadsheetExport::class)->download($ICM688M2Col, 'Closedorderlinesreport_' . $reportDateWD . '-' . $toreportDateWD . '.xlsx');
# Add true at the end to include fields names in the Header
return app(\Modules\M3\Services\SpreadsheetExport::class)->download($ICM688M2Col, 'Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'.xlsx');
// return $ICM688M2Col->downloadExcel('Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'.csv',\Maatwebsite\Excel\Excel::CSV,false); // return $ICM688M2Col->downloadExcel('Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'.csv',\Maatwebsite\Excel\Excel::CSV,false);
} } catch (\Throwable $th) {
catch (\Throwable $th) {
Log::error($th); Log::error($th);
} }
} }
public static function StoreExcelToDisk(Request $request){ public static function StoreExcelToDisk(Request $request)
{
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
try { try {
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : ''; $SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER); // dd($SHUSER);
if ($SHUSER!='') { if ($SHUSER != '') {
# Get User CO & WH from Table ICM428M // Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH','R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US','=',$SHUSER) ->where('R428US', '=', $SHUSER)
->first(); ->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; # User $R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; // User
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; # Company $COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; # Plant $PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; # WareHouse $WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; // WareHouse
} }
# Warehouse Table // Warehouse Table
$IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get(); $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
# Get URL PARAMS // Get URL PARAMS
$urlParams = count($request->all())>0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
// dd($urlParams); // dd($urlParams);
$reportDate = isset($urlParams["REPORTDATE"]) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams["REPORTDATE"]))->format('Ymd') : today()->format('Ymd'); $reportDate = isset($urlParams['REPORTDATE']) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams['REPORTDATE']))->format('Ymd') : today()->format('Ymd');
$toreportDate = isset($urlParams["TOREPORTDATE"]) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams["TOREPORTDATE"]))->format('Ymd') : today()->format('Ymd'); $toreportDate = isset($urlParams['TOREPORTDATE']) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams['TOREPORTDATE']))->format('Ymd') : today()->format('Ymd');
// dump($reportDate); // dump($reportDate);
// dd($toreportDate); // dd($toreportDate);
$reportDateWD = isset($urlParams["REPORTDATE"]) ? trim($urlParams["REPORTDATE"]) : today()->format('Y-m-d'); $reportDateWD = isset($urlParams['REPORTDATE']) ? trim($urlParams['REPORTDATE']) : today()->format('Y-m-d');
$toreportDateWD = isset($urlParams["TOREPORTDATE"]) ? trim($urlParams["TOREPORTDATE"]) : today()->format('Y-m-d'); $toreportDateWD = isset($urlParams['TOREPORTDATE']) ? trim($urlParams['TOREPORTDATE']) : today()->format('Y-m-d');
$WHDDA = $COMPANY.$PLANT.$WHS; $WHDDA = $COMPANY . $PLANT . $WHS;
// dump($WHDDA); // dump($WHDDA);
if($reportDate!='' && $COMPANY!='' && $WHS!='' && $PLANT!=''){ if ($reportDate != '' && $COMPANY != '' && $WHS != '' && $PLANT != '') {
# Case 729: Add Currency code A1SHCURR FROM ICM666M // Case 729: Add Currency code A1SHCURR FROM ICM666M
$ICM688M2 = DB::connection(config('m3.connection', 'pgsql')) $ICM688M2 = DB::connection(config('m3.connection', 'pgsql'))
->select(" ->select("
SELECT (SHDT || ' ' || SHTIME) AS DATECLOSED, A5MACPKR, A5ONO, SELECT (SHDT || ' ' || SHTIME) AS DATECLOSED, A5MACPKR, A5ONO,
A4OFSTRM, A4OFSTRM,
A5PMPWHT*A5PACKED AS WEIGHT, A5PMPWHT*A5PACKED AS WEIGHT,
@@ -267,8 +265,8 @@ class OrderLinesOfClosedOrder extends Controller
A1SHCURR, A1SHCURR,
CASE CASE
WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL' WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL'
THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL'))/100 ." THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * " . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL')) / 100 . '
ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel'))/100 ." ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ' . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel')) / 100 . "
END AS FREIGHT END AS FREIGHT
FROM ICM688M2 FROM ICM688M2
LEFT JOIN ICM699M ON SHMACPKR=A5MACPKR AND SHTYPE='M3-Res-out' AND SHDATA LIKE 'Success%' AND SHSOURCE='CloseShipmentCoChargeAPI' LEFT JOIN ICM699M ON SHMACPKR=A5MACPKR AND SHTYPE='M3-Res-out' AND SHDATA LIKE 'Success%' AND SHSOURCE='CloseShipmentCoChargeAPI'
@@ -282,37 +280,35 @@ class OrderLinesOfClosedOrder extends Controller
AND A5CO=$COMPANY AND A5WHS=$WHS AND A5PLANT=$PLANT AND A5CO=$COMPANY AND A5WHS=$WHS AND A5PLANT=$PLANT
"); ");
$newItem = ["DATECLOSED" => 'Close Date',"A5MACPKR" => 'Delivery #', "A5ONO" => 'Order #', $newItem = ['DATECLOSED' => 'Close Date', 'A5MACPKR' => 'Delivery #', 'A5ONO' => 'Order #',
"A4OFSTRM" => 'Terms',"WEIGHT" => 'Weight',"A4SCAC" => 'Carrier',"A4SHIPTYPE" => 'Mode (Parcel, Air, TL or LTL)', 'A4OFSTRM' => 'Terms', 'WEIGHT' => 'Weight', 'A4SCAC' => 'Carrier', 'A4SHIPTYPE' => 'Mode (Parcel, Air, TL or LTL)',
"A4REFORD" => 'Order Type',"A5PART" => 'Part #',"A5RSVQTY" => 'Reserved', 'A4REFORD' => 'Order Type', 'A5PART' => 'Part #', 'A5RSVQTY' => 'Reserved',
"A5PACKED" => 'Packed',"CALCULATED_COLUMN" => 'Back Order Qty',"ANOTHER_CALCULATED_COLUMN" => 'Value Packed $',"A4SHSHNM" => 'Customer name', 'A5PACKED' => 'Packed', 'CALCULATED_COLUMN' => 'Back Order Qty', 'ANOTHER_CALCULATED_COLUMN' => 'Value Packed $', 'A4SHSHNM' => 'Customer name',
"REASON" => 'Failure Reason','A1SHCURR'=> 'Currency Code','FREIGHT'=> 'Freight']; 'REASON' => 'Failure Reason', 'A1SHCURR' => 'Currency Code', 'FREIGHT' => 'Freight'];
$ICM688M2Col = collect($ICM688M2); $ICM688M2Col = collect($ICM688M2);
$ICM688M2Col->prepend($newItem); $ICM688M2Col->prepend($newItem);
// dd($ICM688M2Col); // dd($ICM688M2Col);
# Count records before exporting to excel : Max 20K records are allowed // Count records before exporting to excel : Max 20K records are allowed
$ICM688M2Count = $ICM688M2Col->count(); $ICM688M2Count = $ICM688M2Col->count();
# Set Max allowed records // Set Max allowed records
$maxRecords = Config::get('arrays.maxRecCL'); $maxRecords = Config::get('arrays.maxRecCL');
if ($ICM688M2Count>$maxRecords) { if ($ICM688M2Count > $maxRecords) {
return redirect()->back()->withInput()->with('message', 'Maximum allowed records for Excel Download is: '.number_format($maxRecords). return redirect()->back()->withInput()->with('message', 'Maximum allowed records for Excel Download is: ' . number_format($maxRecords) .
' current records: '.number_format($ICM688M2Count) . ' , change your search criteria.'); ' current records: ' . number_format($ICM688M2Count) . ' , change your search criteria.');
} }
} } else {
else{ $ICM688M2Col = '';
$ICM688M2Col = "";
} }
if ($WHS == '321') { if ($WHS == '321') {
$prevMonthFile = 'Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'.xlsx'; $prevMonthFile = 'Closedorderlinesreport_' . $reportDateWD . '-' . $toreportDateWD . '.xlsx';
} } else {
else{ $prevMonthFile = $WHS . '/Closedorderlinesreport_' . $reportDateWD . '-' . $toreportDateWD . '-' . $WHS . '.xlsx';
$prevMonthFile = $WHS.'/Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'-'.$WHS.'.xlsx';
} }
# MAK Store the File to Storage // MAK Store the File to Storage
app(\Modules\M3\Services\SpreadsheetExport::class)->store($ICM688M2Col, $prevMonthFile, 'publicCL'); app(SpreadsheetExport::class)->store($ICM688M2Col, $prevMonthFile, 'publicCL');
// $ICM688M2Col->storeExcel('Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'.csv', 'publicCL',\Maatwebsite\Excel\Excel::CSV); // $ICM688M2Col->storeExcel('Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'.csv', 'publicCL',\Maatwebsite\Excel\Excel::CSV);
@@ -320,27 +316,27 @@ class OrderLinesOfClosedOrder extends Controller
// dump('Done Saving Excel...'); // dump('Done Saving Excel...');
return back(); return back();
} } catch (\Throwable $th) {
catch (\Throwable $th) {
Log::error($th); Log::error($th);
} }
} }
# Download File // Download File
public static function downloadFiles(Request $request){ public static function downloadFiles(Request $request)
{
// dd($request->all()); // dd($request->all());
$fileName = $request->filename; $fileName = $request->filename;
if (Storage::disk('publicCL')->exists($fileName)) { if (Storage::disk('publicCL')->exists($fileName)) {
# File exists, retrieve content or URL // File exists, retrieve content or URL
// $content = Storage::disk('publicCL')->get($fileName); // $content = Storage::disk('publicCL')->get($fileName);
$fileUrl = Storage::disk('publicCL')->url($fileName); $fileUrl = Storage::disk('publicCL')->url($fileName);
// dd($fileUrl); // dd($fileUrl);
$fileNameOnly = strpos($fileName, '/')!= false ? substr($fileName, strpos($fileName, '/') + 1) : $fileName; $fileNameOnly = strpos($fileName, '/') != false ? substr($fileName, strpos($fileName, '/') + 1) : $fileName;
# Download the file
// Download the file
return Storage::disk('publicCL')->download($fileName, $fileNameOnly); return Storage::disk('publicCL')->download($fileName, $fileNameOnly);
} else { } else {
// Download the file (use code below) // Download the file (use code below)
} }
} }
} }
@@ -2,49 +2,46 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Modules\M3\Models\ICM658M;
use Datatables; use Datatables;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Modules\M3\Models\ICM658M;
class ReplenishSettingsController extends Controller class ReplenishSettingsController extends Controller
{ {
public static function index(Request $request) public static function index(Request $request)
{ {
# Replenishment Table // Replenishment Table
// $REFCAT658 = DB::connection(config('m3.connection', 'pgsql'))->table('icm658m')->get(); // $REFCAT658 = DB::connection(config('m3.connection', 'pgsql'))->table('icm658m')->get();
# Warehouse Table // Warehouse Table
// $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get(); // $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
# Get Logged user Id // Get Logged user Id
$userId = m3_user() !== '' ? strtoupper(m3_user()) : '' ; $userId = m3_user() !== '' ? strtoupper(m3_user()) : '';
// $userId = 'E1135818'; // Brad : E1135818 Malak : E2011812 ACOM_PDF // $userId = 'E1135818'; // Brad : E1135818 Malak : E2011812 ACOM_PDF
$connection = config('m3.connection', 'pgsql'); $connection = config('m3.connection', 'pgsql');
$ICM428M = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('icm428m') $ICM428M = Schema::connection($connection)->hasTable('icm428m')
? DB::connection($connection)->table('icm428m')->where('R428US',$userId)->where('R428STS','A')->first() ? DB::connection($connection)->table('icm428m')->where('R428US', $userId)->where('R428STS', 'A')->first()
: null; : null;
$userCO = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; $userCO = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '';
$userPL = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; $userPL = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '';
$userWH = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '' ; $userWH = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '';
if ($userCO!='') { if ($userCO != '') {
# Warehouse Table // Warehouse Table
$IC670M = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('ic670m') $IC670M = Schema::connection($connection)->hasTable('ic670m')
? DB::connection($connection)->table('ic670m') ? DB::connection($connection)->table('ic670m')
->where('WDCO',$userCO) ->where('WDCO', $userCO)
->where('WDPL',$userPL) ->where('WDPL', $userPL)
->where('WDWHS',$userWH) ->where('WDWHS', $userWH)
->get() ->get()
: []; : [];
} } else {
else{
// $REFCAT658 =[]; // $REFCAT658 =[];
$IC670M =[]; $IC670M = [];
} }
// $sqlstmt="SELECT t1.REFKEY,t2.FULLID ,t2.* // $sqlstmt="SELECT t1.REFKEY,t2.FULLID ,t2.*
@@ -62,14 +59,15 @@ class ReplenishSettingsController extends Controller
{ {
// dd( $request->all() ); // dd( $request->all() );
$formInputs = $request->all(); $formInputs = $request->all();
$formInputs = array_filter($formInputs); $formInputs = array_filter($formInputs);
unset($formInputs["_token"]); unset($formInputs['_token']);
$formInputs['R658IZLCF'] = isset($formInputs['R658IZLCF']) ? $formInputs['R658IZLCF'] : '0'; $formInputs['R658IZLCF'] = isset($formInputs['R658IZLCF']) ? $formInputs['R658IZLCF'] : '0';
// dd($formInputs); // dd($formInputs);
$ICM658MINS = ICM658M::insert($formInputs); $ICM658MINS = ICM658M::insert($formInputs);
// dd($ICM658MINS); // dd($ICM658MINS);
return redirect()->route('m3.replenishmentSettings.index'); return redirect()->route('m3.replenishmentSettings.index');
} }
@@ -77,22 +75,22 @@ class ReplenishSettingsController extends Controller
public function update(Request $request) public function update(Request $request)
{ {
// dd($request->all()); // dd($request->all());
$R658PN = (trim($request->R658PN) ?? trim($request->R658PN)) != null ? trim($request->R658PN) : ""; $R658PN = (trim($request->R658PN) ?? trim($request->R658PN)) != null ? trim($request->R658PN) : '';
$R658CO = (trim($request->R658CO) ?? trim($request->R658CO)) != null ? trim($request->R658CO) : ""; $R658CO = (trim($request->R658CO) ?? trim($request->R658CO)) != null ? trim($request->R658CO) : '';
$R658PL = (trim($request->R658PL) ?? trim($request->R658PL)) != null ? trim($request->R658PL) : ""; $R658PL = (trim($request->R658PL) ?? trim($request->R658PL)) != null ? trim($request->R658PL) : '';
$R658WH = (trim($request->R658WH) ?? trim($request->R658WH)) != null ? trim($request->R658WH) : ""; $R658WH = (trim($request->R658WH) ?? trim($request->R658WH)) != null ? trim($request->R658WH) : '';
$R658MQ = trim($request->R658MQ); $R658MQ = trim($request->R658MQ);
$R658RQ = trim($request->R658RQ); $R658RQ = trim($request->R658RQ);
$R658RMQ = trim($request->R658RMQ); $R658RMQ = trim($request->R658RMQ);
$R658TL = trim($request->R658TL); $R658TL = trim($request->R658TL);
$R658IZLCF = (trim($request->R658IZLCF) ?? trim($request->R658IZLCF)) != null ? trim($request->R658IZLCF) : "0"; $R658IZLCF = (trim($request->R658IZLCF) ?? trim($request->R658IZLCF)) != null ? trim($request->R658IZLCF) : '0';
DB::connection(config('m3.connection', 'pgsql'))->table('icm658m') DB::connection(config('m3.connection', 'pgsql'))->table('icm658m')
->where('R658PN', $R658PN) ->where('R658PN', $R658PN)
->where('R658CO', $R658CO) ->where('R658CO', $R658CO)
->where('R658PL', $R658PL) ->where('R658PL', $R658PL)
->where('R658WH', $R658WH) ->where('R658WH', $R658WH)
->update([ 'R658MQ'=>$R658MQ,'R658RQ'=>$R658RQ,'R658RMQ'=>$R658RMQ,'R658TL'=>$R658TL,'R658IZLCF'=>$R658IZLCF ]); ->update(['R658MQ' => $R658MQ, 'R658RQ' => $R658RQ, 'R658RMQ' => $R658RMQ, 'R658TL' => $R658TL, 'R658IZLCF' => $R658IZLCF]);
return redirect()->route('m3.replenishmentSettings.index'); return redirect()->route('m3.replenishmentSettings.index');
} }
@@ -107,22 +105,22 @@ class ReplenishSettingsController extends Controller
$R658WH = trim($request->R658WH); $R658WH = trim($request->R658WH);
$deleteRecord = DB::connection(config('m3.connection', 'pgsql'))->table('icm658m') $deleteRecord = DB::connection(config('m3.connection', 'pgsql'))->table('icm658m')
->where('R658PN', $R658PN) ->where('R658PN', $R658PN)
->where('R658CO', $R658CO) ->where('R658CO', $R658CO)
->where('R658LC', $R658LC) ->where('R658LC', $R658LC)
->where('R658PL', $R658PL) ->where('R658PL', $R658PL)
->where('R658WH', $R658WH) ->where('R658WH', $R658WH)
->delete(); ->delete();
return response()->json(['success'=>'Record Deleted']); return response()->json(['success' => 'Record Deleted']);
} }
public function checkRecExit(Request $request) public function checkRecExit(Request $request)
{ {
// dd( $request->all() ); // dd( $request->all() );
$params = array(); $params = [];
parse_str($request['data'], $params); parse_str($request['data'], $params);
$paramsObj = (object)$params; $paramsObj = (object) $params;
// dd($paramsObj); // dd($paramsObj);
$R658PN = trim($paramsObj->R658PN); $R658PN = trim($paramsObj->R658PN);
@@ -132,54 +130,54 @@ class ReplenishSettingsController extends Controller
$R658WH = trim($paramsObj->R658WH); $R658WH = trim($paramsObj->R658WH);
$recordExistSQL = DB::connection(config('m3.connection', 'pgsql'))->table('icm658m') $recordExistSQL = DB::connection(config('m3.connection', 'pgsql'))->table('icm658m')
->where('R658PN', $R658PN) ->where('R658PN', $R658PN)
->where('R658CO', $R658CO) ->where('R658CO', $R658CO)
->where('R658LC', $R658LC) ->where('R658LC', $R658LC)
->where('R658PL', $R658PL) ->where('R658PL', $R658PL)
->where('R658WH', $R658WH) ->where('R658WH', $R658WH)
->first(); ->first();
// dd($recordExists); // dd($recordExists);
$recordExists = $recordExistSQL == null ? true : false; $recordExists = $recordExistSQL == null ? true : false;
return response()->json(['recordExists'=>$recordExists]); return response()->json(['recordExists' => $recordExists]);
} }
public function datatables(Request $request){ public function datatables(Request $request)
# Replenishment Table {
// Replenishment Table
// $REFCAT658 = DB::connection(config('m3.connection', 'pgsql'))->table('icm658m')->get(); // $REFCAT658 = DB::connection(config('m3.connection', 'pgsql'))->table('icm658m')->get();
# Warehouse Table // Warehouse Table
// $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get(); // $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
# Get Logged user Id // Get Logged user Id
$userId = m3_user() !== '' ? strtoupper(m3_user()) : '' ; $userId = m3_user() !== '' ? strtoupper(m3_user()) : '';
// $userId = 'E1135818'; // Brad : E1135818 Malak : E2011812 ACOM_PDF // $userId = 'E1135818'; // Brad : E1135818 Malak : E2011812 ACOM_PDF
$connection = config('m3.connection', 'pgsql'); $connection = config('m3.connection', 'pgsql');
$ICM428M = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('icm428m') $ICM428M = Schema::connection($connection)->hasTable('icm428m')
? DB::connection($connection)->table('icm428m')->where('R428US',$userId)->where('R428STS','A')->first() ? DB::connection($connection)->table('icm428m')->where('R428US', $userId)->where('R428STS', 'A')->first()
: null; : null;
$userCO = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; $userCO = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '';
$userPL = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; $userPL = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '';
$userWH = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '' ; $userWH = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '';
if ($userCO!='') { if ($userCO != '') {
# Replenishment Table // Replenishment Table
$REFCAT658 = DB::connection(config('m3.connection', 'pgsql'))->table('icm658m') $REFCAT658 = DB::connection(config('m3.connection', 'pgsql'))->table('icm658m')
->select('*') ->select('*')
->where('R658CO',$userCO) ->where('R658CO', $userCO)
->where('R658PL',$userPL) ->where('R658PL', $userPL)
->where('R658WH',$userWH) ->where('R658WH', $userWH)
->orderBy('R658CO','asc'); ->orderBy('R658CO', 'asc');
# Warehouse Table // Warehouse Table
// $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m') // $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')
// ->where('WDCO',$userCO) // ->where('WDCO',$userCO)
// ->where('WDPL',$userPL) // ->where('WDPL',$userPL)
// ->where('WDWHS',$userWH) // ->where('WDWHS',$userWH)
// ->get(); // ->get();
} } else {
else{ $REFCAT658 = [];
$REFCAT658 =[];
// $IC670M =[]; // $IC670M =[];
} }
@@ -194,5 +192,4 @@ class ReplenishSettingsController extends Controller
return Datatables::of($REFCAT658)->addIndexColumn()->make(true); return Datatables::of($REFCAT658)->addIndexColumn()->make(true);
} }
} }
@@ -2,14 +2,11 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Models\ShipTo;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Datatables; use Datatables;
use Illuminate\Http\Request;
use Modules\M3\Helpers\CAProvinces;
use Modules\M3\Helpers\USStates;
use Modules\M3\Models\ShipTo;
class ShipToController extends Controller class ShipToController extends Controller
{ {
@@ -28,22 +25,24 @@ class ShipToController extends Controller
$actionBtn .= '<form method="POST" action="' . url('ship-to/' . urlencode(trim($row->AUSHSHZP)) . '/' . urlencode(trim($row->AUSHWHS))) . '" style="display:inline">'; $actionBtn .= '<form method="POST" action="' . url('ship-to/' . urlencode(trim($row->AUSHSHZP)) . '/' . urlencode(trim($row->AUSHWHS))) . '" style="display:inline">';
$actionBtn .= csrf_field() . method_field('DELETE'); $actionBtn .= csrf_field() . method_field('DELETE');
$actionBtn .= '<button type="submit" class="btn btn-danger btn-sm" onclick="return confirm(\'Are you sure?\')">Delete</button></form>'; $actionBtn .= '<button type="submit" class="btn btn-danger btn-sm" onclick="return confirm(\'Are you sure?\')">Delete</button></form>';
return $actionBtn; return $actionBtn;
}) })
->rawColumns(['checkbox', 'action']) ->rawColumns(['checkbox', 'action'])
->make(true); ->make(true);
} }
return view('m3::liberty-theme.pages.ship-to.index'); return view('m3::liberty-theme.pages.ship-to.index');
} }
public function create() public function create()
{ {
# US // US
$USstates = \Modules\M3\Helpers\USStates::all(); $USstates = USStates::all();
# CA // CA
$CAstates = \Modules\M3\Helpers\CAProvinces::all(); $CAstates = CAProvinces::all();
# All States // All States
$states = array_merge($USstates, $CAstates); $states = array_merge($USstates, $CAstates);
return view('m3::liberty-theme.pages.ship-to.create', compact('states')); return view('m3::liberty-theme.pages.ship-to.create', compact('states'));
@@ -53,7 +52,7 @@ class ShipToController extends Controller
{ {
$validated = $request->validate( $validated = $request->validate(
[ [
'AUSTCN' => 'nullable|max:11', 'AUSTCN' => 'nullable|max:11',
'AUSHSHNM' => 'required|max:36', 'AUSHSHNM' => 'required|max:36',
'AUSHSHA1' => 'required|max:36', 'AUSHSHA1' => 'required|max:36',
'AUSHSHA2' => 'required|max:36', 'AUSHSHA2' => 'required|max:36',
@@ -63,7 +62,7 @@ class ShipToController extends Controller
'AUSHSHST' => 'required|max:2', 'AUSHSHST' => 'required|max:2',
'AUSHSHZP' => 'required|max:10', 'AUSHSHZP' => 'required|max:10',
'AUSHSHCT' => 'required|max:3', 'AUSHSHCT' => 'required|max:3',
'AUSHWHS' => 'required|max:3' 'AUSHWHS' => 'required|max:3',
], ],
[ [
'AUSHSHNM.required' => 'Name is required', 'AUSHSHNM.required' => 'Name is required',
@@ -73,9 +72,9 @@ class ShipToController extends Controller
'AUSHSHST.required' => 'State is required', 'AUSHSHST.required' => 'State is required',
'AUSHSHZP.required' => 'Zip code is required', 'AUSHSHZP.required' => 'Zip code is required',
'AUSHSHCT.required' => 'Country is required', 'AUSHSHCT.required' => 'Country is required',
'AUSHWHS.required' => 'Warehouse is required', 'AUSHWHS.required' => 'Warehouse is required',
'AUSTCN.max' => 'Customer Number cannot exceed 11 characters', 'AUSTCN.max' => 'Customer Number cannot exceed 11 characters',
'AUSHSHNM.max' => 'Name cannot exceed 36 characters', 'AUSHSHNM.max' => 'Name cannot exceed 36 characters',
'AUSHSHA1.max' => 'Address 1 cannot exceed 36 characters', 'AUSHSHA1.max' => 'Address 1 cannot exceed 36 characters',
'AUSHSHA2.max' => 'Address 2 cannot exceed 36 characters', 'AUSHSHA2.max' => 'Address 2 cannot exceed 36 characters',
@@ -85,12 +84,12 @@ class ShipToController extends Controller
'AUSHSHST.max' => 'State cannot exceed 2 characters', 'AUSHSHST.max' => 'State cannot exceed 2 characters',
'AUSHSHZP.max' => 'Zip code cannot exceed 10 characters', 'AUSHSHZP.max' => 'Zip code cannot exceed 10 characters',
'AUSHSHCT.max' => 'Country cannot exceed 3 characters', 'AUSHSHCT.max' => 'Country cannot exceed 3 characters',
'AUSHWHS.max' => 'Warehouse cannot exceed 3 characters' 'AUSHWHS.max' => 'Warehouse cannot exceed 3 characters',
] ],
); );
$validated['AUSTCN'] = $validated['AUSTCN'] ?? ' '; $validated['AUSTCN'] = $validated['AUSTCN'] ?? ' ';
$model = new ShipTo(); $model = new ShipTo;
$model->fill($validated); $model->fill($validated);
$success = $model->save(); $success = $model->save();
// ShipTo::create($validated); // ShipTo::create($validated);
@@ -105,17 +104,18 @@ class ShipToController extends Controller
public function edit($aushshzp, $aushwhs) public function edit($aushshzp, $aushwhs)
{ {
# US // US
$USstates = \Modules\M3\Helpers\USStates::all(); $USstates = USStates::all();
# CA // CA
$CAstates = \Modules\M3\Helpers\CAProvinces::all(); $CAstates = CAProvinces::all();
# All States // All States
$states = array_merge($USstates, $CAstates); $states = array_merge($USstates, $CAstates);
$shipTo = ShipTo::where('AUSHSHZP', $aushshzp) $shipTo = ShipTo::where('AUSHSHZP', $aushshzp)
->where('AUSHWHS', $aushwhs) ->where('AUSHWHS', $aushwhs)
->firstOrFail(); ->firstOrFail();
return view('m3::liberty-theme.pages.ship-to.edit', compact('shipTo', 'states')); return view('m3::liberty-theme.pages.ship-to.edit', compact('shipTo', 'states'));
} }
@@ -124,40 +124,40 @@ class ShipToController extends Controller
$validated = array_map(function ($value) { $validated = array_map(function ($value) {
return $value === null ? '' : $value; return $value === null ? '' : $value;
}, $request->validate( }, $request->validate(
[ [
'AUSTCN' => 'nullable|string|max:11', 'AUSTCN' => 'nullable|string|max:11',
'AUSHSHNM' => 'required|max:36', 'AUSHSHNM' => 'required|max:36',
'AUSHSHA1' => 'required|max:36', 'AUSHSHA1' => 'required|max:36',
'AUSHSHA2' => 'required|max:36', 'AUSHSHA2' => 'required|max:36',
'AUSHSHA3' => 'nullable|string|max:36', 'AUSHSHA3' => 'nullable|string|max:36',
'AUSHSHA4' => 'nullable|string|max:36', 'AUSHSHA4' => 'nullable|string|max:36',
'AUSHSHCI' => 'required|max:20', 'AUSHSHCI' => 'required|max:20',
'AUSHSHST' => 'required|max:2', 'AUSHSHST' => 'required|max:2',
'AUSHSHCT' => 'required|max:3' 'AUSHSHCT' => 'required|max:3',
], ],
[ [
'AUSHSHNM.required' => 'Name is required', 'AUSHSHNM.required' => 'Name is required',
'AUSHSHA1.required' => 'Address 1 is required', 'AUSHSHA1.required' => 'Address 1 is required',
'AUSHSHA2.required' => 'Address 2 is required', 'AUSHSHA2.required' => 'Address 2 is required',
'AUSHSHCI.required' => 'City is required', 'AUSHSHCI.required' => 'City is required',
'AUSHSHST.required' => 'State is required', 'AUSHSHST.required' => 'State is required',
'AUSHSHZP.required' => 'Zip code is required', 'AUSHSHZP.required' => 'Zip code is required',
'AUSHSHCT.required' => 'Country is required', 'AUSHSHCT.required' => 'Country is required',
'AUSHWHS.required' => 'Warehouse is required', 'AUSHWHS.required' => 'Warehouse is required',
'AUSTCN.max' => 'Customer Number cannot exceed 11 characters', 'AUSTCN.max' => 'Customer Number cannot exceed 11 characters',
'AUSHSHNM.max' => 'Name cannot exceed 36 characters', 'AUSHSHNM.max' => 'Name cannot exceed 36 characters',
'AUSHSHA1.max' => 'Address 1 cannot exceed 36 characters', 'AUSHSHA1.max' => 'Address 1 cannot exceed 36 characters',
'AUSHSHA2.max' => 'Address 2 cannot exceed 36 characters', 'AUSHSHA2.max' => 'Address 2 cannot exceed 36 characters',
'AUSHSHA3.max' => 'Address 3 cannot exceed 36 characters', 'AUSHSHA3.max' => 'Address 3 cannot exceed 36 characters',
'AUSHSHA4.max' => 'Address 4 cannot exceed 36 characters', 'AUSHSHA4.max' => 'Address 4 cannot exceed 36 characters',
'AUSHSHCI.max' => 'City cannot exceed 20 characters', 'AUSHSHCI.max' => 'City cannot exceed 20 characters',
'AUSHSHST.max' => 'State cannot exceed 2 characters', 'AUSHSHST.max' => 'State cannot exceed 2 characters',
'AUSHSHZP.max' => 'Zip code cannot exceed 10 characters', 'AUSHSHZP.max' => 'Zip code cannot exceed 10 characters',
'AUSHSHCT.max' => 'Country cannot exceed 3 characters', 'AUSHSHCT.max' => 'Country cannot exceed 3 characters',
'AUSHWHS.max' => 'Warehouse cannot exceed 3 characters' 'AUSHWHS.max' => 'Warehouse cannot exceed 3 characters',
] ],
)); ));
$updated = ShipTo::where('AUSHSHZP', $aushshzp) $updated = ShipTo::where('AUSHSHZP', $aushshzp)
->where('AUSHWHS', $aushwhs) ->where('AUSHWHS', $aushwhs)
@@ -183,5 +183,4 @@ class ShipToController extends Controller
} }
} }
} }
+36 -40
View File
@@ -2,48 +2,46 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use DB;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Str;
use Log; use Log;
use Excel;
use Storage; use Storage;
use Str;
class WhsPerfMetrics extends Controller class WhsPerfMetrics extends Controller
{ {
public static function index(Request $request){ public static function index(Request $request)
{
try { try {
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : ''; $SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER); // dd($SHUSER);
if ($SHUSER!='') { if ($SHUSER != '') {
# Get User CO & WH from Table ICM428M // Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH','R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US','=',$SHUSER) ->where('R428US', '=', $SHUSER)
->first(); ->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; # User $R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; // User
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '110'; # Company $COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '110'; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '144'; # Plant $PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '144'; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '322'; # WareHouse $WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '322'; // WareHouse
} }
# Warehouse Table // Warehouse Table
$IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get(); $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
# Get URL PARAMS // Get URL PARAMS
$urlParams = count($request->all())>0 ? $request->all() : ''; $urlParams = count($request->all()) > 0 ? $request->all() : '';
// dump($urlParams); // dump($urlParams);
$REPORTDATEDisp = isset($urlParams["REPORTDATEDisp"]) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams["REPORTDATEDisp"]))->format('Ymd') : today()->format('Ymd'); $REPORTDATEDisp = isset($urlParams['REPORTDATEDisp']) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams['REPORTDATEDisp']))->format('Ymd') : today()->format('Ymd');
$WHDDA = $COMPANY.$PLANT.$WHS; $WHDDA = $COMPANY . $PLANT . $WHS;
// dump($WHDDA); // dump($WHDDA);
if($REPORTDATEDisp!='' && $COMPANY!='' && $WHS!='' && $PLANT!=''){ if ($REPORTDATEDisp != '' && $COMPANY != '' && $WHS != '' && $PLANT != '') {
# Case 729: Add Currency code A1SHCURR FROM ICM666M // Case 729: Add Currency code A1SHCURR FROM ICM666M
$selectContent = " $selectContent = "
SELECT A5MACPKR, A5ONO, SELECT A5MACPKR, A5ONO,
(SELECT A4REFORD FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) AS A4REFORD, (SELECT A4REFORD FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) AS A4REFORD,
@@ -55,8 +53,8 @@ class WhsPerfMetrics extends Controller
A1SHCURR, A1SHCURR,
CASE CASE
WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL' WHEN (SELECT A4SHIPTYPE FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) = 'LTL'
THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL'))/100 ." THEN (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * " . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceLTL')) / 100 . '
ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ".(100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel') )/100 ." ELSE (SELECT A4RATETCP FROM ICM688M1 WHERE A4MACPKR=A5MACPKR) * ' . (100.00 - Config::get('arrays.misc.discountCarrierRateForCustomerPriceParcel')) / 100 . "
END AS FREIGHT END AS FREIGHT
FROM ICM688M2 FROM ICM688M2
LEFT JOIN ICM699M ON SHMACPKR=A5MACPKR AND SHTYPE='M3-Res-out' AND SHDATA LIKE 'Success%' AND SHSOURCE='CloseShipmentCoChargeAPI' LEFT JOIN ICM699M ON SHMACPKR=A5MACPKR AND SHTYPE='M3-Res-out' AND SHDATA LIKE 'Success%' AND SHSOURCE='CloseShipmentCoChargeAPI'
@@ -70,46 +68,44 @@ class WhsPerfMetrics extends Controller
// dump($selectContent); // dump($selectContent);
$ICM688M2 = DB::connection(config('m3.connection', 'pgsql')) $ICM688M2 = DB::connection(config('m3.connection', 'pgsql'))
->select($selectContent); ->select($selectContent);
// dd($ICM688M2); // dd($ICM688M2);
} } else {
else{
$ICM688M2 = collect(); $ICM688M2 = collect();
} }
# Get List of Files // Get List of Files
$allReportsUrls = []; $allReportsUrls = [];
$files = Storage::disk('publicLabels')->allFiles('WhsPerf/'.$WHS); $files = Storage::disk('publicLabels')->allFiles('WhsPerf/' . $WHS);
// $whsPerfFile = 'WhsPerf/'.$WHS.'/WhsPerfMetrics_'.$DateToday.'-'.$WHS.'.xlsx'; // $whsPerfFile = 'WhsPerf/'.$WHS.'/WhsPerfMetrics_'.$DateToday.'-'.$WHS.'.xlsx';
foreach ($files as $file) { foreach ($files as $file) {
# Get the file URL (if URL is configured in filesystems.php) // Get the file URL (if URL is configured in filesystems.php)
$url = Storage::disk('publicLabels')->url($file); $url = Storage::disk('publicLabels')->url($file);
$allReportsUrls[$file] = $url; $allReportsUrls[$file] = $url;
} }
// dd($allReportsUrls); // dd($allReportsUrls);
} } catch (\Throwable $th) {
catch (\Throwable $th) {
Log::error($th); Log::error($th);
} }
return view('m3::liberty-theme.pages.WhsPerfMetrics',compact('IC670M','WHDDA','COMPANY','PLANT','WHS','allReportsUrls')); return view('m3::liberty-theme.pages.WhsPerfMetrics', compact('IC670M', 'WHDDA', 'COMPANY', 'PLANT', 'WHS', 'allReportsUrls'));
} }
// Download File
# Download File public static function downloadFiles(Request $request)
public static function downloadFiles(Request $request){ {
// dd($request->all()); // dd($request->all());
$fileName = $request->filename; $fileName = $request->filename;
if (Storage::disk('publicLabels')->exists($fileName)) { if (Storage::disk('publicLabels')->exists($fileName)) {
# File exists, retrieve content or URL // File exists, retrieve content or URL
$fileUrl = Storage::disk('publicLabels')->url($fileName); $fileUrl = Storage::disk('publicLabels')->url($fileName);
$fileNameOnly = basename($fileName); $fileNameOnly = basename($fileName);
# Download the file
// Download the file
return Storage::disk('publicLabels')->download($fileName, $fileNameOnly); return Storage::disk('publicLabels')->download($fileName, $fileNameOnly);
} else { } else {
// Download the file (use code below) // Download the file (use code below)
} }
} }
} }
@@ -4,7 +4,8 @@ namespace Modules\M3\Http\Controllers;
class authController extends Controller class authController extends Controller
{ {
public static function logout(){ public static function logout()
{
return view('m3::liberty-theme.pages.logout'); return view('m3::liberty-theme.pages.logout');
@@ -2,104 +2,105 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB; use DB;
use Config;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response; use Illuminate\Support\Facades\Schema;
use Modules\M3\Models\ICM160M;
use Modules\M3\Helpers\Helper; use Modules\M3\Helpers\Helper;
use Modules\M3\Models\ICM160M;
class carrierMaintController extends Controller class carrierMaintController extends Controller
{ {
public static function index(Request $request)
public static function index(Request $request) { {
$currentUser = Helper::getUserCOWHSPLT(); $currentUser = Helper::getUserCOWHSPLT();
$UserCO = $currentUser['UserCO'] ?? ''; $UserCO = $currentUser['UserCO'] ?? '';
$ICM160M = []; $ICM160M = [];
$power_user = []; $power_user = [];
$schema = \Illuminate\Support\Facades\Schema::connection(config('m3.connection', 'pgsql')); $schema = Schema::connection(config('m3.connection', 'pgsql'));
if ($schema->hasTable('icm160m')) { if ($schema->hasTable('icm160m')) {
$ICM160M = DB::connection(config('m3.connection', 'pgsql'))->select(" $ICM160M = DB::connection(config('m3.connection', 'pgsql'))->select('
select canum, canam, substr(CATPID,1,3) as TwoshipCarrierCode, substr(CATPID,4,1) as ParcelCarrierCode, caspr10A01, caspr1A01 select canum, canam, substr(CATPID,1,3) as TwoshipCarrierCode, substr(CATPID,4,1) as ParcelCarrierCode, caspr10A01, caspr1A01
from icm160m WHERE CACO=?", [$UserCO]); from icm160m WHERE CACO=?', [$UserCO]);
} }
if ($schema->hasTable('icm428m')) { if ($schema->hasTable('icm428m')) {
$power_user = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $power_user = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428PWRUSR', 'R428CO', 'R428PL', 'R428WH') ->select('R428PWRUSR', 'R428CO', 'R428PL', 'R428WH')
->where('R428US', strtoUpper(m3_user()))->get()->all(); ->where('R428US', strtoupper(m3_user()))->get()->all();
} }
return view('m3::liberty-theme.pages.carrierMaint', compact('ICM160M','power_user'));
return view('m3::liberty-theme.pages.carrierMaint', compact('ICM160M', 'power_user'));
} }
# Process data from Add modal // Process data from Add modal
public static function savecarrierAdd(Request $request) { public static function savecarrierAdd(Request $request)
{
$currentUser = Helper::getUserCOWHSPLT(); $currentUser = Helper::getUserCOWHSPLT();
$UserCO = $currentUser['UserCO'] ?? ''; $UserCO = $currentUser['UserCO'] ?? '';
// $UserWHS = $currentUser['UserWHS'] ?? ''; // $UserWHS = $currentUser['UserWHS'] ?? '';
// $UserPL = $currentUser['UserPL'] ?? ''; // $UserPL = $currentUser['UserPL'] ?? '';
# Insert record to ICM160M // Insert record to ICM160M
# Verify record does not already exist in ICM160M // Verify record does not already exist in ICM160M
if($request->CANUM == NULL) { if ($request->CANUM == null) {
return "null"; return 'null';
} }
$icm160m=DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from ICM160M where CANUM='$request->CANUM' AND CACO='$UserCO'"); $icm160m = DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from ICM160M where CANUM='$request->CANUM' AND CACO='$UserCO'");
if($icm160m[0]->COUNT1=="1") { if ($icm160m[0]->COUNT1 == '1') {
return "exists"; return 'exists';
} else { } else {
$CASPR10A01 = isset($request->CASPR10A01) && $request->CASPR10A01 != NULL ? $request->CASPR10A01 : ' '; $CASPR10A01 = isset($request->CASPR10A01) && $request->CASPR10A01 != null ? $request->CASPR10A01 : ' ';
$CASPR1A01 = isset($request->CASPR1A01) && $request->CASPR1A01 != NULL ? $request->CASPR1A01 : ' '; $CASPR1A01 = isset($request->CASPR1A01) && $request->CASPR1A01 != null ? $request->CASPR1A01 : ' ';
$data=['CANUM'=>$request->CANUM, 'CANAM'=>$request->CANAM, $data = ['CANUM' => $request->CANUM, 'CANAM' => $request->CANAM,
'CATPID'=>str_pad(substr($request->TWOSHIPCARRIERCODE,0,3),3," ").substr($request->PARCELCARRIERCODE,0,1), 'CATPID' => str_pad(substr($request->TWOSHIPCARRIERCODE, 0, 3), 3, ' ') . substr($request->PARCELCARRIERCODE, 0, 1),
'CASPR10A01'=>$CASPR10A01, 'CASPR1A01'=>$CASPR1A01,'CACO'=>$UserCO]; // ,'CAPLNT'=>$UserPL,'CAWHS'=>$UserWHS 'CASPR10A01' => $CASPR10A01, 'CASPR1A01' => $CASPR1A01, 'CACO' => $UserCO]; // ,'CAPLNT'=>$UserPL,'CAWHS'=>$UserWHS
$insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('icm160m')->insert($data); $insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('icm160m')->insert($data);
if($insertSQL) { if ($insertSQL) {
return "success"; return 'success';
} }
} }
} }
public static function savecarrierAdd2(Request $request) {
public static function savecarrierAdd2(Request $request)
{
$currentUser = Helper::getUserCOWHSPLT(); $currentUser = Helper::getUserCOWHSPLT();
$UserCO = $currentUser['UserCO'] ?? ''; $UserCO = $currentUser['UserCO'] ?? '';
// $UserWHS = $currentUser['UserWHS'] ?? ''; // $UserWHS = $currentUser['UserWHS'] ?? '';
// $UserPL = $currentUser['UserPL'] ?? ''; // $UserPL = $currentUser['UserPL'] ?? '';
# Insert record to ICM160M // Insert record to ICM160M
if($request->CANUM == NULL) { if ($request->CANUM == null) {
return "null"; return 'null';
} }
$CASPR10A01 = isset($request->CASPR10A01) && $request->CASPR10A01 != NULL ? $request->CASPR10A01 : ' '; $CASPR10A01 = isset($request->CASPR10A01) && $request->CASPR10A01 != null ? $request->CASPR10A01 : ' ';
$CASPR1A01 = isset($request->CASPR1A01) && $request->CASPR1A01 != NULL ? $request->CASPR1A01 : ' '; $CASPR1A01 = isset($request->CASPR1A01) && $request->CASPR1A01 != null ? $request->CASPR1A01 : ' ';
$data=['CANUM'=>$request->CANUM, 'CANAM'=>$request->CANAM, 'CATPID'=>str_pad(substr($request->TWOSHIPCARRIERCODE,0,3),3," ").substr($request->PARCELCARRIERCODE,0,1), $data = ['CANUM' => $request->CANUM, 'CANAM' => $request->CANAM, 'CATPID' => str_pad(substr($request->TWOSHIPCARRIERCODE, 0, 3), 3, ' ') . substr($request->PARCELCARRIERCODE, 0, 1),
'CASPR10A01'=>$CASPR10A01, 'CASPR1A01'=>$CASPR1A01,'CACO'=>$UserCO]; // ,'CAPLNT'=>$UserPL,'CAWHS'=>$UserWHS 'CASPR10A01' => $CASPR10A01, 'CASPR1A01' => $CASPR1A01, 'CACO' => $UserCO]; // ,'CAPLNT'=>$UserPL,'CAWHS'=>$UserWHS
$insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('icm160m')->insert($data); $insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('icm160m')->insert($data);
if($insertSQL) { if ($insertSQL) {
return "success"; return 'success';
} }
} }
# Process data from Edit modal // Process data from Edit modal
public static function savecarrierEdit(Request $request) { public static function savecarrierEdit(Request $request)
{
$currentUser = Helper::getUserCOWHSPLT(); $currentUser = Helper::getUserCOWHSPLT();
$UserCO = $currentUser['UserCO'] ?? ''; $UserCO = $currentUser['UserCO'] ?? '';
if($request->CANUM == NULL) { if ($request->CANUM == null) {
return "null"; return 'null';
} }
DB::connection(config('m3.connection', 'pgsql'))->update("update ICM160M DB::connection(config('m3.connection', 'pgsql'))->update("update ICM160M
set CANAM='$request->CANAM', CATPID='".str_pad(substr($request->TWOSHIPCARRIERCODE,0,3),3," ").substr($request->PARCELCARRIERCODE,0,1)."', set CANAM='$request->CANAM', CATPID='" . str_pad(substr($request->TWOSHIPCARRIERCODE, 0, 3), 3, ' ') . substr($request->PARCELCARRIERCODE, 0, 1) . "',
CASPR10A01='$request->CASPR10A01', CASPR1A01='$request->CASPR1A01' CASPR10A01='$request->CASPR10A01', CASPR1A01='$request->CASPR1A01'
where CANUM='$request->CANUM' AND CACO='$UserCO'"); where CANUM='$request->CANUM' AND CACO='$UserCO'");
return "success"; return 'success';
} }
} }
@@ -1,12 +1,11 @@
<?php <?php
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use DB;
use Symfony\Component\HttpFoundation\Request;
class dashboardController extends Controller class dashboardController extends Controller
{ {
public static function index(){ public static function index()
{
return view('m3::liberty-theme.pages.dashboard'); return view('m3::liberty-theme.pages.dashboard');
// , compact('data','whs','whs_array','starting','ending') // , compact('data','whs','whs_array','starting','ending')
} }
@@ -2,18 +2,15 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB; use DB;
use Config;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Str;
use Log; use Log;
use Str;
class execSummaryController extends Controller class execSummaryController extends Controller
{ {
public static function index(Request $request){ public static function index(Request $request)
{
$IC670M = collect(); $IC670M = collect();
$WHDDA = ''; $WHDDA = '';
$COMPANY = '110'; $COMPANY = '110';
@@ -21,114 +18,114 @@ class execSummaryController extends Controller
$WHS = '322'; $WHS = '322';
try { try {
# Ajax Call // Ajax Call
if ($request->ajax()) { if ($request->ajax()) {
// dump($request->all()); // dump($request->all());
$WHDDA = isset($request->WHDDA) ? $request->WHDDA : array(); $WHDDA = isset($request->WHDDA) ? $request->WHDDA : [];
$WHArr = array(); $WHArr = [];
foreach ($WHDDA as $key => $WHDDAV) { foreach ($WHDDA as $key => $WHDDAV) {
$CO = substr($WHDDAV, 0, 3); $CO = substr($WHDDAV, 0, 3);
// $R428PL = substr($WHDDAV, 3, 3); // $R428PL = substr($WHDDAV, 3, 3);
$WHArr[] = substr($WHDDAV, 6, 3); $WHArr[] = substr($WHDDAV, 6, 3);
} }
$reportPeriod = isset($request->reportPeriod) ? $request->reportPeriod : ''; # monthly , quarter , year , daily $reportPeriod = isset($request->reportPeriod) ? $request->reportPeriod : ''; // monthly , quarter , year , daily
# Current // Current
$checkSales = isset($request->checkSales) ? $request->checkSales : ''; # on $checkSales = isset($request->checkSales) ? $request->checkSales : ''; // on
$checkWeight = isset($request->checkWeight) ? $request->checkWeight : ''; # on $checkWeight = isset($request->checkWeight) ? $request->checkWeight : ''; // on
$checkLines = isset($request->checkLines) ? $request->checkLines : ''; # on $checkLines = isset($request->checkLines) ? $request->checkLines : ''; // on
if(count($WHArr)>0 && $CO!='' && $reportPeriod!=''){ if (count($WHArr) > 0 && $CO != '' && $reportPeriod != '') {
switch ($reportPeriod) { switch ($reportPeriod) {
case 'year': case 'year':
# Set Dates based on reportPeriod type // Set Dates based on reportPeriod type
$firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : ''; $firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : '';
$reportDate = $firstDay->modify('first day of January')->format('Ymd'); $reportDate = $firstDay->modify('first day of January')->format('Ymd');
$lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : ''; $lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : '';
$toreportDate = $lastDay->modify('last day of December')->format('Ymd'); $toreportDate = $lastDay->modify('last day of December')->format('Ymd');
# Build SQL // Build SQL
$selectContent = "with tempfile as ( $selectContent = "with tempfile as (
select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs, select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs,
(select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only) (select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only)
from icm688m2 where a5macpkr in ( from icm688m2 where a5macpkr in (
select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate ) select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate )
) and a5co='".$CO."' and a5whs in(".implode(",", $WHArr).") ) and a5co='" . $CO . "' and a5whs in(" . implode(',', $WHArr) . ')
) )
select substr(ayapr8N002,1,4) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed,sum(a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars,a5whs as whs from tempfile select substr(ayapr8N002,1,4) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed,sum(a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars,a5whs as whs from tempfile
group by substr(ayapr8N002,1,4),a5whs order by 1 "; group by substr(ayapr8N002,1,4),a5whs order by 1 ';
break; break;
case 'quarter': case 'quarter':
# Set Dates based on reportPeriod type // Set Dates based on reportPeriod type
$firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : ''; $firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : '';
$reportDate = $firstDay->modify('first day of January')->format('Ymd'); $reportDate = $firstDay->modify('first day of January')->format('Ymd');
$lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : ''; $lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : '';
$toreportDate = $lastDay->modify('last day of December')->format('Ymd'); $toreportDate = $lastDay->modify('last day of December')->format('Ymd');
# Build SQL // Build SQL
$selectContent = "with tempfile as ( $selectContent = "with tempfile as (
select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs, select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs,
(select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only) (select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only)
from icm688m2 where a5macpkr in ( from icm688m2 where a5macpkr in (
select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate ) select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate )
) and a5co='".$CO."' and a5whs in (".implode(",", $WHArr).") ) and a5co='" . $CO . "' and a5whs in (" . implode(',', $WHArr) . ")
) )
select substr(ayapr8N002,3,2) ||'-' || 'Q' || EXTRACT(QUARTER FROM TO_DATE(CAST(ayapr8n002 AS TEXT),'YYYYMMDD')) as years,count(*) as lines, select substr(ayapr8N002,3,2) ||'-' || 'Q' || EXTRACT(QUARTER FROM TO_DATE(CAST(ayapr8n002 AS TEXT),'YYYYMMDD')) as years,count(*) as lines,
sum(a5rsvqty) as reserveqty, sum(a5packed) as packed,sum (a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars, a5whs as whs sum(a5rsvqty) as reserveqty, sum(a5packed) as packed,sum (a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars, a5whs as whs
from tempfile from tempfile
group by substr(ayapr8N002,3,2) ||'-' || 'Q' || EXTRACT(QUARTER FROM TO_DATE(CAST(ayapr8n002 AS TEXT),'YYYYMMDD')),a5whs order by 1 "; group by substr(ayapr8N002,3,2) ||'-' || 'Q' || EXTRACT(QUARTER FROM TO_DATE(CAST(ayapr8n002 AS TEXT),'YYYYMMDD')),a5whs order by 1 ";
break; break;
case 'monthly': case 'monthly':
# Set Dates based on reportPeriod type // Set Dates based on reportPeriod type
$firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : ''; $firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : '';
$reportDate = $firstDay->modify('first day of this month')->format('Ymd'); $reportDate = $firstDay->modify('first day of this month')->format('Ymd');
$lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : ''; $lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : '';
$toreportDate =$lastDay->modify('last day of this month')->format('Ymd'); $toreportDate = $lastDay->modify('last day of this month')->format('Ymd');
# Build SQL // Build SQL
$selectContent = "with tempfile as ( $selectContent = "with tempfile as (
select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs, select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs,
(select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only) (select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only)
from icm688m2 where a5macpkr in ( from icm688m2 where a5macpkr in (
select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate ) select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate )
) and a5co='".$CO."' and a5whs in (".implode(",", $WHArr).") ) and a5co='" . $CO . "' and a5whs in (" . implode(',', $WHArr) . ")
) )
select substr(ayapr8N002,1,4) || '-' || substr(ayapr8N002,5,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed, select substr(ayapr8N002,1,4) || '-' || substr(ayapr8N002,5,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed,
sum(a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars, a5whs as whs sum(a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars, a5whs as whs
from tempfile from tempfile
group by substr(ayapr8N002,1,4) || '-' || substr(ayapr8N002,5,2),a5whs order by 1 "; group by substr(ayapr8N002,1,4) || '-' || substr(ayapr8N002,5,2),a5whs order by 1 ";
break; break;
case 'custom': case 'custom':
# Set Dates based on reportPeriod type // Set Dates based on reportPeriod type
$firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : ''; $firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : '';
$reportDate = $firstDay->modify('first day of this month')->format('Ymd'); $reportDate = $firstDay->modify('first day of this month')->format('Ymd');
$toreportDate = $firstDay->modify('last day of this month')->format('Ymd'); $toreportDate = $firstDay->modify('last day of this month')->format('Ymd');
// $lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : ''; // $lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : '';
// $toreportDate =$lastDay->modify('last day of this month')->format('Ymd'); // $toreportDate =$lastDay->modify('last day of this month')->format('Ymd');
# Build SQL // Build SQL
$selectContent = "with tempfile as ( $selectContent = "with tempfile as (
select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs, select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs,
(select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only) (select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only)
from icm688m2 where a5macpkr in ( from icm688m2 where a5macpkr in (
select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate ) select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate )
) and a5co='".$CO."' and a5whs in (".implode(",", $WHArr).") ) and a5co='" . $CO . "' and a5whs in (" . implode(',', $WHArr) . ')
) )
select substr(ayapr8N002,7,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed, select substr(ayapr8N002,7,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed,
sum(a5lnwght*a5packed/a5rsvqty) as weight, sum(dollars) as dollars, a5whs as whs sum(a5lnwght*a5packed/a5rsvqty) as weight, sum(dollars) as dollars, a5whs as whs
from tempfile from tempfile
group by substr(ayapr8N002,7,2),a5whs order by 1 "; group by substr(ayapr8N002,7,2),a5whs order by 1 ';
break; break;
default: default:
$selectContent = ""; $selectContent = '';
break; break;
} }
// dump($reportDate); // dump($reportDate);
@@ -136,41 +133,39 @@ class execSummaryController extends Controller
// dump($selectContent); // dump($selectContent);
$execSummaryRes = DB::connection(config('m3.connection', 'pgsql'))->select($selectContent); $execSummaryRes = DB::connection(config('m3.connection', 'pgsql'))->select($selectContent);
} } else {
else{
$execSummaryRes = collect(); $execSummaryRes = collect();
} }
// dump($execSummaryRes); // dump($execSummaryRes);
return response()->json(['success'=>true,'reportPeriod'=> $reportPeriod, 'result'=>$execSummaryRes, 'checkSales'=>$checkSales, return response()->json(['success' => true, 'reportPeriod' => $reportPeriod, 'result' => $execSummaryRes, 'checkSales' => $checkSales,
'checkWeight'=>$checkWeight, 'checkLines'=>$checkLines]); 'checkWeight' => $checkWeight, 'checkLines' => $checkLines]);
} }
# Init Page // Init Page
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : ''; $SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER); // dd($SHUSER);
if ($SHUSER!='') { if ($SHUSER != '') {
# Get User CO & WH from Table ICM428M // Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH','R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US','=',$SHUSER) ->where('R428US', '=', $SHUSER)
->first(); ->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; # User $R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; // User
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '110'; # Company $COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '110'; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '144'; # Plant $PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '144'; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '322'; # WareHouse $WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '322'; // WareHouse
} }
$WHDDA = $COMPANY.$PLANT.$WHS; $WHDDA = $COMPANY . $PLANT . $WHS;
// dump($WHDDA); // dump($WHDDA);
# Warehouse Table // Warehouse Table
$IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get(); $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
} } catch (\Throwable $th) {
catch (\Throwable $th) {
Log::error($th); Log::error($th);
} }
return view('m3::liberty-theme.pages.execSummary',compact('IC670M','WHDDA')); return view('m3::liberty-theme.pages.execSummary', compact('IC670M', 'WHDDA'));
// ,'ICM688M2',,'COMPANY','PLANT','WHS','reportDate' // ,'ICM688M2',,'COMPANY','PLANT','WHS','reportDate'
} }
} }
@@ -2,74 +2,71 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB; use DB;
use Config;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Str;
use Log; use Log;
use Str;
class execSummaryLineController extends Controller class execSummaryLineController extends Controller
{ {
public static function index(Request $request){ public static function index(Request $request)
{
try { try {
# Ajax Call // Ajax Call
if ($request->ajax()) { if ($request->ajax()) {
// dump($request->all()); // dump($request->all());
$WHDDA = isset($request->WHDDA) ? $request->WHDDA : array(); $WHDDA = isset($request->WHDDA) ? $request->WHDDA : [];
$WHArr = array(); $WHArr = [];
foreach ($WHDDA as $key => $WHDDAV) { foreach ($WHDDA as $key => $WHDDAV) {
$CO = substr($WHDDAV, 0, 3); $CO = substr($WHDDAV, 0, 3);
// $R428PL = substr($WHDDAV, 3, 3); // $R428PL = substr($WHDDAV, 3, 3);
$WHArr[] = substr($WHDDAV, 6, 3); $WHArr[] = substr($WHDDAV, 6, 3);
} }
$reportPeriod = isset($request->reportPeriod) ? $request->reportPeriod : ''; # monthly , quarter , year , daily $reportPeriod = isset($request->reportPeriod) ? $request->reportPeriod : ''; // monthly , quarter , year , daily
# Current // Current
$checkSales = isset($request->checkSales) ? $request->checkSales : ''; # on $checkSales = isset($request->checkSales) ? $request->checkSales : ''; // on
$checkWeight = isset($request->checkWeight) ? $request->checkWeight : ''; # on $checkWeight = isset($request->checkWeight) ? $request->checkWeight : ''; // on
$checkLines = isset($request->checkLines) ? $request->checkLines : ''; # on $checkLines = isset($request->checkLines) ? $request->checkLines : ''; // on
if(count($WHArr)>0 && $CO!='' && $reportPeriod!=''){ if (count($WHArr) > 0 && $CO != '' && $reportPeriod != '') {
switch ($reportPeriod) { switch ($reportPeriod) {
case 'year': case 'year':
# Set Dates based on reportPeriod type // Set Dates based on reportPeriod type
$firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : ''; $firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : '';
$reportDate = $firstDay->modify('first day of January')->format('Ymd'); $reportDate = $firstDay->modify('first day of January')->format('Ymd');
$lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : ''; $lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : '';
$toreportDate = $lastDay->modify('last day of December')->format('Ymd'); $toreportDate = $lastDay->modify('last day of December')->format('Ymd');
# Build SQL // Build SQL
$selectContent = "with tempfile as ( $selectContent = "with tempfile as (
select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs, select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs,
(select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only) (select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only)
from icm688m2 where a5macpkr in ( from icm688m2 where a5macpkr in (
select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate ) select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate )
) and a5co='".$CO."' and a5whs in(".implode(",", $WHArr).") ) and a5co='" . $CO . "' and a5whs in(" . implode(',', $WHArr) . ')
) )
select substr(ayapr8N002,1,4) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed,sum(a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars,a5whs as whs from tempfile select substr(ayapr8N002,1,4) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed,sum(a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars,a5whs as whs from tempfile
group by substr(ayapr8N002,1,4),a5whs order by 1 "; group by substr(ayapr8N002,1,4),a5whs order by 1 ';
$execSummaryResLY = []; $execSummaryResLY = [];
break; break;
case 'quarter': case 'quarter':
# Set Dates based on reportPeriod type // Set Dates based on reportPeriod type
$firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : ''; $firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : '';
$reportDate = $firstDay->modify('first day of January')->format('Ymd'); $reportDate = $firstDay->modify('first day of January')->format('Ymd');
$lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : ''; $lastDay = isset($request->TOREPORTDATE) ? \DateTime::createFromFormat('Y-m', trim($request->TOREPORTDATE)) : '';
$toreportDate = $lastDay->modify('last day of December')->format('Ymd'); $toreportDate = $lastDay->modify('last day of December')->format('Ymd');
# Build SQL // Build SQL
$selectContent = "with tempfile as ( $selectContent = "with tempfile as (
select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs, select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs,
(select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only) (select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only)
from icm688m2 where a5macpkr in ( from icm688m2 where a5macpkr in (
select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate ) select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate )
) and a5co='".$CO."' and a5whs in (".implode(",", $WHArr).") ) and a5co='" . $CO . "' and a5whs in (" . implode(',', $WHArr) . ")
) )
select 'Q' || EXTRACT(QUARTER FROM TO_DATE(CAST(ayapr8n002 AS TEXT),'YYYYMMDD')) ||'-' || substr(ayapr8N002,3,2) as years,count(*) as lines, select 'Q' || EXTRACT(QUARTER FROM TO_DATE(CAST(ayapr8n002 AS TEXT),'YYYYMMDD')) ||'-' || substr(ayapr8N002,3,2) as years,count(*) as lines,
sum(a5rsvqty) as reserveqty, sum(a5packed) as packed,sum (a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars, a5whs as whs sum(a5rsvqty) as reserveqty, sum(a5packed) as packed,sum (a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars, a5whs as whs
@@ -78,27 +75,27 @@ class execSummaryLineController extends Controller
$execSummaryResLY = []; $execSummaryResLY = [];
break; break;
case 'monthly': case 'monthly':
# Set Dates based on reportPeriod type // Set Dates based on reportPeriod type
$firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : null; $firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : null;
$lastDay = (clone $firstDay); $lastDay = (clone $firstDay);
$reportDate = $firstDay->modify('-11 months')->modify('first day of this month')->format('Ymd'); // $reportDate = $firstDay->modify('-11 months')->modify('first day of this month')->format('Ymd'); //
$toreportDate = $lastDay ? $lastDay->modify('last day of this month')->format('Ymd') : ''; $toreportDate = $lastDay ? $lastDay->modify('last day of this month')->format('Ymd') : '';
# Last Year Dates // Last Year Dates
// Same period, but for Last Year (LY) // Same period, but for Last Year (LY)
$reportDateLY = (clone $firstDay)->modify('-1 year')->modify('first day of this month')->format('Ymd'); $reportDateLY = (clone $firstDay)->modify('-1 year')->modify('first day of this month')->format('Ymd');
$toreportDateLY = (clone $lastDay)->modify('-1 year')->modify('last day of this month')->format('Ymd'); $toreportDateLY = (clone $lastDay)->modify('-1 year')->modify('last day of this month')->format('Ymd');
# Build SQL // Build SQL
$selectContent = "with tempfile as ( $selectContent = "with tempfile as (
select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs, select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs,
(select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only) (select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only)
from icm688m2 where a5macpkr in ( from icm688m2 where a5macpkr in (
select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate ) select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate )
) and a5co='".$CO."' and a5whs in (".implode(",", $WHArr).") ) and a5co='" . $CO . "' and a5whs in (" . implode(',', $WHArr) . ")
) )
select substr(ayapr8N002,1,4) || '-' || substr(ayapr8N002,5,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed, select substr(ayapr8N002,1,4) || '-' || substr(ayapr8N002,5,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed,
sum(a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars, a5whs as whs sum(a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars, a5whs as whs
@@ -110,7 +107,7 @@ class execSummaryLineController extends Controller
(select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only) (select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only)
from icm688m2 where a5macpkr in ( from icm688m2 where a5macpkr in (
select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDateLY and ayapr8N002<=$toreportDateLY ) select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDateLY and ayapr8N002<=$toreportDateLY )
) and a5co='".$CO."' and a5whs in (".implode(",", $WHArr).") ) and a5co='" . $CO . "' and a5whs in (" . implode(',', $WHArr) . ")
) )
select substr(ayapr8N002,1,4) || '-' || substr(ayapr8N002,5,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed, select substr(ayapr8N002,1,4) || '-' || substr(ayapr8N002,5,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed,
sum(a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars, a5whs as whs sum(a5lnwght*a5packed/a5rsvqty) as weight,sum(dollars) as dollars, a5whs as whs
@@ -119,87 +116,85 @@ class execSummaryLineController extends Controller
$execSummaryResLY = DB::connection(config('m3.connection', 'pgsql'))->select($selectContentLY); $execSummaryResLY = DB::connection(config('m3.connection', 'pgsql'))->select($selectContentLY);
break; break;
case 'custom': case 'custom':
# Set Dates based on reportPeriod type // Set Dates based on reportPeriod type
$firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : ''; $firstDay = isset($request->REPORTDATE) ? \DateTime::createFromFormat('Y-m', $request->REPORTDATE) : '';
$reportDate = $firstDay->modify('first day of this month')->format('Ymd'); $reportDate = $firstDay->modify('first day of this month')->format('Ymd');
$toreportDate = $firstDay->modify('last day of this month')->format('Ymd'); $toreportDate = $firstDay->modify('last day of this month')->format('Ymd');
# Last Year Dates // Last Year Dates
$reportDateLY = (clone $firstDay)->modify('-1 year')->modify('first day of this month')->format('Ymd'); $reportDateLY = (clone $firstDay)->modify('-1 year')->modify('first day of this month')->format('Ymd');
$toreportDateLY = (clone $firstDay)->modify('-1 year')->modify('last day of this month')->format('Ymd'); $toreportDateLY = (clone $firstDay)->modify('-1 year')->modify('last day of this month')->format('Ymd');
# Build SQL // Build SQL
$selectContent = "with tempfile as ( $selectContent = "with tempfile as (
select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs, select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs,
(select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only) (select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only)
from icm688m2 where a5macpkr in ( from icm688m2 where a5macpkr in (
select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate ) select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDate and ayapr8N002<=$toreportDate )
) and a5co='".$CO."' and a5whs in (".implode(",", $WHArr).") ) and a5co='" . $CO . "' and a5whs in (" . implode(',', $WHArr) . ')
) )
select substr(ayapr8N002,7,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed, select substr(ayapr8N002,7,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed,
sum(a5lnwght*a5packed/a5rsvqty) as weight, sum(dollars) as dollars, a5whs as whs sum(a5lnwght*a5packed/a5rsvqty) as weight, sum(dollars) as dollars, a5whs as whs
from tempfile from tempfile
group by substr(ayapr8N002,7,2),a5whs order by 1 "; group by substr(ayapr8N002,7,2),a5whs order by 1 ';
$selectContentLY = "with tempfile as ( $selectContentLY = "with tempfile as (
select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs, select a5rsvqty,a5packed,a5slunpr*a5packed as dollars,a5lnwght,a5whs,
(select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only) (select max(ayapr8N002) as ayapr8N002 from icm695m1 where a5macpkr=aymacpkr fetch first 1 rows only)
from icm688m2 where a5macpkr in ( from icm688m2 where a5macpkr in (
select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDateLY and ayapr8N002<=$toreportDateLY ) select distinct aymacpkr from icm695m1 where (AYSTATUS in ('Z','z') and ayapr8N002>=$reportDateLY and ayapr8N002<=$toreportDateLY )
) and a5co='".$CO."' and a5whs in (".implode(",", $WHArr).") ) and a5co='" . $CO . "' and a5whs in (" . implode(',', $WHArr) . ')
) )
select substr(ayapr8N002,7,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed, select substr(ayapr8N002,7,2) as years,count(*) as lines,sum(a5rsvqty) as reserveqty,sum(a5packed) as packed,
sum(a5lnwght*a5packed/a5rsvqty) as weight, sum(dollars) as dollars, a5whs as whs sum(a5lnwght*a5packed/a5rsvqty) as weight, sum(dollars) as dollars, a5whs as whs
from tempfile from tempfile
group by substr(ayapr8N002,7,2),a5whs order by 1 "; group by substr(ayapr8N002,7,2),a5whs order by 1 ';
$execSummaryResLY = DB::connection(config('m3.connection', 'pgsql'))->select($selectContentLY); $execSummaryResLY = DB::connection(config('m3.connection', 'pgsql'))->select($selectContentLY);
break; break;
default: default:
$selectContent = ""; $selectContent = '';
break; break;
} }
$execSummaryRes = DB::connection(config('m3.connection', 'pgsql'))->select($selectContent); $execSummaryRes = DB::connection(config('m3.connection', 'pgsql'))->select($selectContent);
} } else {
else{ $execSummaryRes = collect();
$execSummaryRes = collect();
$execSummaryResLY = collect(); $execSummaryResLY = collect();
} }
return response()->json(['success'=>true,'reportPeriod'=> $reportPeriod, 'result'=>$execSummaryRes, 'resultLY'=>$execSummaryResLY, return response()->json(['success' => true, 'reportPeriod' => $reportPeriod, 'result' => $execSummaryRes, 'resultLY' => $execSummaryResLY,
'checkSales'=>$checkSales, 'checkWeight'=>$checkWeight, 'checkLines'=>$checkLines]); 'checkSales' => $checkSales, 'checkWeight' => $checkWeight, 'checkLines' => $checkLines]);
} }
# Init Page // Init Page
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : ''; $SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER); // dd($SHUSER);
if ($SHUSER!='') { if ($SHUSER != '') {
# Get User CO & WH from Table ICM428M // Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH','R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US','=',$SHUSER) ->where('R428US', '=', $SHUSER)
->first(); ->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; # User $R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; // User
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '110'; # Company $COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '110'; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '144'; # Plant $PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '144'; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '322'; # WareHouse $WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '322'; // WareHouse
} }
$WHDDA = $COMPANY.$PLANT.$WHS; $WHDDA = $COMPANY . $PLANT . $WHS;
// dump($WHDDA); // dump($WHDDA);
# Warehouse Table // Warehouse Table
$IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get(); $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
} } catch (\Throwable $th) {
catch (\Throwable $th) {
Log::error($th); Log::error($th);
} }
return view('m3::liberty-theme.pages.execSummaryLine',compact('IC670M','WHDDA')); return view('m3::liberty-theme.pages.execSummaryLine', compact('IC670M', 'WHDDA'));
// ,'ICM688M2',,'COMPANY','PLANT','WHS','reportDate' // ,'ICM688M2',,'COMPANY','PLANT','WHS','reportDate'
} }
} }
+156 -165
View File
@@ -2,15 +2,8 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config;
use Storage;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Modules\M3\Services\BillOfLadingService; use Modules\M3\Services\BillOfLadingService;
use setasign\Fpdi\Fpdi;
class fillBOL2Controller extends Controller class fillBOL2Controller extends Controller
{ {
@@ -21,7 +14,8 @@ class fillBOL2Controller extends Controller
$this->bolService = $bolService; $this->bolService = $bolService;
} }
public static function index(Request $request) { public static function index(Request $request)
{
return view('m3::liberty-theme.pages.fillBOL2'); return view('m3::liberty-theme.pages.fillBOL2');
@@ -30,7 +24,7 @@ class fillBOL2Controller extends Controller
public function fillBOL(Request $request) public function fillBOL(Request $request)
{ {
## $BOL = BOL::findOrFail($request); // # $BOL = BOL::findOrFail($request);
$BOL = $request; $BOL = $request;
$data = [ $data = [
@@ -63,160 +57,160 @@ Line 3
Line 4 Line 4
Line 5', Line 5',
'DTESHIPED.1' => date('d/m/Y'), 'DTESHIPED.1' => date('d/m/Y'),
'invoice_number' => $BOL['BOL_number'], 'invoice_number' => $BOL['BOL_number'],
'amount_due' => number_format($BOL['amount'], 2), 'amount_due' => number_format($BOL['amount'], 2),
'TYPEANDESCPTN.1' => 'TOTAL: 20 SKIDS 8320 #', 'TYPEANDESCPTN.1' => 'TOTAL: 20 SKIDS 8320 #',
'TYPEANDESCPTN.10' => 'ROTTERDAM ETA: 11/22', 'TYPEANDESCPTN.10' => 'ROTTERDAM ETA: 11/22',
'TYPEANDESCPTN.13' => 'CONTAINER:', 'TYPEANDESCPTN.13' => 'CONTAINER:',
'TYPEANDESCPTN.2' => 'MECHANICAL / CADDY/ ELECTRICAL', 'TYPEANDESCPTN.2' => 'MECHANICAL / CADDY/ ELECTRICAL',
'TYPEANDESCPTN.4' => 'BOOKING: 150744100', 'TYPEANDESCPTN.4' => 'BOOKING: 150744100',
'TYPEANDESCPTN.5' => 'REFERENCE: 3140028046', 'TYPEANDESCPTN.5' => 'REFERENCE: 3140028046',
'TYPEANDESCPTN.6' => 'VESSEL: INDEPENDENT HORIZON V. 1023E', 'TYPEANDESCPTN.6' => 'VESSEL: INDEPENDENT HORIZON V. 1023E',
'TYPEANDESCPTN.7' => 'SEAL: 637053', 'TYPEANDESCPTN.7' => 'SEAL: 637053',
'TYPEANDESCPTN.9' => 'CHESTER, PA ETD: 11/05', 'TYPEANDESCPTN.9' => 'CHESTER, PA ETD: 11/05',
'BOFLADNGAGYCD' => $BOL['BOL_number'], 'BOFLADNGAGYCD' => $BOL['BOL_number'],
'CLASSORATE1' => '50', 'CLASSORATE1' => '50',
'CNMETRKLICNSE' => 'ICL / Expeditors', 'CNMETRKLICNSE' => 'ICL / Expeditors',
'CONSIGTONMADDR' => 'ERICO EUROPE BV JULES VERNEWEG 75 TILBURG . 5015 BG', 'CONSIGTONMADDR' => 'ERICO EUROPE BV JULES VERNEWEG 75 TILBURG . 5015 BG',
'DATE' => date('d/m/Y'), 'DATE' => date('d/m/Y'),
'FRMNMADDR' => 'ERICO INTERNATIONAL CORP 6800 ARNOLD MILLER PARKWAY SOLON, OH 44139 USA', 'FRMNMADDR' => 'ERICO INTERNATIONAL CORP 6800 ARNOLD MILLER PARKWAY SOLON, OH 44139 USA',
'LNITEMWT1' => '8320', 'LNITEMWT1' => '8320',
'PARTOFMSTRBILL' => 'No', 'PARTOFMSTRBILL' => 'No',
'PKGTYPECOUNT1' => '20', 'PKGTYPECOUNT1' => '20',
'SHPRNMBR' => '3140028046', 'SHPRNMBR' => '3140028046',
'TOTALWT' => '8320', 'TOTALWT' => '8320',
'TOTPIECES' => '20', 'TOTPIECES' => '20',
'ckFREIGHTCOLECT' => 'Yes', 'ckFREIGHTCOLECT' => 'Yes',
'ckPREPAY' => 'Off', 'ckPREPAY' => 'Off',
'DTESHIPED.2' => '', 'DTESHIPED.2' => '',
'LNITEMWT24' => '', 'LNITEMWT24' => '',
'CLASSORATE24' => '', 'CLASSORATE24' => '',
'LNITEMCLAS24' => '', 'LNITEMCLAS24' => '',
'TYPEANDESCPTN.24' => '', 'TYPEANDESCPTN.24' => '',
'PKGTYPECOUNT24' => '', 'PKGTYPECOUNT24' => '',
'LNITEMWT23' => '', 'LNITEMWT23' => '',
'CLASSORATE23' => '', 'CLASSORATE23' => '',
'LNITEMCLAS23' => '', 'LNITEMCLAS23' => '',
'TYPEANDESCPTN.23' => '', 'TYPEANDESCPTN.23' => '',
'PKGTYPECOUNT23' => '', 'PKGTYPECOUNT23' => '',
'LNITEMWT22' => '', 'LNITEMWT22' => '',
'CLASSORATE22' => '', 'CLASSORATE22' => '',
'LNITEMCLAS22' => '', 'LNITEMCLAS22' => '',
'TYPEANDESCPTN.22' => '', 'TYPEANDESCPTN.22' => '',
'PKGTYPECOUNT22' => '', 'PKGTYPECOUNT22' => '',
'LNITEMWT21' => '', 'LNITEMWT21' => '',
'CLASSORATE21' => '', 'CLASSORATE21' => '',
'LNITEMCLAS21' => '', 'LNITEMCLAS21' => '',
'TYPEANDESCPTN.21' => '', 'TYPEANDESCPTN.21' => '',
'PKGTYPECOUNT21' => '', 'PKGTYPECOUNT21' => '',
'LNITEMWT20' => '', 'LNITEMWT20' => '',
'CLASSORATE20' => '', 'CLASSORATE20' => '',
'LNITEMCLAS20' => '', 'LNITEMCLAS20' => '',
'TYPEANDESCPTN.20' => '', 'TYPEANDESCPTN.20' => '',
'PKGTYPECOUNT20' => '', 'PKGTYPECOUNT20' => '',
'LNITEMWT19' => '', 'LNITEMWT19' => '',
'CLASSORATE19' => '', 'CLASSORATE19' => '',
'LNITEMCLAS19' => '', 'LNITEMCLAS19' => '',
'TYPEANDESCPTN.19' => '', 'TYPEANDESCPTN.19' => '',
'PKGTYPECOUNT19' => '', 'PKGTYPECOUNT19' => '',
'LNITEMWT18' => '', 'LNITEMWT18' => '',
'CLASSORATE18' => '', 'CLASSORATE18' => '',
'LNITEMCLAS18' => '', 'LNITEMCLAS18' => '',
'TYPEANDESCPTN.18' => '', 'TYPEANDESCPTN.18' => '',
'PKGTYPECOUNT18' => '', 'PKGTYPECOUNT18' => '',
'LNITEMWT17' => '', 'LNITEMWT17' => '',
'CLASSORATE17' => '', 'CLASSORATE17' => '',
'LNITEMCLAS17' => '', 'LNITEMCLAS17' => '',
'TYPEANDESCPTN.17' => '', 'TYPEANDESCPTN.17' => '',
'PKGTYPECOUNT17' => '', 'PKGTYPECOUNT17' => '',
'LNITEMWT16' => '', 'LNITEMWT16' => '',
'CLASSORATE16' => '', 'CLASSORATE16' => '',
'LNITEMCLAS16' => '', 'LNITEMCLAS16' => '',
'TYPEANDESCPTN.16' => '', 'TYPEANDESCPTN.16' => '',
'PKGTYPECOUNT16' => '', 'PKGTYPECOUNT16' => '',
'LNITEMWT15' => '', 'LNITEMWT15' => '',
'CLASSORATE15' => '', 'CLASSORATE15' => '',
'LNITEMCLAS15' => '', 'LNITEMCLAS15' => '',
'TYPEANDESCPTN.15' => '', 'TYPEANDESCPTN.15' => '',
'PKGTYPECOUNT15' => '', 'PKGTYPECOUNT15' => '',
'LNITEMWT14' => '', 'LNITEMWT14' => '',
'CLASSORAT14' => '', 'CLASSORAT14' => '',
'LNITEMCLAS14' => '', 'LNITEMCLAS14' => '',
'TYPEANDESCPTN.14' => '', 'TYPEANDESCPTN.14' => '',
'PKGTYPECOUNT14' => '', 'PKGTYPECOUNT14' => '',
'LNITEMWT13' => '', 'LNITEMWT13' => '',
'CLASSORATE13' => '', 'CLASSORATE13' => '',
'LNITEMCLAS13' => '', 'LNITEMCLAS13' => '',
'PKGTYPECOUNT13' => '', 'PKGTYPECOUNT13' => '',
'LNITEMWT12' => '', 'LNITEMWT12' => '',
'CLASSORATE12' => '', 'CLASSORATE12' => '',
'LNITEMCLAS12' => '', 'LNITEMCLAS12' => '',
'TYPEANDESCPTN.12' => '', 'TYPEANDESCPTN.12' => '',
'PKGTYPECOUNT12' => '', 'PKGTYPECOUNT12' => '',
'LNITEMWT11' => '', 'LNITEMWT11' => '',
'CLASSORATE11' => '', 'CLASSORATE11' => '',
'LNITEMCLAS11' => '', 'LNITEMCLAS11' => '',
'TYPEANDESCPTN.11' => '', 'TYPEANDESCPTN.11' => '',
'PKGTYPECOUNT11' => '', 'PKGTYPECOUNT11' => '',
'LNITEMWT10' => '', 'LNITEMWT10' => '',
'CLASSORATE10' => '', 'CLASSORATE10' => '',
'LNITEMCLAS10' => '', 'LNITEMCLAS10' => '',
'PKGTYPECOUNT10' => '', 'PKGTYPECOUNT10' => '',
'LNITEMWT9' => '', 'LNITEMWT9' => '',
'CLASSORATE9' => '', 'CLASSORATE9' => '',
'LNITEMCLAS8' => '', 'LNITEMCLAS8' => '',
'PKGTYPECOUNT9' => '', 'PKGTYPECOUNT9' => '',
'LNITEMWT8' => '', 'LNITEMWT8' => '',
'CLASSORATE8' => '', 'CLASSORATE8' => '',
'TYPEANDESCPTN.8' => '', 'TYPEANDESCPTN.8' => '',
'PKGTYPECOUNT8' => '', 'PKGTYPECOUNT8' => '',
'LNITEMWT7' => '', 'LNITEMWT7' => '',
'CLASSORATE7' => '', 'CLASSORATE7' => '',
'LNITEMCLAS7' => '', 'LNITEMCLAS7' => '',
'PKGTYPECOUNT7' => '', 'PKGTYPECOUNT7' => '',
'LNITEMWT6' => '', 'LNITEMWT6' => '',
'CLASSORATE6' => '', 'CLASSORATE6' => '',
'LNITEMCLAS6' => '', 'LNITEMCLAS6' => '',
'PKGTYPECOUNT6' => '', 'PKGTYPECOUNT6' => '',
'LNITEMWT5' => '', 'LNITEMWT5' => '',
'CLASSORATE5' => '', 'CLASSORATE5' => '',
'LNITEMCLAS5' => '', 'LNITEMCLAS5' => '',
'PKGTYPECOUNT5' => '', 'PKGTYPECOUNT5' => '',
'LNITEMWT4' => '', 'LNITEMWT4' => '',
'CLASSORATE4' => '', 'CLASSORATE4' => '',
'LNITEMCLAS4' => '', 'LNITEMCLAS4' => '',
'PKGTYPECOUNT4' => '', 'PKGTYPECOUNT4' => '',
'LNITEMWT3' => '', 'LNITEMWT3' => '',
'CLASSORATE3' => '', 'CLASSORATE3' => '',
'LNITEMCLAS3' => '', 'LNITEMCLAS3' => '',
'TYPEANDESCPTN.3' => '', 'TYPEANDESCPTN.3' => '',
'PKGTYPECOUNT3' => '', 'PKGTYPECOUNT3' => '',
'LNITEMWT2' => '', 'LNITEMWT2' => '',
'CLASSORATE2' => '', 'CLASSORATE2' => '',
'LNITEMCLAS2' => '', 'LNITEMCLAS2' => '',
'PKGTYPECOUNT2' => '', 'PKGTYPECOUNT2' => '',
'LNITEMCLAS1' => '', 'LNITEMCLAS1' => '',
'HAZLNITEMWT3' => '', 'HAZLNITEMWT3' => '',
'HAZCLASSORATE3' => '', 'HAZCLASSORATE3' => '',
'HAZLNITEMCLAS3' => '', 'HAZLNITEMCLAS3' => '',
'HAZMATERDESL3' => '', 'HAZMATERDESL3' => '',
'HAZMATERL3' => '', 'HAZMATERL3' => '',
'HAZLNITEMWT2' => '', 'HAZLNITEMWT2' => '',
'HAZCLASSORATE2' => '', 'HAZCLASSORATE2' => '',
'HAZLNITEMCLAS2' => '', 'HAZLNITEMCLAS2' => '',
'HAZMATERDESL2' => '', 'HAZMATERDESL2' => '',
'HAZMATERL2' => '', 'HAZMATERL2' => '',
'HAZLNITEMWT1' => '', 'HAZLNITEMWT1' => '',
'HAZCLASSORATE1' => '', 'HAZCLASSORATE1' => '',
'HAZLNITEMCLAS1' => '', 'HAZLNITEMCLAS1' => '',
'HAZMATERDESL1' => '', 'HAZMATERDESL1' => '',
'HAZMATERL1' => '', 'HAZMATERL1' => '',
'24HREMGCYRSPNS' => '', '24HREMGCYRSPNS' => '',
'CARIERFEDEMPID' => '', 'CARIERFEDEMPID' => '',
'BILLTOADDR' => '', 'BILLTOADDR' => '',
'NUMDROPS' => '', 'NUMDROPS' => '',
]; ];
@@ -228,8 +222,5 @@ Line 5',
return response()->json(['error' => $e->getMessage()], 500); return response()->json(['error' => $e->getMessage()], 500);
} }
} }
} }
+170 -173
View File
@@ -2,18 +2,16 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config;
use Storage;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use mikehaertl\pdftk\Pdf; use mikehaertl\pdftk\Pdf;
//use mikehaertl\tmp\File; use Storage;
// use mikehaertl\tmp\File;
class fillBOLController extends Controller class fillBOLController extends Controller
{ {
public static function index(Request $request) { public static function index(Request $request)
{
return view('m3::liberty-theme.pages.fillBOL'); return view('m3::liberty-theme.pages.fillBOL');
@@ -21,7 +19,7 @@ class fillBOLController extends Controller
public static function fillBOL(Request $request) public static function fillBOL(Request $request)
{ {
## $BOL = BOL::findOrFail($request); // # $BOL = BOL::findOrFail($request);
$BOL = $request; $BOL = $request;
$pdf = new Pdf(Storage::disk('public')->path('ETN-BOL.pdf')); $pdf = new Pdf(Storage::disk('public')->path('ETN-BOL.pdf'));
@@ -30,196 +28,195 @@ class fillBOLController extends Controller
// 'useExec' => true, // 'useExec' => true,
// ]); // ]);
if ($pdf === false) { if ($pdf === false) {
var_dump("step 1"); var_dump('step 1');
$error = $pdf->getError(); $error = $pdf->getError();
dd($error); dd($error);
} }
#$test = Storage::disk('public')->exists('ETN-BOL.pdf'); // $test = Storage::disk('public')->exists('ETN-BOL.pdf');
#dd($test); // dd($test);
$newfile="BOL-{$BOL['BOL_number']}.pdf"; $newfile = "BOL-{$BOL['BOL_number']}.pdf";
var_dump($newfile); var_dump($newfile);
$test = Storage::disk('public')->put($newfile, ''); $test = Storage::disk('public')->put($newfile, '');
if ($test === false) { if ($test === false) {
var_dump("step 2"); var_dump('step 2');
$error = $test->getError(); $error = $test->getError();
dd($error); dd($error);
} }
#$test=$pdf->addFile(Storage::disk('public')->path($newfile), 'A'); // $test=$pdf->addFile(Storage::disk('public')->path($newfile), 'A');
#dd($test); // dd($test);
$result = $pdf->fillForm([ $result = $pdf->fillForm([
'DTESHIPED.1' => date('d/m/Y'), 'DTESHIPED.1' => date('d/m/Y'),
'invoice_number' => $BOL['BOL_number'], 'invoice_number' => $BOL['BOL_number'],
'amount_due' => number_format($BOL['amount'], 2), 'amount_due' => number_format($BOL['amount'], 2),
'TYPEANDESCPTN.1' => 'TOTAL: 20 SKIDS 8320 #', 'TYPEANDESCPTN.1' => 'TOTAL: 20 SKIDS 8320 #',
'TYPEANDESCPTN.10' => 'ROTTERDAM ETA: 11/22', 'TYPEANDESCPTN.10' => 'ROTTERDAM ETA: 11/22',
'TYPEANDESCPTN.13' => 'CONTAINER:', 'TYPEANDESCPTN.13' => 'CONTAINER:',
'TYPEANDESCPTN.2' => 'MECHANICAL / CADDY/ ELECTRICAL', 'TYPEANDESCPTN.2' => 'MECHANICAL / CADDY/ ELECTRICAL',
'TYPEANDESCPTN.4' => 'BOOKING: 150744100', 'TYPEANDESCPTN.4' => 'BOOKING: 150744100',
'TYPEANDESCPTN.5' => 'REFERENCE: 3140028046', 'TYPEANDESCPTN.5' => 'REFERENCE: 3140028046',
'TYPEANDESCPTN.6' => 'VESSEL: INDEPENDENT HORIZON V. 1023E', 'TYPEANDESCPTN.6' => 'VESSEL: INDEPENDENT HORIZON V. 1023E',
'TYPEANDESCPTN.7' => 'SEAL: 637053', 'TYPEANDESCPTN.7' => 'SEAL: 637053',
'TYPEANDESCPTN.9' => 'CHESTER, PA ETD: 11/05', 'TYPEANDESCPTN.9' => 'CHESTER, PA ETD: 11/05',
'BOFLADNGAGYCD' => $BOL['BOL_number'], 'BOFLADNGAGYCD' => $BOL['BOL_number'],
'CLASSORATE1' => '50', 'CLASSORATE1' => '50',
'CNMETRKLICNSE' => 'ICL / Expeditors', 'CNMETRKLICNSE' => 'ICL / Expeditors',
'CONSIGTONMADDR' => 'ERICO EUROPE BV JULES VERNEWEG 75 TILBURG . 5015 BG', 'CONSIGTONMADDR' => 'ERICO EUROPE BV JULES VERNEWEG 75 TILBURG . 5015 BG',
'DATE' => date('d/m/Y'), 'DATE' => date('d/m/Y'),
'FRMNMADDR' => 'ERICO INTERNATIONAL CORP 6800 ARNOLD MILLER PARKWAY SOLON, OH 44139 USA', 'FRMNMADDR' => 'ERICO INTERNATIONAL CORP 6800 ARNOLD MILLER PARKWAY SOLON, OH 44139 USA',
'LNITEMWT1' => '8320', 'LNITEMWT1' => '8320',
'PARTOFMSTRBILL' => 'No', 'PARTOFMSTRBILL' => 'No',
'PKGTYPECOUNT1' => '20', 'PKGTYPECOUNT1' => '20',
'SHPRNMBR' => '3140028046', 'SHPRNMBR' => '3140028046',
'TOTALWT' => '8320', 'TOTALWT' => '8320',
'TOTPIECES' => '20', 'TOTPIECES' => '20',
'ckFREIGHTCOLECT' => 'Yes', 'ckFREIGHTCOLECT' => 'Yes',
'ckPREPAY' => 'Off', 'ckPREPAY' => 'Off',
'DTESHIPED.2' => '', 'DTESHIPED.2' => '',
'LNITEMWT24' => '', 'LNITEMWT24' => '',
'CLASSORATE24' => '', 'CLASSORATE24' => '',
'LNITEMCLAS24' => '', 'LNITEMCLAS24' => '',
'TYPEANDESCPTN.24' => '', 'TYPEANDESCPTN.24' => '',
'PKGTYPECOUNT24' => '', 'PKGTYPECOUNT24' => '',
'LNITEMWT23' => '', 'LNITEMWT23' => '',
'CLASSORATE23' => '', 'CLASSORATE23' => '',
'LNITEMCLAS23' => '', 'LNITEMCLAS23' => '',
'TYPEANDESCPTN.23' => '', 'TYPEANDESCPTN.23' => '',
'PKGTYPECOUNT23' => '', 'PKGTYPECOUNT23' => '',
'LNITEMWT22' => '', 'LNITEMWT22' => '',
'CLASSORATE22' => '', 'CLASSORATE22' => '',
'LNITEMCLAS22' => '', 'LNITEMCLAS22' => '',
'TYPEANDESCPTN.22' => '', 'TYPEANDESCPTN.22' => '',
'PKGTYPECOUNT22' => '', 'PKGTYPECOUNT22' => '',
'LNITEMWT21' => '', 'LNITEMWT21' => '',
'CLASSORATE21' => '', 'CLASSORATE21' => '',
'LNITEMCLAS21' => '', 'LNITEMCLAS21' => '',
'TYPEANDESCPTN.21' => '', 'TYPEANDESCPTN.21' => '',
'PKGTYPECOUNT21' => '', 'PKGTYPECOUNT21' => '',
'LNITEMWT20' => '', 'LNITEMWT20' => '',
'CLASSORATE20' => '', 'CLASSORATE20' => '',
'LNITEMCLAS20' => '', 'LNITEMCLAS20' => '',
'TYPEANDESCPTN.20' => '', 'TYPEANDESCPTN.20' => '',
'PKGTYPECOUNT20' => '', 'PKGTYPECOUNT20' => '',
'LNITEMWT19' => '', 'LNITEMWT19' => '',
'CLASSORATE19' => '', 'CLASSORATE19' => '',
'LNITEMCLAS19' => '', 'LNITEMCLAS19' => '',
'TYPEANDESCPTN.19' => '', 'TYPEANDESCPTN.19' => '',
'PKGTYPECOUNT19' => '', 'PKGTYPECOUNT19' => '',
'LNITEMWT18' => '', 'LNITEMWT18' => '',
'CLASSORATE18' => '', 'CLASSORATE18' => '',
'LNITEMCLAS18' => '', 'LNITEMCLAS18' => '',
'TYPEANDESCPTN.18' => '', 'TYPEANDESCPTN.18' => '',
'PKGTYPECOUNT18' => '', 'PKGTYPECOUNT18' => '',
'LNITEMWT17' => '', 'LNITEMWT17' => '',
'CLASSORATE17' => '', 'CLASSORATE17' => '',
'LNITEMCLAS17' => '', 'LNITEMCLAS17' => '',
'TYPEANDESCPTN.17' => '', 'TYPEANDESCPTN.17' => '',
'PKGTYPECOUNT17' => '', 'PKGTYPECOUNT17' => '',
'LNITEMWT16' => '', 'LNITEMWT16' => '',
'CLASSORATE16' => '', 'CLASSORATE16' => '',
'LNITEMCLAS16' => '', 'LNITEMCLAS16' => '',
'TYPEANDESCPTN.16' => '', 'TYPEANDESCPTN.16' => '',
'PKGTYPECOUNT16' => '', 'PKGTYPECOUNT16' => '',
'LNITEMWT15' => '', 'LNITEMWT15' => '',
'CLASSORATE15' => '', 'CLASSORATE15' => '',
'LNITEMCLAS15' => '', 'LNITEMCLAS15' => '',
'TYPEANDESCPTN.15' => '', 'TYPEANDESCPTN.15' => '',
'PKGTYPECOUNT15' => '', 'PKGTYPECOUNT15' => '',
'LNITEMWT14' => '', 'LNITEMWT14' => '',
'CLASSORAT14' => '', 'CLASSORAT14' => '',
'LNITEMCLAS14' => '', 'LNITEMCLAS14' => '',
'TYPEANDESCPTN.14' => '', 'TYPEANDESCPTN.14' => '',
'PKGTYPECOUNT14' => '', 'PKGTYPECOUNT14' => '',
'LNITEMWT13' => '', 'LNITEMWT13' => '',
'CLASSORATE13' => '', 'CLASSORATE13' => '',
'LNITEMCLAS13' => '', 'LNITEMCLAS13' => '',
'PKGTYPECOUNT13' => '', 'PKGTYPECOUNT13' => '',
'LNITEMWT12' => '', 'LNITEMWT12' => '',
'CLASSORATE12' => '', 'CLASSORATE12' => '',
'LNITEMCLAS12' => '', 'LNITEMCLAS12' => '',
'TYPEANDESCPTN.12' => '', 'TYPEANDESCPTN.12' => '',
'PKGTYPECOUNT12' => '', 'PKGTYPECOUNT12' => '',
'LNITEMWT11' => '', 'LNITEMWT11' => '',
'CLASSORATE11' => '', 'CLASSORATE11' => '',
'LNITEMCLAS11' => '', 'LNITEMCLAS11' => '',
'TYPEANDESCPTN.11' => '', 'TYPEANDESCPTN.11' => '',
'PKGTYPECOUNT11' => '', 'PKGTYPECOUNT11' => '',
'LNITEMWT10' => '', 'LNITEMWT10' => '',
'CLASSORATE10' => '', 'CLASSORATE10' => '',
'LNITEMCLAS10' => '', 'LNITEMCLAS10' => '',
'PKGTYPECOUNT10' => '', 'PKGTYPECOUNT10' => '',
'LNITEMWT9' => '', 'LNITEMWT9' => '',
'CLASSORATE9' => '', 'CLASSORATE9' => '',
'LNITEMCLAS8' => '', 'LNITEMCLAS8' => '',
'PKGTYPECOUNT9' => '', 'PKGTYPECOUNT9' => '',
'LNITEMWT8' => '', 'LNITEMWT8' => '',
'CLASSORATE8' => '', 'CLASSORATE8' => '',
'TYPEANDESCPTN.8' => '', 'TYPEANDESCPTN.8' => '',
'PKGTYPECOUNT8' => '', 'PKGTYPECOUNT8' => '',
'LNITEMWT7' => '', 'LNITEMWT7' => '',
'CLASSORATE7' => '', 'CLASSORATE7' => '',
'LNITEMCLAS7' => '', 'LNITEMCLAS7' => '',
'PKGTYPECOUNT7' => '', 'PKGTYPECOUNT7' => '',
'LNITEMWT6' => '', 'LNITEMWT6' => '',
'CLASSORATE6' => '', 'CLASSORATE6' => '',
'LNITEMCLAS6' => '', 'LNITEMCLAS6' => '',
'PKGTYPECOUNT6' => '', 'PKGTYPECOUNT6' => '',
'LNITEMWT5' => '', 'LNITEMWT5' => '',
'CLASSORATE5' => '', 'CLASSORATE5' => '',
'LNITEMCLAS5' => '', 'LNITEMCLAS5' => '',
'PKGTYPECOUNT5' => '', 'PKGTYPECOUNT5' => '',
'LNITEMWT4' => '', 'LNITEMWT4' => '',
'CLASSORATE4' => '', 'CLASSORATE4' => '',
'LNITEMCLAS4' => '', 'LNITEMCLAS4' => '',
'PKGTYPECOUNT4' => '', 'PKGTYPECOUNT4' => '',
'LNITEMWT3' => '', 'LNITEMWT3' => '',
'CLASSORATE3' => '', 'CLASSORATE3' => '',
'LNITEMCLAS3' => '', 'LNITEMCLAS3' => '',
'TYPEANDESCPTN.3' => '', 'TYPEANDESCPTN.3' => '',
'PKGTYPECOUNT3' => '', 'PKGTYPECOUNT3' => '',
'LNITEMWT2' => '', 'LNITEMWT2' => '',
'CLASSORATE2' => '', 'CLASSORATE2' => '',
'LNITEMCLAS2' => '', 'LNITEMCLAS2' => '',
'PKGTYPECOUNT2' => '', 'PKGTYPECOUNT2' => '',
'LNITEMCLAS1' => '', 'LNITEMCLAS1' => '',
'HAZLNITEMWT3' => '', 'HAZLNITEMWT3' => '',
'HAZCLASSORATE3' => '', 'HAZCLASSORATE3' => '',
'HAZLNITEMCLAS3' => '', 'HAZLNITEMCLAS3' => '',
'HAZMATERDESL3' => '', 'HAZMATERDESL3' => '',
'HAZMATERL3' => '', 'HAZMATERL3' => '',
'HAZLNITEMWT2' => '', 'HAZLNITEMWT2' => '',
'HAZCLASSORATE2' => '', 'HAZCLASSORATE2' => '',
'HAZLNITEMCLAS2' => '', 'HAZLNITEMCLAS2' => '',
'HAZMATERDESL2' => '', 'HAZMATERDESL2' => '',
'HAZMATERL2' => '', 'HAZMATERL2' => '',
'HAZLNITEMWT1' => '', 'HAZLNITEMWT1' => '',
'HAZCLASSORATE1' => '', 'HAZCLASSORATE1' => '',
'HAZLNITEMCLAS1' => '', 'HAZLNITEMCLAS1' => '',
'HAZMATERDESL1' => '', 'HAZMATERDESL1' => '',
'HAZMATERL1' => '', 'HAZMATERL1' => '',
'24HREMGCYRSPNS' => '', '24HREMGCYRSPNS' => '',
'CARIERFEDEMPID' => '', 'CARIERFEDEMPID' => '',
'BILLTOADDR' => '', 'BILLTOADDR' => '',
'NUMDROPS' => '', 'NUMDROPS' => '',
]) ])
->needAppearances() // ensures values are visible in viewer ->needAppearances() // ensures values are visible in viewer
->saveAs(Storage::disk('public')->path($newfile)); ->saveAs(Storage::disk('public')->path($newfile));
// Always check for errors // Always check for errors
if ($result === false) { if ($result === false) {
var_dump("step 3"); var_dump('step 3');
$error = $pdf->getError(); $error = $pdf->getError();
dd($error); dd($error);
} else { } else {
return response()->file(Storage::disk('public')->path($newfile)); return response()->file(Storage::disk('public')->path($newfile));
dd("step 4"); dd('step 4');
} }
} }
} }
@@ -2,74 +2,80 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use DB;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response; use Illuminate\Support\Facades\Schema;
use Modules\M3\Models\ICM709M; use Modules\M3\Models\ICM709M;
class palletQtyController extends Controller class palletQtyController extends Controller
{ {
public static function index(Request $request)
public static function index(Request $request) { {
$connection = config('m3.connection', 'pgsql'); $connection = config('m3.connection', 'pgsql');
$power_user = (object) ['R428PWRUSR'=>'N','R428US'=>strtoUpper(m3_user()),'R428CO'=>'','R428PL'=>'','R428WH'=>'']; $power_user = (object) ['R428PWRUSR' => 'N', 'R428US' => strtoupper(m3_user()), 'R428CO' => '', 'R428PL' => '', 'R428WH' => ''];
if (\Illuminate\Support\Facades\Schema::connection($connection)->hasTable('icm428m')) { if (Schema::connection($connection)->hasTable('icm428m')) {
$power_user = DB::connection($connection)->table('icm428m') $power_user = DB::connection($connection)->table('icm428m')
->select('R428PWRUSR','R428US','R428CO','R428PL','R428WH') ->select('R428PWRUSR', 'R428US', 'R428CO', 'R428PL', 'R428WH')
->where('R428US','=',strtoUpper(m3_user()))->first() ?? $power_user; ->where('R428US', '=', strtoupper(m3_user()))->first() ?? $power_user;
} }
$co=$power_user->R428CO; $plant=$power_user->R428PL; $whs=$power_user->R428WH; $co = $power_user->R428CO;
$ICM709M = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('icm709m') $plant = $power_user->R428PL;
? DB::connection($connection)->table('icm709m')->where('AT9CO',$co)->where('AT9PLT',$plant)->where('AT9WHS',$whs)->get() : collect(); $whs = $power_user->R428WH;
$IC670M = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('ic670m') $ICM709M = Schema::connection($connection)->hasTable('icm709m')
? DB::connection($connection)->table('ic670m')->where('WDCO',$co)->where('WDPL',$plant)->where('WDWHS',$whs)->get() : collect(); ? DB::connection($connection)->table('icm709m')->where('AT9CO', $co)->where('AT9PLT', $plant)->where('AT9WHS', $whs)->get() : collect();
return view('m3::liberty-theme.pages.palletQty', compact('ICM709M','IC670M','power_user')); $IC670M = Schema::connection($connection)->hasTable('ic670m')
? DB::connection($connection)->table('ic670m')->where('WDCO', $co)->where('WDPL', $plant)->where('WDWHS', $whs)->get() : collect();
return view('m3::liberty-theme.pages.palletQty', compact('ICM709M', 'IC670M', 'power_user'));
} }
// //
// Process data from Add modal // Process data from Add modal
// //
public static function saveQtyAdd(Request $request) { public static function saveQtyAdd(Request $request)
{
// Insert record to ICM709M // Insert record to ICM709M
#var_dump($request); // var_dump($request);
#console.log($request); // console.log($request);
// Verify record does not already exist in ICM709M // Verify record does not already exist in ICM709M
$icm709m=DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from ICM709M $icm709m = DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from ICM709M
where AT9CO='$request->AT9CO' and AT9PLT='$request->AT9PLT' and AT9WHS='$request->AT9WHS' and AT9PART='$request->AT9PART'"); where AT9CO='$request->AT9CO' and AT9PLT='$request->AT9PLT' and AT9WHS='$request->AT9WHS' and AT9PART='$request->AT9PART'");
if($icm709m[0]->COUNT1>="1") { if ($icm709m[0]->COUNT1 >= '1') {
return "exists"; return 'exists';
} else { } else {
// Verify Part# already exists in ICM630M // Verify Part# already exists in ICM630M
$ic630m= DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from IC630M $ic630m = DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from IC630M
where LLCO='$request->AT9CO' and LLWHNO='$request->AT9WHS' and LLPPN='$request->AT9PART'"); where LLCO='$request->AT9CO' and LLWHNO='$request->AT9WHS' and LLPPN='$request->AT9PART'");
if($ic630m[0]->COUNT1=="0") { if ($ic630m[0]->COUNT1 == '0') {
return "not exist"; return 'not exist';
} else { } else {
DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM709M (AT9CO, AT9PLT, AT9WHS, AT9PART, AT9QTY, AT9WRN) DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM709M (AT9CO, AT9PLT, AT9WHS, AT9PART, AT9QTY, AT9WRN)
values ('$request->AT9CO', '$request->AT9PLT', '$request->AT9WHS', '$request->AT9PART', '$request->AT9QTY', '$request->AT9WRN')"); values ('$request->AT9CO', '$request->AT9PLT', '$request->AT9WHS', '$request->AT9PART', '$request->AT9QTY', '$request->AT9WRN')");
return "success";
return 'success';
} }
} }
} }
public static function saveQtyAdd2(Request $request) {
public static function saveQtyAdd2(Request $request)
{
// Insert record to ICM709M // Insert record to ICM709M
#var_dump($request); // var_dump($request);
#console.log($request); // console.log($request);
// Verify record does not already exist in ICM709M // Verify record does not already exist in ICM709M
//DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM709M (AT9CO, AT9PLT, AT9WHS, AT9PART, AT9QTY) // DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM709M (AT9CO, AT9PLT, AT9WHS, AT9PART, AT9QTY)
// values ('$request->AT9CO', '$request->AT9PLT', '$request->AT9WHS', '$request->AT9PART', '$request->AT9QTY')"); // values ('$request->AT9CO', '$request->AT9PLT', '$request->AT9WHS', '$request->AT9PART', '$request->AT9QTY')");
// $data=['AT9CO'=>$request->AT9CO, 'AT9PLT'=>$request->AT9PLT, 'AT9WHS'=>$request->AT9WHS, 'AT9PART'=>$request->AT9PART, // $data=['AT9CO'=>$request->AT9CO, 'AT9PLT'=>$request->AT9PLT, 'AT9WHS'=>$request->AT9WHS, 'AT9PART'=>$request->AT9PART,
// 'AT9QTY'=>$request->AT9QTY, 'AT9WRN'=>$request->AT9WRN]; // 'AT9QTY'=>$request->AT9QTY, 'AT9WRN'=>$request->AT9WRN];
// $insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('icm709m')->insert($data); // $insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('icm709m')->insert($data);
DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM709M (AT9CO, AT9PLT, AT9WHS, AT9PART, AT9QTY, AT9WRN) DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM709M (AT9CO, AT9PLT, AT9WHS, AT9PART, AT9QTY, AT9WRN)
values ('$request->AT9CO', '$request->AT9PLT', '$request->AT9WHS', '$request->AT9PART', '$request->AT9QTY', '$request->AT9WRN')"); values ('$request->AT9CO', '$request->AT9PLT', '$request->AT9WHS', '$request->AT9PART', '$request->AT9QTY', '$request->AT9WRN')");
// if($insertSQL) { // if($insertSQL) {
return "success"; return 'success';
// } // }
} }
@@ -77,21 +83,21 @@ class palletQtyController extends Controller
// //
// Process data from Edit modal // Process data from Edit modal
// //
public static function saveQtyEdit(Request $request) { public static function saveQtyEdit(Request $request)
{
#dump($request); // dump($request);
#console.log($request); // console.log($request);
//$icm709m=DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from ICM709M // $icm709m=DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from ICM709M
// where AT9CO='$request->AT9CO' and AT9PLT='$request->AT9PLT' and AT9WHS='$request->AT9WHS' and AT9PART='$request->AT9PART'"); // where AT9CO='$request->AT9CO' and AT9PLT='$request->AT9PLT' and AT9WHS='$request->AT9WHS' and AT9PART='$request->AT9PART'");
//var_dump($icm709m); // var_dump($icm709m);
DB::connection(config('m3.connection', 'pgsql'))->update("update ICM709M DB::connection(config('m3.connection', 'pgsql'))->update("update ICM709M
set AT9QTY='$request->AT9QTY', AT9WRN='$request->AT9WRN' set AT9QTY='$request->AT9QTY', AT9WRN='$request->AT9WRN'
where AT9CO='$request->AT9CO' and AT9PLT='$request->AT9PLT' and AT9WHS='$request->AT9WHS' and AT9PART='$request->AT9PART'"); where AT9CO='$request->AT9CO' and AT9PLT='$request->AT9PLT' and AT9WHS='$request->AT9WHS' and AT9PART='$request->AT9PART'");
return "success"; return 'success';
} }
} }
@@ -1,28 +1,28 @@
<?php <?php
#732
// 732
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use DB; use DB;
use Config;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
class pendingClosureController extends Controller class pendingClosureController extends Controller
{ {
public static function index(Request $request) public static function index(Request $request)
{ {
# Get Users from ICM428M // Get Users from ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH', 'R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US','=',strtoUpper(m3_user())) ->where('R428US', '=', strtoupper(m3_user()))
->first(); ->first();
$user = $ICM428M->R428US; $user = $ICM428M->R428US;
$co = $ICM428M->R428CO; $co = $ICM428M->R428CO;
$whs = $ICM428M->R428WH; $whs = $ICM428M->R428WH;
$plant = $ICM428M->R428PL; $plant = $ICM428M->R428PL;
# ICM705M1 Statement // ICM705M1 Statement
$sqlstmt = "select APMANIFEST,APDOCKDOOR,APCARRIER,APTRUCKIDT,APSPARE1,APLDSTRU,APLDSTRD,APLDSTRT, $sqlstmt = "select APMANIFEST,APDOCKDOOR,APCARRIER,APTRUCKIDT,APSPARE1,APLDSTRU,APLDSTRD,APLDSTRT,
APLDCLOU,APLDCLOD,APLDCLOT,APCO,APWHS,APPLT,APSPARE2,APLDCLOZ APLDCLOU,APLDCLOD,APLDCLOT,APCO,APWHS,APPLT,APSPARE2,APLDCLOZ
from ICM705M1 from ICM705M1
@@ -30,92 +30,90 @@ class pendingClosureController extends Controller
$ICM705M1 = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt); $ICM705M1 = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt);
$ICM698Ma=array(); $ICM698Ma = [];
$ICM699Ma=array(); $ICM699Ma = [];
foreach($ICM705M1 as $key=>$val) { foreach ($ICM705M1 as $key => $val) {
$sqlstmt1="select LGUSER,LGCONFDT,LGCONFTM $sqlstmt1 = "select LGUSER,LGCONFDT,LGCONFTM
from ICM698M from ICM698M
where LGCO='$val->APCO' and LGWHS='$val->APWHS'and LGURL='op605api.php' where LGCO='$val->APCO' and LGWHS='$val->APWHS'and LGURL='op605api.php'
and LGRESPONSE like 'Close of Sentinel Manifest%' and LGRESPONSE like 'Close of Sentinel Manifest%'
and LGRESPONSE like '%' || right('000000000' || '$val->APMANIFEST',9) || '%'"; and LGRESPONSE like '%' || right('000000000' || '$val->APMANIFEST',9) || '%'";
$ICM698M = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt1); $ICM698M = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt1);
$ICM698Ma[$val->APMANIFEST]['TMSUSER']=''; $ICM698Ma[$val->APMANIFEST]['TMSUSER'] = '';
$ICM698Ma[$val->APMANIFEST]['TMSDATE']=''; $ICM698Ma[$val->APMANIFEST]['TMSDATE'] = '';
$ICM698Ma[$val->APMANIFEST]['TMSTIME']=''; $ICM698Ma[$val->APMANIFEST]['TMSTIME'] = '';
foreach($ICM698M as $key2=>$val2) { foreach ($ICM698M as $key2 => $val2) {
$ICM698Ma[$val->APMANIFEST]['TMSUSER']=$val2->LGUSER; $ICM698Ma[$val->APMANIFEST]['TMSUSER'] = $val2->LGUSER;
$ICM698Ma[$val->APMANIFEST]['TMSDATE']=$val2->LGCONFDT; $ICM698Ma[$val->APMANIFEST]['TMSDATE'] = $val2->LGCONFDT;
$ICM698Ma[$val->APMANIFEST]['TMSTIME']=$val2->LGCONFTM; $ICM698Ma[$val->APMANIFEST]['TMSTIME'] = $val2->LGCONFTM;
} }
$ICM699MSel1 = "select SHMACPKR,SHDT,SHTIME from ICM699M
$ICM699MSel1 ="select SHMACPKR,SHDT,SHTIME from ICM699M
WHERE SHMACPKR='$val->APMANIFEST' AND SHCO='$co' AND SHWHS='$whs' WHERE SHMACPKR='$val->APMANIFEST' AND SHCO='$co' AND SHWHS='$whs'
AND SHSOURCE='CloseShipmentCoChargeAPI' AND SHERROR='' AND SHTYPE='M3-Req-out' limit 1"; AND SHSOURCE='CloseShipmentCoChargeAPI' AND SHERROR='' AND SHTYPE='M3-Req-out' limit 1";
$ICM699MSel = DB::connection(config('m3.connection', 'pgsql'))->select($ICM699MSel1); $ICM699MSel = DB::connection(config('m3.connection', 'pgsql'))->select($ICM699MSel1);
foreach($ICM699MSel as $key2=>$val2) { foreach ($ICM699MSel as $key2 => $val2) {
$ICM699Ma[$val2->SHMACPKR]['SHDT'] = $val2->SHDT; $ICM699Ma[$val2->SHMACPKR]['SHDT'] = $val2->SHDT;
$ICM699Ma[$val2->SHMACPKR]['SHTIME'] = $val2->SHTIME; $ICM699Ma[$val2->SHMACPKR]['SHTIME'] = $val2->SHTIME;
} }
} }
// dump($ICM699Ma); // dump($ICM699Ma);
$sqlstmt = "select count(*) as COUNT1 from ICM699M
$sqlstmt="select count(*) as COUNT1 from ICM699M
where SHCO='$co' and SHWHS='$whs' and SHTYPE like '%M3%' and SHERROR='X' where SHCO='$co' and SHWHS='$whs' and SHTYPE like '%M3%' and SHERROR='X'
and SHSOURCE='CloseShipmentCoChargeAPI'"; and SHSOURCE='CloseShipmentCoChargeAPI'";
$ICM699M = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt); $ICM699M = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt);
# Get Unprocessed Orders // Get Unprocessed Orders
$unprocessedArr = array(); $unprocessedArr = [];
$sqlstmt3 = "WITH TEMPFILE AS ( $sqlstmt3 = "WITH TEMPFILE AS (
SELECT A4MACPKR,A4SPKRFUD,(SELECT AYAPRF1551 FROM ICM695M1 WHERE AYMACPKR=A4MACPKR AND AYSLWHS='$whs' FETCH FIRST 1 ROWS ONLY) AS MF FROM ICM688M1 SELECT A4MACPKR,A4SPKRFUD,(SELECT AYAPRF1551 FROM ICM695M1 WHERE AYMACPKR=A4MACPKR AND AYSLWHS='$whs' FETCH FIRST 1 ROWS ONLY) AS MF FROM ICM688M1
WHERE A4PICKSTS='B' AND A4WHS='$whs' ORDER BY A4SPKRFUD WHERE A4PICKSTS='B' AND A4WHS='$whs' ORDER BY A4SPKRFUD
) )
SELECT APMANIFEST,APSPARE2 FROM ICM705M1 WHERE APMANIFEST IN (SELECT DISTINCT MF FROM TEMPFILE) AND APSPARE2='X' AND APWHS='$whs' "; SELECT APMANIFEST,APSPARE2 FROM ICM705M1 WHERE APMANIFEST IN (SELECT DISTINCT MF FROM TEMPFILE) AND APSPARE2='X' AND APWHS='$whs' ";
// AND APSPARE2!='' // AND APSPARE2!=''
// dump($sqlstmt3); // dump($sqlstmt3);
$UproccessedOrders = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt3); $UproccessedOrders = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt3);
foreach($UproccessedOrders as $key=>$UproccessedOrder) { foreach ($UproccessedOrders as $key => $UproccessedOrder) {
// $unprocessedArr[] = $UproccessedOrder->APMANIFEST; // $unprocessedArr[] = $UproccessedOrder->APMANIFEST;
$unprocessedArr[] = '<a class="btn btn-link mb-1" target="_blank" href="'.url('MFOrders', ['id' => trim($UproccessedOrder->APMANIFEST)]).'"> '. $unprocessedArr[] = '<a class="btn btn-link mb-1" target="_blank" href="' . url('MFOrders', ['id' => trim($UproccessedOrder->APMANIFEST)]) . '"> ' .
trim($UproccessedOrder->APMANIFEST).'</a>'; trim($UproccessedOrder->APMANIFEST) . '</a>';
} }
// dump($unprocessedArr); // dump($unprocessedArr);
return view('m3::liberty-theme.pages.pendingClosure', return view(
compact('ICM705M1', 'ICM698Ma', 'ICM699M', 'user', 'request','unprocessedArr','ICM699Ma') 'm3::liberty-theme.pages.pendingClosure',
compact('ICM705M1', 'ICM698Ma', 'ICM699M', 'user', 'request', 'unprocessedArr', 'ICM699Ma'),
); );
} }
public static function allowRetry(Request $request){ public static function allowRetry(Request $request)
# Get URL PARAMS {
$urlParams = count($request->all())>0 ? $request->all() : ''; // Get URL PARAMS
// dd($urlParams); $urlParams = count($request->all()) > 0 ? $request->all() : '';
// $SHUSER = isset($urlParams["SHUSER"]) ? $urlParams["SHUSER"] : ''; // dd($urlParams);
$MANIFEST = isset($urlParams["MANIFEST"]) ? $urlParams["MANIFEST"] : ''; // $SHUSER = isset($urlParams["SHUSER"]) ? $urlParams["SHUSER"] : '';
$APCO = isset($urlParams["APCO"]) ? $urlParams["APCO"] : ''; $MANIFEST = isset($urlParams['MANIFEST']) ? $urlParams['MANIFEST'] : '';
$APWHS = isset($urlParams["APWHS"]) ? $urlParams["APWHS"] : ''; $APCO = isset($urlParams['APCO']) ? $urlParams['APCO'] : '';
$APWHS = isset($urlParams['APWHS']) ? $urlParams['APWHS'] : '';
try { try {
DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1') DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1')
->where('APCO',$APCO) ->where('APCO', $APCO)
->where('APWHS',$APWHS) ->where('APWHS', $APWHS)
->where('APMANIFEST','=',$MANIFEST) ->where('APMANIFEST', '=', $MANIFEST)
->update(['APSPARE2'=>'']); ->update(['APSPARE2' => '']);
return response()->json([
'code' => '200',
'status' => 'Success',
'message'=> 'Manifest Closing submitted'
]);
} catch (\Throwable $th) {
//throw $th;
}
return response()->json([
'code' => '200',
'status' => 'Success',
'message' => 'Manifest Closing submitted',
]);
} catch (\Throwable $th) {
// throw $th;
}
} }
} }
@@ -2,55 +2,50 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB; use DB;
use Config;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Modules\M3\Models\ICM428M;
class sentinelController extends Controller class sentinelController extends Controller
{ {
public static function packSyst5Func(Request $request)
{
public static function packSyst5Func(Request $request) { $AYINTBOX = isset($request->AYINTBOX) ? trim($request->AYINTBOX) : '';
$AYCO = isset($request->AYCO) ? trim($request->AYCO) : '';
$AYWHS = isset($request->AYWHS) ? trim($request->AYWHS) : '';
$AYUSER = isset($request->AYUSER) ? trim($request->AYUSER) : '';
$AYINTBOX = isset($request->AYINTBOX) ? trim($request->AYINTBOX) : ''; if ($AYINTBOX != '') {
$AYCO = isset($request->AYCO) ? trim($request->AYCO) : ''; // Get the record from ICM695M1
$AYWHS = isset($request->AYWHS) ? trim($request->AYWHS) : ''; $ICM695M1Sel = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
$AYUSER = isset($request->AYUSER) ? trim($request->AYUSER) : '';
if ($AYINTBOX!='') {
# Get the record from ICM695M1
$ICM695M1Sel = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
->select() ->select()
->where('AYINTBOX',$AYINTBOX) ->where('AYINTBOX', $AYINTBOX)
->where('AYCO',$AYCO) ->where('AYCO', $AYCO)
->where('AYWHS',$AYWHS) ->where('AYWHS', $AYWHS)
->where('AYSTATUS','') ->where('AYSTATUS', '')
->first(); ->first();
$allowDeletion = isset($ICM695M1Sel->AYSENTPKR) ? ($ICM695M1Sel->AYSENTPKR !='' ? true : false ) : false; $allowDeletion = isset($ICM695M1Sel->AYSENTPKR) ? ($ICM695M1Sel->AYSENTPKR != '' ? true : false) : false;
if ($allowDeletion) { if ($allowDeletion) {
$timestamp = date('Y-m-d H:i:s.u'); $timestamp = date('Y-m-d H:i:s.u');
$date1 = date('Ymd'); $date1 = date('Ymd');
$time1 = date('His'); $time1 = date('His');
# Delete Records from ICM695M1 And ICM695M2 // Delete Records from ICM695M1 And ICM695M2
$ICM695M1Del = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1') $ICM695M1Del = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
->where('AYINTBOX',$AYINTBOX) ->where('AYINTBOX', $AYINTBOX)
->where('AYCO',$AYCO) ->where('AYCO', $AYCO)
->where('AYWHS',$AYWHS) ->where('AYWHS', $AYWHS)
->delete(); ->delete();
$ICM695M2Del = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m2') $ICM695M2Del = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m2')
->where('AZINTBOX',$AYINTBOX) ->where('AZINTBOX', $AYINTBOX)
->where('AZCO',$AYCO) ->where('AZCO', $AYCO)
->where('AZWHS',$AYWHS) ->where('AZWHS', $AYWHS)
->delete(); ->delete();
# Log the event as an unusual transaction to appear on SPD bottom right: // Log the event as an unusual transaction to appear on SPD bottom right:
$InsertValues = "'$ICM695M1Sel->AYCO', '$ICM695M1Sel->AYWHS', '$ICM695M1Sel->AYSENTPKR', '$ICM695M1Sel->AYMACPKR', '$ICM695M1Sel->AYONO', '$ICM695M1Sel->AYRLNO', '$ICM695M1Sel->AYSHNO', '', 'Box $AYINTBOX emptied and repacked', $InsertValues = "'$ICM695M1Sel->AYCO', '$ICM695M1Sel->AYWHS', '$ICM695M1Sel->AYSENTPKR', '$ICM695M1Sel->AYMACPKR', '$ICM695M1Sel->AYONO', '$ICM695M1Sel->AYRLNO', '$ICM695M1Sel->AYSHNO', '', 'Box $AYINTBOX emptied and repacked',
'$timestamp', '$date1', '$time1', '$AYUSER','$timestamp', '$date1', '$time1', '$AYUSER','$AYINTBOX'"; '$timestamp', '$date1', '$time1', '$AYUSER','$timestamp', '$date1', '$time1', '$AYUSER','$AYINTBOX'";
@@ -58,16 +53,13 @@ class sentinelController extends Controller
(A7CO, A7WHS, A7SENTPKR, A7MACPKR, A7ONO, A7RLNO, A7SHNO, A7SOURCE, A7ERRMSG, A7DISRAITS, A7DISRAID, A7DISRAIT, A7DISRAIU, A7DISRESTS ,A7DISRESD ,A7DISREST ,A7DISRESU , A7SPR15A01) (A7CO, A7WHS, A7SENTPKR, A7MACPKR, A7ONO, A7RLNO, A7SHNO, A7SOURCE, A7ERRMSG, A7DISRAITS, A7DISRAID, A7DISRAIT, A7DISRAIU, A7DISRESTS ,A7DISRESD ,A7DISREST ,A7DISRESU , A7SPR15A01)
values ($InsertValues)"); values ($InsertValues)");
return response()->json(['success'=>true , 'message' => 'Line Deleted']); return response()->json(['success' => true, 'message' => 'Line Deleted']);
} else {
return response()->json(['success' => false, 'message' => 'Line already packed']);
} }
else{ } else {
return response()->json(['success'=>false , 'message' => 'Line already packed']); return response()->json(['success' => false, 'message' => 'Line missing']);
}
}
else{
return response()->json(['success'=>false , 'message' => 'Line missing']);
} }
} }
} }
@@ -2,129 +2,135 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use DB;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response; use Illuminate\Support\Facades\Schema;
use Modules\M3\Models\ICM428M; use Modules\M3\Models\ICM428M;
use Modules\M3\Services\PostgresProgramBridge;
class userControlController extends Controller class userControlController extends Controller
{ {
public static function index(Request $request)
public static function index(Request $request) { {
$connection = config('m3.connection', 'pgsql'); $connection = config('m3.connection', 'pgsql');
$profile = null; $profile = null;
if (\Illuminate\Support\Facades\Schema::connection($connection)->hasTable('icm428m')) { if (Schema::connection($connection)->hasTable('icm428m')) {
$profile = DB::connection($connection)->table('icm428m')->where('R428US',strtoUpper(m3_user()))->first(); $profile = DB::connection($connection)->table('icm428m')->where('R428US', strtoupper(m3_user()))->first();
} }
$co=$profile->R428CO ?? ''; $whs=$profile->R428WH ?? ''; $co = $profile->R428CO ?? '';
$ICM428M = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('icm428m') $whs = $profile->R428WH ?? '';
? DB::connection($connection)->table('icm428m')->where('R428CO',$co)->where('R428WH',$whs)->get() : collect(); $ICM428M = Schema::connection($connection)->hasTable('icm428m')
$USER_INFO = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('icm428m') ? DB::connection($connection)->table('icm428m')->where('R428CO', $co)->where('R428WH', $whs)->get() : collect();
$USER_INFO = Schema::connection($connection)->hasTable('icm428m')
? DB::connection($connection)->table('icm428m')->selectRaw('R428US as USERPRF, R428STS as STATUS, NULL as DATE_EXPIRED, NULL as EXPIRED')->get()->all() : []; ? DB::connection($connection)->table('icm428m')->selectRaw('R428US as USERPRF, R428STS as STATUS, NULL as DATE_EXPIRED, NULL as EXPIRED')->get()->all() : [];
$power_user = [(object)['R428PWRUSR'=>$profile->R428PWRUSR ?? 'N','R428CO'=>$co,'R428PL'=>$profile->R428PL ?? '','R428WH'=>$whs]]; $power_user = [(object) ['R428PWRUSR' => $profile->R428PWRUSR ?? 'N', 'R428CO' => $co, 'R428PL' => $profile->R428PL ?? '', 'R428WH' => $whs]];
$IC670M = \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('ic670m') $IC670M = Schema::connection($connection)->hasTable('ic670m')
? DB::connection($connection)->table('ic670m')->get() : collect(); ? DB::connection($connection)->table('ic670m')->get() : collect();
return view('m3::liberty-theme.pages.userControl', compact('ICM428M','IC670M','power_user','USER_INFO'));
return view('m3::liberty-theme.pages.userControl', compact('ICM428M', 'IC670M', 'power_user', 'USER_INFO'));
} }
// //
// Process data from Add modal // Process data from Add modal
// //
public static function saveUserAdd(Request $request) { public static function saveUserAdd(Request $request)
{
if($request->R428EMPCDE=="") { if ($request->R428EMPCDE == '') {
$request->R428EMPCDE=0; $request->R428EMPCDE = 0;
} }
// Insert record to ICM428M // Insert record to ICM428M
#dump($request); // dump($request);
// Validate user profile exists on the system // Validate user profile exists on the system
$usrprf = [(object) ['COUNT' => 0]]; // PostgreSQL/Core owns M3 profiles; no QSYS2 lookup. $usrprf = [(object) ['COUNT' => 0]]; // PostgreSQL/Core owns M3 profiles; no QSYS2 lookup.
// Validate employee code exists in LBPF file // Validate employee code exists in LBPF file
#if($request->R428EMPCDE>0) { // if($request->R428EMPCDE>0) {
# $empcde=DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT2 from LBPF where EMPNO='$request->R428EMPCDE'"); // $empcde=DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT2 from LBPF where EMPNO='$request->R428EMPCDE'");
# if($empcde[0]->COUNT2=="0") { // if($empcde[0]->COUNT2=="0") {
# #echo "<script>alert('Employee code entered does not exist, please try again');</script>"; // #echo "<script>alert('Employee code entered does not exist, please try again');</script>";
# return "error empcd"; // return "error empcd";
# } // }
#} // }
$icm428m=DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from ICM428M where R428US='$request->R428US'"); $icm428m = DB::connection(config('m3.connection', 'pgsql'))->select("select count(*) as COUNT1 from ICM428M where R428US='$request->R428US'");
if($icm428m[0]->COUNT1=="1") { if ($icm428m[0]->COUNT1 == '1') {
return "error exists"; return 'error exists';
} else { } else {
if($usrprf[0]->COUNT=="1") { if ($usrprf[0]->COUNT == '1') {
DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM428M DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM428M
(R428CO, R428PL, R428WH, R428STS, R428US, R428FIRST, R428FAMILY, R428EMAIL, R428EMPCDE, R428ADMUSR, R428PWRUSR, MENU2OPT, MENU3OPT, MENU4OPT, MENU5OPT, MENU6OPT, R42811A) (R428CO, R428PL, R428WH, R428STS, R428US, R428FIRST, R428FAMILY, R428EMAIL, R428EMPCDE, R428ADMUSR, R428PWRUSR, MENU2OPT, MENU3OPT, MENU4OPT, MENU5OPT, MENU6OPT, R42811A)
values ('$request->R428CO', '$request->R428PL', '$request->R428WH', '$request->R428STS', '$request->R428US', '$request->R428FIRST', values ('$request->R428CO', '$request->R428PL', '$request->R428WH', '$request->R428STS', '$request->R428US', '$request->R428FIRST',
'$request->R428FAMILY', '$request->R428EMAIL', $request->R428EMPCDE, '$request->R428ADMUSR', '$request->R428PWRUSR', '$request->R428FAMILY', '$request->R428EMAIL', $request->R428EMPCDE, '$request->R428ADMUSR', '$request->R428PWRUSR',
'NN".$request->MENU2OPT3."NNN".$request->MENU2OPT7.$request->MENU2OPT8."N', '".$request->MENU3OPT1.$request->MENU3OPT2."NNNNNNN', 'NN" . $request->MENU2OPT3 . 'NNN' . $request->MENU2OPT7 . $request->MENU2OPT8 . "N', '" . $request->MENU3OPT1 . $request->MENU3OPT2 . "NNNNNNN',
'".$request->MENU4OPT1.$request->MENU4OPT2.$request->MENU4OPT3."NNNNNN', '" . $request->MENU4OPT1 . $request->MENU4OPT2 . $request->MENU4OPT3 . "NNNNNN',
'".$request->MENU5OPT1.$request->MENU5OPT2.$request->MENU5OPT3."N".$request->MENU5OPT5."NNNN','".$request->MENU6OPT1.$request->MENU6OPT2.$request->MENU6OPT3."','".$request->R42811A."')"); '" . $request->MENU5OPT1 . $request->MENU5OPT2 . $request->MENU5OPT3 . 'N' . $request->MENU5OPT5 . "NNNN','" . $request->MENU6OPT1 . $request->MENU6OPT2 . $request->MENU6OPT3 . "','" . $request->R42811A . "')");
return "success";
} else {
#echo "<script>alert('User profile entered does not exist, please try again');</script>";
# CL program call here (ewobjtst.)ICMUSRPRF parms(R428US, R428FIRST, R428FAMILY) return 'success';
} else {
// echo "<script>alert('User profile entered does not exist, please try again');</script>";
// CL program call here (ewobjtst.)ICMUSRPRF parms(R428US, R428FIRST, R428FAMILY)
// connect to toolkit using DB2 credentials (can also leave blank for default authority) // connect to toolkit using DB2 credentials (can also leave blank for default authority)
try { try {
$conn = app(\Modules\M3\Services\PostgresProgramBridge::class); $conn = app(PostgresProgramBridge::class);
} } catch (\Exception $e) {
catch (\Exception $e)
{
// Determine reason for failure. // Determine reason for failure.
// Probably database authentication error or invalid or unreachable database. // Probably database authentication error or invalid or unreachable database.
$code = $e->getCode(); $code = $e->getCode();
$msg = $e->getMessage(); $msg = $e->getMessage();
switch ($code) { switch ($code) {
case 8001: case 8001:
// "Authorization failure on distributed database connection attempt" // "Authorization failure on distributed database connection attempt"
// Usually means a wrong DB2 user or password // Usually means a wrong DB2 user or password
$PGMERRORS = 'Could not connect due to wrong user or password.'; $PGMERRORS = 'Could not connect due to wrong user or password.';
return "error profile3";
return 'error profile3';
break; break;
case 42705: case 42705:
$PGMERRORS = 'Database not found. Try WRKRDBDIRE to check.'; $PGMERRORS = 'Database not found. Try WRKRDBDIRE to check.';
return "error profile4";
return 'error profile4';
break; break;
default: default:
$PGMERRORS = 'Could not connect. Error: ' . $code . ' ' . $msg; $PGMERRORS = 'Could not connect. Error: ' . $code . ' ' . $msg;
return "error profile5";
return 'error profile5';
break; break;
} }
} }
$conn->setOptions(array('persistent' => false, 'stateless' => true, 'debug' => true,'debugLogFile' => '/www/sentm3test/htdocs/M3/storage/logs/toolkit_debug.log')); $conn->setOptions(['persistent' => false, 'stateless' => true, 'debug' => true, 'debugLogFile' => '/www/sentm3test/htdocs/M3/storage/logs/toolkit_debug.log']);
// Add LIB // Add LIB
// $result = $conn->CLCommand('ADDLIBLE LIB(MPDAT10)'); // $result = $conn->CLCommand('ADDLIBLE LIB(MPDAT10)');
// define several input/output params // define several input/output params
$params = []; $params = [];
$params[] = $conn->AddParameterChar('in',10,'User profile','E#iUsrPrf',$request->R428US); $params[] = $conn->AddParameterChar('in', 10, 'User profile', 'E#iUsrPrf', $request->R428US);
$params[] = $conn->AddParameterChar('in',20,'First name','FIRST',$request->R428FIRST); $params[] = $conn->AddParameterChar('in', 20, 'First name', 'FIRST', $request->R428FIRST);
$params[] = $conn->AddParameterChar('in',30,'Family name','FAMILY',$request->R428FAMILY); $params[] = $conn->AddParameterChar('in', 30, 'Family name', 'FAMILY', $request->R428FAMILY);
## $result = $conn->PgmCall(Config::get('eproconf.misc.PGM1'), Config::get('eproconf.misc.libname4'), $params, array(), array()); // # $result = $conn->PgmCall(Config::get('eproconf.misc.PGM1'), Config::get('eproconf.misc.libname4'), $params, array(), array());
$result = $conn->PgmCall('ICMUSRPRF', 'EWOBJ', $params, array(), array()); $result = $conn->PgmCall('ICMUSRPRF', 'EWOBJ', $params, [], []);
if (!$result) { if (! $result) {
$PGMERRORS = 'Error calling program. Code: ' . $conn->getErrorCode() . ' Msg: ' . $conn->getErrorMsg(); $PGMERRORS = 'Error calling program. Code: ' . $conn->getErrorCode() . ' Msg: ' . $conn->getErrorMsg();
//echo "<script>alert($PGMERRORS);</script>";
return "error profile2"; // echo "<script>alert($PGMERRORS);</script>";
return 'error profile2';
} else { } else {
// Successful Call : User profile created with default password // Successful Call : User profile created with default password
//dd($result); // dd($result);
//echo "<script>alert('User profile $request->R428US was created on the system with default password.');</script>"; // echo "<script>alert('User profile $request->R428US was created on the system with default password.');</script>";
DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM428M DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM428M
(R428CO, R428PL, R428WH, R428STS, R428US, R428FIRST, R428FAMILY, R428EMAIL, R428EMPCDE, R428ADMUSR, R428PWRUSR, MENU2OPT, MENU3OPT, MENU4OPT, MENU5OPT, MENU6OPT, R42811A,R42821A) (R428CO, R428PL, R428WH, R428STS, R428US, R428FIRST, R428FAMILY, R428EMAIL, R428EMPCDE, R428ADMUSR, R428PWRUSR, MENU2OPT, MENU3OPT, MENU4OPT, MENU5OPT, MENU6OPT, R42811A,R42821A)
values ('$request->R428CO', '$request->R428PL', '$request->R428WH', '$request->R428STS', '$request->R428US', '$request->R428FIRST', values ('$request->R428CO', '$request->R428PL', '$request->R428WH', '$request->R428STS', '$request->R428US', '$request->R428FIRST',
'$request->R428FAMILY', '$request->R428EMAIL', $request->R428EMPCDE, '$request->R428ADMUSR', '$request->R428PWRUSR', '$request->R428FAMILY', '$request->R428EMAIL', $request->R428EMPCDE, '$request->R428ADMUSR', '$request->R428PWRUSR',
'NN".$request->MENU2OPT3."NNN".$request->MENU2OPT7.$request->MENU2OPT8."N', '".$request->MENU3OPT1.$request->MENU3OPT2."NNNNNNN', 'NN" . $request->MENU2OPT3 . 'NNN' . $request->MENU2OPT7 . $request->MENU2OPT8 . "N', '" . $request->MENU3OPT1 . $request->MENU3OPT2 . "NNNNNNN',
'".$request->MENU4OPT1.$request->MENU4OPT2.$request->MENU4OPT3."NNNNNN', '" . $request->MENU4OPT1 . $request->MENU4OPT2 . $request->MENU4OPT3 . "NNNNNN',
'".$request->MENU5OPT1.$request->MENU5OPT2.$request->MENU5OPT3."N".$request->MENU5OPT5."NNNN','".$request->MENU6OPT1.$request->MENU6OPT2.$request->MENU6OPT3."','".$request->R42811A."','".$request->R42821A."')"); '" . $request->MENU5OPT1 . $request->MENU5OPT2 . $request->MENU5OPT3 . 'N' . $request->MENU5OPT5 . "NNNN','" . $request->MENU6OPT1 . $request->MENU6OPT2 . $request->MENU6OPT3 . "','" . $request->R42811A . "','" . $request->R42821A . "')");
return "success2";
return 'success2';
} }
##kd return "error profile"; // #kd return "error profile";
} }
} }
@@ -133,62 +139,62 @@ class userControlController extends Controller
// //
// Process data from Edit modal // Process data from Edit modal
// //
public static function saveUserEdit(Request $request) { public static function saveUserEdit(Request $request)
{
#dump($request); // dump($request);
if($request->R428EMPCDE=="") { if ($request->R428EMPCDE == '') {
$request->R428EMPCDE=0; $request->R428EMPCDE = 0;
} }
// Validate employee code exists in LBPF file // Validate employee code exists in LBPF file
//dump($request->R428EMPCDE); // dump($request->R428EMPCDE);
#if($request->R428EMPCDE>0) { // if($request->R428EMPCDE>0) {
# $sqlstmt="select count(*) as COUNT from LBPF where EMPNO='$request->R428EMPCDE'"; // $sqlstmt="select count(*) as COUNT from LBPF where EMPNO='$request->R428EMPCDE'";
# #echo "$sqlstmt<br>"; // #echo "$sqlstmt<br>";
# $empcde=DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt); // $empcde=DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt);
# #dump($empcde); // #dump($empcde);
# if($empcde[0]->COUNT=="0") { // if($empcde[0]->COUNT=="0") {
# #echo "<script>alert('Employee code entered does not exist, please try again');</script>"; // #echo "<script>alert('Employee code entered does not exist, please try again');</script>";
# return "error empcd"; // return "error empcd";
# } // }
#} // }
// Update record to ICM428M // Update record to ICM428M
$ICM428M=DB::connection(config('m3.connection', 'pgsql'))->select("select * from ICM428M where R428US='$request->R428US'"); $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->select("select * from ICM428M where R428US='$request->R428US'");
//var_dump($ICM428M); // var_dump($ICM428M);
DB::connection(config('m3.connection', 'pgsql'))->update("update ICM428M DB::connection(config('m3.connection', 'pgsql'))->update("update ICM428M
set R428CO='$request->R428CO', R428PL='$request->R428PL', R428WH='$request->R428WH', R428STS='$request->R428STS', R428FIRST='$request->R428FIRST', set R428CO='$request->R428CO', R428PL='$request->R428PL', R428WH='$request->R428WH', R428STS='$request->R428STS', R428FIRST='$request->R428FIRST',
R428FAMILY='$request->R428FAMILY', R428EMAIL='$request->R428EMAIL', R428EMPCDE=$request->R428EMPCDE, R428ADMUSR='$request->R428ADMUSR', R428FAMILY='$request->R428FAMILY', R428EMAIL='$request->R428EMAIL', R428EMPCDE=$request->R428EMPCDE, R428ADMUSR='$request->R428ADMUSR',
R428PWRUSR='$request->R428PWRUSR', R428PWRUSR='$request->R428PWRUSR',
MENU2OPT='".substr($ICM428M[0]->MENU2OPT,0,2).$request->MENU2OPT3.substr($ICM428M[0]->MENU2OPT,3,3).$request->MENU2OPT7.$request->MENU2OPT8."', MENU2OPT='" . substr($ICM428M[0]->MENU2OPT, 0, 2) . $request->MENU2OPT3 . substr($ICM428M[0]->MENU2OPT, 3, 3) . $request->MENU2OPT7 . $request->MENU2OPT8 . "',
MENU3OPT='".$request->MENU3OPT1.$request->MENU3OPT2.substr($ICM428M[0]->MENU3OPT,2,-1)."', MENU3OPT='" . $request->MENU3OPT1 . $request->MENU3OPT2 . substr($ICM428M[0]->MENU3OPT, 2, -1) . "',
MENU4OPT='".$request->MENU4OPT1.$request->MENU4OPT2.$request->MENU4OPT3.substr($ICM428M[0]->MENU4OPT,3,-1)."', MENU4OPT='" . $request->MENU4OPT1 . $request->MENU4OPT2 . $request->MENU4OPT3 . substr($ICM428M[0]->MENU4OPT, 3, -1) . "',
MENU5OPT='".$request->MENU5OPT1.$request->MENU5OPT2.$request->MENU5OPT3.substr($ICM428M[0]->MENU5OPT,3,1).$request->MENU5OPT5.substr($ICM428M[0]->MENU5OPT,5,-1)."', MENU5OPT='" . $request->MENU5OPT1 . $request->MENU5OPT2 . $request->MENU5OPT3 . substr($ICM428M[0]->MENU5OPT, 3, 1) . $request->MENU5OPT5 . substr($ICM428M[0]->MENU5OPT, 5, -1) . "',
MENU6OPT='".$request->MENU6OPT1.$request->MENU6OPT2.$request->MENU6OPT3.substr($ICM428M[0]->MENU6OPT,3,-1)."', MENU6OPT='" . $request->MENU6OPT1 . $request->MENU6OPT2 . $request->MENU6OPT3 . substr($ICM428M[0]->MENU6OPT, 3, -1) . "',
R42811A='".$request->R42811A."',R42821A='".$request->R42821A."' R42811A='" . $request->R42811A . "',R42821A='" . $request->R42821A . "'
where R428US='$request->R428US'"); where R428US='$request->R428US'");
return "success"; return 'success';
} }
#590 // 590
public static function callCL(Request $request) { public static function callCL(Request $request)
{
$PGMERRORS = ''; $PGMERRORS = '';
// connect to toolkit using DB2 credentials (can also leave blank for default authority) // connect to toolkit using DB2 credentials (can also leave blank for default authority)
try { try {
$conn = app(\Modules\M3\Services\PostgresProgramBridge::class); $conn = app(PostgresProgramBridge::class);
} } catch (\Exception $e) {
catch (\Exception $e)
{
// Determine reason for failure. // Determine reason for failure.
// Probably database authentication error or invalid or unreachable database. // Probably database authentication error or invalid or unreachable database.
$code = $e->getCode(); $code = $e->getCode();
$msg = $e->getMessage(); $msg = $e->getMessage();
switch ($code) { switch ($code) {
case 8001: case 8001:
@@ -211,45 +217,46 @@ class userControlController extends Controller
// $result = $conn->CLCommand('ADDLIBLE LIB(MPDAT10)'); // $result = $conn->CLCommand('ADDLIBLE LIB(MPDAT10)');
// define several input/output params // define several input/output params
$params = []; $params = [];
// AddParameterChar($io, $size, $comment, $varName, $value, $varying, $dimension) // AddParameterChar($io, $size, $comment, $varName, $value, $varying, $dimension)
# Add Warehouse Param // Add Warehouse Param
$params[] = $conn->AddParameterChar('in', 10, 'userid','USERID',$request->USERID); $params[] = $conn->AddParameterChar('in', 10, 'userid', 'USERID', $request->USERID);
$params[] = $conn->AddParameterChar('in', 1, 'action','ACTION',$request->ACTION); $params[] = $conn->AddParameterChar('in', 1, 'action', 'ACTION', $request->ACTION);
// AddParameterPackDec($io, $length, $scale, $comment, $varName, $value,$dimension) // AddParameterPackDec($io, $length, $scale, $comment, $varName, $value,$dimension)
// Add Delivery Note Param // Add Delivery Note Param
//$params[] = $conn->AddParameterPackDec('in', 11, 0, 'ParamIn','','00000087125'); // $params[] = $conn->AddParameterPackDec('in', 11, 0, 'ParamIn','','00000087125');
// $params[] = $conn->AddParameterZoned('in', 11, 0, 'ParamIn'); // $params[] = $conn->AddParameterZoned('in', 11, 0, 'ParamIn');
// Start Time Tracking // Start Time Tracking
// $start = microtime(true); // $start = microtime(true);
//dump('Calling: EWOBJ/ICMCHGPRF action='.$request->ACTION.' user='.$request->USERID); // dump('Calling: EWOBJ/ICMCHGPRF action='.$request->ACTION.' user='.$request->USERID);
// Config::get('eproconf.misc.PGM1'), Config::get('eproconf.misc.libname4') // Config::get('eproconf.misc.PGM1'), Config::get('eproconf.misc.libname4')
// ICM700C EWOBJTST ICM700C ICM700CSBM // ICM700C EWOBJTST ICM700C ICM700CSBM
$result = $conn->PgmCall('ICMCHGPRF', 'EWOBJ', $params, array(), array()); $result = $conn->PgmCall('ICMCHGPRF', 'EWOBJ', $params, [], []);
if (!$result) { if (! $result) {
$PGMERRORS = 'Error calling program. Code: ' . $conn->getErrorCode() . ' Msg: ' . $conn->getErrorMsg(); $PGMERRORS = 'Error calling program. Code: ' . $conn->getErrorCode() . ' Msg: ' . $conn->getErrorMsg();
//dump($PGMERRORS); // dump($PGMERRORS);
echo "<script>alert($PGMERRORS);</script>"; echo "<script>alert($PGMERRORS);</script>";
return "error";
die(); return 'error';
exit();
} }
// Successful Call // Successful Call
else{ else {
//dump($result); // dump($result);
// $AWREQN = $result['io_param']["var0"]; // $AWREQN = $result['io_param']["var0"];
//return "success"; // return "success";
if($request->ACTION=="P") { if ($request->ACTION == 'P') {
echo "<script>alert('The password has been reset to QAZ1WSX2 for '".$request->USERID."'. The user will need to enter a new password on next green screen connection.');</script>"; echo "<script>alert('The password has been reset to QAZ1WSX2 for '" . $request->USERID . "'. The user will need to enter a new password on next green screen connection.');</script>";
} }
if($request->ACTION=="R") { if ($request->ACTION == 'R') {
echo "<script>alert('User '".$request->USERID."' has been re-enabled successfully');</script>"; echo "<script>alert('User '" . $request->USERID . "' has been re-enabled successfully');</script>";
} }
echo "<script>window.location.replace('.')</script>"; echo "<script>window.location.replace('.')</script>";
} }
@@ -263,35 +270,33 @@ class userControlController extends Controller
// } // }
} }
// 765
public static function savePassword(Request $request)
{
#765 // dd('B4');
public static function savePassword(Request $request) {
#dd('B4');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut')); ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
$PGMERRORS = ''; $PGMERRORS = '';
#console_log("request> "); // console_log("request> ");
#echo "request="; var_dump($request); // echo "request="; var_dump($request);
#echo "B3<br>"; // echo "B3<br>";
// connect to toolkit using DB2 credentials (can also leave blank for default authority) // connect to toolkit using DB2 credentials (can also leave blank for default authority)
try { try {
$conn = app(\Modules\M3\Services\PostgresProgramBridge::class); $conn = app(PostgresProgramBridge::class);
#dump($conn); // dump($conn);
#echo "B4<br>"; // echo "B4<br>";
} } catch (\Exception $e) {
catch (\Exception $e) // echo "B5<br>";
{
#echo "B5<br>";
// Determine reason for failure. // Determine reason for failure.
// Probably database authentication error or invalid or unreachable database. // Probably database authentication error or invalid or unreachable database.
### $conn->setOptions(array('persistent' => false, 'stateless' => true, 'debug' => true,'debugLogFile' => '/www/sentm3test/htdocs/storage/logs/toolkit_debug.log')); // ## $conn->setOptions(array('persistent' => false, 'stateless' => true, 'debug' => true,'debugLogFile' => '/www/sentm3test/htdocs/storage/logs/toolkit_debug.log'));
$code = $e->getCode(); $code = $e->getCode();
$msg = $e->getMessage(); $msg = $e->getMessage();
switch ($code) { switch ($code) {
case 8001: case 8001:
@@ -308,26 +313,27 @@ class userControlController extends Controller
} }
} }
#$params = []; // $params = [];
#$params[] = $conn->AddParameterChar('in', 10, 'userid','USRPRF',$request->USERID); // $params[] = $conn->AddParameterChar('in', 10, 'userid','USRPRF',$request->USERID);
#$params[] = $conn->AddParameterChar('in', 10, 'pwd','PASSWORD',$request->PASSWORD); // $params[] = $conn->AddParameterChar('in', 10, 'pwd','PASSWORD',$request->PASSWORD);
#$params[] = $conn->AddParameterChar('in', 9, 'sts','STATUS','*ENABLED'); // $params[] = $conn->AddParameterChar('in', 9, 'sts','STATUS','*ENABLED');
#$params[] = $conn->AddParameterChar('in', 4, 'pwdexp','PWDEXP','*NO'); // $params[] = $conn->AddParameterChar('in', 4, 'pwdexp','PWDEXP','*NO');
//dump('Before CHGUSRPRF'); // dump('Before CHGUSRPRF');
$result = $conn->CLCommand('QSYS/CHGUSRPRF USRPRF('.$request->R428US_PWD.') PASSWORD('.$request->NEW_PASSWORD.') STATUS(*ENABLED) PWDEXP(*NO)'); $result = $conn->CLCommand('QSYS/CHGUSRPRF USRPRF(' . $request->R428US_PWD . ') PASSWORD(' . $request->NEW_PASSWORD . ') STATUS(*ENABLED) PWDEXP(*NO)');
#$result = $conn->PgmCall('CHGUSRPRF', 'QSYS', $params, array(), array()); // $result = $conn->PgmCall('CHGUSRPRF', 'QSYS', $params, array(), array());
#echo "<script>alert('After CHGUSRPRF');</script>"; // echo "<script>alert('After CHGUSRPRF');</script>";
if (!$result) { if (! $result) {
$PGMERRORS = 'Error calling program. Code: ' . $conn->getErrorCode() . ' Msg: ' . $conn->getErrorMsg(); $PGMERRORS = 'Error calling program. Code: ' . $conn->getErrorCode() . ' Msg: ' . $conn->getErrorMsg();
dump($PGMERRORS); dump($PGMERRORS);
echo "<script>alert($PGMERRORS);</script>"; echo "<script>alert($PGMERRORS);</script>";
return "error pwd";
return 'error pwd';
} }
// Successful Call // Successful Call
else{ else {
return "success"; return 'success';
} }
} }
+113 -114
View File
@@ -2,44 +2,44 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use DB;
use Config; use Config;
use DB;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
class userPickingStats4 extends Controller class userPickingStats4 extends Controller
{ {
public static function index(Request $request) public static function index(Request $request)
{ {
#$start = microtime(true); // $start = microtime(true);
#dd($request); // dd($request);
// Filter by date // Filter by date
if (isset($request->dates)) { if (isset($request->dates)) {
$date = $request->dates; $date = $request->dates;
$starting = $date; $starting = $date;
} else { } else {
$starting = date("Y-m-d", strtotime("-1 days")); $starting = date('Y-m-d', strtotime('-1 days'));
} }
##$min_work_hours_for_break = 4; // #$min_work_hours_for_break = 4;
$min_work_hours_for_break = implode(",", Config::get('arrays.min_work_hours_for_break')); $min_work_hours_for_break = implode(',', Config::get('arrays.min_work_hours_for_break'));
##$ignore_picks_that_last_longer_than_this_many_hours = 8; // #$ignore_picks_that_last_longer_than_this_many_hours = 8;
$ignore_picks_that_last_longer_than_this_many_hours = implode(",", Config::get('arrays.ignore_picks_that_last_longer_than_this_many_hours')); $ignore_picks_that_last_longer_than_this_many_hours = implode(',', Config::get('arrays.ignore_picks_that_last_longer_than_this_many_hours'));
#$user_array = Config::get('arrays.user_array'); // $user_array = Config::get('arrays.user_array');
#618 // 618
# Get Logged User CO & WH // Get Logged User CO & WH
# Get Users from ICM428M // Get Users from ICM428M
$co = ''; $co = '';
$whs = ''; $whs = '';
$ICM428M = []; $ICM428M = [];
$schema = \Illuminate\Support\Facades\Schema::connection(config('m3.connection', 'pgsql')); $schema = Schema::connection(config('m3.connection', 'pgsql'));
if ($schema->hasTable('icm428m')) { if ($schema->hasTable('icm428m')) {
$profile = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $profile = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH') ->select('R428US', 'R428CO', 'R428WH')
->where('R428US','=',strtoUpper(m3_user())) ->where('R428US', '=', strtoupper(m3_user()))
->first(); ->first();
$co = $profile->R428CO ?? ''; $co = $profile->R428CO ?? '';
$whs = $profile->R428WH ?? ''; $whs = $profile->R428WH ?? '';
@@ -50,22 +50,22 @@ class userPickingStats4 extends Controller
->where('R428CO', $co)->where('R428WH', $whs)->get()->all(); ->where('R428CO', $co)->where('R428WH', $whs)->get()->all();
} }
$user_array=array(); $user_array = [];
#while($row = odbc_fetch_object($result)) { // while($row = odbc_fetch_object($result)) {
$x=0; $x = 0;
foreach($ICM428M as $key=>$row) { foreach ($ICM428M as $key => $row) {
// print_r($row); // print_r($row);
$user_array[$x]['userprf']=trim($row->USERPRF); $user_array[$x]['userprf'] = trim($row->USERPRF);
#$user_array[$x]['name']=trim($row->R428FIRST)+' '+trim($row->R428FAMILY); // $user_array[$x]['name']=trim($row->R428FIRST)+' '+trim($row->R428FAMILY);
$user_array[$x]['name']=trim($row->NAME); $user_array[$x]['name'] = trim($row->NAME);
$user_array[$x]['empno']=$row->EMPNO; $user_array[$x]['empno'] = $row->EMPNO;
$x++; $x++;
} }
array_multisort(array_column($user_array, 'name'), SORT_ASC, $user_array); array_multisort(array_column($user_array, 'name'), SORT_ASC, $user_array);
// fill array of Lines per Hour per Monitor // fill array of Lines per Hour per Monitor
$lph_per_monitor_array = Config::get('arrays_custom.lph_per_code_array'); $lph_per_monitor_array = Config::get('arrays_custom.lph_per_code_array');
#echo "<pre>"; print_r($user_array); echo "</pre>"; // echo "<pre>"; print_r($user_array); echo "</pre>";
if (isset($request->user)) { if (isset($request->user)) {
$user = $request->user; $user = $request->user;
$empno = 0; $empno = 0;
@@ -76,14 +76,14 @@ class userPickingStats4 extends Controller
} }
} else { } else {
$empno = 0; $empno = 0;
$user = ""; $user = '';
} }
// get data from LBPF for user and day // get data from LBPF for user and day
$payrollCodes = ""; $payrollCodes = '';
ksort($lph_per_monitor_array); ksort($lph_per_monitor_array);
foreach ($lph_per_monitor_array as $key => $val) { foreach ($lph_per_monitor_array as $key => $val) {
$payrollCodes .= $key . ","; $payrollCodes .= $key . ',';
} }
$payrollCodes = substr($payrollCodes, 0, -1); $payrollCodes = substr($payrollCodes, 0, -1);
@@ -95,7 +95,7 @@ class userPickingStats4 extends Controller
and oppno in ($payrollCodes) and oppno in ($payrollCodes)
group by oppno"; group by oppno";
#echo "$sqlstmt<br>"; // echo "$sqlstmt<br>";
$lbpf1 = $schema->hasTable('lbpf') $lbpf1 = $schema->hasTable('lbpf')
? DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt) ? DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt)
@@ -107,62 +107,62 @@ class userPickingStats4 extends Controller
} }
$sql = "select * from perfstat where dt='$starting' and a5pickcomu='$user' "; $sql = "select * from perfstat where dt='$starting' and a5pickcomu='$user' ";
#@dd($sql); // @dd($sql);
if ((isset($request->dates) || isset($request->user)) && $schema->hasTable('perfstat')) { if ((isset($request->dates) || isset($request->user)) && $schema->hasTable('perfstat')) {
$statistic4 = DB::connection(config('m3.connection', 'pgsql'))->select($sql); $statistic4 = DB::connection(config('m3.connection', 'pgsql'))->select($sql);
} else { } else {
$statistic4 = array(); $statistic4 = [];
} }
#echo "<pre>"; print_r($statistic4); echo "</pre>"; // echo "<pre>"; print_r($statistic4); echo "</pre>";
#$duration = microtime(true) - $start; // $duration = microtime(true) - $start;
// initialize arrays // initialize arrays
$monitor_array = $totals_array = $perf_array = array(); $monitor_array = $totals_array = $perf_array = [];
$totals_array["value"] = 0; $totals_array['value'] = 0;
$totals_array["weight"] = 0; $totals_array['weight'] = 0;
$totals_array["timediff"] = 0; $totals_array['timediff'] = 0;
$totals_array["picked"] = 0; $totals_array['picked'] = 0;
$totals_array["entries"] = 0; $totals_array['entries'] = 0;
$diff = 0; $diff = 0;
#echo "<pre>"; print_r($lbpf1); echo "</pre>"; // echo "<pre>"; print_r($lbpf1); echo "</pre>";
foreach ($lbpf1 as $key => $val) { foreach ($lbpf1 as $key => $val) {
$monitor_array[$val->OPPNO]['tot_hours'] = $val->HRS; $monitor_array[$val->OPPNO]['tot_hours'] = $val->HRS;
// Initialize these variables in case not existant in statistic4 // Initialize these variables in case not existant in statistic4
$monitor_array[$val->OPPNO]['header'] = "Mon" . $val->OPPNO; $monitor_array[$val->OPPNO]['header'] = 'Mon' . $val->OPPNO;
$monitor_array[$val->OPPNO]['timediff'] = 0; $monitor_array[$val->OPPNO]['timediff'] = 0;
$monitor_array[$val->OPPNO]["percent_per_monitor"] = 0; $monitor_array[$val->OPPNO]['percent_per_monitor'] = 0;
$monitor_array[$val->OPPNO]["percent_per_activity"] = 0; $monitor_array[$val->OPPNO]['percent_per_activity'] = 0;
$monitor_array[$val->OPPNO]["lph_blended_per_activity"] = 0; $monitor_array[$val->OPPNO]['lph_blended_per_activity'] = 0;
$monitor_array[$val->OPPNO]["picked"] = 0; $monitor_array[$val->OPPNO]['picked'] = 0;
$monitor_array[$val->OPPNO]["weight"] = 0; $monitor_array[$val->OPPNO]['weight'] = 0;
$monitor_array[$val->OPPNO]["lines"] = 0; $monitor_array[$val->OPPNO]['lines'] = 0;
} }
if (!empty($statistic4)) { if (! empty($statistic4)) {
#echo "in !empty<br>"; // echo "in !empty<br>";
// Initialize the Monitor array // Initialize the Monitor array
foreach ($statistic4 as $key => $val) { foreach ($statistic4 as $key => $val) {
// Initialize these variables in case not existant in LBPF // Initialize these variables in case not existant in LBPF
$monitor_array[$val->CODE]['header'] = "Mon" . $statistic4[$key]->CODE; $monitor_array[$val->CODE]['header'] = 'Mon' . $statistic4[$key]->CODE;
$monitor_array[$val->CODE]['timediff'] = 0; $monitor_array[$val->CODE]['timediff'] = 0;
$monitor_array[$val->CODE]["percent_per_monitor"] = 0; $monitor_array[$val->CODE]['percent_per_monitor'] = 0;
$monitor_array[$val->CODE]["percent_per_activity"] = 0; $monitor_array[$val->CODE]['percent_per_activity'] = 0;
$monitor_array[$val->CODE]["lph_blended_per_activity"] = 0; $monitor_array[$val->CODE]['lph_blended_per_activity'] = 0;
$monitor_array[$val->CODE]["picked"] = 0; $monitor_array[$val->CODE]['picked'] = 0;
$monitor_array[$val->CODE]["weight"] = 0; $monitor_array[$val->CODE]['weight'] = 0;
$monitor_array[$val->CODE]["lines"] = 0; $monitor_array[$val->CODE]['lines'] = 0;
} }
#echo "after 1st init<br>"; // echo "after 1st init<br>";
// add another element (0) in monitor_array to capture the total blended lph value expected // add another element (0) in monitor_array to capture the total blended lph value expected
$monitor_array[0]["lph_blended_per_activity"] = 0; $monitor_array[0]['lph_blended_per_activity'] = 0;
$monitor_array[0]['header'] = "0"; $monitor_array[0]['header'] = '0';
// cycle thru stats again, and accumulate totals at global level (totals_array) and at monitor level (monitor_array) // cycle thru stats again, and accumulate totals at global level (totals_array) and at monitor level (monitor_array)
foreach ($statistic4 as $key => $val) { foreach ($statistic4 as $key => $val) {
@@ -174,7 +174,7 @@ class userPickingStats4 extends Controller
$statistic4[$key]->A5PICKCMTS = date('Y-m-d H:i', strtotime($statistic4[$key]->A5PICKCMTS)); $statistic4[$key]->A5PICKCMTS = date('Y-m-d H:i', strtotime($statistic4[$key]->A5PICKCMTS));
// Calculate difference from previous time entry in seconds and save in TIMEDIFF key of STATISTIC4 array // Calculate difference from previous time entry in seconds and save in TIMEDIFF key of STATISTIC4 array
# $time_now=strtotime($statistic4[$key]->A5PICKCMTSADJ); // $time_now=strtotime($statistic4[$key]->A5PICKCMTSADJ);
$time_now = strtotime($statistic4[$key]->A5CMTSADJ); $time_now = strtotime($statistic4[$key]->A5CMTSADJ);
if ($key > 0) { if ($key > 0) {
$diff = round(abs($time_now - $time_prev)); $diff = round(abs($time_now - $time_prev));
@@ -186,20 +186,20 @@ class userPickingStats4 extends Controller
$statistic4[$key]->TIMEDIFF = $diff; $statistic4[$key]->TIMEDIFF = $diff;
if ($diff / 60 < 5) { if ($diff / 60 < 5) {
$statistic4[$key]->COLOUR = ""; $statistic4[$key]->COLOUR = '';
} }
if ($diff / 60 >= 5 && $diff / 60 <= 10) { if ($diff / 60 >= 5 && $diff / 60 <= 10) {
$statistic4[$key]->COLOUR = "yellow"; $statistic4[$key]->COLOUR = 'yellow';
} }
if ($diff / 60 > 10 && $diff / 60 <= 15) { if ($diff / 60 > 10 && $diff / 60 <= 15) {
$statistic4[$key]->COLOUR = "#88ace0"; $statistic4[$key]->COLOUR = '#88ace0';
} }
if ($diff / 60 > 15) { if ($diff / 60 > 15) {
$statistic4[$key]->COLOUR = "red"; $statistic4[$key]->COLOUR = 'red';
} }
// save the time for previous entry // save the time for previous entry
# $time_prev=strtotime($statistic4[$key]->A5PICKCMTSADJ); // $time_prev=strtotime($statistic4[$key]->A5PICKCMTSADJ);
$time_prev = strtotime($statistic4[$key]->A5CMTSADJ); $time_prev = strtotime($statistic4[$key]->A5CMTSADJ);
// accumulate totals at monitor level // accumulate totals at monitor level
@@ -208,26 +208,25 @@ class userPickingStats4 extends Controller
$monitor_array[$val->CODE]['weight'] += $statistic4[$key]->WEIGHT; $monitor_array[$val->CODE]['weight'] += $statistic4[$key]->WEIGHT;
$monitor_array[$val->CODE]['lines']++; $monitor_array[$val->CODE]['lines']++;
// calculate totals at global level // calculate totals at global level
$totals_array["entries"] = count($statistic4); $totals_array['entries'] = count($statistic4);
$totals_array["weight"] += $statistic4[$key]->WEIGHT; $totals_array['weight'] += $statistic4[$key]->WEIGHT;
$totals_array["value"] += $statistic4[$key]->A5VALUE; $totals_array['value'] += $statistic4[$key]->A5VALUE;
$totals_array["timediff"] += $diff; $totals_array['timediff'] += $diff;
$totals_array["picked"] += $statistic4[$key]->A5PICKED; $totals_array['picked'] += $statistic4[$key]->A5PICKED;
} }
#echo "after 2<pre>"; print_r($statistic4); // echo "after 2<pre>"; print_r($statistic4);
// build array for Performance with Greg's time entry (at one point we had a [0] array as well) // build array for Performance with Greg's time entry (at one point we had a [0] array as well)
if (!is_null($lbpf)) { if (! is_null($lbpf)) {
$perf_array["tot_hours"] = (isset($lbpf) ? $lbpf : 0); $perf_array['tot_hours'] = (isset($lbpf) ? $lbpf : 0);
if ($perf_array["tot_hours"] <> 0) { if ($perf_array['tot_hours'] != 0) {
$perf_array["per_hour_actual"] = $totals_array["entries"] / $perf_array["tot_hours"]; $perf_array['per_hour_actual'] = $totals_array['entries'] / $perf_array['tot_hours'];
} else { } else {
$perf_array["per_hour_actual"] = 0; $perf_array['per_hour_actual'] = 0;
} }
} }
@@ -235,85 +234,85 @@ class userPickingStats4 extends Controller
// cycle through monitors array and compute percentage to allocate to each monitor (code) // cycle through monitors array and compute percentage to allocate to each monitor (code)
ksort($monitor_array); ksort($monitor_array);
foreach ($monitor_array as $key => $val) { foreach ($monitor_array as $key => $val) {
if ($key != "0") { if ($key != '0') {
if (!isset($monitor_array[$key]["tot_hours"])) { if (! isset($monitor_array[$key]['tot_hours'])) {
$monitor_array[$key]["tot_hours"] = 0; $monitor_array[$key]['tot_hours'] = 0;
} }
if ($totals_array["timediff"] <> 0) { if ($totals_array['timediff'] != 0) {
$monitor_array[$key]["percent_per_monitor"] = $monitor_array[$key]["timediff"] / $totals_array["timediff"]; $monitor_array[$key]['percent_per_monitor'] = $monitor_array[$key]['timediff'] / $totals_array['timediff'];
} }
if ($lbpf <> 0) { if ($lbpf != 0) {
$monitor_array[$key]["percent_per_activity"] = $monitor_array[$key]["tot_hours"] / $lbpf; $monitor_array[$key]['percent_per_activity'] = $monitor_array[$key]['tot_hours'] / $lbpf;
} }
$monitor_array[$key]["lph_blended_per_activity"] = $monitor_array[$key]["percent_per_activity"] * (isset($lph_per_monitor_array[$key]) ? $lph_per_monitor_array[$key] : 0); $monitor_array[$key]['lph_blended_per_activity'] = $monitor_array[$key]['percent_per_activity'] * (isset($lph_per_monitor_array[$key]) ? $lph_per_monitor_array[$key] : 0);
$monitor_array[0]["lph_blended_per_activity"] += $monitor_array[$key]["lph_blended_per_activity"]; $monitor_array[0]['lph_blended_per_activity'] += $monitor_array[$key]['lph_blended_per_activity'];
} }
} }
if ($monitor_array[0]["lph_blended_per_activity"] <> 0) { if ($monitor_array[0]['lph_blended_per_activity'] != 0) {
$perf_array["performance_activity"] = $perf_array["per_hour_actual"] / $monitor_array[0]["lph_blended_per_activity"]; $perf_array['performance_activity'] = $perf_array['per_hour_actual'] / $monitor_array[0]['lph_blended_per_activity'];
} }
} }
#echo "<pre>"; // echo "<pre>";
#print_r($request); // print_r($request);
#print_r($perf_array); print_r($monitor_array); // print_r($perf_array); print_r($monitor_array);
// return encoded json if input field named format is json // return encoded json if input field named format is json
if ($request->format == "json") { if ($request->format == 'json') {
if (!array_key_exists("performance_activity", $perf_array)) { if (! array_key_exists('performance_activity', $perf_array)) {
$performance = 0; $performance = 0;
} else { } else {
$performance = number_format($perf_array["performance_activity"] * 100, 0); $performance = number_format($perf_array['performance_activity'] * 100, 0);
} }
if (!array_key_exists("0", $monitor_array)) { if (! array_key_exists('0', $monitor_array)) {
$blendedTargetLPH = 0; $blendedTargetLPH = 0;
} else { } else {
$blendedTargetLPH = number_format($monitor_array[0]["lph_blended_per_activity"], 1); $blendedTargetLPH = number_format($monitor_array[0]['lph_blended_per_activity'], 1);
} }
if (!array_key_exists("per_hour_actual", $perf_array)) { if (! array_key_exists('per_hour_actual', $perf_array)) {
$actualLPH = 0; $actualLPH = 0;
} else { } else {
$actualLPH = number_format($perf_array["per_hour_actual"], 1); $actualLPH = number_format($perf_array['per_hour_actual'], 1);
} }
if (!array_key_exists("tot_hours", $perf_array)) { if (! array_key_exists('tot_hours', $perf_array)) {
$grossHours = 0; $grossHours = 0;
} else { } else {
$grossHours = $perf_array["tot_hours"]; $grossHours = $perf_array['tot_hours'];
} }
$json_data = array( $json_data = [
"day" => $starting, 'day' => $starting,
"performance" => $performance, 'performance' => $performance,
"blendedTargetLPH" => $blendedTargetLPH, 'blendedTargetLPH' => $blendedTargetLPH,
"actualLPH" => $actualLPH, 'actualLPH' => $actualLPH,
"grossHours" => $grossHours 'grossHours' => $grossHours,
); ];
#echo "<pre>"; print_r($json_data);
// echo "<pre>"; print_r($json_data);
return json_encode($json_data); return json_encode($json_data);
} else { } else {
// display webpage of statistic version 4 // display webpage of statistic version 4
$request->ports = Config::get('arrays.env_ports'); $request->ports = Config::get('arrays.env_ports');
$no_data = "N"; $no_data = 'N';
if (count($statistic4) == 0 && $_SERVER['REQUEST_URI'] != "/userPickingStats4") { if (count($statistic4) == 0 && $_SERVER['REQUEST_URI'] != '/userPickingStats4') {
$no_data = "Y"; $no_data = 'Y';
} }
#error_log("Time required to xyz: " . $duration . "\n", 3, "/temp/v4.log"); // error_log("Time required to xyz: " . $duration . "\n", 3, "/temp/v4.log");
return view( return view(
'm3::liberty-theme.pages.userPickingStats4', 'm3::liberty-theme.pages.userPickingStats4',
compact('statistic4', 'starting', 'user', 'user_array', 'monitor_array', 'totals_array', 'perf_array', 'request', 'no_data') compact('statistic4', 'starting', 'user', 'user_array', 'monitor_array', 'totals_array', 'perf_array', 'request', 'no_data'),
); );
} }
} }
} }
@@ -1,30 +1,28 @@
<?php <?php
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use DB;
use Config;
use Symfony\Component\HttpFoundation\Request;
use Illuminate\Support\Facades\Http; #added this for curl call to v4
use DateTime; use DateTime;
use DatePeriod; use DB;
use DateInterval; use Illuminate\Support\Facades\Http; // added this for curl call to v4
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\HttpFoundation\Request;
class userPickingStats5 extends Controller class userPickingStats5 extends Controller
{ {
public static function index(Request $request)
{
public static function index(Request $request){ // 618
// Get Logged User CO & WH. Legacy M3 profile data may not yet exist in PostgreSQL.
#618
# Get Logged User CO & WH. Legacy M3 profile data may not yet exist in PostgreSQL.
$co = ''; $co = '';
$whs = ''; $whs = '';
$user_array = []; $user_array = [];
try { try {
if (\Illuminate\Support\Facades\Schema::connection(config('m3.connection', 'pgsql'))->hasTable('icm428m')) { if (Schema::connection(config('m3.connection', 'pgsql'))->hasTable('icm428m')) {
$profile = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $profile = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH') ->select('R428US', 'R428CO', 'R428WH')
->where('R428US', strtoupper((string) m3_user())) ->where('R428US', strtoupper((string) m3_user()))
->first(); ->first();
$co = trim((string) ($profile->R428CO ?? '')); $co = trim((string) ($profile->R428CO ?? ''));
@@ -48,42 +46,42 @@ class userPickingStats5 extends Controller
} }
} }
} catch (\Throwable $e) { } catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::warning('M3 picking user list unavailable', ['exception' => $e->getMessage()]); Log::warning('M3 picking user list unavailable', ['exception' => $e->getMessage()]);
$user_array = []; $user_array = [];
} }
// Filter by date // Filter by date
if (isset($request->dates)) { if (isset($request->dates)) {
$date = explode (' - ', $request->dates); $date = explode(' - ', $request->dates);
$start = str_replace(array(' ', '-'), '', $date[0]); $start = str_replace([' ', '-'], '', $date[0]);
$end = str_replace(array(' ', '-'), '', $date[1]); $end = str_replace([' ', '-'], '', $date[1]);
$starting = $date[0]; $starting = $date[0];
$ending = $date[1]; $ending = $date[1];
} else { } else {
$start = date("Ymd", strtotime("-5 days")); $start = date('Ymd', strtotime('-5 days'));
$end = date("Ymd"); $end = date('Ymd');
$starting = date("Y-m-d", strtotime("-5 days")); $starting = date('Y-m-d', strtotime('-5 days'));
#$starting = "2021-11-01"; // $starting = "2021-11-01";
$ending = date("Y-m-d"); $ending = date('Y-m-d');
} }
// calculate day difference between 2 dates // calculate day difference between 2 dates
$str_date = new DateTime($starting); $str_date = new DateTime($starting);
$end_date = new DateTime($ending); $end_date = new DateTime($ending);
$interval = $str_date->diff($end_date); $interval = $str_date->diff($end_date);
$days = $interval->format('%a'); //retrieve number of days %a $days = $interval->format('%a'); // retrieve number of days %a
#echo "diff=$days<br>"; // echo "diff=$days<br>";
$user=$request->user; $user = $request->user;
// retrieve session user and pw, also the HTTP server host address and port // retrieve session user and pw, also the HTTP server host address and port
$username = $request->header('php-auth-user'); $username = $request->header('php-auth-user');
$pw = $request->header('php-auth-pw'); $pw = $request->header('php-auth-pw');
$http_host = $request->server('HTTP_HOST'); $http_host = $request->server('HTTP_HOST');
$urlStats4 = "http://$http_host/userPickingStats4"; $urlStats4 = "http://$http_host/userPickingStats4";
// initialize arrays // initialize arrays
$statistic5 = $totals_array = array(); $statistic5 = $totals_array = [];
// initialize totals // initialize totals
$totals_array['performance'] = 0; $totals_array['performance'] = 0;
$totals_array['blendedTargetLPH'] = 0; $totals_array['blendedTargetLPH'] = 0;
@@ -93,53 +91,53 @@ class userPickingStats5 extends Controller
// loop for the days difference and passing proper date to v4 to get json encoded response // loop for the days difference and passing proper date to v4 to get json encoded response
if (isset($request->dates)) { if (isset($request->dates)) {
for($x=0;$x<=$days;$x++) { for ($x = 0; $x <= $days; $x++) {
$next_date = date("Y-m-d",strtotime($starting."+$x days")); $next_date = date('Y-m-d', strtotime($starting . "+$x days"));
$parameters = ['dates'=>$next_date, 'user'=>$request->user, 'format'=>'json']; $parameters = ['dates' => $next_date, 'user' => $request->user, 'format' => 'json'];
#echo "<pre>"; print_r($parameters); echo "$urlStats4</pre>"; // echo "<pre>"; print_r($parameters); echo "$urlStats4</pre>";
$response = Http::withBasicAuth($username, $pw)->get($urlStats4, $parameters); $response = Http::withBasicAuth($username, $pw)->get($urlStats4, $parameters);
#echo $response; // echo $response;
$statusCode = $response->status(); $statusCode = $response->status();
#echo "$statusCode json return=".$response->getBody()." <br>"; // echo "$statusCode json return=".$response->getBody()." <br>";
$statistic5[$x] = json_decode($response->getBody(),true); $statistic5[$x] = json_decode($response->getBody(), true);
$totals_array['performance'] += isset($statistic5[$x]['performance'])?$statistic5[$x]['performance']:0; $totals_array['performance'] += isset($statistic5[$x]['performance']) ? $statistic5[$x]['performance'] : 0;
$totals_array['blendedTargetLPH'] += isset($statistic5[$x]['blendedTargetLPH'])?$statistic5[$x]['blendedTargetLPH']:0; $totals_array['blendedTargetLPH'] += isset($statistic5[$x]['blendedTargetLPH']) ? $statistic5[$x]['blendedTargetLPH'] : 0;
$totals_array['actualLPH'] += isset($statistic5[$x]['actualLPH'])?$statistic5[$x]['actualLPH']:0; $totals_array['actualLPH'] += isset($statistic5[$x]['actualLPH']) ? $statistic5[$x]['actualLPH'] : 0;
$totals_array['grossHours'] += isset($statistic5[$x]['grossHours'])?$statistic5[$x]['grossHours']:0; $totals_array['grossHours'] += isset($statistic5[$x]['grossHours']) ? $statistic5[$x]['grossHours'] : 0;
if(!isset($statistic5[$x]['day'])) { if (! isset($statistic5[$x]['day'])) {
$statistic5[$x]['day'] = $next_date; $statistic5[$x]['day'] = $next_date;
} }
if(isset($statistic5[$x]['performance'])) { if (isset($statistic5[$x]['performance'])) {
if($statistic5[$x]['performance']>0) { if ($statistic5[$x]['performance'] > 0) {
$y++; $y++;
} }
} else { } else {
$statistic5[$x]['performance']=0; $statistic5[$x]['performance'] = 0;
} }
} }
} }
if($y>0) { if ($y > 0) {
$totals_array['performance'] /= $y; $totals_array['performance'] /= $y;
$totals_array['blendedTargetLPH'] /= $y; $totals_array['blendedTargetLPH'] /= $y;
$totals_array['actualLPH'] /= $y; $totals_array['actualLPH'] /= $y;
$totals_array['grossHours'] /= $y; $totals_array['grossHours'] /= $y;
} }
if($request->format=="json") { if ($request->format == 'json') {
echo "<pre>"; echo '<pre>';
print_r($statistic5); print_r($statistic5);
echo "</pre>"; echo '</pre>';
}else{ } else {
#dd($statistic5); // dd($statistic5);
#if($statistic5[1]!=null) // if($statistic5[1]!=null)
return view('m3::liberty-theme.pages.userPickingStats5', compact('statistic5', 'totals_array', 'user_array', 'user', 'starting', 'ending', 'request')); return view('m3::liberty-theme.pages.userPickingStats5', compact('statistic5', 'totals_array', 'user_array', 'user', 'starting', 'ending', 'request'));
} }
@@ -2,89 +2,83 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB; use DB;
use Config;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Modules\M3\Models\ICM428M; use Modules\M3\Models\ICM428M;
class userProfileController extends Controller class userProfileController extends Controller
{ {
public static function index(Request $request)
{
public static function index(Request $request) { // Get Current USER
$loggedUser = strtoupper(m3_user());
# Get Current USER
$loggedUser = strtoUpper(m3_user());
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH','R428PL','R428FIRST','R428FAMILY') ->select('R428US', 'R428CO', 'R428WH', 'R428PL', 'R428FIRST', 'R428FAMILY')
->where('R428US','=',$loggedUser) ->where('R428US', '=', $loggedUser)
->where('R42821A','=','Y') ->where('R42821A', '=', 'Y')
->first(); ->first();
$IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get(); $IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
# Check if user is eligible for Profile update // Check if user is eligible for Profile update
if (isset($ICM428M->R428US)) { if (isset($ICM428M->R428US)) {
return view('m3::liberty-theme.pages.userProfile', compact('ICM428M','IC670M')); return view('m3::liberty-theme.pages.userProfile', compact('ICM428M', 'IC670M'));
} } else {
else{
abort(404); abort(404);
} }
} }
public static function updateUserProfile(Request $request) { public static function updateUserProfile(Request $request)
{
// dd($request->all()); // dd($request->all());
$R428US = isset($request->R428US) ? trim($request->R428US) : ''; $R428US = isset($request->R428US) ? trim($request->R428US) : '';
$R428DPW = isset($request->R428DPW) ? trim($request->R428DPW) : ''; $R428DPW = isset($request->R428DPW) ? trim($request->R428DPW) : '';
$R428CO = substr($R428DPW, 0, 3); $R428CO = substr($R428DPW, 0, 3);
$R428PL = substr($R428DPW, 3, 3); $R428PL = substr($R428DPW, 3, 3);
$R428WH = substr($R428DPW, 6, 3); $R428WH = substr($R428DPW, 6, 3);
// dd($R428US.'-'.$R428CO.'-'.$R428PL.'-'.$R428WH ); // dd($R428US.'-'.$R428CO.'-'.$R428PL.'-'.$R428WH );
if ($R428US!='') { if ($R428US != '') {
# Update record to ICM428M // Update record to ICM428M
DB::connection(config('m3.connection', 'pgsql'))->update("update ICM428M DB::connection(config('m3.connection', 'pgsql'))->update("update ICM428M
set R428CO='$R428CO', R428PL='$R428PL', R428WH='$R428WH' set R428CO='$R428CO', R428PL='$R428PL', R428WH='$R428WH'
where R428US='$R428US'"); where R428US='$R428US'");
// return "success"; // return "success";
return redirect('/userprofile')->with('success', 'Profile updated successfully!'); return redirect('/userprofile')->with('success', 'Profile updated successfully!');
} } else {
else{
return redirect('/userprofile')->with('success', 'Profile updated successfully!'); return redirect('/userprofile')->with('success', 'Profile updated successfully!');
} }
} }
public static function updateUserProfileAjax(Request $request) { public static function updateUserProfileAjax(Request $request)
{
// dd($request->all()); // dd($request->all());
$R428US = isset($request->R428US) ? trim($request->R428US) : ''; $R428US = isset($request->R428US) ? trim($request->R428US) : '';
$R428DPW = isset($request->R428DPW) ? trim($request->R428DPW) : ''; $R428DPW = isset($request->R428DPW) ? trim($request->R428DPW) : '';
$R428CO = substr($R428DPW, 0, 3); $R428CO = substr($R428DPW, 0, 3);
$R428PL = substr($R428DPW, 3, 3); $R428PL = substr($R428DPW, 3, 3);
$R428WH = substr($R428DPW, 6, 3); $R428WH = substr($R428DPW, 6, 3);
// dd($R428US.'-'.$R428CO.'-'.$R428PL.'-'.$R428WH ); // dd($R428US.'-'.$R428CO.'-'.$R428PL.'-'.$R428WH );
if ($R428US!='') { if ($R428US != '') {
# Update record to ICM428M // Update record to ICM428M
DB::connection(config('m3.connection', 'pgsql'))->update("update ICM428M DB::connection(config('m3.connection', 'pgsql'))->update("update ICM428M
set R428CO='$R428CO', R428PL='$R428PL', R428WH='$R428WH' set R428CO='$R428CO', R428PL='$R428PL', R428WH='$R428WH'
where R428US='$R428US'"); where R428US='$R428US'");
return response()->json(['success'=>true]); return response()->json(['success' => true]);
} } else {
else{ return response()->json(['success' => false]);
return response()->json(['success'=>false]);
} }
} }
} }
+104 -111
View File
@@ -1,35 +1,28 @@
<?php <?php
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use DB;
use Ayeo\Barcode;
// use Symfony\Component\HttpFoundation\Request; // use Symfony\Component\HttpFoundation\Request;
use Smalot\PdfParser\Parser;
use File;
use Cache; use Cache;
use DateTime;
use Config; use Config;
use Artisan; use DB;
use Dompdf\Dompdf;
use File;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use Ayeo\Barcode;
use PDF;
use Log; use Log;
use Http; use Modules\M3\Services\PostgresProgramBridge;
use PDF;
use Picqer\Barcode\BarcodeGeneratorPNG; use Picqer\Barcode\BarcodeGeneratorPNG;
use Dompdf\Dompdf; use Smalot\PdfParser\Parser;
use Zebra\Client;
use Zebra\Zpl\Image; use Zebra\Zpl\Image;
use Zebra\Zpl\Builder;
use Zebra\Zpl\GdDecoder;
use Modules\M3\Http\Controllers\GetContentsController;
class utilitiesContoller extends Controller class utilitiesContoller extends Controller
{ {
public static function index(Request $request) public static function index(Request $request)
{ {
dd("SentM3Test"); dd('SentM3Test');
// Get The Next ID by Calling POM002C // Get The Next ID by Calling POM002C
$PGMERRORS = ''; $PGMERRORS = '';
@@ -37,7 +30,7 @@ class utilitiesContoller extends Controller
// connect to toolkit using DB2 credentials (can also leave blank for default authority) // connect to toolkit using DB2 credentials (can also leave blank for default authority)
try { try {
$conn = app(\Modules\M3\Services\PostgresProgramBridge::class); $conn = app(PostgresProgramBridge::class);
} catch (\Exception $e) { } catch (\Exception $e) {
// Determine reason for failure. // Determine reason for failure.
// Probably database authentication error or invalid or unreachable database. // Probably database authentication error or invalid or unreachable database.
@@ -58,7 +51,7 @@ class utilitiesContoller extends Controller
break; break;
} }
} }
$conn->setOptions(array('persistent' => false, 'stateless' => true, 'debug' => true, 'debugLogFile' => '/www/sentustesx/htdocs/storage/logs/toolkit_debug.log')); $conn->setOptions(['persistent' => false, 'stateless' => true, 'debug' => true, 'debugLogFile' => '/www/sentustesx/htdocs/storage/logs/toolkit_debug.log']);
// Add LIB // Add LIB
// $result = $conn->CLCommand('ADDLIBLE LIB(MPDAT10)'); // $result = $conn->CLCommand('ADDLIBLE LIB(MPDAT10)');
@@ -68,7 +61,7 @@ class utilitiesContoller extends Controller
// $params[] = $conn->AddParameterChar('out',7,'eqNumber'); // $params[] = $conn->AddParameterChar('out',7,'eqNumber');
// AddParameterChar($io, $size, $comment, $varName, $value, $varying, $dimension) // AddParameterChar($io, $size, $comment, $varName, $value, $varying, $dimension)
# Add Warehouse Param // Add Warehouse Param
$params[] = $conn->AddParameterChar('in', 3, 'eqNumber', '', '111'); $params[] = $conn->AddParameterChar('in', 3, 'eqNumber', '', '111');
// AddParameterPackDec($io, $length, $scale, $comment, $varName, $value,$dimension) // AddParameterPackDec($io, $length, $scale, $comment, $varName, $value,$dimension)
@@ -84,9 +77,9 @@ class utilitiesContoller extends Controller
// Config::get('eproconf.misc.PGM1'), Config::get('eproconf.misc.libname4') // Config::get('eproconf.misc.PGM1'), Config::get('eproconf.misc.libname4')
// ICM700C EWOBJTST ICM700C ICM700CSBM // ICM700C EWOBJTST ICM700C ICM700CSBM
$result = $conn->PgmCall('ICM700CSBM', 'EWOBJTST', $params, array(), array()); $result = $conn->PgmCall('ICM700CSBM', 'EWOBJTST', $params, [], []);
if (!$result) { if (! $result) {
$PGMERRORS = 'Error calling program. Code: ' . $conn->getErrorCode() . ' Msg: ' . $conn->getErrorMsg(); $PGMERRORS = 'Error calling program. Code: ' . $conn->getErrorCode() . ' Msg: ' . $conn->getErrorMsg();
} }
// Successful Call // Successful Call
@@ -95,7 +88,7 @@ class utilitiesContoller extends Controller
// $AWREQN = $result['io_param']["var0"]; // $AWREQN = $result['io_param']["var0"];
} }
if ($PGMERRORS != "") { if ($PGMERRORS != '') {
// return back()->withMessage('Can not Create PR: '.$PGMERRORS); // return back()->withMessage('Can not Create PR: '.$PGMERRORS);
dump($PGMERRORS); dump($PGMERRORS);
} else { } else {
@@ -108,12 +101,12 @@ class utilitiesContoller extends Controller
public static function pdfReadWrite(Request $request) public static function pdfReadWrite(Request $request)
{ {
dump("PDF Read Write"); dump('PDF Read Write');
$pdfFileName = "E1232824-10826596"; $pdfFileName = 'E1232824-10826596';
// Parse PDF file and build necessary objects. // Parse PDF file and build necessary objects.
$parser = new \Smalot\PdfParser\Parser(); $parser = new Parser;
// $pdf = $parser->parseFile('/www/sentm3test/htdocs/labels/E1232824-10826596.pdf'); // $pdf = $parser->parseFile('/www/sentm3test/htdocs/labels/E1232824-10826596.pdf');
// dump($pdf); // dump($pdf);
@@ -129,19 +122,19 @@ class utilitiesContoller extends Controller
// Output base64 string // Output base64 string
// dump($base64PDF); // dump($base64PDF);
# Save Cache // Save Cache
Cache::put($pdfFileName, $base64PDF, now()->addMinutes(60)); Cache::put($pdfFileName, $base64PDF, now()->addMinutes(60));
# Retrieve Cache // Retrieve Cache
$cachedPdfFile = Cache::get($pdfFileName); $cachedPdfFile = Cache::get($pdfFileName);
dump("Retrieve Base64 Encoded PDF saved in Cache:"); dump('Retrieve Base64 Encoded PDF saved in Cache:');
dump($cachedPdfFile); dump($cachedPdfFile);
# remove File from Cache // remove File from Cache
// Cache::put(pdfFileName, 'value', -5); // Cache::put(pdfFileName, 'value', -5);
// Cache::forget($pdfFileName); // Cache::forget($pdfFileName);
# Base64 Decode and Display // Base64 Decode and Display
// $pdf = $parser->parseContent(base64_decode($base64PDF)); // $pdf = $parser->parseContent(base64_decode($base64PDF));
// $text = $pdf->getText(); // $text = $pdf->getText();
// dump($text); // dump($text);
@@ -155,12 +148,12 @@ class utilitiesContoller extends Controller
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL')); ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
dump("Run Fix IMSENTPKR..."); dump('Run Fix IMSENTPKR...');
$SHUSER = 'TWOSHIP'; $SHUSER = 'TWOSHIP';
# Get User CO & WH // Get User CO & WH
# Get users from ICM428M // Get users from ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US', 'R428CO', 'R428WH') ->select('R428US', 'R428CO', 'R428WH')
->where('R428US', '=', $SHUSER) ->where('R428US', '=', $SHUSER)
@@ -169,7 +162,7 @@ class utilitiesContoller extends Controller
$DIVI = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; $DIVI = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '';
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; $WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '';
# Get Parts And Lots from ICM688M2 // Get Parts And Lots from ICM688M2
$ICM688M2SLTMP = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m2') $ICM688M2SLTMP = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m2')
->select('A5MACPKR', 'A5SENTPKR', 'A5PICKSTRD') ->select('A5MACPKR', 'A5SENTPKR', 'A5PICKSTRD')
->distinct() ->distinct()
@@ -187,16 +180,16 @@ class utilitiesContoller extends Controller
$A5MACPKR = isset($ICM688M2SL->A5MACPKR) ? $ICM688M2SL->A5MACPKR : ''; $A5MACPKR = isset($ICM688M2SL->A5MACPKR) ? $ICM688M2SL->A5MACPKR : '';
$A5SENTPKR = isset($ICM688M2SL->A5SENTPKR) ? $ICM688M2SL->A5SENTPKR : ''; $A5SENTPKR = isset($ICM688M2SL->A5SENTPKR) ? $ICM688M2SL->A5SENTPKR : '';
dump("ICM688M2 Record: " . $A5MACPKR . '-' . $A5SENTPKR); dump('ICM688M2 Record: ' . $A5MACPKR . '-' . $A5SENTPKR);
$ICM799MINS = DB::connection(config('m3.connection', 'pgsql'))->table('icm799m') $ICM799MINS = DB::connection(config('m3.connection', 'pgsql'))->table('icm799m')
->where("IMDELNO", '=', $A5MACPKR) ->where('IMDELNO', '=', $A5MACPKR)
->update(["IMSENTPKR" => $A5SENTPKR]); ->update(['IMSENTPKR' => $A5SENTPKR]);
} }
} }
# Generate GS1-128 // Generate GS1-128
public static function generateGS128(Request $request) public static function generateGS128(Request $request)
{ {
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL')); ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
@@ -205,34 +198,34 @@ class utilitiesContoller extends Controller
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
try { try {
Log::channel('LabelCron')->info(">>> Run GS1 Label creation Command..."); Log::channel('LabelCron')->info('>>> Run GS1 Label creation Command...');
# Get the Calling User // Get the Calling User
// $userId = 'TWOSHIP'; // $userId = 'TWOSHIP';
// $SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : ''); // $SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : '');
# Get Manifest Array // Get Manifest Array
$GSArray = $request->query(); $GSArray = $request->query();
// dump($GSArray); // dump($GSArray);
$SHUSER = isset($GSArray['User']) ? trim($GSArray['User']) : ''; $SHUSER = isset($GSArray['User']) ? trim($GSArray['User']) : '';
if ($SHUSER != '') { if ($SHUSER != '') {
# Get User CO & WH from Table ICM428M // Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US', 'R428CO', 'R428WH', 'R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US', '=', $SHUSER) ->where('R428US', '=', $SHUSER)
->first(); ->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; # User $R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; // User
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; # Company $COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; # Plant $PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; # WareHouse $WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; // WareHouse
$Macpkr = $GSArray['Macpkr']; $Macpkr = $GSArray['Macpkr'];
$packageType = trim($GSArray['packageType']); # 1 => Pallet , 0 => Carton $packageType = trim($GSArray['packageType']); // 1 => Pallet , 0 => Carton
$packageTypeDesc = $packageType == 1 ? 'Pallet' : 'Carton'; $packageTypeDesc = $packageType == 1 ? 'Pallet' : 'Carton';
$manufactID = '0826528'; # MAK : get ID from Nvent and save to Config File $manufactID = '0826528'; // MAK : get ID from Nvent and save to Config File
$total_length = 9; $total_length = 9;
$html = ' $html = '
@@ -263,73 +256,73 @@ class utilitiesContoller extends Controller
</head> </head>
<body style="font-family: Arial, sans-serif;">'; <body style="font-family: Arial, sans-serif;">';
# Get number of Pallets // Get number of Pallets
$packageCount = count($GSArray['PackagesArray']); $packageCount = count($GSArray['PackagesArray']);
$packageNum = 1; $packageNum = 1;
# Get GS1 Label MAX ID from ICM695M3 : // Get GS1 Label MAX ID from ICM695M3 :
$GS1SEQUENCESel = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m3')->max('ID'); $GS1SEQUENCESel = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m3')->max('ID');
$GS1SEQUENCE = isset($GS1SEQUENCESel) ? $GS1SEQUENCESel : 0; $GS1SEQUENCE = isset($GS1SEQUENCESel) ? $GS1SEQUENCESel : 0;
# Loop PackagesArray : Build Table for PDF and Insert to ICM695m3 // Loop PackagesArray : Build Table for PDF and Insert to ICM695m3
foreach ($GSArray['PackagesArray'] as $key => $value) { foreach ($GSArray['PackagesArray'] as $key => $value) {
$table_style = $packageNum < $packageCount ? ' style="page-break-after: always;" ' : ''; $table_style = $packageNum < $packageCount ? ' style="page-break-after: always;" ' : '';
$A2INTBOX = trim($value); $A2INTBOX = trim($value);
$GS1SEQUENCE++; $GS1SEQUENCE++;
$GS1SEQUENCEID = str_pad($GS1SEQUENCE, $total_length, "0", STR_PAD_LEFT); $GS1SEQUENCEID = str_pad($GS1SEQUENCE, $total_length, '0', STR_PAD_LEFT);
# Build GS1 18 Digits Code // Build GS1 18 Digits Code
$gs1_128_bc_1 = '00' . $packageType . $manufactID . $GS1SEQUENCEID; $gs1_128_bc_1 = '00' . $packageType . $manufactID . $GS1SEQUENCEID;
# Calculate Check Digit // Calculate Check Digit
$digits = str_split($gs1_128_bc_1); $digits = str_split($gs1_128_bc_1);
$sum = 0; $sum = 0;
$length = count($digits); $length = count($digits);
# Loop through each digit starting from the right // Loop through each digit starting from the right
for ($i = 0; $i < $length; $i++) { for ($i = 0; $i < $length; $i++) {
$digit = $digits[$length - $i - 1]; $digit = $digits[$length - $i - 1];
# Assign a weight of 3 or 1 alternately // Assign a weight of 3 or 1 alternately
$weight = ($i % 2 == 0) ? 3 : 1; $weight = ($i % 2 == 0) ? 3 : 1;
# Add the product of the digit and its weight to the sum // Add the product of the digit and its weight to the sum
$sum += $digit * $weight; $sum += $digit * $weight;
} }
# Calculate the remainder when sum is divided by 10 // Calculate the remainder when sum is divided by 10
$remainder = $sum % 10; $remainder = $sum % 10;
# If remainder is 0, check digit is 0; otherwise, subtract remainder from 10 // If remainder is 0, check digit is 0; otherwise, subtract remainder from 10
$checkDigit = ($remainder == 0) ? 0 : 10 - $remainder; $checkDigit = ($remainder == 0) ? 0 : 10 - $remainder;
# End Check Digit Calculation // End Check Digit Calculation
# SSCC 18 Digits Code // SSCC 18 Digits Code
$gs1_128_bc = $gs1_128_bc_1 . $checkDigit; $gs1_128_bc = $gs1_128_bc_1 . $checkDigit;
$gs1_128_bc_desc = '(00)' . $packageType . $manufactID . $GS1SEQUENCEID . $checkDigit; $gs1_128_bc_desc = '(00)' . $packageType . $manufactID . $GS1SEQUENCEID . $checkDigit;
$data = [ $data = [
'ship_to' => $GSArray["Recipient_CompanyName"] . '<br>' . $GSArray["Recipient_Address1"] . '<br>' . 'ship_to' => $GSArray['Recipient_CompanyName'] . '<br>' . $GSArray['Recipient_Address1'] . '<br>' .
$GSArray["Recipient_City"] . ',' . $GSArray["Recipient_State"] $GSArray['Recipient_City'] . ',' . $GSArray['Recipient_State']
. '<br>' . $GSArray["Recipient_PostalCode"], . '<br>' . $GSArray['Recipient_PostalCode'],
'from' => $GSArray["Sender_CompanyName"] . '<br>' . $GSArray["Sender_Address1"] . '<br>' . 'from' => $GSArray['Sender_CompanyName'] . '<br>' . $GSArray['Sender_Address1'] . '<br>' .
$GSArray["Sender_City"] . ',' . $GSArray["Sender_State"] $GSArray['Sender_City'] . ',' . $GSArray['Sender_State']
. '<br>' . $GSArray["Sender_PostalCode"], . '<br>' . $GSArray['Sender_PostalCode'],
'ship_to_lbl' => '420' . $GSArray["Recipient_PostalCode"], 'ship_to_lbl' => '420' . $GSArray['Recipient_PostalCode'],
'ship_to_desc' => '(420)' . $GSArray["Recipient_PostalCode"], 'ship_to_desc' => '(420)' . $GSArray['Recipient_PostalCode'],
'pro' => '190071217845706', # MAK : Check missing info with Brad 'pro' => '190071217845706', // MAK : Check missing info with Brad
'item_number' => '10000B', 'item_number' => '10000B',
'upc' => '098506095310', 'upc' => '098506095310',
'quantity' => '1', 'quantity' => '1',
'serial_shipping_container' => $gs1_128_bc_desc 'serial_shipping_container' => $gs1_128_bc_desc,
]; ];
# Initialize barcode generator // Initialize barcode generator
$generator = new BarcodeGeneratorPNG(); $generator = new BarcodeGeneratorPNG;
# Generate barcodes // Generate barcodes
$shipToPostalCodeBarcode = $generator->getBarcode($data['ship_to_lbl'], $generator::TYPE_CODE_128); $shipToPostalCodeBarcode = $generator->getBarcode($data['ship_to_lbl'], $generator::TYPE_CODE_128);
$serialShippingContainerBarcode = $generator->getBarcode($data['serial_shipping_container'], $generator::TYPE_CODE_128, 2, 50); $serialShippingContainerBarcode = $generator->getBarcode($data['serial_shipping_container'], $generator::TYPE_CODE_128, 2, 50);
# HTML content for the label // HTML content for the label
$html .= ' $html .= '
<table ' . $table_style . '> <table ' . $table_style . '>
<tr> <tr>
@@ -346,15 +339,15 @@ class utilitiesContoller extends Controller
' . $data['ship_to_desc'] . ' ' . $data['ship_to_desc'] . '
</td> </td>
<td class="border_btm margin_t align_lft"> <td class="border_btm margin_t align_lft">
Carrier: ' . $GSArray["CarrierName"] . ' <br> Carrier: ' . $GSArray['CarrierName'] . ' <br>
PRO #: ' . $GSArray["trackingno"] . ' <br> PRO #: ' . $GSArray['trackingno'] . ' <br>
B/L #: ' . $GSArray["BOLnumber"] . ' <br> B/L #: ' . $GSArray['BOLnumber'] . ' <br>
Ref : ' . $A2INTBOX . ' Ref : ' . $A2INTBOX . '
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="4" class="border_btm margin_t align_lft"> <td colspan="4" class="border_btm margin_t align_lft">
PURCHASE ORDER: ' . $GSArray["ShipmentPONumber"] . ' <br> PURCHASE ORDER: ' . $GSArray['ShipmentPONumber'] . ' <br>
Vendor: ' . $manufactID . ' Vendor: ' . $manufactID . '
</td> </td>
</tr> </tr>
@@ -373,11 +366,11 @@ class utilitiesContoller extends Controller
$packageNum++; $packageNum++;
# Insert new Record to ICM695M3 $gs1_128_bc // Insert new Record to ICM695M3 $gs1_128_bc
$ICM695M3SQLInsert = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m3') $ICM695M3SQLInsert = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m3')
->insert(['A2CO' => $COMPANY, 'A2WHS' => $WHS, 'A2PLANT'=>$PLANT,'A2MACPKR' => $Macpkr, 'A2GS1LABEL' => $gs1_128_bc, "A2INTBOX" => $A2INTBOX]); ->insert(['A2CO' => $COMPANY, 'A2WHS' => $WHS, 'A2PLANT' => $PLANT, 'A2MACPKR' => $Macpkr, 'A2GS1LABEL' => $gs1_128_bc, 'A2INTBOX' => $A2INTBOX]);
Log::channel('LabelCron')->info("<<< GS1-128...End of Label Creation for Mackpkr: " . $Macpkr); Log::channel('LabelCron')->info('<<< GS1-128...End of Label Creation for Mackpkr: ' . $Macpkr);
} }
$html .= '</body> </html>'; $html .= '</body> </html>';
@@ -385,25 +378,25 @@ class utilitiesContoller extends Controller
ob_start(); ob_start();
# Initialize Dompdf // Initialize Dompdf
$dompdf = new Dompdf(); $dompdf = new Dompdf;
$dompdf->loadHtml($html); $dompdf->loadHtml($html);
$dompdf->setPaper('a6', 'portrait'); $dompdf->setPaper('a6', 'portrait');
# Render the HTML as PDF // Render the HTML as PDF
$dompdf->render(); $dompdf->render();
# Output the generated PDF to Browser // Output the generated PDF to Browser
// $dompdf->stream(); // $dompdf->stream();
$pdfContent = $dompdf->output(); $pdfContent = $dompdf->output();
// dump($pdfContent); // dump($pdfContent);
$labelsPath = Config::get('arrays.PdfPath'); // '/www/sentm3live/htdocs/labels/'; $labelsPath = Config::get('arrays.PdfPath'); // '/www/sentm3live/htdocs/labels/';
# Put the PDF in labels/CarrierLabel // Put the PDF in labels/CarrierLabel
$GSFolder = "GSLabel"; $GSFolder = 'GSLabel';
$carrierFileName = $GSFolder . '_' . $Macpkr . '_' . $COMPANY . '_' . $WHS . '_' . $A2INTBOX; $carrierFileName = $GSFolder . '_' . $Macpkr . '_' . $COMPANY . '_' . $WHS . '_' . $A2INTBOX;
# LTL // LTL
// if ($packageType=='1') { // if ($packageType=='1') {
// $carrierFileName = $GSFolder.'_'.$Macpkr.'_'.$COMPANY.'_'.$WHS; // $carrierFileName = $GSFolder.'_'.$Macpkr.'_'.$COMPANY.'_'.$WHS;
// } // }
@@ -424,19 +417,20 @@ class utilitiesContoller extends Controller
// Log::channel('LabelCron')->info("<<< GS1-128...End of Label Creation for Mackpkr: ".$Macpkr); // Log::channel('LabelCron')->info("<<< GS1-128...End of Label Creation for Mackpkr: ".$Macpkr);
return json_encode(["result" => "success", "GS1File" => $GS1FileNameNoRoot]); return json_encode(['result' => 'success', 'GS1File' => $GS1FileNameNoRoot]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
// Log::error($th); // Log::error($th);
Log::channel('LabelCron')->error($th); Log::channel('LabelCron')->error($th);
return json_encode(["result" => "error", "GS1File" => $th]);
return json_encode(['result' => 'error', 'GS1File' => $th]);
} }
} }
public static function generateGS128Tst(Request $request) public static function generateGS128Tst(Request $request)
{ {
print_r(">>> Generate PDF"); print_r('>>> Generate PDF');
// $builder = new Barcode\Builder(); // $builder = new Barcode\Builder();
// $image = $builder->output('(10)123456(400)11(3906)333333'); // $image = $builder->output('(10)123456(400)11(3906)333333');
@@ -462,18 +456,18 @@ class utilitiesContoller extends Controller
'item_number' => '10000B', 'item_number' => '10000B',
'upc' => '098506095310', 'upc' => '098506095310',
'quantity' => '1', 'quantity' => '1',
'serial_shipping_container' => '(00)107904370000005' 'serial_shipping_container' => '(00)107904370000005',
]; ];
// Initialize barcode generator // Initialize barcode generator
$generator = new BarcodeGeneratorPNG(); $generator = new BarcodeGeneratorPNG;
// Generate barcodes // Generate barcodes
$shipToPostalCodeBarcode = $generator->getBarcode($data['ship_to_postal_code'], $generator::TYPE_CODE_128); $shipToPostalCodeBarcode = $generator->getBarcode($data['ship_to_postal_code'], $generator::TYPE_CODE_128);
$proBarcode = $generator->getBarcode($data['pro'], $generator::TYPE_CODE_128); $proBarcode = $generator->getBarcode($data['pro'], $generator::TYPE_CODE_128);
$serialShippingContainerBarcode = $generator->getBarcode($data['serial_shipping_container'], $generator::TYPE_CODE_128, 2, 50); $serialShippingContainerBarcode = $generator->getBarcode($data['serial_shipping_container'], $generator::TYPE_CODE_128, 2, 50);
# HTML content for the label // HTML content for the label
// border="1" style="border-collapse: collapse; width: 100%; height: 300px;" // border="1" style="border-collapse: collapse; width: 100%; height: 300px;"
$html = ' $html = '
<html> <html>
@@ -545,7 +539,7 @@ class utilitiesContoller extends Controller
// return ($html); // return ($html);
// Initialize Dompdf // Initialize Dompdf
$dompdf = new Dompdf(); $dompdf = new Dompdf;
$dompdf->loadHtml($html); $dompdf->loadHtml($html);
$dompdf->setPaper('a6', 'portrait'); $dompdf->setPaper('a6', 'portrait');
// Render the HTML as PDF // Render the HTML as PDF
@@ -554,13 +548,12 @@ class utilitiesContoller extends Controller
// Output the generated PDF to Browser // Output the generated PDF to Browser
// $dompdf->stream(); // $dompdf->stream();
$pdfContent = $dompdf->output(); $pdfContent = $dompdf->output();
// // return $pdfContent; // // return $pdfContent;
$labelsPath = '/www/sentm3live/htdocs/labels/'; $labelsPath = '/www/sentm3live/htdocs/labels/';
// # Put the PDF in labels/CarrierLabel // # Put the PDF in labels/CarrierLabel
$GSFolder = "GSLabel"; $GSFolder = 'GSLabel';
$carrierFileName = "GSLabel"; $carrierFileName = 'GSLabel';
file_put_contents($labelsPath . $GSFolder . '/' . $carrierFileName . '.pdf', $pdfContent); file_put_contents($labelsPath . $GSFolder . '/' . $carrierFileName . '.pdf', $pdfContent);
// Save the PDF string to a temporary file for debugging // Save the PDF string to a temporary file for debugging
@@ -573,7 +566,7 @@ class utilitiesContoller extends Controller
// throw new Exception('PDF generation failed.'); // throw new Exception('PDF generation failed.');
// } // }
# Create an Imagick instance // Create an Imagick instance
// $imagick = new \Imagick(); // $imagick = new \Imagick();
// // Read the PDF from the string // // Read the PDF from the string
@@ -601,25 +594,25 @@ class utilitiesContoller extends Controller
// $GS1SEQUENCEID = str_pad($GS1SEQUENCE, $total_length, "0", STR_PAD_LEFT); // $GS1SEQUENCEID = str_pad($GS1SEQUENCE, $total_length, "0", STR_PAD_LEFT);
// dump($GS1SEQUENCEID); // dump($GS1SEQUENCEID);
# MAK Get Contents // MAK Get Contents
# ESN1 // ESN1
# $AYMACPKR='888568'; // LTL example // $AYMACPKR='888568'; // LTL example
# $AYMACPKR='894337'; // another LTL example with smaller orders, therefore pallets are more mixed // $AYMACPKR='894337'; // another LTL example with smaller orders, therefore pallets are more mixed
# $AYMACPKR='1225311'; // parcel example // $AYMACPKR='1225311'; // parcel example
# ESN2 // ESN2
// $AYMACPKR='999999'; // LTL example // $AYMACPKR='999999'; // LTL example
$AYMACPKR = '748101'; // LTL example $AYMACPKR = '748101'; // LTL example
$myRequest = new Request(); $myRequest = new Request;
$myRequest->setMethod('POST'); $myRequest->setMethod('POST');
$myRequest->request->add([ $myRequest->request->add([
'MACPKR' => $AYMACPKR 'MACPKR' => $AYMACPKR,
]); ]);
// Call the controller method properly // Call the controller method properly
$controller = new GetContentsController(); $controller = new GetContentsController;
$response = $controller->processShipment($myRequest); $response = $controller->processShipment($myRequest);
$responseData = $response->getData(); $responseData = $response->getData();
@@ -630,13 +623,13 @@ class utilitiesContoller extends Controller
$error = isset($responseData->error) ? $responseData->error : ''; $error = isset($responseData->error) ? $responseData->error : '';
if ($error == '') { if ($error == '') {
# Get Commodities // Get Commodities
$commoditiesTmp = isset($responseData->commodities) ? $responseData->commodities : ''; $commoditiesTmp = isset($responseData->commodities) ? $responseData->commodities : '';
if ($commoditiesTmp != '') { if ($commoditiesTmp != '') {
$commodities = json_encode($commoditiesTmp); $commodities = json_encode($commoditiesTmp);
dump($commodities); dump($commodities);
} else { } else {
dump("Commodities Empty..."); dump('Commodities Empty...');
} }
} else { } else {
dump($error); dump($error);
@@ -2,83 +2,81 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use DB;
use Config; use Config;
use DB;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
// use Modules\M3\Models\ICM711M; // use Modules\M3\Models\ICM711M;
use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class whsePerfController extends Controller class whsePerfController extends Controller
{ {
public static function index(Request $request)
public static function index(Request $request) { {
return view('m3::liberty-theme.pages.whsePerfRequest'); return view('m3::liberty-theme.pages.whsePerfRequest');
} }
public static function displayTable(Request $request) { public static function displayTable(Request $request)
{
// ********************************************************************************** // **********************************************************************************
// **** Changes in this section must be replicated in function exportTable below **** // **** Changes in this section must be replicated in function exportTable below ****
// ********************************************************************************** // **********************************************************************************
$date_in_yr = isset($request->date_in_yr)?$request->date_in_yr:date('Y'); $date_in_yr = isset($request->date_in_yr) ? $request->date_in_yr : date('Y');
$date_in_mth = isset($request->date_in_mth)?$request->date_in_mth:date('m'); $date_in_mth = isset($request->date_in_mth) ? $request->date_in_mth : date('m');
#$date_in = isset($request->date_in)?$request->date_in:date('Ymd'); // $date_in = isset($request->date_in)?$request->date_in:date('Ymd');
$date_in = $date_in_yr.$date_in_mth."01"; $date_in = $date_in_yr . $date_in_mth . '01';
$sqlstmt = "select AVDATE, AVANOTESCL,AVADLRCL,AVAWGTCL,AVANOTESCH,AVADLRCH,AVAWGTCH,AVANOTESOP,AVADLROP,AVAWGTOP, $sqlstmt = 'select AVDATE, AVANOTESCL,AVADLRCL,AVAWGTCL,AVANOTESCH,AVADLRCH,AVAWGTCH,AVANOTESOP,AVADLROP,AVAWGTOP,
AVLNOTESCL,AVLDLRCL,AVLWGTCL,AVLNOTESCH,AVLDLRCH,AVLWGTCH,AVLNOTESOP,AVLDLROP,AVLWGTOP, AVLNOTESCL,AVLDLRCL,AVLWGTCL,AVLNOTESCH,AVLDLRCH,AVLWGTCH,AVLNOTESOP,AVLDLROP,AVLWGTOP,
AVPNOTESCL,AVPDLRCL,AVPWGTCL,AVPNOTESCH,AVPDLRCH,AVPWGTCH,AVPNOTESOP,AVPDLROP,AVPWGTOP, AVPNOTESCL,AVPDLRCL,AVPWGTCL,AVPNOTESCH,AVPDLRCH,AVPWGTCH,AVPNOTESOP,AVPDLROP,AVPWGTOP,
AVINOTESCL,AVIDLRCL,AVIWGTCL,AVINOTESOP,AVIDLROP,AVIWGTOP AVINOTESCL,AVIDLRCL,AVIWGTCL,AVINOTESOP,AVIDLROP,AVIWGTOP
from ICM711M from ICM711M
where AVDATE between ".date('Ym', strtotime($date_in))."00 and ".date('Ym', strtotime($date_in))."32"; where AVDATE between ' . date('Ym', strtotime($date_in)) . '00 and ' . date('Ym', strtotime($date_in)) . '32';
$ICM711M = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt); $ICM711M = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt);
$USER_INFO = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')->selectRaw('R428US as USERPRF, R428STS as STATUS, NULL as DATE_EXPIRED, NULL as EXPIRED')->get()->all(); $USER_INFO = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')->selectRaw('R428US as USERPRF, R428STS as STATUS, NULL as DATE_EXPIRED, NULL as EXPIRED')->get()->all();
$power_user = DB::connection(config('m3.connection', 'pgsql'))->select("select R428PWRUSR, R428CO, R428PL, R428WH from ICM428M where R428US='".strtoUpper(m3_user())."'"); $power_user = DB::connection(config('m3.connection', 'pgsql'))->select("select R428PWRUSR, R428CO, R428PL, R428WH from ICM428M where R428US='" . strtoupper(m3_user()) . "'");
$pct_array = Config::get('arrays.whsePerf_targets'); $pct_array = Config::get('arrays.whsePerf_targets');
return view('m3::liberty-theme.pages.whsePerf', compact('ICM711M','power_user','USER_INFO','date_in','pct_array')); return view('m3::liberty-theme.pages.whsePerf', compact('ICM711M', 'power_user', 'USER_INFO', 'date_in', 'pct_array'));
} }
public function exportTable(Request $request) { public function exportTable(Request $request)
{
$date_in_yr = isset($request->date_in_yr)?$request->date_in_yr:date('Y'); $date_in_yr = isset($request->date_in_yr) ? $request->date_in_yr : date('Y');
$date_in_mth = isset($request->date_in_mth)?$request->date_in_mth:date('m'); $date_in_mth = isset($request->date_in_mth) ? $request->date_in_mth : date('m');
#$date_in = isset($request->date_in)?$request->date_in:date('Ymd'); // $date_in = isset($request->date_in)?$request->date_in:date('Ymd');
$date_in = $date_in_yr.$date_in_mth."01"; $date_in = $date_in_yr . $date_in_mth . '01';
$sqlstmt = "select AVDATE, AVANOTESCL,AVADLRCL,AVAWGTCL,AVANOTESCH,AVADLRCH,AVAWGTCH,AVANOTESOP,AVADLROP,AVAWGTOP, $sqlstmt = 'select AVDATE, AVANOTESCL,AVADLRCL,AVAWGTCL,AVANOTESCH,AVADLRCH,AVAWGTCH,AVANOTESOP,AVADLROP,AVAWGTOP,
AVLNOTESCL,AVLDLRCL,AVLWGTCL,AVLNOTESCH,AVLDLRCH,AVLWGTCH,AVLNOTESOP,AVLDLROP,AVLWGTOP, AVLNOTESCL,AVLDLRCL,AVLWGTCL,AVLNOTESCH,AVLDLRCH,AVLWGTCH,AVLNOTESOP,AVLDLROP,AVLWGTOP,
AVPNOTESCL,AVPDLRCL,AVPWGTCL,AVPNOTESCH,AVPDLRCH,AVPWGTCH,AVPNOTESOP,AVPDLROP,AVPWGTOP, AVPNOTESCL,AVPDLRCL,AVPWGTCL,AVPNOTESCH,AVPDLRCH,AVPWGTCH,AVPNOTESOP,AVPDLROP,AVPWGTOP,
AVINOTESCL,AVIDLRCL,AVIWGTCL,AVINOTESOP,AVIDLROP,AVIWGTOP AVINOTESCL,AVIDLRCL,AVIWGTCL,AVINOTESOP,AVIDLROP,AVIWGTOP
from ICM711M from ICM711M
where AVDATE between ".date('Ym', strtotime($date_in))."00 and ".date('Ym', strtotime($date_in))."32"; where AVDATE between ' . date('Ym', strtotime($date_in)) . '00 and ' . date('Ym', strtotime($date_in)) . '32';
$ICM711M = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt); $ICM711M = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt);
$USER_INFO = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')->selectRaw('R428US as USERPRF, R428STS as STATUS, NULL as DATE_EXPIRED, NULL as EXPIRED')->get()->all(); $USER_INFO = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')->selectRaw('R428US as USERPRF, R428STS as STATUS, NULL as DATE_EXPIRED, NULL as EXPIRED')->get()->all();
$power_user = DB::connection(config('m3.connection', 'pgsql'))->select("select R428PWRUSR, R428CO, R428PL, R428WH from ICM428M where R428US='".strtoUpper(m3_user())."'"); $power_user = DB::connection(config('m3.connection', 'pgsql'))->select("select R428PWRUSR, R428CO, R428PL, R428WH from ICM428M where R428US='" . strtoupper(m3_user()) . "'");
$pct_array = Config::get('arrays.whsePerf_targets'); $pct_array = Config::get('arrays.whsePerf_targets');
$html = view('m3::liberty-theme.pages.whsePerf', compact('ICM711M','power_user','USER_INFO','date_in','pct_array'))->render(); $html = view('m3::liberty-theme.pages.whsePerf', compact('ICM711M', 'power_user', 'USER_INFO', 'date_in', 'pct_array'))->render();
libxml_use_internal_errors(true); libxml_use_internal_errors(true);
$doc = new \DOMDocument(); $doc = new \DOMDocument;
$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); // Extract only table elements $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); // Extract only table elements
$tables = $doc->getElementsByTagName('table'); $tables = $doc->getElementsByTagName('table');
if ($tables->length === 0) { if ($tables->length === 0) {
abort(400, 'No table found in HTML'); abort(400, 'No table found in HTML');
} }
// Create new document with only the table // Create new document with only the table
$newDoc = new \DOMDocument(); $newDoc = new \DOMDocument;
$newDoc->appendChild($newDoc->importNode($tables->item(0), true)); $newDoc->appendChild($newDoc->importNode($tables->item(0), true));
$cleanHtml = '<!DOCTYPE html><html><body>' . $newDoc->saveHTML() . '</body></html>'; $cleanHtml = '<!DOCTYPE html><html><body>' . $newDoc->saveHTML() . '</body></html>';
libxml_clear_errors(); libxml_clear_errors();
@@ -91,7 +89,7 @@ class whsePerfController extends Controller
$tempExcel = tempnam(sys_get_temp_dir(), 'excel'); $tempExcel = tempnam(sys_get_temp_dir(), 'excel');
$writer->save($tempExcel); $writer->save($tempExcel);
unlink($tempFile); unlink($tempFile);
return response()->download($tempExcel, $fileName)->deleteFileAfterSend(true); return response()->download($tempExcel, $fileName)->deleteFileAfterSend(true);
} }
} }
@@ -2,33 +2,29 @@
namespace Modules\M3\Http\Controllers; namespace Modules\M3\Http\Controllers;
use Modules\M3\Http\Controllers\Controller;
use Str;
use DB; use DB;
use Config;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response; use Str;
class whsePerfDetailsController extends Controller class whsePerfDetailsController extends Controller
{ {
public static function index(Request $request)
public static function index(Request $request) { {
// $date_in = date('Y-m-d', strtotime($request->date_in)); // $date_in = date('Y-m-d', strtotime($request->date_in));
$date_in = isset($request->date)?date('Y-m-d',strtotime($request->date)):date('Y-m-d'); $date_in = isset($request->date) ? date('Y-m-d', strtotime($request->date)) : date('Y-m-d');
$date_in_minus_4_months = date('Y-m-d', strtotime($date_in .' -4 months')); $date_in_minus_4_months = date('Y-m-d', strtotime($date_in . ' -4 months'));
$for = isset($request->for)?$request->for:'a'; $for = isset($request->for) ? $request->for : 'a';
$username = m3_user() !== '' ? Str::upper(trim(m3_user())) : ''; $username = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
# Get Logged User CO & WH & PL // Get Logged User CO & WH & PL
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m') $ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US','R428CO', 'R428WH', 'R428PL') ->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US','=',$username) ->where('R428US', '=', $username)
->first(); ->first();
$co = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; $co = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '';
$whseno = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; $whseno = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '';
$plantno = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; $plantno = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '';
$all = "tempfile4 as ( $all = "tempfile4 as (
@@ -64,27 +60,26 @@ class whsePerfDetailsController extends Controller
select * from tempfile4 order by source"; select * from tempfile4 order by source";
switch ($for) { switch ($for) {
case "a": case 'a':
$stmt2=$all; $stmt2 = $all;
break; break;
case "l": case 'l':
$stmt2=$ltl; $stmt2 = $ltl;
break; break;
case "p": case 'p':
$stmt2=$parcel; $stmt2 = $parcel;
break; break;
case "i": case 'i':
$stmt2=$io; $stmt2 = $io;
break; break;
} }
#phpinfo(); // phpinfo();
include($_SERVER['DOCUMENT_ROOT'].'/../../KPI2_update711M_SQL_main.inc.php'); include $_SERVER['DOCUMENT_ROOT'] . '/../../KPI2_update711M_SQL_main.inc.php';
#var_dump($sqlstmt1.$stmt2); // var_dump($sqlstmt1.$stmt2);
$perfDetails = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt1.$stmt2); $perfDetails = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt1 . $stmt2);
#var_dump($perfDetails); // var_dump($perfDetails);
return view('m3::liberty-theme.pages.whsePerfDetails', compact('perfDetails','date_in','for')); return view('m3::liberty-theme.pages.whsePerfDetails', compact('perfDetails', 'date_in', 'for'));
} }
} }
+3 -1
View File
@@ -3,13 +3,15 @@
namespace Modules\M3\Http\Middleware; namespace Modules\M3\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware; use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class Authenticate extends Middleware class Authenticate extends Middleware
{ {
/** /**
* Get the path the user should be redirected to when they are not authenticated. * Get the path the user should be redirected to when they are not authenticated.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
*
* @return string|null * @return string|null
*/ */
protected function redirectTo($request) protected function redirectTo($request)
+27 -22
View File
@@ -10,19 +10,20 @@ class BasicAuth
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
*
* @return mixed * @return mixed
*/ */
public function handle(Request $request, Closure $next) public function handle(Request $request, Closure $next)
{ {
//select md5 or crypt for $mode. md5 is for md5 encoded passwords, crypt is for passwords encoded using apache's httpasswd // select md5 or crypt for $mode. md5 is for md5 encoded passwords, crypt is for passwords encoded using apache's httpasswd
$mode = "crypt"; $mode = 'crypt';
if (!m3_user() !== '') { if (! m3_user() !== '') {
$this->authenticate(); $this->authenticate();
} else { } else {
if($this->check_pass(m3_user(), m3_legacy_password(), $mode, "%%SYSTEM%%")) { if ($this->check_pass(m3_user(), m3_legacy_password(), $mode, '%%SYSTEM%%')) {
return $next($request); return $next($request);
} else { } else {
$this->authenticate(); $this->authenticate();
@@ -31,26 +32,29 @@ class BasicAuth
} }
public static function check_pass($login, $password, $mode, $password_file) { public static function check_pass($login, $password, $mode, $password_file)
if(!$fh = fopen($password_file, "r")) { die("<P>Could Not Open Password File"); } {
if (! $fh = fopen($password_file, 'r')) {
exit('<P>Could Not Open Password File');
}
$match = 0; $match = 0;
while(!feof($fh)) { while (! feof($fh)) {
$line = fgets($fh, 4096); $line = fgets($fh, 4096);
$from_file = explode(":", $line); $from_file = explode(':', $line);
if($from_file[0] == $login) { if ($from_file[0] == $login) {
if($mode == "crypt"){ if ($mode == 'crypt') {
$salt = substr($from_file[1],0,2); $salt = substr($from_file[1], 0, 2);
$user_pass = crypt($password,$salt); $user_pass = crypt($password, $salt);
} elseif ($mode == "md5") { } elseif ($mode == 'md5') {
$user_pass = md5($password); $user_pass = md5($password);
} }
if(rtrim($from_file[1]) == $user_pass) { if (rtrim($from_file[1]) == $user_pass) {
$match = 1; $match = 1;
break; break;
} }
} }
} }
if($match) { if ($match) {
return 1; return 1;
} else { } else {
return 0; return 0;
@@ -58,10 +62,11 @@ class BasicAuth
fclose($fh); fclose($fh);
} }
public static function authenticate() { public static function authenticate()
Header("WWW-Authenticate: Basic realm=\"RESTRICTED ACCESS\""); {
Header("HTTP/1.0 401 Unauthorized"); header('WWW-Authenticate: Basic realm="RESTRICTED ACCESS"');
echo ("<h1>INVALID USERNAME OR PASSWORD. ACCESS DENIED<h1>"); header('HTTP/1.0 401 Unauthorized');
echo '<h1>INVALID USERNAME OR PASSWORD. ACCESS DENIED<h1>';
exit; exit;
} }
} }
@@ -2,19 +2,20 @@
namespace Modules\M3\Http\Middleware; namespace Modules\M3\Http\Middleware;
use Modules\M3\Providers\RouteServiceProvider;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Modules\M3\Providers\RouteServiceProvider;
class RedirectIfAuthenticated class RedirectIfAuthenticated
{ {
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
* @param string|null ...$guards * @param string|null ...$guards
*
* @return mixed * @return mixed
*/ */
public function handle(Request $request, Closure $next, ...$guards) public function handle(Request $request, Closure $next, ...$guards)
+7 -5
View File
@@ -4,24 +4,26 @@ namespace Modules\M3\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Config;
class ICM428M extends Model class ICM428M extends Model
{ {
use HasFactory; use HasFactory;
protected $connection = 'pgsql'; protected $connection = 'pgsql';
protected $table; protected $table;
public $incrementing = false; public $incrementing = false;
public $timestamps = false;
public $timestamps = false;
public function __construct(){ public function __construct()
{
$this->table = 'ICM428M'; $this->table = 'ICM428M';
} }
# R428DV R428PL R428WHS R428STS R428US R428FIRST R428FAMILY R428EMPCDE R428ADMUSR R428PWRUSR --> // R428DV R428PL R428WHS R428STS R428US R428FIRST R428FAMILY R428EMPCDE R428ADMUSR R428PWRUSR -->
protected $fillable = [ protected $fillable = [
'R428CO', 'R428PL', 'R428WH', 'R428STS', 'R428US', 'R428FIRST', 'R428FAMILY', 'R428EMPCDE', 'R428ADMUSR', 'R428PWRUSR' 'R428CO', 'R428PL', 'R428WH', 'R428STS', 'R428US', 'R428FIRST', 'R428FAMILY', 'R428EMPCDE', 'R428ADMUSR', 'R428PWRUSR',
]; ];
} }
+6 -4
View File
@@ -4,23 +4,25 @@ namespace Modules\M3\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Config;
class ICM658M extends Model class ICM658M extends Model
{ {
use HasFactory; use HasFactory;
protected $connection = 'pgsql'; protected $connection = 'pgsql';
protected $table; protected $table;
public $incrementing = false; public $incrementing = false;
public $timestamps = false;
public $timestamps = false;
public function __construct(){ public function __construct()
{
$this->table = 'ICM658M'; $this->table = 'ICM658M';
} }
protected $fillable = [ protected $fillable = [
'R658CO', 'R658PL', 'R658WH', 'R658LC', 'R658PN', 'R658MQ', 'R658RQ', 'R658TL','R658RMQ','R658IZLCF' 'R658CO', 'R658PL', 'R658WH', 'R658LC', 'R658PN', 'R658MQ', 'R658RQ', 'R658TL', 'R658RMQ', 'R658IZLCF',
]; ];
} }
+7 -5
View File
@@ -2,16 +2,18 @@
namespace Modules\M3\Models; namespace Modules\M3\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Config;
class ShipTo extends Model class ShipTo extends Model
{ {
protected $table = 'ICM665M'; protected $table = 'ICM665M';
public $timestamps = false; public $timestamps = false;
protected $primaryKey = ['AUSHSHZP', 'AUSHWHS']; protected $primaryKey = ['AUSHSHZP', 'AUSHWHS'];
protected $uniqueKey = ['AUSHSHZP', 'AUSHWHS']; protected $uniqueKey = ['AUSHSHZP', 'AUSHWHS'];
public $incrementing = false; public $incrementing = false;
protected $fillable = [ protected $fillable = [
@@ -23,7 +25,7 @@ class ShipTo extends Model
'AUSHSHST', 'AUSHSHST',
'AUSHSHZP', 'AUSHSHZP',
'AUSHSHCT', 'AUSHSHCT',
'AUSHWHS' 'AUSHWHS',
]; ];
public function save(array $options = []) public function save(array $options = [])
@@ -42,11 +44,11 @@ class ShipTo extends Model
{ {
$query = self::query(); $query = self::query();
# Check if the combination of AUSHSHZP and AUSHWHS already exists // Check if the combination of AUSHSHZP and AUSHWHS already exists
$existingRecord = $query->where('AUSHSHZP', $this->AUSHSHZP) $existingRecord = $query->where('AUSHSHZP', $this->AUSHSHZP)
->where('AUSHWHS', $this->AUSHWHS); ->where('AUSHWHS', $this->AUSHWHS);
# If this is an existing record being updated, exclude itself from the check // If this is an existing record being updated, exclude itself from the check
if ($this->exists) { if ($this->exists) {
$existingRecord->where($this->getKeyName(), '!=', $this->getKey()); $existingRecord->where($this->getKeyName(), '!=', $this->getKey());
} }
-1
View File
@@ -2,7 +2,6 @@
namespace Modules\M3\Models; namespace Modules\M3\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
+40 -38
View File
@@ -2,31 +2,29 @@
namespace Modules\M3\Providers; namespace Modules\M3\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Factory;
use Illuminate\Support\Facades\File;
use Modules\M3\Support\ModuleInfo;
use Config; use Config;
use Illuminate\Support\Facades\File;
use Illuminate\Support\ServiceProvider;
use Modules\M3\Support\ModuleInfo;
class M3ServiceProvider extends ServiceProvider class M3ServiceProvider extends ServiceProvider
{ {
/** /**
* @var string $moduleName * @var string
*/ */
protected string $moduleName = 'M3'; protected string $moduleName = 'M3';
/** /**
* @var string $moduleNameLower * @var string
*/ */
protected string $moduleNameLower = 'm3'; protected string $moduleNameLower = 'm3';
/**
/** * Get the services provided by the provider.
* Get the services provided by the provider. *
* * @return array
* @return array */
*/ public function provides(): array
public function provides():array
{ {
return []; return [];
} }
@@ -36,7 +34,7 @@ class M3ServiceProvider extends ServiceProvider
* *
* @return void * @return void
*/ */
public function boot() : void public function boot(): void
{ {
$this->registerTranslations(); $this->registerTranslations();
$this->registerConfig(); $this->registerConfig();
@@ -63,34 +61,35 @@ class M3ServiceProvider extends ServiceProvider
*/ */
protected function registerHelpers(): void protected function registerHelpers(): void
{ {
foreach (glob(__DIR__.'/../Helpers/*.php') as $filename) { foreach (glob(__DIR__ . '/../Helpers/*.php') as $filename) {
require_once $filename; require_once $filename;
} }
} }
/** /**
* Dynamically Register Commands. * Dynamically Register Commands.
* *
* @return void * @return void
*/ */
public function registerCommands(): void public function registerCommands(): void
{ {
if (!$this->app->runningInConsole()) { if (! $this->app->runningInConsole()) {
return; return;
}
$commandPath = __DIR__ . '/../Console';
$commands = collect(File::allFiles($commandPath))
->map(function ($file) {
$class = 'Modules\\' . $this->moduleName . '\\Console\\' . $file->getFilenameWithoutExtension();
return $class;
})
->filter(function ($class) {
return class_exists($class);
})
->values()
->all();
$this->commands($commands);
} }
$commandPath = __DIR__ . '/../Console';
$commands = collect(File::allFiles($commandPath))
->map(function ($file) {
$class = 'Modules\\' . $this->moduleName . '\\Console\\' . $file->getFilenameWithoutExtension();
return $class;
})
->filter(function ($class) {
return class_exists($class);
})
->values()
->all();
$this->commands($commands);
}
/** /**
* Register config. * Register config.
@@ -100,10 +99,11 @@ class M3ServiceProvider extends ServiceProvider
protected function registerConfig(): void protected function registerConfig(): void
{ {
$this->publishes([ $this->publishes([
module_path(ModuleInfo::name(), 'Config/config.php') => config_path( ModuleInfo::nameLower(). '.php'), module_path(ModuleInfo::name(), 'Config/config.php') => config_path(ModuleInfo::nameLower() . '.php'),
], 'config'); ], 'config');
$this->mergeConfigFrom( $this->mergeConfigFrom(
module_path(ModuleInfo::name(), 'Config/config.php'), ModuleInfo::nameLower() module_path(ModuleInfo::name(), 'Config/config.php'),
ModuleInfo::nameLower(),
); );
// The legacy M3 application reads these keys directly as arrays.* and // The legacy M3 application reads these keys directly as arrays.* and
@@ -139,9 +139,9 @@ class M3ServiceProvider extends ServiceProvider
$viewPath = resource_path('views/modules/' . ModuleInfo::nameLower()); $viewPath = resource_path('views/modules/' . ModuleInfo::nameLower());
$sourcePath = module_path(ModuleInfo::name(), 'Resources/views'); $sourcePath = module_path(ModuleInfo::name(), 'Resources/views');
$this->publishes([ $this->publishes([
$sourcePath => $viewPath $sourcePath => $viewPath,
], ['views', ModuleInfo::nameLower() . '-module-views']); ], ['views', ModuleInfo::nameLower() . '-module-views']);
$this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), ModuleInfo::nameLower()); $this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), ModuleInfo::nameLower());
} }
/** /**
@@ -151,10 +151,10 @@ class M3ServiceProvider extends ServiceProvider
*/ */
public function registerTranslations(): void public function registerTranslations(): void
{ {
$langPath = resource_path('lang/modules/' . ModuleInfo::nameLower()); $langPath = resource_path('lang/modules/' . ModuleInfo::nameLower());
if (is_dir($langPath)) { if (is_dir($langPath)) {
$this->loadTranslationsFrom($langPath, ModuleInfo::nameLower()); $this->loadTranslationsFrom($langPath, ModuleInfo::nameLower());
} else { } else {
$this->loadTranslationsFrom(module_path(ModuleInfo::name(), 'Resources/lang'), ModuleInfo::nameLower()); $this->loadTranslationsFrom(module_path(ModuleInfo::name(), 'Resources/lang'), ModuleInfo::nameLower());
} }
@@ -162,6 +162,7 @@ class M3ServiceProvider extends ServiceProvider
/** /**
* Regsiter View Paths * Regsiter View Paths
*
* @return array * @return array
*/ */
private function getPublishableViewPaths(): array private function getPublishableViewPaths(): array
@@ -172,6 +173,7 @@ class M3ServiceProvider extends ServiceProvider
$paths[] = $path . '/modules/' . ModuleInfo::nameLower(); $paths[] = $path . '/modules/' . ModuleInfo::nameLower();
} }
} }
return $paths; return $paths;
} }
} }
@@ -2,8 +2,8 @@
namespace Modules\M3\Providers; namespace Modules\M3\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider class RouteServiceProvider extends ServiceProvider
{ {
+4 -8
View File
@@ -2,16 +2,14 @@
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use Modules\M3\Http\Controllers\API\M3Controller;
use Modules\M3\Http\Controllers\API\M3InventoryReport;
use Modules\M3\Http\Controllers\API\TransferAPI;
use Modules\M3\Http\Controllers\API\ReplenAPI;
use Modules\M3\Http\Controllers\API\CloseShipment; use Modules\M3\Http\Controllers\API\CloseShipment;
use Modules\M3\Http\Controllers\API\M3Controller;
use Modules\M3\Http\Controllers\API\M3InventoryReport;
use Modules\M3\Http\Controllers\API\PdfStorage; use Modules\M3\Http\Controllers\API\PdfStorage;
use Modules\M3\Http\Controllers\API\ReplenAPI;
use Modules\M3\Http\Controllers\API\TransferAPI;
use Modules\M3\Http\Controllers\API\TwoShipAPIs; use Modules\M3\Http\Controllers\API\TwoShipAPIs;
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| API Routes | API Routes
@@ -42,5 +40,3 @@ Route::any('/CloseShipmentCoChargeAPI', [CloseShipment::class, 'CloseShipmentCoC
Route::any('/PdfStorageAPI', [PdfStorage::class, 'PdfStorageAPI'])->name('PdfStorageAPI'); Route::any('/PdfStorageAPI', [PdfStorage::class, 'PdfStorageAPI'])->name('PdfStorageAPI');
Route::any('/twoshipupdatehold', [TwoShipAPIs::class, 'TwoShipUpdateHold'])->name('twoshipupdatehold'); Route::any('/twoshipupdatehold', [TwoShipAPIs::class, 'TwoShipUpdateHold'])->name('twoshipupdatehold');
+42 -46
View File
@@ -1,43 +1,40 @@
<?php <?php
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use Modules\M3\Http\Controllers\dashboardController;
use Modules\M3\Http\Controllers\authController; use Modules\M3\Http\Controllers\authController;
use Modules\M3\Http\Controllers\utilitiesContoller; use Modules\M3\Http\Controllers\BoxPackToPalletController;
use Modules\M3\Http\Controllers\userControlController;
use Modules\M3\Http\Controllers\palletQtyController;
use Modules\M3\Http\Controllers\M3DeliveryController;
use Modules\M3\Http\Controllers\carrierMaintController; use Modules\M3\Http\Controllers\carrierMaintController;
use Modules\M3\Http\Controllers\dashboardController;
use Modules\M3\Http\Controllers\M3CallCloseAPIController;
use Modules\M3\Http\Controllers\userPickingStats5;
use Modules\M3\Http\Controllers\userPickingStats4;
use Modules\M3\Http\Controllers\pendingClosureController;
use Modules\M3\Http\Controllers\ShipToController;
use Modules\M3\Http\Controllers\MFOrdersController;
use Modules\M3\Http\Controllers\GetContentsController;
use Modules\M3\Http\Controllers\userProfileController;
use Modules\M3\Http\Controllers\execSummaryController; use Modules\M3\Http\Controllers\execSummaryController;
use Modules\M3\Http\Controllers\execSummaryLineController; use Modules\M3\Http\Controllers\execSummaryLineController;
use Modules\M3\Http\Controllers\fillBOLController;
use Modules\M3\Http\Controllers\fillBOL2Controller; use Modules\M3\Http\Controllers\fillBOL2Controller;
use Modules\M3\Http\Controllers\fillBOLController;
# Sentinel use Modules\M3\Http\Controllers\GetContentsController;
use Modules\M3\Http\Controllers\M3CallCloseAPIController;
use Modules\M3\Http\Controllers\M3DeliveryController;
use Modules\M3\Http\Controllers\MFOrdersController;
use Modules\M3\Http\Controllers\palletQtyController;
use Modules\M3\Http\Controllers\pendingClosureController;
use Modules\M3\Http\Controllers\sentinelController; use Modules\M3\Http\Controllers\sentinelController;
# Warehouse Performance use Modules\M3\Http\Controllers\ShipToController;
use Modules\M3\Http\Controllers\userControlController;
use Modules\M3\Http\Controllers\userPickingStats4;
use Modules\M3\Http\Controllers\userPickingStats5;
// Sentinel
use Modules\M3\Http\Controllers\userProfileController;
// Warehouse Performance
use Modules\M3\Http\Controllers\utilitiesContoller;
use Modules\M3\Http\Controllers\WhsePerfController; use Modules\M3\Http\Controllers\WhsePerfController;
// Pack Box To Pallet
use Modules\M3\Http\Controllers\WhsePerfDetailsController; use Modules\M3\Http\Controllers\WhsePerfDetailsController;
# Pack Box To Pallet
use Modules\M3\Http\Controllers\BoxPackToPalletController;
use Modules\M3\Http\Controllers\WhsPerfMetrics; use Modules\M3\Http\Controllers\WhsPerfMetrics;
# Not Used
// Not Used
// use Modules\M3\Http\Controllers\orderInquiryController; // use Modules\M3\Http\Controllers\orderInquiryController;
// use Modules\M3\Http\Controllers\ordersOnHoldReqController; // use Modules\M3\Http\Controllers\ordersOnHoldReqController;
// use Modules\M3\Http\Controllers\userPickingStats4; // use Modules\M3\Http\Controllers\userPickingStats4;
// use Modules\M3\Http\Controllers\ReplenishSettingsController; // use Modules\M3\Http\Controllers\ReplenishSettingsController;
Route::get('/assets/{path}', function (string $path) { Route::get('/assets/{path}', function (string $path) {
abort_if(str_contains($path, '..') || str_contains($path, "\0"), 404); abort_if(str_contains($path, '..') || str_contains($path, "\0"), 404);
@@ -91,7 +88,7 @@ Route::get('/logout', [authController::class, 'logout'])->name('logout');
Route::get('/userPickingStats4', [userPickingStats4::class, 'index'])->name('userPickingStats4'); Route::get('/userPickingStats4', [userPickingStats4::class, 'index'])->name('userPickingStats4');
Route::post('/userPickingStats4', [userPickingStats4::class, 'index'])->name('userPickingStats4'); Route::post('/userPickingStats4', [userPickingStats4::class, 'index'])->name('userPickingStats4');
# userControl // userControl
Route::get('/userControl', [userControlController::class, 'index'])->name('userControl'); Route::get('/userControl', [userControlController::class, 'index'])->name('userControl');
Route::post('/userControl', [userControlController::class, 'index'])->name('userControl'); Route::post('/userControl', [userControlController::class, 'index'])->name('userControl');
Route::post('/userControl/saveUserAdd', [userControlController::class, 'saveUserAdd'])->name('saveUserAdd'); Route::post('/userControl/saveUserAdd', [userControlController::class, 'saveUserAdd'])->name('saveUserAdd');
@@ -99,104 +96,103 @@ Route::post('/userControl/saveUserEdit', [userControlController::class, 'saveUse
Route::get('/userControl/callCL', [userControlController::class, 'callCL'])->name('callCL'); Route::get('/userControl/callCL', [userControlController::class, 'callCL'])->name('callCL');
Route::post('/userControl/savePassword', [userControlController::class, 'savePassword'])->name('savePassword'); Route::post('/userControl/savePassword', [userControlController::class, 'savePassword'])->name('savePassword');
# palletQty // palletQty
Route::get('/palletQty', [palletQtyController::class, 'index'])->name('palletQty'); Route::get('/palletQty', [palletQtyController::class, 'index'])->name('palletQty');
Route::post('/palletQty', [palletQtyController::class, 'index'])->name('palletQty'); Route::post('/palletQty', [palletQtyController::class, 'index'])->name('palletQty');
Route::post('/palletQty/saveQtyAdd', [palletQtyController::class, 'saveQtyAdd'])->name('saveQtyAdd'); Route::post('/palletQty/saveQtyAdd', [palletQtyController::class, 'saveQtyAdd'])->name('saveQtyAdd');
Route::post('/palletQty/saveQtyAdd2', [palletQtyController::class, 'saveQtyAdd2'])->name('saveQtyAdd2'); Route::post('/palletQty/saveQtyAdd2', [palletQtyController::class, 'saveQtyAdd2'])->name('saveQtyAdd2');
Route::post('/palletQty/saveQtyEdit', [palletQtyController::class, 'saveQtyEdit'])->name('saveQtyEdit'); Route::post('/palletQty/saveQtyEdit', [palletQtyController::class, 'saveQtyEdit'])->name('saveQtyEdit');
# carrierMaint // carrierMaint
Route::get('/carrierMaint', [carrierMaintController::class, 'index'])->name('carrierMaint'); Route::get('/carrierMaint', [carrierMaintController::class, 'index'])->name('carrierMaint');
Route::post('/carrierMaint', [carrierMaintController::class, 'index'])->name('carrierMaint'); Route::post('/carrierMaint', [carrierMaintController::class, 'index'])->name('carrierMaint');
Route::post('/carrierMaint/saveCarrierAdd', [carrierMaintController::class, 'saveCarrierAdd'])->name('saveCarrierAdd'); Route::post('/carrierMaint/saveCarrierAdd', [carrierMaintController::class, 'saveCarrierAdd'])->name('saveCarrierAdd');
Route::post('/carrierMaint/saveCarrierAdd2', [carrierMaintController::class, 'saveCarrierAdd2'])->name('saveCarrierAdd2'); Route::post('/carrierMaint/saveCarrierAdd2', [carrierMaintController::class, 'saveCarrierAdd2'])->name('saveCarrierAdd2');
Route::post('/carrierMaint/saveCarrierEdit', [carrierMaintController::class, 'saveCarrierEdit'])->name('saveCarrierEdit'); Route::post('/carrierMaint/saveCarrierEdit', [carrierMaintController::class, 'saveCarrierEdit'])->name('saveCarrierEdit');
# M3Delivery Maint // M3Delivery Maint
Route::get('/M3Delivery', [M3DeliveryController::class, 'index'])->name('M3Delivery'); Route::get('/M3Delivery', [M3DeliveryController::class, 'index'])->name('M3Delivery');
Route::post('/M3Delivery', [M3DeliveryController::class, 'index'])->name('M3Delivery'); Route::post('/M3Delivery', [M3DeliveryController::class, 'index'])->name('M3Delivery');
Route::post('/M3Delivery/saveM3DeliveryAdd', [M3DeliveryController::class, 'saveM3DeliveryAdd'])->name('saveM3DeliveryAdd'); Route::post('/M3Delivery/saveM3DeliveryAdd', [M3DeliveryController::class, 'saveM3DeliveryAdd'])->name('saveM3DeliveryAdd');
Route::post('/M3Delivery/saveM3DeliveryEdit', [M3DeliveryController::class, 'saveM3DeliveryEdit'])->name('saveM3DeliveryEdit'); Route::post('/M3Delivery/saveM3DeliveryEdit', [M3DeliveryController::class, 'saveM3DeliveryEdit'])->name('saveM3DeliveryEdit');
# Replenishement Settings // Replenishement Settings
Route::resource('/replenishmentSettings', 'Modules\M3\Http\Controllers\ReplenishSettingsController', ['except' => ['create', 'edit', 'update', 'destroy']]); // 'store', Route::resource('/replenishmentSettings', 'Modules\M3\Http\Controllers\ReplenishSettingsController', ['except' => ['create', 'edit', 'update', 'destroy']]); // 'store',
Route::post('/replenishmentSettingsUpdate', 'Modules\M3\Http\Controllers\ReplenishSettingsController@update')->name('replenishmentSettingsUpdate'); Route::post('/replenishmentSettingsUpdate', 'Modules\M3\Http\Controllers\ReplenishSettingsController@update')->name('replenishmentSettingsUpdate');
Route::post('/replenishmentSettingsDelete', 'Modules\M3\Http\Controllers\ReplenishSettingsController@deleteRec')->name('replenishmentSettingsDelete'); Route::post('/replenishmentSettingsDelete', 'Modules\M3\Http\Controllers\ReplenishSettingsController@deleteRec')->name('replenishmentSettingsDelete');
Route::post('/replenishmentSettingsExist', 'Modules\M3\Http\Controllers\ReplenishSettingsController@checkRecExit')->name('replenishmentSettingsExist'); Route::post('/replenishmentSettingsExist', 'Modules\M3\Http\Controllers\ReplenishSettingsController@checkRecExit')->name('replenishmentSettingsExist');
Route::get('/replenishmentSettingsDT', 'Modules\M3\Http\Controllers\ReplenishSettingsController@datatables')->name('replenishmentSettingsDT'); Route::get('/replenishmentSettingsDT', 'Modules\M3\Http\Controllers\ReplenishSettingsController@datatables')->name('replenishmentSettingsDT');
# M3 Errors Display M3ErrorsDispController // M3 Errors Display M3ErrorsDispController
Route::resource('/M3ErrorsDisplay', 'Modules\M3\Http\Controllers\M3ErrorsDispController', ['except' => ['create', 'store', 'edit', 'update', 'destroy']]); Route::resource('/M3ErrorsDisplay', 'Modules\M3\Http\Controllers\M3ErrorsDispController', ['except' => ['create', 'store', 'edit', 'update', 'destroy']]);
Route::get('/M3ErrorsDisplayDT', 'Modules\M3\Http\Controllers\M3ErrorsDispController@datatables')->name('M3ErrorsDisplayDT'); Route::get('/M3ErrorsDisplayDT', 'Modules\M3\Http\Controllers\M3ErrorsDispController@datatables')->name('M3ErrorsDisplayDT');
Route::post('/M3ErrorsDisplay699', 'Modules\M3\Http\Controllers\M3ErrorsDispController@update699M')->name('M3ErrorsDisplay699'); Route::post('/M3ErrorsDisplay699', 'Modules\M3\Http\Controllers\M3ErrorsDispController@update699M')->name('M3ErrorsDisplay699');
Route::post('/exporttoExcel699', 'Modules\M3\Http\Controllers\M3ErrorsDispController@exporttoExcel')->name('exporttoExcel699'); Route::post('/exporttoExcel699', 'Modules\M3\Http\Controllers\M3ErrorsDispController@exporttoExcel')->name('exporttoExcel699');
# M3 Cached PDF // M3 Cached PDF
Route::resource('/M3GetPDFFromCache', 'Modules\M3\Http\Controllers\M3GetPDFFromCacheController', ['except' => ['create', 'store', 'edit', 'update', 'destroy']]); Route::resource('/M3GetPDFFromCache', 'Modules\M3\Http\Controllers\M3GetPDFFromCacheController', ['except' => ['create', 'store', 'edit', 'update', 'destroy']]);
Route::any('/M3GetPDFFromCache', 'Modules\M3\Http\Controllers\M3GetPDFFromCacheController@index'); Route::any('/M3GetPDFFromCache', 'Modules\M3\Http\Controllers\M3GetPDFFromCacheController@index');
// Route::get('/M3GetPDFFromCacheDT', 'Modules\M3\Http\Controllers\M3GetPDFFromCacheController@datatables')->name('M3GetPDFFromCacheDT'); // Route::get('/M3GetPDFFromCacheDT', 'Modules\M3\Http\Controllers\M3GetPDFFromCacheController@datatables')->name('M3GetPDFFromCacheDT');
# M3 Call Close API // M3 Call Close API
Route::any('/M3ManifestCloseAPI', [M3CallCloseAPIController::class,'index'])->name('M3ManifestCloseAPI'); Route::any('/M3ManifestCloseAPI', [M3CallCloseAPIController::class, 'index'])->name('M3ManifestCloseAPI');
# Closed order lines report // Closed order lines report
Route::any('/OrderLinesOfClosedOrder', 'Modules\M3\Http\Controllers\OrderLinesOfClosedOrder@index')->name('OrderLinesOfClosedOrder'); Route::any('/OrderLinesOfClosedOrder', 'Modules\M3\Http\Controllers\OrderLinesOfClosedOrder@index')->name('OrderLinesOfClosedOrder');
Route::post('/exporttoExcel', 'Modules\M3\Http\Controllers\OrderLinesOfClosedOrder@exporttoExcel')->name('exporttoExcel'); Route::post('/exporttoExcel', 'Modules\M3\Http\Controllers\OrderLinesOfClosedOrder@exporttoExcel')->name('exporttoExcel');
Route::any('/StoreExcelToDisk', 'Modules\M3\Http\Controllers\OrderLinesOfClosedOrder@StoreExcelToDisk')->name('StoreExcelToDisk'); Route::any('/StoreExcelToDisk', 'Modules\M3\Http\Controllers\OrderLinesOfClosedOrder@StoreExcelToDisk')->name('StoreExcelToDisk');
Route::any('/downloadFiles', 'Modules\M3\Http\Controllers\OrderLinesOfClosedOrder@downloadFiles')->name('downloadFiles'); Route::any('/downloadFiles', 'Modules\M3\Http\Controllers\OrderLinesOfClosedOrder@downloadFiles')->name('downloadFiles');
// v5
# v5
Route::get('/userPickingStats5', [userPickingStats5::class, 'index'])->name('userPickingStats5'); Route::get('/userPickingStats5', [userPickingStats5::class, 'index'])->name('userPickingStats5');
Route::post('/userPickingStats5', [userPickingStats5::class, 'index'])->name('userPickingStats5'); Route::post('/userPickingStats5', [userPickingStats5::class, 'index'])->name('userPickingStats5');
#732 // 732
# pendingClosure // pendingClosure
Route::get('/pendingClosure', [pendingClosureController::class, 'index'])->name('pendingClosure'); Route::get('/pendingClosure', [pendingClosureController::class, 'index'])->name('pendingClosure');
Route::post('/pendingClosure', [pendingClosureController::class, 'index'])->name('pendingClosure'); Route::post('/pendingClosure', [pendingClosureController::class, 'index'])->name('pendingClosure');
Route::post('/allowRetry', [pendingClosureController::class, 'allowRetry'])->name('allowRetry'); Route::post('/allowRetry', [pendingClosureController::class, 'allowRetry'])->name('allowRetry');
# Ship To // Ship To
Route::resource('ship-to', ShipToController::class)->parameters(['ship-to' => 'austcn'])->except(['show']); Route::resource('ship-to', ShipToController::class)->parameters(['ship-to' => 'austcn'])->except(['show']);
Route::get('/ship-to/{aushshzp}/{aushwhs}/edit', [ShipToController::class, 'edit'])->name('ship-to.edit'); Route::get('/ship-to/{aushshzp}/{aushwhs}/edit', [ShipToController::class, 'edit'])->name('ship-to.edit');
Route::put('/ship-to/{aushshzp}/{aushwhs}', [ShipToController::class, 'update'])->name('ship-to.update'); Route::put('/ship-to/{aushshzp}/{aushwhs}', [ShipToController::class, 'update'])->name('ship-to.update');
Route::delete('/ship-to/{aushshzp}/{aushwhs}', [ShipToController::class, 'destroy'])->name('ship-to.destroy'); Route::delete('/ship-to/{aushshzp}/{aushwhs}', [ShipToController::class, 'destroy'])->name('ship-to.destroy');
# MF Orders // MF Orders
Route::get('/MFOrders/{id}', [MFOrdersController::class, 'index'])->name('MFOrders'); Route::get('/MFOrders/{id}', [MFOrdersController::class, 'index'])->name('MFOrders');
# Get Contents for CloseShipment // Get Contents for CloseShipment
Route::any('/GetContentsForClose', [GetContentsController::class, 'processShipment'])->name('GetContentsForClose'); Route::any('/GetContentsForClose', [GetContentsController::class, 'processShipment'])->name('GetContentsForClose');
# Update Profile // Update Profile
Route::any('/userprofile', [userProfileController::class, 'index'])->name('userprofile'); Route::any('/userprofile', [userProfileController::class, 'index'])->name('userprofile');
Route::post('/userprofileupdate', [userProfileController::class, 'updateUserProfile'])->name('userprofileupdate'); Route::post('/userprofileupdate', [userProfileController::class, 'updateUserProfile'])->name('userprofileupdate');
Route::any('/userprofileupdateajax', [userProfileController::class, 'updateUserProfileAjax'])->name('userprofileupdateajax'); Route::any('/userprofileupdateajax', [userProfileController::class, 'updateUserProfileAjax'])->name('userprofileupdateajax');
# Sentinel Functions // Sentinel Functions
Route::any('/packSyst5Func', [sentinelController::class, 'packSyst5Func'])->name('packSyst5Func'); Route::any('/packSyst5Func', [sentinelController::class, 'packSyst5Func'])->name('packSyst5Func');
# Executives summary // Executives summary
Route::any('/execsummary', [execSummaryController::class, 'index'])->name('execsummary'); Route::any('/execsummary', [execSummaryController::class, 'index'])->name('execsummary');
Route::any('/execsummaryline', [execSummaryLineController::class, 'index'])->name('execsummaryline'); Route::any('/execsummaryline', [execSummaryLineController::class, 'index'])->name('execsummaryline');
# Warehouse Perf Metrics // Warehouse Perf Metrics
Route::any('/whsePerf', [WhsePerfController::class, 'index'])->name('whsePerf'); Route::any('/whsePerf', [WhsePerfController::class, 'index'])->name('whsePerf');
Route::any('/whsePerfExcel', [WhsePerfController::class, 'exportTable'])->name('whsePerfExcel'); Route::any('/whsePerfExcel', [WhsePerfController::class, 'exportTable'])->name('whsePerfExcel');
Route::any('/whsePerfShow', [WhsePerfController::class, 'displayTable'])->name('whsePerfShow'); Route::any('/whsePerfShow', [WhsePerfController::class, 'displayTable'])->name('whsePerfShow');
Route::any('/whsePerfDetails', [WhsePerfDetailsController::class, 'index'])->name('whsePerfDetails'); Route::any('/whsePerfDetails', [WhsePerfDetailsController::class, 'index'])->name('whsePerfDetails');
Route::any('/downloadFilesWhs', [WhsPerfMetrics::class, 'downloadFiles'])->name('downloadFilesWhs'); Route::any('/downloadFilesWhs', [WhsPerfMetrics::class, 'downloadFiles'])->name('downloadFilesWhs');
# BOL PDFs // BOL PDFs
Route::any('/fillBOL', [fillBOLController::class, 'index'])->name('fillBOL'); Route::any('/fillBOL', [fillBOLController::class, 'index'])->name('fillBOL');
Route::any('/fillBOLPDF', [fillBOLController::class, 'fillBOL'])->name('fillBOLPDF'); Route::any('/fillBOLPDF', [fillBOLController::class, 'fillBOL'])->name('fillBOLPDF');
Route::any('/fillBOL2', [fillBOL2Controller::class, 'index'])->name('fillBOL2'); Route::any('/fillBOL2', [fillBOL2Controller::class, 'index'])->name('fillBOL2');
Route::any('/fillBOL2PDF', [fillBOL2Controller::class, 'fillBOL'])->name('fillBOL2PDF'); Route::any('/fillBOL2PDF', [fillBOL2Controller::class, 'fillBOL'])->name('fillBOL2PDF');
# Pack Box to Pallet BoxPackToPalletController // Pack Box to Pallet BoxPackToPalletController
Route::any('/BoxPackToPallet', [BoxPackToPalletController::class, 'index'])->name('BoxPackToPallet'); Route::any('/BoxPackToPallet', [BoxPackToPalletController::class, 'index'])->name('BoxPackToPallet');
Route::any('/BoxPackToPallet/getboxes', [BoxPackToPalletController::class, 'getBoxes'])->name('BoxPackToPallet.getboxes'); Route::any('/BoxPackToPallet/getboxes', [BoxPackToPalletController::class, 'getBoxes'])->name('BoxPackToPallet.getboxes');
Route::any('/BoxPackToPallet/scanboxes', [BoxPackToPalletController::class, 'scanBoxes'])->name('BoxPackToPallet.scanboxes'); Route::any('/BoxPackToPallet/scanboxes', [BoxPackToPalletController::class, 'scanBoxes'])->name('BoxPackToPallet.scanboxes');
+9 -10
View File
@@ -2,18 +2,18 @@
namespace Modules\M3\Services; namespace Modules\M3\Services;
use Storage;
use setasign\Fpdi\Fpdi; use setasign\Fpdi\Fpdi;
use Storage;
class BillOfLadingService class BillOfLadingService
{ {
public function fillBillOfLading($data, $outputPath = null) public function fillBillOfLading($data, $outputPath = null)
{ {
$templatePath = Storage::disk('public')->path('ETN-BOL2.pdf'); //storage_path('app/templates/ETN-BOL.pdf'); $templatePath = Storage::disk('public')->path('ETN-BOL2.pdf'); // storage_path('app/templates/ETN-BOL.pdf');
$newfile='BOL_' . $data['bol_number'] . '.pdf'; #was using time() $newfile = 'BOL_' . $data['bol_number'] . '.pdf'; // was using time()
$outputPath = $outputPath ?? Storage::disk('public')->path($newfile); //storage_path('app/filled/BOL_' . $data['bol_number'] . '.pdf'); $outputPath = $outputPath ?? Storage::disk('public')->path($newfile); // storage_path('app/filled/BOL_' . $data['bol_number'] . '.pdf');
$pdf = new Fpdi(); $pdf = new Fpdi;
// Set source file // Set source file
$pageCount = $pdf->setSourceFile($templatePath); $pageCount = $pdf->setSourceFile($templatePath);
@@ -26,7 +26,7 @@ class BillOfLadingService
// Set font // Set font
$pdf->SetFont('Helvetica', '', 10); $pdf->SetFont('Helvetica', '', 10);
$pdf->SetTextColor(0, 0, 0); $pdf->SetTextColor(0, 0, 0);
#$pdf->SetLineWidth(50); // $pdf->SetLineWidth(50);
// Fill form fields at specific coordinates // Fill form fields at specific coordinates
// You'll need to adjust X,Y positions based on your PDF // You'll need to adjust X,Y positions based on your PDF
@@ -101,7 +101,7 @@ class BillOfLadingService
$pdf->Write(0, $data['consignee_address3']); $pdf->Write(0, $data['consignee_address3']);
} }
//Freight Collect // Freight Collect
if (isset($data['freight_collect'])) { if (isset($data['freight_collect'])) {
$pdf->SetXY(127, 90); $pdf->SetXY(127, 90);
$pdf->Write(0, $data['freight_collect']); $pdf->Write(0, $data['freight_collect']);
@@ -225,7 +225,7 @@ class BillOfLadingService
$pdf->Write(0, $data['consignee_address3']); $pdf->Write(0, $data['consignee_address3']);
} }
//Freight Collect // Freight Collect
if (isset($data['freight_collect'])) { if (isset($data['freight_collect'])) {
$pdf->SetXY(127, 90); $pdf->SetXY(127, 90);
$pdf->Write(0, $data['freight_collect']); $pdf->Write(0, $data['freight_collect']);
@@ -237,8 +237,7 @@ class BillOfLadingService
$pdf->Write(0, $data['carrier_name']); $pdf->Write(0, $data['carrier_name']);
} }
// KD : add fields as you need
# KD : add fields as you need
// Save the PDF // Save the PDF
$pdf->Output('F', $outputPath); $pdf->Output('F', $outputPath);
@@ -17,6 +17,7 @@ use Illuminate\Support\Facades\Schema;
class PostgresProgramBridge class PostgresProgramBridge
{ {
private string $errorCode = ''; private string $errorCode = '';
private string $errorMessage = ''; private string $errorMessage = '';
public function setOptions(array $options): self public function setOptions(array $options): self
@@ -91,6 +92,7 @@ class PostgresProgramBridge
$this->errorCode = (string) $e->getCode(); $this->errorCode = (string) $e->getCode();
$this->errorMessage = $e->getMessage(); $this->errorMessage = $e->getMessage();
Log::error('Unable to queue M3 program request.', ['exception' => $e]); Log::error('Unable to queue M3 program request.', ['exception' => $e]);
return false; return false;
} }
} }
+9 -4
View File
@@ -14,6 +14,7 @@ class SpreadsheetExport
{ {
$path = storage_path('app/m3-exports/' . uniqid('', true) . '-' . basename($filename)); $path = storage_path('app/m3-exports/' . uniqid('', true) . '-' . basename($filename));
$this->write($rows, $path); $this->write($rows, $path);
return response()->download($path, basename($filename))->deleteFileAfterSend(true); return response()->download($path, basename($filename))->deleteFileAfterSend(true);
} }
@@ -25,16 +26,16 @@ class SpreadsheetExport
if ($disk && config("filesystems.disks.$disk")) { if ($disk && config("filesystems.disks.$disk")) {
Storage::disk($disk)->put($filename, file_get_contents($tmp)); Storage::disk($disk)->put($filename, file_get_contents($tmp));
@unlink($tmp); @unlink($tmp);
return $filename; return $filename;
} }
return $tmp; return $tmp;
} }
public function storeSheets(array $sheets, string $filename, ?string $disk = null): string public function storeSheets(array $sheets, string $filename, ?string $disk = null): string
{ {
$book = new Spreadsheet(); $book = new Spreadsheet;
$book->removeSheetByIndex(0); $book->removeSheetByIndex(0);
foreach ($sheets as $title => $rows) { foreach ($sheets as $title => $rows) {
$sheet = $book->createSheet(); $sheet = $book->createSheet();
@@ -45,13 +46,17 @@ class SpreadsheetExport
} }
} }
$tmp = storage_path('app/m3-exports/' . uniqid('', true) . '-' . basename($filename)); $tmp = storage_path('app/m3-exports/' . uniqid('', true) . '-' . basename($filename));
if (! is_dir(dirname($tmp))) { mkdir(dirname($tmp), 0775, true); } if (! is_dir(dirname($tmp))) {
mkdir(dirname($tmp), 0775, true);
}
(new Xlsx($book))->save($tmp); (new Xlsx($book))->save($tmp);
if ($disk && config("filesystems.disks.$disk")) { if ($disk && config("filesystems.disks.$disk")) {
Storage::disk($disk)->put($filename, file_get_contents($tmp)); Storage::disk($disk)->put($filename, file_get_contents($tmp));
@unlink($tmp); @unlink($tmp);
return $filename; return $filename;
} }
return $tmp; return $tmp;
} }
@@ -61,7 +66,7 @@ class SpreadsheetExport
mkdir(dirname($path), 0775, true); mkdir(dirname($path), 0775, true);
} }
$sheet = (new Spreadsheet())->getActiveSheet(); $sheet = (new Spreadsheet)->getActiveSheet();
$array = $rows->map(fn ($row) => (array) $row)->values(); $array = $rows->map(fn ($row) => (array) $row)->values();
$headers = $array->first() ? array_keys($array->first()) : []; $headers = $array->first() ? array_keys($array->first()) : [];
if ($headers) { if ($headers) {
+3 -1
View File
@@ -4,10 +4,11 @@ namespace Modules\M3\Support;
class ModuleInfo class ModuleInfo
{ {
protected static string $moduleName = 'M3'; protected static string $moduleName = 'M3';
/** /**
* defines the Module Name * defines the Module Name
*
* @return string * @return string
*/ */
public static function name(): string public static function name(): string
@@ -17,6 +18,7 @@ class ModuleInfo
/** /**
* define the lowercase version * define the lowercase version
*
* @return string * @return string
*/ */
public static function nameLower(): string public static function nameLower(): string
+2 -2
View File
@@ -16,7 +16,7 @@ class ExportSource extends Command
{ {
$project = basename(base_path()); $project = basename(base_path());
$timestamp = now()->format('Ymd-His'); $timestamp = now()->format('Ymd-His');
$downloads = rtrim((string) getenv('HOME'), '/').'/Downloads'; $downloads = rtrim((string) getenv('HOME'), '/') . '/Downloads';
$archive = "{$downloads}/{$project}-source-{$timestamp}.zip"; $archive = "{$downloads}/{$project}-source-{$timestamp}.zip";
$this->info("Exporting {$project}..."); $this->info("Exporting {$project}...");
@@ -40,7 +40,7 @@ class ExportSource extends Command
return self::FAILURE; return self::FAILURE;
} }
$zip = new ZipArchive(); $zip = new ZipArchive;
if ($zip->open($archive) !== true) { if ($zip->open($archive) !== true) {
$this->error('Could not open ZIP.'); $this->error('Could not open ZIP.');