M3 Security Fixes for pass 28

This commit is contained in:
Mark Gregory
2026-09-17 10:50:37 +01:00
parent 1037c1c202
commit ed3db89018
77 changed files with 82 additions and 2387 deletions
View File
-73
View File
@@ -1,73 +0,0 @@
<?php
namespace Modules\M3\Console;
use Config;
use DB;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
use Log;
use Modules\M3\Http\Controllers\API\CloseShipment;
use Str;
class CallCloseAPI extends Command
{
protected $signature = 'command:CallCloseAPI {user?} {manifest?} {co?} {whs?} ';
protected $description = 'Call Close API';
public function handle()
{
self::configureTimeouts();
try {
$manifest = (string) ($this->argument('manifest') ?? '');
if ($manifest !== '') {
return $this->closeSpecificManifest($manifest, (string) ($this->argument('co') ?? ''), (string) ($this->argument('whs') ?? ''));
}
$this->closePendingManifests();
return self::SUCCESS;
} catch (\Throwable $th) {
Log::channel('dailyCron')->error($th);
return self::FAILURE;
}
}
private static function configureTimeouts(): void
{
$timeout = Config::get('arrays.PHPTimeOut');
ini_set('max_execution_time', $timeout);
ini_set('max_input_time', $timeout);
ini_set('default_socket_timeout', $timeout);
}
private function closePendingManifests(): void
{
$rows = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1')
->select('APMANIFEST', 'APCO', 'APWHS')->where('APSPARE2', '')->where('APMANIFEST', '!=', '0')
->whereRaw('EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - APLDCLOZ)) / 60 > 15')->orderBy('APMANIFEST', 'desc')->get();
foreach ($rows as $row) {
$this->closeManifest((string) $row->APMANIFEST, (string) ($row->APCO ?? ''), (string) ($row->APWHS ?? ''));
}
}
private function closeSpecificManifest(string $manifest, string $co, string $whs): int
{
$exists = DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1')
->where('APSPARE2', '')->where('APCO', $co)->where('APWHS', $whs)->where('APMANIFEST', $manifest)->exists();
if (! $exists) {
Log::channel('dailyCron')->warning('Manifest not available for close', compact('manifest', 'co', 'whs'));
return self::FAILURE;
}
$this->closeManifest($manifest, $co, $whs);
return self::SUCCESS;
}
private function closeManifest(string $manifest, string $co, string $whs): void
{
DB::connection(config('m3.connection', 'pgsql'))->table('icm705m1')
->where('APMANIFEST', $manifest)->where('APCO', $co)->where('APWHS', $whs)->update(['APSPARE2' => 'P']);
$request = Request::create('', 'POST', ['WHS' => $whs, 'COMPANY' => $co, 'TRANSTYPE' => 'M', 'MANIFEST' => $manifest]);
$response = CloseShipment::CloseShipmentCoChargeAPI($request);
$json = json_encode($response->getData());
Log::channel('dailyCron')->info('Close Shipment API Response for Manifest:' . $manifest . '-' . $json);
}
}
@@ -46,7 +46,6 @@ class ClosedOrderSaveXls extends Command
*/
public function handle()
{
// $this->info('Start CallCloseAPI...');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
@@ -122,7 +121,6 @@ class ClosedOrderSaveXls extends Command
AND A5CO=$COMPANY AND A5WHS=$WHS AND A5PLANT=$PLANT
");
// $newItem = ["A5MACPKR" => 'Delivery #', "A5ONO" => 'Order #', "A4REFORD" => 'Order Type',"A5PART" => 'Part #',"A5RSVQTY" => 'Reserved',
// "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'];
@@ -208,7 +206,6 @@ class ClosedOrderSaveXls extends Command
AND A5CO=$COMPANY AND A5WHS=$WHS AND A5PLANT=$PLANT
");
// $newItem2 = ["A5MACPKR" => 'Delivery #', "A5ONO" => 'Order #', "A4REFORD" => 'Order Type',"A5PART" => 'Part #',"A5RSVQTY" => 'Reserved',
// "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'];
@@ -245,7 +242,6 @@ class ClosedOrderSaveXls extends Command
$this->info('Cron...End Save Orders Closed Lines to Excel');
} catch (\Throwable $th) {
// Log::error($th);
Log::channel('dailyCron')->error($th);
}
}
-4
View File
@@ -40,7 +40,6 @@ class DeleteOldLabels extends Command
*/
public function handle(): void
{
// $this->info('Start CallCloseAPI...');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
@@ -62,7 +61,6 @@ class DeleteOldLabels extends Command
Log::channel('dailyCron')->info('Getting Files From Directory: ' . $labelsDirectory);
exec('find ' . $labelsDirectory . ' -ctime +180 -type f -exec rm {} \;');
// exec('find '.$labelsDirectory.' -ctime +190 -type f -print | wc -l');
}
$labelsFolder = $labelsDirectoryTmp;
@@ -82,7 +80,6 @@ class DeleteOldLabels extends Command
}
}
// $this->info("Files to Delete...");
// dump($filesToDeleteArr);
// Delete Old Files
@@ -92,7 +89,6 @@ class DeleteOldLabels extends Command
$this->info('End Delete Old Labels Command...');
} catch (\Throwable $th) {
// Log::error($th);
Log::channel('dailyCron')->error($th);
}
}
-5
View File
@@ -48,7 +48,6 @@ class GenerateGS1Cmd extends Command
*/
public function handle()
{
// $this->info('Start CallCloseAPI...');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
@@ -66,7 +65,6 @@ class GenerateGS1Cmd extends Command
// Get Manifest Array
$GSArray1 = $this->option('gsarray');
$GSArray = json_decode($GSArray1, true);
// dump($GSArray);
// MAK : Used for debug only
$GSArray = ['Macpkr' => '55555', 'Recipient_Address1' => '9571 Pan American DR', 'Recipient_Address2' => 'C/O AEE Solar', 'Recipient_City' => 'El Paso',
@@ -230,7 +228,6 @@ class GenerateGS1Cmd extends Command
}
$html .= '</body> </html>';
// dump($html);
// App::call('App\Http\Controllers\utilitiesContoller@generateGS128');
ob_start();
@@ -246,7 +243,6 @@ class GenerateGS1Cmd extends Command
// $dompdf->stream();
$pdfContent = $dompdf->output();
// dump($pdfContent);
$labelsPath = Config::get('arrays.PdfPath');
// Put the PDF in labels/CarrierLabel
@@ -266,7 +262,6 @@ class GenerateGS1Cmd extends Command
$this->info('<<< GS1-128...End of Label Creation');
} catch (\Throwable $th) {
// Log::error($th);
Log::channel('LabelCron')->error($th);
}
}
-4
View File
@@ -41,7 +41,6 @@ class UtilitiesCmd extends Command
*/
public function handle(): void
{
// $this->info('Start CallCloseAPI...');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
@@ -50,15 +49,12 @@ class UtilitiesCmd extends Command
try {
$this->info('Start Utilities Command...');
// $this->info('User: '.$SHUSER);
$myRequest = new Request;
utilitiesContoller::fixICM799MSentPKR($myRequest);
// Log::channel('dailyCron')->info("Cron...End Save Orders Closed Lines to Excel");
$this->info('End Utilities Command...');
} catch (\Throwable $th) {
// Log::error($th);
Log::channel('dailyCron')->error($th);
}
}
-8
View File
@@ -42,7 +42,6 @@ class WHSMetricsSaveXls extends Command
*/
public function handle()
{
// $this->info('Start CallCloseAPI...');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOutCL'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOutCL'));
@@ -56,13 +55,10 @@ class WHSMetricsSaveXls extends Command
$SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : '');
$CO = $this->argument('co');
// $COMPANY = isset($CO) ? trim($CO) : '110';
$COMPANY = '110';
$PWHS = $this->argument('whs');
// $WHS = isset($PWHS) ? trim($PWHS) : '321';
$WHS = '321';
$PPL = $this->argument('pl');
// $PLANT = isset($PPL) ? trim($PPL) : '143';
$PLANT = '143';
$date = new \DateTime;
@@ -92,7 +88,6 @@ class WHSMetricsSaveXls extends Command
GROUP BY A4SHIPTYPE,STATUS,SOURCE
ORDER BY 1,3,2
");
// dd($ICM700MHeadSel);
$newItem = ['A4SHIPTYPE' => 'Method', 'STATUS' => 'Status', 'SOURCE' => 'Source', 'PICKERS' => 'Pickers',
'WEIGHT' => 'Weight', 'LINES' => 'Lines', 'DOLLARS' => 'Dollars'];
@@ -110,7 +105,6 @@ class WHSMetricsSaveXls extends Command
// Prepend Header to Collection
$ICM700MHeadCol->prepend($newItem);
// $this->info($ICM700MHeadCol);
// Log::channel('dailyCron')->info(">>> Header Content");
// Log::channel('dailyCron')->info($ICM700MHeadCol);
@@ -158,7 +152,6 @@ class WHSMetricsSaveXls extends Command
} else {
$ICM700MDetailsCol = collect();
}
// Log::channel('dailyCron')->info(">>> Detail Content");
// Log::channel('dailyCron')->info($ICM700MDetailsCol);
// Save Head and Details to XLS file
@@ -180,7 +173,6 @@ class WHSMetricsSaveXls extends Command
$this->info('Cron...End Save Today WHS Performance Report to Excel');
} catch (\Throwable $th) {
// Log::error($th);
Log::channel('dailyCron')->error($th);
}
}
@@ -1,30 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::connection(config('m3.connection', 'pgsql'))->create('m3_program_requests', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('type', 20);
$table->string('operation', 255);
$table->string('library', 255)->nullable();
$table->jsonb('payload')->nullable();
$table->string('requested_by', 255)->nullable();
$table->string('status', 30)->default('pending')->index();
$table->text('result')->nullable();
$table->text('error')->nullable();
$table->timestamp('processed_at')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::connection(config('m3.connection', 'pgsql'))->dropIfExists('m3_program_requests');
}
};
@@ -16,6 +16,5 @@ class M3DatabaseSeeder extends Seeder
{
Model::unguard();
// $this->call("OthersTableSeeder");
}
}
View File
-27
View File
@@ -1,27 +0,0 @@
<?php
// app/Helpers/USStates.php
namespace Modules\M3\Helpers;
class CAProvinces
{
public static function all()
{
return [
'AB' => 'Alberta',
'BC' => 'British Columbia',
'MB' => 'Manitoba',
'NB' => 'New Brunswick',
'NL' => 'Newfoundland and Labrador',
'NS' => 'Nova Scotia',
'NT' => 'Northwest Territories',
'NU' => 'Nunavut',
'ON' => 'Ontario',
'PE' => 'Prince Edward Island',
'QC' => 'Quebec',
'SK' => 'Saskatchewan',
'YT' => 'Yukon',
];
}
}
-12
View File
@@ -22,7 +22,6 @@ class Helper
if (isset($token)) {
$IonToken = $token;
// Log::info("Cached Token: ".$IonToken);
} else {
// ## CURL
// ## Generate Token
@@ -47,7 +46,6 @@ class Helper
]);
$response = curl_exec($curl);
// dd($response);
$responseJ = json_decode($response);
if ($response === false) {
@@ -58,11 +56,9 @@ class Helper
]);
} elseif (isset($responseJ->access_token)) {
$IonToken = $responseJ->access_token;
// Log::info("New Token: " . $IonToken);
Cache::put('token', $IonToken, now()->addMinutes(59));
} else {
// dd($response);
return response()->json([
'code' => '400',
'status' => 'Failed',
@@ -74,7 +70,6 @@ class Helper
}
return $IonToken;
// return response()->json([
// 'code' => '200',
// 'token' => $IonToken
// ]);
@@ -94,7 +89,6 @@ class Helper
if (isset($token)) {
$IonToken = $token;
// Log::info("Cached Token: ".$IonToken);
} else {
// ## CURL
// ## Generate Token
@@ -119,7 +113,6 @@ class Helper
]);
$response = curl_exec($curl);
// dd($response);
$responseJ = json_decode($response);
curl_close($curl);
@@ -135,7 +128,6 @@ class Helper
]);
} elseif (isset($responseJ->access_token)) {
$IonToken = $responseJ->access_token;
// Log::info("New Token: " . $IonToken);
Cache::put('token', $IonToken, now()->addMinutes(59));
} else {
// Clear Cache
@@ -149,7 +141,6 @@ class Helper
}
}
// return $IonToken;
return response()->json([
'code' => '200',
'token' => $IonToken,
@@ -241,7 +232,6 @@ class Helper
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
$insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('ICM699M')->insert($data);
// dump($data);
// dump($insertSQL);
}
@@ -282,7 +272,6 @@ class Helper
}
$TYPE = $TYPE == 'integer' || $TYPE == 'DEC' ? 'number' : $TYPE;
// Log::info( $JSONL .' L: '. strlen($JSONL) .' DBL: '. $DBL .' Type:'.$JSONType.':'.$TYPE );
// Check Json Field should be < DB Field
$LengthOK[413] = (strlen($JSONL) <= $DBL) ? true : false;
@@ -322,7 +311,6 @@ class Helper
// $goodString = "";
// }
// dump($goodString);
return $goodString;
}
-36
View File
@@ -1,36 +0,0 @@
<?php
if (! function_exists('m3_user')) {
/**
* Return the current Core username in the format expected by the legacy M3 data.
* M3 previously depended on PHP Basic Auth and read PHP_AUTH_USER directly.
*/
function m3_user(): string
{
$user = auth()->user();
$value = $user?->username
?? $user?->user_name
?? $user?->name
?? $user?->email
?? request()->server('PHP_AUTH_USER')
?? '';
if (str_contains((string) $value, '@')) {
$value = strstr((string) $value, '@', true) ?: $value;
}
return strtoupper(trim((string) $value));
}
}
if (! function_exists('m3_legacy_password')) {
/**
* Passwords are intentionally unavailable in Core. PostgreSQL access uses
* Laravel's configured connection and never reuses a user's login password.
*/
function m3_legacy_password(): string
{
return '';
}
}
@@ -1,14 +0,0 @@
<?php
if (! function_exists('subdirAsset')) {
function subdirAsset($path)
{
return asset((App::environment('production') ? env('APP_DIR') : '') . '/' . $path);
}
}
if (! function_exists('subdirMix')) {
function subdirMix($path)
{
return mix((App::environment('production') ? env('APP_DIR') : '') . '/' . $path);
}
}
-65
View File
@@ -1,65 +0,0 @@
<?php
// app/Helpers/USStates.php
namespace Modules\M3\Helpers;
class USStates
{
public static function all()
{
return [
'AL' => 'Alabama',
'AK' => 'Alaska',
'AZ' => 'Arizona',
'AR' => 'Arkansas',
'CA' => 'California',
'CO' => 'Colorado',
'CT' => 'Connecticut',
'DE' => 'Delaware',
'FL' => 'Florida',
'GA' => 'Georgia',
'HI' => 'Hawaii',
'ID' => 'Idaho',
'IL' => 'Illinois',
'IN' => 'Indiana',
'IA' => 'Iowa',
'KS' => 'Kansas',
'KY' => 'Kentucky',
'LA' => 'Louisiana',
'ME' => 'Maine',
'MD' => 'Maryland',
'MA' => 'Massachusetts',
'MI' => 'Michigan',
'MN' => 'Minnesota',
'MS' => 'Mississippi',
'MO' => 'Missouri',
'MT' => 'Montana',
'NE' => 'Nebraska',
'NV' => 'Nevada',
'NH' => 'New Hampshire',
'NJ' => 'New Jersey',
'NM' => 'New Mexico',
'NY' => 'New York',
'NC' => 'North Carolina',
'ND' => 'North Dakota',
'OH' => 'Ohio',
'OK' => 'Oklahoma',
'OR' => 'Oregon',
'PA' => 'Pennsylvania',
'RI' => 'Rhode Island',
'SC' => 'South Carolina',
'SD' => 'South Dakota',
'TN' => 'Tennessee',
'TX' => 'Texas',
'UT' => 'Utah',
'VT' => 'Vermont',
'VA' => 'Virginia',
'WA' => 'Washington',
'WV' => 'West Virginia',
'WI' => 'Wisconsin',
'WY' => 'Wyoming',
'DC' => 'District of Columbia',
];
}
}
@@ -14,7 +14,6 @@ use Modules\M3\Http\Controllers\Controller;
use Modules\M3\Http\Controllers\GetContentsController;
use Str;
// use Request;
class CloseShipment extends Controller
{
private const ZERO_PAD = '000000';
@@ -55,7 +54,6 @@ class CloseShipment extends Controller
$pdfFilePath = Config::get('arrays.PdfPath');
$DELIVERYNO = $MANIFEST != '' ? $MANIFEST : self::ZERO_PAD;
// Log::channel('dailyCron')->info("Close Manifest:".$MANIFEST.'-WHS: '.$WHS."-CO:".$COMPANY);
if ($urlParams != '') {
// Write to Logs : JSON
@@ -65,7 +63,6 @@ class CloseShipment extends Controller
'MANIFEST-MACPKR' => $MANIFEST,
'TRANSTYPE' => $TRANSTYPE,
]);
// dd($JSONIN);
$data = [
'SHMACPKR' => $DELIVERYNO,
@@ -81,13 +78,11 @@ class CloseShipment extends Controller
'SHWHS' => $WHS,
];
Helper::logToICM699M($data);
// dd($JSONIN);
// Get Token
$tokenResponse = Helper::checkReceiveTokenV2();
$tokenData = $tokenResponse->getData();
// dd($IonToken->code);
if ($tokenData->code == '200') {
$IonToken = isset($tokenData->token) ? $tokenData->token : '';
@@ -160,14 +155,12 @@ class CloseShipment extends Controller
->where('SHERROR', 'Z')
->where('SHTYPE', 'M3-QtyChg')
->get();
// dd($ICM699MQtyChg);
foreach ($ICM699MQtyChg as $key => $ICM699MQtyChgR) {
$string = $ICM699MQtyChgR->SHDATA;
$start = 'PickerLine:';
$end = ' -';
$LineAck[] = Helper::getSubstringBetween($string, $start, $end);
}
// dd($LineAck);
} elseif ($TRANSTYPE == 'Z') {
$ICM695M1PREP = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->select()
@@ -179,7 +172,6 @@ class CloseShipment extends Controller
}
$ICM695M1TMP = $ICM695M1PREP->get();
// dump($ICM695M1TMP);
// Log::channel('dailyCron')->info($ICM695M1TMP);
// PFC if MACKPKR already Closed : Case 671
@@ -193,10 +185,8 @@ class CloseShipment extends Controller
return trim($post->AYMACPKR);
});
}
// dump($ICM695M1TMPCOLF);
$ICM695M1TMPCOLFA = $ICM695M1TMPCOLF->toArray();
// dump($ICM695M1TMPCOLFA);
$ICM699MSuccess = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
->select('SHMACPKR')
@@ -208,12 +198,10 @@ class CloseShipment extends Controller
->where('SHTYPE', 'M3-Res-out')
->where('SHDATA', 'like', '%Success%')
->get();
// dump($ICM699MSuccess);
$ICM699MSuccessCol = collect($ICM699MSuccess);
$ICM699MSuccessColF = $ICM699MSuccessCol->map(function ($post) {
return $post->SHMACPKR;
});
// dump($ICM699MSuccessColF);
$ICM699MSuccessColFAr = $ICM699MSuccessColF->toArray();
if ($TRANSTYPE == 'Z') {
@@ -229,9 +217,7 @@ class CloseShipment extends Controller
}
$ICM695M1TMP = $ICM695M1TMPF;
// Log::channel('dailyCron')->info($ICM695M1TMP);
// dd($ICM695M1TMP);
$FreightTermsTMP = DB::connection(config('m3.connection', 'pgsql'))->table('icm321m')
->selectRaw('TRIM(ARCODE) as FREIGHTTERMS,ARCHARGE as BILLABLE')
->get();
@@ -311,7 +297,6 @@ class CloseShipment extends Controller
->where('AYWHS', $AYWHS)
->orderBy('AYINTBOX')
->get();
// dd($ICM695M1JOINTMP);
foreach ($ICM695M1JOINTMP as $key => $ICM695M1JOINR) {
$A4SHIPVIA = isset($ICM695M1JOINR->A4SHIPVIA) ? trim(str_replace('&', '_', $ICM695M1JOINR->A4SHIPVIA)) : '';
@@ -421,7 +406,6 @@ class CloseShipment extends Controller
->first();
$AlreadySentToM3 = isset($ICM699MS->SHMACPKR) ? trim($ICM699MS->SHMACPKR) : '';
// dump($AlreadySentToM3);
if ($AlreadySentToM3 != '') {
// Add Message
@@ -482,7 +466,6 @@ class CloseShipment extends Controller
$DOCNUMT = $AYINTBOX;
$PDFKey = $value . '/' . $value . '_' . $AYMACPKR . '_' . $DOCNUMT . '_' . $COMPANY . '_' . $WHS;
$pdfFileName = $pdfFilePath . $PDFKey . '.pdf';
// dd($pdfFileName);
if (File::exists($pdfFileName)) {
$CarrierLabel = route('m3.M3GetPDFFromCache.index', ['MACPKR' => $AYMACPKR, 'DOCTYPE' => $DOCTYPE]);
@@ -494,7 +477,6 @@ class CloseShipment extends Controller
$DOCNUMT = $AYINTBOX;
$PDFKey = $value . '/' . $value . '_' . $AYMACPKR . '_' . $DOCNUMT . '_' . $COMPANY . '_' . $WHS;
$pdfFileName = $pdfFilePath . $PDFKey . '.pdf';
// dd($pdfFileName);
if (File::exists($pdfFileName)) {
$ContentLabel = route('m3.M3GetPDFFromCache.index', ['MACPKR' => $AYMACPKR, 'DOCTYPE' => $DOCTYPE]);
@@ -535,7 +517,6 @@ class CloseShipment extends Controller
'CONTENTLABELDOC' => $ContentLabel,
];
}
// dump($PACKAGES);
// Check Packages array before proceeding with CloseShipment
if (count($PACKAGES) > 0) {
@@ -545,12 +526,10 @@ class CloseShipment extends Controller
$DOCNUMT = $AYMACPKR;
$PDFKey = $DOCTYPE . '/' . $DOCTYPE . '_' . $AYMACPKR . '_' . $DOCNUMT . '_' . $COMPANY . '_' . $WHS;
$pdfFileName = $pdfFilePath . $PDFKey . '.pdf';
// dd($pdfFileName);
if (File::exists($pdfFileName)) {
$PackingList = route('m3.M3GetPDFFromCache.index', ['MACPKR' => $AYMACPKR, 'DOCTYPE' => $DOCTYPE]);
}
// dd($PackingList);
// Add Cocharge
if (count($JSONCoCharge) > 0) {
@@ -604,7 +583,6 @@ class CloseShipment extends Controller
'ENDFLAG' => $EndFlag,
]);
}
// dump($JSONCS);
// No Errors Proceed in Calling M3 CLose API
if ($ErrorMsgs == '') {
@@ -670,7 +648,6 @@ class CloseShipment extends Controller
// Check M3 Response for Errors
$responseResult = $responseContents->result;
$M3Errors = Helper::checkM3Errors($responseResult);
// dd($M3Errors);
// If you get a successful response, update database file ICM688M1/A4RATEm3=X
// Update ICM688M1 : Change A4RATEM3
@@ -811,7 +788,6 @@ class CloseShipment extends Controller
}
// Close Shipment for Zero Picks
elseif (count($ICM695M1TMP) > 0 && $TRANSTYPE == 'Z') {
// dd($ICM695M1TMP);
$ErrorMsgs = '';
foreach ($ICM695M1TMP as $key => $ICM695M1JOINR) {
@@ -825,7 +801,6 @@ class CloseShipment extends Controller
$A4CLOSEM3 = trim($ICM695M1JOINR->A4CLOSEM3);
$AYWHS = trim($ICM695M1JOINR->A4WHS);
$AYCO = trim($ICM695M1JOINR->A4CO);
// dump($AYMACPKR);
// Construct Json for CloseShipment Without PDF Files
$JSONCS = json_encode([
@@ -939,7 +914,6 @@ class CloseShipment extends Controller
'SHCO' => $COMPANY,
'SHWHS' => $WHS,
];
// dump($data);
Helper::logToICM699M($data);
// Add Message
$ErrorMsgs = $ErrorMsgs . $M3Errors . '-';
@@ -1031,7 +1005,6 @@ class CloseShipment extends Controller
]);
}
} catch (\Throwable $th) {
// Log::error($th);
$getCurlErrors = str_contains($th->getMessage(), 'cURL error');
if ($getCurlErrors) {
// dd($getCurlErrors);
@@ -19,7 +19,6 @@ class M3Controller extends Controller
// Split Data and Write to ICM666M2
public function insertToICM666M2($dataSplit, $commentData)
{
// dump($commentData);
// dump($dataSplit);
$commentDataSS = explode("\n", $dataSplit);
@@ -29,7 +28,6 @@ class M3Controller extends Controller
$fullData = $commentData;
$fullData['AXCOMMENT'] = $substring;
$fullData['AXLINENO'] = $AXLINENO;
// dump($fullData);
$insertSQL = DB::connection(config('m3.connection', 'pgsql'))->table('icm666m2')->insert($fullData);
$AXLINENO++;
@@ -217,12 +215,10 @@ class M3Controller extends Controller
$commentData = ['AXCO' => $AXCO, 'AXPLANT' => $AXPLANT, 'AXWHS' => $AXWHS, 'AXDELNO' => $AXDELNO, 'AXONO' => $AXONO,
'AXRLNO' => $AXRLNO, 'AXSHNO' => $AXSHNO, 'AXDOCUMENT' => $AXDOCUMENT];
// dump($commentData);
switch ($AXDOCUMENT) {
case 'Picker':
$Picker = isset($comment) ? Helper::sanityzeString($comment) : 'null';
// dump($Picker);
if ($Picker != 'null') {
$this->insertToICM666M2($Picker, $commentData);
}
@@ -230,7 +226,6 @@ class M3Controller extends Controller
case 'Packer':
$Packer = isset($comment) ? Helper::sanityzeString($comment) : 'null';
// dump($Packer);
if ($Packer != 'null') {
$this->insertToICM666M2($Packer, $commentData);
}
@@ -238,7 +233,6 @@ class M3Controller extends Controller
case 'Carrier':
$Carrier = isset($comment) ? Helper::sanityzeString($comment) : 'null';
// dump($Carrier);
if ($Carrier != 'null') {
$this->insertToICM666M2($Carrier, $commentData);
}
@@ -246,7 +240,6 @@ class M3Controller extends Controller
case 'Other':
$Other = isset($comment) ? Helper::sanityzeString($comment) : 'null';
// dump($Other);
if ($Other != 'null') {
$this->insertToICM666M2($Other, $commentData);
}
@@ -399,7 +392,6 @@ class M3Controller extends Controller
$InsertArray[$value[0]] = $fieldValue;
}
}
// Log::info($InsertArray);
// Check ICM709M
$ICM709MSEL = DB::connection(config('m3.connection', 'pgsql'))->table('icm709m')
@@ -418,7 +410,6 @@ class M3Controller extends Controller
$HazMat = isset($ICM709MSEL->AT9WRN) ? $ICM709MSEL->AT9WRN : '';
$InsertArray['A1MATWRN'] = $HazMat;
// if ($PalletQty!='') {
// $InsertArray['A1USRN01']=$palletQty;
// }
@@ -461,7 +452,6 @@ class M3Controller extends Controller
// define several input/output params
$params = [];
// $params[] = $conn->AddParameterChar('out',7,'eqNumber');
// AddParameterChar($io, $size, $comment, $varName, $value, $varying, $dimension)
// Add Warehouse Param
@@ -473,7 +463,6 @@ class M3Controller extends Controller
// Add Delivery Note Param
$PickerNumberNoZero = ltrim(strval($PickerNumber), '0');
$params[] = $conn->AddParameterChar('in', 11, 'PickerNumber', '', $PickerNumberNoZero);
// $params[] = $conn->AddParameterZoned('in', 11, 0, 'ParamIn');
// Start Time Tracking
$start = microtime(true);
@@ -523,7 +512,6 @@ class M3Controller extends Controller
'SHDATA' => 'General Catchable Error - ' . substr($th, 0, 300) . self::M3_LIST_SUFFIX . json_encode($jsonFile), 'SHUSER' => $REQKPKUS, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $Company, 'SHWHS' => $Warehouse];
Helper::logToICM699M($data);
// Log::error($th);
return response()->json([
'code' => '405',
'status' => 'error',
@@ -1,150 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers\API;
use Cache;
use Config;
use File;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\M3\Helpers\Helper;
use Modules\M3\Http\Controllers\Controller;
use Str;
class PdfStorage extends Controller
{
private const ZERO_PAD = '000000';
public function PdfStorageAPI(Request $request): JsonResponse
{
$this->configureTimeouts();
$context = $this->requestContext($request);
if ($context === null) {
return $this->errorResponse('No URL Parameters Sent', self::ZERO_PAD, '', '', '');
}
try {
$this->logRequest($context);
$cacheKey = $this->buildCacheKey($context);
$pdfFileName = (string) Config::get('arrays.PdfPath') . $context['FILENAME'] . '.pdf';
$error = $this->validateStorageRequest($pdfFileName, $cacheKey);
if ($error !== null) {
return $this->errorResponse($error, $context['DELIVERYNO'], $context['DOCNUM'], $context['COMPANY'], $context['WHS']);
}
Cache::forever($cacheKey, base64_encode(File::get($pdfFileName)));
$this->logResult($context, 'PDF File converted to Base64 and Saved to Cache.Key: ' . $cacheKey);
return response()->json(['code' => '200', 'status' => 'Success', 'cacheKey' => $cacheKey]);
} catch (\Throwable $exception) {
$message = 'An Error Occured - ' . substr($exception->getMessage(), 0, 300);
$this->safeLog($context, $message, true);
return response()->json([
'code' => '405',
'status' => 'error',
'message' => 'Catched Error: ' . $exception->getMessage(),
]);
}
}
private function configureTimeouts(): void
{
$timeout = (string) Config::get('arrays.PHPTimeOut');
ini_set('max_execution_time', $timeout);
ini_set('max_input_time', $timeout);
ini_set('default_socket_timeout', $timeout);
}
private function requestContext(Request $request): ?array
{
if ($request->all() === []) {
return null;
}
$context = [];
foreach (['COMPANY', 'WHS', 'DOCTYPE', 'FILENAME', 'DOCNUM', 'A4MACPKR'] as $key) {
$context[$key] = trim((string) $request->input($key, ''));
}
$context['DELIVERYNO'] = $context['A4MACPKR'] !== '' ? $context['A4MACPKR'] : self::ZERO_PAD;
$context['SHUSER'] = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
$context['SHSOURCE'] = 'PdfStorageAPI';
return $context;
}
private function buildCacheKey(array $context): string
{
foreach (['A4MACPKR', 'DOCTYPE', 'DOCNUM', 'COMPANY', 'WHS'] as $required) {
if ($context[$required] === '') {
return '';
}
}
return $context['A4MACPKR'] . $context['DOCTYPE'] . $context['DOCNUM'] . $context['COMPANY'] . $context['WHS'];
}
private function validateStorageRequest(string $pdfFileName, string $cacheKey): ?string
{
$messages = [];
if (! File::exists($pdfFileName)) {
$messages[] = 'PDF File Not Found-';
}
if ($cacheKey === '') {
$messages[] = 'Cache Key is missing Params';
}
return $messages === [] ? null : implode('', $messages);
}
private function logRequest(array $context): void
{
$params = array_intersect_key($context, array_flip(['COMPANY', 'WHS', 'DOCTYPE', 'FILENAME', 'A4MACPKR', 'DOCNUM']));
$this->safeLog($context, json_encode($params, JSON_THROW_ON_ERROR), false, 'M3-Req-out');
}
private function logResult(array $context, string $message): void
{
$this->safeLog($context, $message);
}
private function safeLog(array $context, string $message, bool $error = false, string $type = 'M3-Res-out'): void
{
try {
Helper::logToICM699M([
'SHMACPKR' => $context['DELIVERYNO'] ?? self::ZERO_PAD,
'SHDT' => date('Y-m-d'),
'SHTIME' => date('H:i:s'),
'SHERROR' => $error ? 'X' : '',
'SHINTBOX' => $context['DOCNUM'] ?? '',
'SHTYPE' => $type,
'SHDATA' => $message,
'SHUSER' => $context['SHUSER'] ?? (m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser'),
'SHSOURCE' => $context['SHSOURCE'] ?? 'PdfStorageAPI',
'SHCO' => $context['COMPANY'] ?? '',
'SHWHS' => $context['WHS'] ?? '',
]);
} catch (\Throwable) {
// Logging must never turn an API response into a 500 error.
}
}
private function errorResponse(string $message, string $deliveryNo, string $docNum, string $company, string $warehouse): JsonResponse
{
$context = [
'DELIVERYNO' => $deliveryNo,
'DOCNUM' => $docNum,
'COMPANY' => $company,
'WHS' => $warehouse,
'SHUSER' => m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser',
'SHSOURCE' => 'PdfStorageAPI',
];
$this->safeLog($context, 'An Error Occured -' . $message, true);
return response()->json(['code' => '405', 'status' => 'Error', 'message' => $message]);
}
}
@@ -56,7 +56,6 @@ class ReplenAPI extends Controller
foreach ($PART as $key => $value) {
$PARTS[] = ['PART' => $value, 'LOT' => ''];
}
// dump($PARTS);
$JSON = json_encode(['WHS' => $WHS, 'PARTS' => $PARTS]);
@@ -68,7 +67,6 @@ class ReplenAPI extends Controller
// Get Token
$tokenResponse = Helper::checkReceiveTokenV2();
$tokenData = $tokenResponse->getData();
// dd($IonToken->code);
if ($tokenData->code == '200') {
$IonToken = isset($tokenData->token) ? $tokenData->token : '';
} else {
@@ -106,9 +104,7 @@ class ReplenAPI extends Controller
$JsonSanytized = Helper::sanityzeString($responseJSON);
// Array
$responseArray = json_decode($JsonSanytized, true);
// LOG::info( $responseArray);
$responseTMP = $responseArray['result'];
// LOG::info($responseTMP);
} else {
$M3Errors = 'Error: No Response from M3';
}
@@ -135,7 +131,6 @@ class ReplenAPI extends Controller
$dataToWrite2 = [];
foreach ($responseTMP as $key => $value) {
// dump($value);
$dataToWrite = [];
foreach ($value as $key2 => $content) {
@@ -143,13 +138,11 @@ class ReplenAPI extends Controller
$dataToWrite[$key2] = $content;
} else {
foreach ($content as $key3 => $content2) {
// dump($content2);
$dataToWrite2[] = array_merge($dataToWrite, $content2);
}
}
}
}
// LOG::info($dataToWrite2);
// Delete Old Records from IC630M
foreach ($dataToWrite2 as $key => $value) {
@@ -167,12 +160,10 @@ class ReplenAPI extends Controller
->where('WSELOC', $value['Warehouse'])
->where('VLOCID', $value['Location'])
->first();
// dd($DE640MSQLSEL);
$LocationExist = isset($DE640MSQLSEL->VLOCID) ? trim($DE640MSQLSEL->VLOCID) : '';
$WHExist = isset($DE640MSQLSEL->WSELOC) ? trim($DE640MSQLSEL->WSELOC) : '';
$COExist = isset($DE640MSQLSEL->LVCO) ? trim($DE640MSQLSEL->LVCO) : '';
// dd($LocationExist .': '.$WHExist.': '.$COExist);
// if No records Founds insert New Record
if ($LocationExist == '' && $WHExist == '' && $COExist == '') {
@@ -220,7 +211,6 @@ class ReplenAPI extends Controller
DB::connection(config('m3.connection', 'pgsql'))->table('ic630m')->insert($SQLInsertPrep630M);
}
// dump($SQLInsertPrep);
// Send Response
return response()->json([
@@ -273,7 +263,6 @@ class ReplenAPI extends Controller
'SHDATA' => 'An Error Occured - ' . substr($th, 0, 300), 'SHUSER' => $SHUSER, 'SHSOURCE' => $SHSOURCE, 'SHCO' => $CO, 'SHWHS' => $WHS];
Helper::logToICM699M($data);
// Log::error($th);
return response()->json([
'code' => '405',
'status' => 'error',
@@ -26,7 +26,6 @@ class TransferAPI extends Controller
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
// dd($request->all());
// Get the Calling User
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
@@ -95,7 +94,6 @@ class TransferAPI extends Controller
->where('SHERROR', 'X')
->where('SHTYPE', $SHTYPE)
->first();
// dump($ICM699MS->SHDATA);
// Read The substring from SHDATA after M3-JSN-out
$word = 'M3-JSN-out';
@@ -120,10 +118,8 @@ class TransferAPI extends Controller
$endPos = strrpos($SHDATAJSON, '}');
// Extract the substring within the curly braces
$SHDATAJSON = substr($SHDATAJSON, $startPos, $endPos - $startPos + 1);
// dd($SHDATAJSON);
$JSONTR = $SHDATAJSON != '' ? json_decode($SHDATAJSON) : '';
// dd($JSONTR);
if ($JSONTR != '') {
$PART = isset($JSONTR->PART) ? $JSONTR->PART : '';
@@ -140,7 +136,6 @@ class TransferAPI extends Controller
$TYPE = isset($JSONTR->TYPE) ? $JSONTR->TYPE : '';
$COLINESUFFIX = isset($JSONTR->COLINESUFFIX) ? $JSONTR->COLINESUFFIX : '';
}
// dd($JSONTR);
// Set SHERROR to Z in ICM699M
$ICM699MU = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m')
@@ -171,7 +166,6 @@ class TransferAPI extends Controller
$ICM688M2SLTMP->where('A5PKLN', $COLINENO);
}
$ICM688M2SL = $ICM688M2SLTMP->first();
// dd($ICM688M2SL->A5BRADLN);
$A5BRADLINE = isset($ICM688M2SL->A5BRADLN) ? $ICM688M2SL->A5BRADLN : '';
$COLINESUFFIX = isset($ICM688M2SL->A5PKSFX) ? $ICM688M2SL->A5PKSFX : ''; // Case 551 : $COLINESUFFIX
@@ -213,7 +207,6 @@ class TransferAPI extends Controller
'TYPE' => $TYPE,
'COLINESUFFIX' => $COLINESUFFIX,
], JSON_UNESCAPED_SLASHES);
// dd($JSON);
// Write JSON Params to Logs Out
$data = ['SHMACPKR' => $DELIVERYNO,
@@ -273,12 +266,9 @@ class TransferAPI extends Controller
$M3ResponseTimeTmp2 = floatval($M3ResponseTimeTmp) / 1000; // $M3ResponseTimeTmp / 1000;
$dateTime = new DateTime;
$dateTime->setTimestamp($M3ResponseTimeTmp2);
// dump( $dateTime->format('d/m/Y H:i:s.v') );
$M3ResponseTime = $M3ResponseTimeTmp != '' ? '-M3ResponseTime:' . $dateTime->format('d/m/Y H:i:s.v') : '-M3ResponseTime';
// dump($M3ResponseTime);
$transferStats = $response->transferStats;
$M3transferTime = $transferStats->getTransferTime() != null ? '-M3transferTime:' . $transferStats->getTransferTime() : '-M3transferTime';
// dd($M3transferTime);
if ($responseStatusCode == '200') {
$responseContents = json_decode($response->getBody()->getContents());
@@ -389,7 +379,6 @@ class TransferAPI extends Controller
]);
}
} catch (\Throwable $th) {
// Log::error($th);
$getCurlErrors = str_contains($th->getMessage(), 'cURL error');
if ($getCurlErrors) {
// Write to Logs Out : Failed
@@ -447,7 +436,6 @@ class TransferAPI extends Controller
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
// dd($request->all());
// Get the Calling User
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
@@ -460,7 +448,6 @@ class TransferAPI extends Controller
$DIVI = isset($urlParams['COMPANY']) ? $urlParams['COMPANY'] : '';
$WHS = isset($urlParams['WHS']) ? $urlParams['WHS'] : '';
$PLANT = isset($urlParams['PLANT']) ? $urlParams['PLANT'] : '';
// dump($urlParams);
try {
if ($urlParams != '') {
@@ -468,7 +455,6 @@ class TransferAPI extends Controller
$DELIVERYNO = isset($urlParams['DELIVERYNO']) ? $urlParams['DELIVERYNO'] : '';
$TYPE = 'UpdateShipmentNumber';
$allMacpkrs = [];
// dd($A4SPR15A01);
if ($A4SPR15A01 != '') {
// Read from ICM688M1
@@ -503,7 +489,6 @@ class TransferAPI extends Controller
'ENDFLAG' => '',
], JSON_UNESCAPED_SLASHES);
// dd($JSON);
// Write JSON Params to Logs Out
$data = ['SHMACPKR' => $DELIVERYNO,
@@ -656,7 +641,6 @@ class TransferAPI extends Controller
]);
}
} catch (\Throwable $th) {
// Log::error($th);
$getCurlErrors = str_contains($th->getMessage(), 'cURL error');
if ($getCurlErrors) {
// Write to Logs Out : Failed
@@ -1,119 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers\API;
use Config;
use DB;
use Illuminate\Http\Client\Response as HttpResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Modules\M3\Helpers\Helper;
use Modules\M3\Http\Controllers\Controller;
use Str;
class TwoShipAPIs extends Controller
{
private const SOURCE = 'TwoShipUpdateHold';
private const RESPONSE_TYPE = 'AggStopRsp';
public function TwoShipUpdateHold(Request $request)
{
$this->configureTimeouts();
$user = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
$params = $request->all();
$whs = (string) ($params['WHS'] ?? '');
$co = (string) ($params['COMPANY'] ?? '');
$macpkr = (string) ($params['MACPKR'] ?? '');
if ($params === []) {
$this->log($macpkr ?: '000000', $co, $whs, $user, 'X', 'No URL Parameters Sent');
return response()->json(['code' => '405', 'status' => 'Error', 'message' => 'No URL Parameters Sent']);
}
try {
$this->logRequest($macpkr, $co, $whs, $user);
$orders = $this->aggregationOrders($macpkr, $co, $whs);
$response = $this->callTwoShip($orders);
$error = $this->responseError($response);
if ($error !== '') {
$this->log($macpkr, $co, $whs, $user, 'X', $response->status() . '-' . $error);
return response()->json(['code' => '405', 'status' => 'error', 'message' => 'Status: ' . $response->status() . '-' . $error]);
}
$this->log($macpkr, $co, $whs, $user, '', $response->body());
$this->markAggregationComplete($orders, $co, $whs);
return response()->json(['code' => '200', 'status' => 'Success']);
} catch (\Throwable $th) {
$message = str_contains($th->getMessage(), 'cURL error')
? 'Curl Error: Communication with 2Ship Timed Out.'
: '2Ship communication failed.';
$this->log($macpkr, $co, $whs, $user, 'X', $message);
return response()->json(['code' => '405', 'status' => 'error', 'message' => $message]);
}
}
private function configureTimeouts(): void
{
$timeout = Config::get('arrays.PHPTimeOut');
ini_set('max_execution_time', $timeout);
ini_set('max_input_time', $timeout);
ini_set('default_socket_timeout', $timeout);
}
private function logRequest(string $macpkr, string $co, string $whs, string $user): void
{
$data = json_encode(['CO' => $co, 'WHS' => $whs, 'MACPKR' => $macpkr]);
Helper::logToICM699M($this->logData($macpkr, $co, $whs, $user, '', (string) $data, 'AggStopReq'));
}
private function aggregationOrders(string $macpkr, string $co, string $whs): array
{
$aggregation = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->where('A4MACPKR', $macpkr)->value('A4SHPAGGCD');
if (empty($aggregation) || (string) $aggregation === '0') {
return [$macpkr];
}
$orders = DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->where('A4SHPAGGCD', $aggregation)->where('A4SHPAGGCD', '<>', 0)->where('A4CONCMPLT', '<>', 'y')
->where('A4CO', $co)->where('A4WHS', $whs)->pluck('A4MACPKR')->all();
return $orders !== [] ? $orders : [$macpkr];
}
private function callTwoShip(array $orders): HttpResponse
{
$payload = [
'WS_Key' => Config::get('arrays.2Ship.TwoShip_Key'),
'OrderNumbers' => [implode(',', $orders)],
'FindBy' => 'ByMultipleOrderNumbers',
'DataToBeUpdated' => ['UpdateAggregationSettings' => true, 'OrderAggregationSettingsInfo' => ['NotConsideredAggregation' => true]],
];
return Http::acceptJson()->asJson()->timeout((int) Config::get('arrays.PHPTimeOut'))
->post(Config::get('arrays.2Ship.end_point') . Config::get('arrays.2Ship.hold_update'), $payload);
}
private function responseError(HttpResponse $response): string
{
if (! $response->successful()) {
return 'Error: No Response from 2Ship';
}
$body = $response->json();
return ($body['Success'] ?? true) === false ? '2Ship Error: ' . ($body['GlobalError'] ?? 'Unknown error') : '';
}
private function markAggregationComplete(array $orders, string $co, string $whs): void
{
DB::connection(config('m3.connection', 'pgsql'))->table('icm688m1')
->whereIn('A4MACPKR', $orders)->where('A4CO', $co)->where('A4WHS', $whs)->update(['A4CONCMPLT' => 'Y']);
}
private function log(string $macpkr, string $co, string $whs, string $user, string $error, string $message): void
{
Helper::logToICM699M($this->logData($macpkr, $co, $whs, $user, $error, $message, self::RESPONSE_TYPE));
}
private function logData(string $macpkr, string $co, string $whs, string $user, string $error, string $message, string $type): array
{
return ['SHMACPKR' => $macpkr, 'SHDT' => date('Y-m-d'), 'SHTIME' => date('H:i:s'), 'SHERROR' => $error,
'SHINTBOX' => '', 'SHTYPE' => $type, 'SHDATA' => $message, 'SHUSER' => $user, 'SHSOURCE' => self::SOURCE, 'SHCO' => $co, 'SHWHS' => $whs];
}
}
@@ -25,7 +25,6 @@ class BoxPackToPalletController extends Controller
$R659PALT = $request->R659PALT ?? abort(404, 'Manifest Not Found');
$userWhsCoPlant = self::getUserWhsCoPlant();
// dump($userWhsCoPlant);
$boxes = DB::connection(config('m3.connection', 'pgsql'))->table(self::PALLET_TABLE_ALIAS)
->select(
@@ -54,7 +53,6 @@ class BoxPackToPalletController extends Controller
->get()
->unique('R659BOX')
->values();
// dump($boxes);
if ($request->ajax()) {
return response()->json([
@@ -64,7 +62,6 @@ class BoxPackToPalletController extends Controller
}
$palletHeader = $boxes->first();
// dump($boxes);
return view('m3::liberty-theme.pages.BoxPackToPalletScan', compact('boxes', 'palletHeader', 'R659PALT'));
}
@@ -1,13 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
@@ -5,7 +5,6 @@ namespace Modules\M3\Http\Controllers;
use DB;
use Illuminate\Http\Request;
// use Modules\M3\Models\ICM709M;
//
class GetContentsController extends Controller
@@ -61,7 +60,6 @@ class GetContentsController extends Controller
$results = DB::table('ICM704M')->get();
return $results->mapWithKeys(function ($row) {
// dump($row);
return [
trim($row->AONMIT) => [
'LTLClassId' => number_format(trim($row->AOFCID), 1),
@@ -145,7 +143,6 @@ class GetContentsController extends Controller
$packagesGS1Array = [];
foreach ($results as $index => $row) {
// dump($row);
$internalBox = trim($row->AYINTBOX);
$package595m1[$internalBox] = [
@@ -1,112 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers;
use Artisan;
use Config;
use DB;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Log;
class M3CallCloseAPIController extends Controller
{
public static function index(Request $request): JsonResponse
{
self::configureTimeouts();
$params = self::validatedParams($request);
if ($params === null) {
Log::channel('dailyCron')->error('Manifest CloseAPI: Manifest, company and warehouse must be defined.');
return self::errorResponse('Manifest CloseAPI: Manifest, company and warehouse must be defined.');
}
try {
$records = self::findOpenManifestRecords($params);
if ($records->isEmpty()) {
Log::channel('dailyCron')->info('Manifest CloseAPI: No records found in ICM705M1.');
return self::errorResponse('Manifest CloseAPI: No records found in ICM705M1.');
}
return self::submitManifest($records->first(), $params['SHUSER']);
} catch (\Throwable $exception) {
Log::error($exception);
return response()->json([
'code' => '500',
'status' => 'Error',
'message' => 'Manifest Closing failed unexpectedly.',
], 500);
}
}
private static function configureTimeouts(): void
{
$timeout = (string) Config::get('arrays.PHPTimeOut');
ini_set('max_execution_time', $timeout);
ini_set('max_input_time', $timeout);
ini_set('default_socket_timeout', $timeout);
}
private static function validatedParams(Request $request): ?array
{
$params = [
'SHUSER' => trim((string) $request->input('SHUSER', '')),
'MANIFEST' => trim((string) $request->input('MANIFEST', '')),
'APCO' => trim((string) $request->input('APCO', '')),
'APWHS' => trim((string) $request->input('APWHS', '')),
];
if ($params['MANIFEST'] === '' || $params['APCO'] === '' || $params['APWHS'] === '') {
return null;
}
return $params;
}
private static function findOpenManifestRecords(array $params)
{
$connection = config('m3.connection', 'pgsql');
if (! Schema::connection($connection)->hasTable('icm705m1')) {
return collect();
}
return DB::connection($connection)->table('icm705m1')
->select('APMANIFEST', 'APCO', 'APWHS')
->where('APSPARE2', '')
->where('APCO', $params['APCO'])
->where('APWHS', $params['APWHS'])
->where('APMANIFEST', $params['MANIFEST'])
->whereRaw('EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - APLDCLOZ)) / 60 > 15')
->orderBy('APMANIFEST')
->get();
}
private static function submitManifest(object $record, string $user): JsonResponse
{
$exitCode = Artisan::call('command:CallCloseAPI', [
'user' => $user,
'manifest' => $record->APMANIFEST ?? '',
'co' => $record->APCO ?? '',
'whs' => $record->APWHS ?? '',
]);
if ($exitCode === 1) {
return response()->json([
'code' => '200',
'status' => 'Success',
'message' => 'Manifest Closing submitted',
]);
}
return self::errorResponse('Manifest Closing Failed');
}
private static function errorResponse(string $message): JsonResponse
{
return response()->json(['code' => '206', 'status' => 'Error', 'message' => $message]);
}
}
@@ -1,91 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class M3Controller extends Controller
{
/**
* Display a listing of the resource.
*
* @return Renderable
*/
public function index()
{
return view('m3::index');
}
/**
* Show the form for creating a new resource.
*
* @return Renderable
*/
public function create()
{
return view('m3::create');
}
/**
* Store a newly created resource in storage.
*
* @param Request $request
*
* @return Renderable
*/
public function store(Request $request)
{
//
}
/**
* Show the specified resource.
*
* @param int $id
*
* @return Renderable
*/
public function show($id)
{
return view('m3::show');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
*
* @return Renderable
*/
public function edit($id)
{
return view('m3::edit');
}
/**
* Update the specified resource in storage.
*
* @param Request $request
* @param int $id
*
* @return Renderable
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
*
* @return Renderable
*/
public function destroy($id)
{
//
}
}
@@ -1,70 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Modules\M3\Models\ICM664M;
class M3DeliveryController extends Controller
{
public static function index(Request $request)
{
$connection = config('m3.connection', 'pgsql');
$power_user = (object) ['R428PWRUSR' => 'N', 'R428US' => strtoupper(m3_user()), 'R428CO' => '', 'R428PL' => '', 'R428WH' => ''];
if (Schema::connection($connection)->hasTable('icm428m')) {
$power_user = DB::connection($connection)->table('icm428m')->select('R428PWRUSR', 'R428US', 'R428CO', 'R428PL', 'R428WH')
->where('R428US', strtoupper(m3_user()))->first() ?? $power_user;
}
$co = $power_user->R428CO;
$plant = $power_user->R428PL;
$whs = $power_user->R428WH;
$ICM664M = Schema::connection($connection)->hasTable('icm664m')
? DB::connection($connection)->table('icm664m')->where('AVCO', $co)->where('AVPLANT', $plant)->where('AVWHS', $whs)->get() : collect();
$IC670M = Schema::connection($connection)->hasTable('ic670m')
? DB::connection($connection)->table('ic670m')->where('WDCO', $co)->where('WDPL', $plant)->where('WDWHS', $whs)->get() : collect();
$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
//
public static function saveM3DeliveryAdd(Request $request)
{
$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'");
if ($icm664m[0]->COUNT1 == '1') {
return 'exists';
} else {
DB::connection(config('m3.connection', 'pgsql'))->insert("insert into ICM664M
(AVCO, AVPLANT, AVWHS, AVDELMETH, AVSHPVIA, AVSHSRT, AVSHORCL)
values ('$request->AVCO', '$request->AVPLANT', '$request->AVWHS', '$request->AVDELMETH',
'$request->AVSHPVIA', '$request->AVSHSRT', '$request->AVSHORCL')");
return 'success';
}
}
//
// Process data from Edit modal
//
public static function saveM3DeliveryEdit(Request $request)
{
// dd($request);
// Update record to ICM664M
DB::connection(config('m3.connection', 'pgsql'))->update("update ICM664M
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'");
return 'success';
}
}
@@ -15,7 +15,6 @@ class M3ErrorsDispController extends Controller
{
public static function index(Request $request)
{
// dump($request->all());
$macpkr = isset($request->macpkr) ? trim($request->macpkr) : '';
$shsource = isset($request->shsource) ? trim($request->shsource) : '';
$showerrors = isset($request->showerrors) ? trim($request->showerrors) : 'N';
@@ -140,7 +139,6 @@ class M3ErrorsDispController extends Controller
public static function update699M(Request $request)
{
// dump($request->all());
$SHMACPKR = $request->SHMACPKR != null ? trim($request->SHMACPKR) : '';
$SHSOURCE = $request->SHSOURCE != null ? trim($request->SHSOURCE) : '';
$SHCO = $request->SHCO != null ? trim($request->SHCO) : '';
@@ -195,7 +193,6 @@ class M3ErrorsDispController extends Controller
ini_set('memory_limit', '1024M');
try {
// dd($request->all());
$SHMACPKR = $request->SHMACPKR != null ? trim($request->SHMACPKR) : '';
$SHSOURCE = $request->SHSOURCE != null ? trim($request->SHSOURCE) : '';
$STARTDATE = $request->STARTDATE != null ? trim($request->STARTDATE) : today()->subDays(1)->format('Y-m-d');
@@ -353,7 +350,6 @@ class M3ErrorsDispController extends Controller
'SHDATA' => 'Error description',
];
$ICM699MCol->prepend($newItem);
// dd($ICM699MCol);
// Download Excel File
return app(SpreadsheetExport::class)->download($ICM699MCol, 'transactionLog_' . $STARTDATE . '-' . $ENDDATE . '.xlsx');
@@ -5,7 +5,6 @@ namespace Modules\M3\Http\Controllers;
use Config;
use DB;
use File;
// use Datatables;
use Illuminate\Http\Request;
use Smalot\PdfParser\Parser;
use Str;
@@ -20,7 +19,6 @@ class M3GetPDFFromCacheController extends Controller
$aggno = $aggmsg = '';
$IC670M = $PDFArray = $carrier = $trackingno = $ICM688M1 = [];
$AYMACPKR = $WHDDA = $COMPANY = $PLANT = $WHS = '';
// $carrier = $trackingno = "";
// PDF File PATH
$pdfFilePath = Config::get('arrays.PdfPath');
@@ -29,7 +27,6 @@ class M3GetPDFFromCacheController extends Controller
$PDFArray = $trackingno = $carrier = $ICM688M1 = [];
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER);
if ($SHUSER != '') {
// Get User CO & WH
@@ -55,7 +52,6 @@ class M3GetPDFFromCacheController extends Controller
$AYMACPKR = isset($urlParams['MACPKR']) ? trim($urlParams['MACPKR']) : ''; // Delivery note number
$DOCTYPE = isset($urlParams['DOCTYPE']) ? trim($urlParams['DOCTYPE']) : ''; // Document type (PackingList, CarrierLabel, ContentLabel)
$WHDDA = $COMPANY . $PLANT . $WHS;
// dump($WHDDA);
// Check Doctype fisrt
$docTypes = $DOCTYPE != '' ? [$DOCTYPE] : ['PackingList', 'ContentLabel', 'CarrierLabel', 'GSLabel']; // document type (PackingList, CarrierLabel, ContentLabel)
@@ -73,15 +69,12 @@ class M3GetPDFFromCacheController extends Controller
->where('AYWHS', $WHS)
->where('AYMACPKR', $AYMACPKR)
->first();
// dump($ICM695M1Agg);
$aggno = isset($ICM695M1Agg->AYTRUCK) ? trim($ICM695M1Agg->AYTRUCK) : '';
if ($aggno != '' && $aggno != '0') {
// dump($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'");
// dump($ICM688M1);
// foreach($ICM688M1 as $key => $ICM688M1R) {
// $aggmsg.=' <a href="M3GetPDFFromCache?MACPKR='.$ICM688M1R->A4MACPKR.'&COMPANY='.$COMPANY.'&PLANT='.$PLANT.'&WHS='.$WHS.'">'.$ICM688M1R->A4MACPKR.'</a>';
// }
@@ -108,7 +101,6 @@ class M3GetPDFFromCacheController extends Controller
->orderBy('AYMACPKR')
->get();
}
// dump($ICM695M1);
$allLabels = [];
@@ -127,7 +119,6 @@ class M3GetPDFFromCacheController extends Controller
// Make Key and Test Validity
if ($AYMACPKR != '' && $COMPANY != '' && $WHS != '') {
// echo "<script>alert('2');</script>";
$CarrierLabel = '';
$ContentLabel = '';
$PackingList = '';
@@ -160,7 +151,6 @@ class M3GetPDFFromCacheController extends Controller
if ($value == 'GSLabel') {
$PDFKey = $value . '/' . $value . '_' . $AYMACPKR . '_' . $COMPANY . '_' . $WHS . '_' . $DOCNUM;
// if ($ContentLabel=='LTL' ) {
// $PDFKey = $value.'/'.$value.'_'.$AYMACPKR.'_'.$COMPANY.'_'.$WHS;
// }
// else{
@@ -173,35 +163,27 @@ class M3GetPDFFromCacheController extends Controller
}
}
}
// dump($tmpCacheArr);
// Get unique values from array $PDFArray
$tmpCacheArr = collect($tmpCacheArr)->unique();
// dump($tmpCacheArr);
foreach ($tmpCacheArr as $key => $value) {
// $isCarrierLabel = Str::contains($value, 'CarrierLabel');
$pdfFileName = $pdfFilePath . $value . '.pdf';
if (File::exists($pdfFileName)) {
// dump($pdfFileName);
$pdfFile = File::get($pdfFileName);
// Transform content to base64
// $base64PDF = $pdfFile;
$base64PDF = base64_encode($pdfFile);
// dd($base64PDF);
$PDFArray[] = $base64PDF;
}
}
// dump($PDFArray);
} else {
// Nothing Found
}
}
} catch (\Throwable $th) {
// Log::error($th);
}
// dump($PDFArray);
// dump($AYMACPKR);
// dump($IC670M);
// dump($ICM695M1);
@@ -30,7 +30,6 @@ class MFOrdersController extends Controller
where APMANIFEST = $MF and APCO='$co' and APWHS='$whs' and APPLT='$plant' limit 1";
$ICM705M1 = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt);
// dump($ICM705M1);
$carrier = isset($ICM705M1[0]->APCARRIER) ? trim($ICM705M1[0]->APCARRIER) : '';
if ($MF != '') {
@@ -42,7 +41,6 @@ class MFOrdersController extends Controller
GROUP BY AYCO,AYPLANT,AYMACPKR,AYONO,A4SHSHNM,A4PICKSTS,AYSPR15A01";
$ICM695M1 = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt);
// dump($ICM695M1);
return view(
'm3::liberty-theme.pages.MFOrders',
@@ -23,7 +23,6 @@ class OrderLinesOfClosedOrder extends Controller
$allReportsUrls = [];
try {
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER);
if ($SHUSER != '') {
// Get User CO & WH from Table ICM428M
@@ -43,11 +42,9 @@ class OrderLinesOfClosedOrder extends Controller
// Get URL PARAMS
$urlParams = count($request->all()) > 0 ? $request->all() : '';
// dump($urlParams);
$REPORTDATEDisp = isset($urlParams['REPORTDATEDisp']) ? \DateTime::createFromFormat('Y-m-d', trim($urlParams['REPORTDATEDisp']))->format('Ymd') : today()->format('Ymd');
$WHDDA = $COMPANY . $PLANT . $WHS;
// dump($WHDDA);
if ($REPORTDATEDisp != '' && $COMPANY != '' && $WHS != '' && $PLANT != '') {
// Case 729: Add Currency code A1SHCURR FROM ICM666M
$selectContent = "
@@ -79,11 +76,9 @@ class OrderLinesOfClosedOrder extends Controller
WHERE AYSTATUS IN ('Z','z') AND AYAPR8N002 = $REPORTDATEDisp
)
AND A5CO=$COMPANY AND A5WHS=$WHS AND A5PLANT=$PLANT";
// dump($selectContent);
$ICM688M2 = DB::connection(config('m3.connection', 'pgsql'))
->select($selectContent);
// dd($ICM688M2);
} else {
$ICM688M2 = collect();
}
@@ -118,7 +113,6 @@ class OrderLinesOfClosedOrder extends Controller
try {
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER);
if ($SHUSER != '') {
// Get User CO & WH from Table ICM428M
@@ -138,7 +132,6 @@ class OrderLinesOfClosedOrder extends Controller
// Get URL PARAMS
$urlParams = count($request->all()) > 0 ? $request->all() : '';
// dd($urlParams);
$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');
@@ -146,7 +139,6 @@ class OrderLinesOfClosedOrder extends Controller
$toreportDateWD = isset($urlParams['TOREPORTDATE']) ? trim($urlParams['TOREPORTDATE']) : today()->format('Y-m-d');
$WHDDA = $COMPANY . $PLANT . $WHS;
// dump($WHDDA);
if ($reportDate != '' && $COMPANY != '' && $WHS != '' && $PLANT != '') {
// Case 729: Add Currency code A1SHCURR FROM ICM666M
$selectContent = "
@@ -187,7 +179,6 @@ class OrderLinesOfClosedOrder extends Controller
'REASON' => 'Failure Reason', 'A1SHCURR' => 'Currency Code', 'FREIGHT' => 'Freight'];
$ICM688M2Col = collect($ICM688M2);
$ICM688M2Col->prepend($newItem);
// dd($ICM688M2Col);
// Count records before exporting to excel : Max 20K records are allowed
$ICM688M2Count = $ICM688M2Col->count();
@@ -205,7 +196,6 @@ class OrderLinesOfClosedOrder extends Controller
// Download Excel
// Add true at the end to include fields names in the Header
return app(SpreadsheetExport::class)->download($ICM688M2Col, 'Closedorderlinesreport_' . $reportDateWD . '-' . $toreportDateWD . self::XLSX_EXTENSION);
// return $ICM688M2Col->downloadExcel('Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'.csv',\Maatwebsite\Excel\Excel::CSV,false);
} catch (\Throwable $th) {
Log::error($th);
}
@@ -220,7 +210,6 @@ class OrderLinesOfClosedOrder extends Controller
try {
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER);
if ($SHUSER != '') {
// Get User CO & WH from Table ICM428M
@@ -240,16 +229,13 @@ class OrderLinesOfClosedOrder extends Controller
// Get URL PARAMS
$urlParams = count($request->all()) > 0 ? $request->all() : '';
// dd($urlParams);
$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');
// dump($reportDate);
// dd($toreportDate);
$reportDateWD = isset($urlParams['REPORTDATE']) ? trim($urlParams['REPORTDATE']) : today()->format('Y-m-d');
$toreportDateWD = isset($urlParams['TOREPORTDATE']) ? trim($urlParams['TOREPORTDATE']) : today()->format('Y-m-d');
$WHDDA = $COMPANY . $PLANT . $WHS;
// dump($WHDDA);
if ($reportDate != '' && $COMPANY != '' && $WHS != '' && $PLANT != '') {
// Case 729: Add Currency code A1SHCURR FROM ICM666M
$ICM688M2 = DB::connection(config('m3.connection', 'pgsql'))
@@ -289,7 +275,6 @@ class OrderLinesOfClosedOrder extends Controller
'REASON' => 'Failure Reason', 'A1SHCURR' => 'Currency Code', 'FREIGHT' => 'Freight'];
$ICM688M2Col = collect($ICM688M2);
$ICM688M2Col->prepend($newItem);
// dd($ICM688M2Col);
// Count records before exporting to excel : Max 20K records are allowed
$ICM688M2Count = $ICM688M2Col->count();
@@ -312,11 +297,8 @@ class OrderLinesOfClosedOrder extends Controller
// MAK Store the File to Storage
app(SpreadsheetExport::class)->store($ICM688M2Col, $prevMonthFile, 'publicCL');
// $ICM688M2Col->storeExcel('Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'.csv', 'publicCL',\Maatwebsite\Excel\Excel::CSV);
// $ICM688M2Col->storeExcel('Closedorderlinesreport_'.$reportDateWD.'-'.$toreportDateWD.'.ods', 'publicCL',\Maatwebsite\Excel\Excel::ODS);
// dump('Done Saving Excel...');
return back();
} catch (\Throwable $th) {
Log::error($th);
@@ -326,13 +308,11 @@ class OrderLinesOfClosedOrder extends Controller
// Download File
public static function downloadFiles(Request $request)
{
// dd($request->all());
$fileName = $request->filename;
if (Storage::disk('publicCL')->exists($fileName)) {
// File exists, retrieve content or URL
// $content = Storage::disk('publicCL')->get($fileName);
$fileUrl = Storage::disk('publicCL')->url($fileName);
// dd($fileUrl);
$fileNameOnly = strpos($fileName, '/') != false ? substr($fileName, strpos($fileName, '/') + 1) : $fileName;
// Download the file
@@ -40,11 +40,9 @@ class ReplenishSettingsController extends Controller
->get()
: [];
} else {
// $REFCAT658 =[];
$IC670M = [];
}
// $sqlstmt="SELECT t1.REFKEY,t2.FULLID ,t2.*
// FROM PRDAT.REFERPS t1 LEFT JOIN ( SELECT R658CO,R658PL,R658WH,R658LC,R658PN,R658MQ,R658RQ,R658TL,R658RMQ,
// TRIM(R658WH)||TRIM(R658LC)||TRIM(R658PN) AS FULLID FROM EWOBJTST.ICM658M
// ) t2 ON t1.REFKEY = t2.FULLID WHERE t1.REFCAT = '658'";
@@ -57,24 +55,20 @@ class ReplenishSettingsController extends Controller
public function store(Request $request)
{
// dd( $request->all() );
$formInputs = $request->all();
$formInputs = array_filter($formInputs);
unset($formInputs['_token']);
$formInputs['R658IZLCF'] = isset($formInputs['R658IZLCF']) ? $formInputs['R658IZLCF'] : '0';
// dd($formInputs);
$ICM658MINS = ICM658M::insert($formInputs);
// dd($ICM658MINS);
return redirect()->route('m3.replenishmentSettings.index');
}
public function update(Request $request)
{
// dd($request->all());
$R658PN = (trim($request->R658PN) ?? trim($request->R658PN)) != null ? trim($request->R658PN) : '';
$R658CO = (trim($request->R658CO) ?? trim($request->R658CO)) != null ? trim($request->R658CO) : '';
$R658PL = (trim($request->R658PL) ?? trim($request->R658PL)) != null ? trim($request->R658PL) : '';
@@ -97,7 +91,6 @@ class ReplenishSettingsController extends Controller
public function deleteRec(Request $request)
{
// dd( $request->all() );
$R658PN = trim($request->R658PN);
$R658CO = trim($request->R658CO);
$R658LC = trim($request->R658LC);
@@ -117,11 +110,9 @@ class ReplenishSettingsController extends Controller
public function checkRecExit(Request $request)
{
// dd( $request->all() );
$params = [];
parse_str($request['data'], $params);
$paramsObj = (object) $params;
// dd($paramsObj);
$R658PN = trim($paramsObj->R658PN);
$R658CO = trim($paramsObj->R658CO);
@@ -136,7 +127,6 @@ class ReplenishSettingsController extends Controller
->where('R658PL', $R658PL)
->where('R658WH', $R658WH)
->first();
// dd($recordExists);
$recordExists = $recordExistSQL == null ? true : false;
return response()->json(['recordExists' => $recordExists]);
@@ -178,17 +168,14 @@ class ReplenishSettingsController extends Controller
// ->get();
} else {
$REFCAT658 = [];
// $IC670M =[];
}
// $sqlstmt="SELECT t1.REFKEY,t2.FULLID ,t2.*
// FROM PRDAT.REFERPS t1 LEFT JOIN ( SELECT R658CO,R658PL,R658WH,R658LC,R658PN,R658MQ,R658RQ,R658TL,R658RMQ,
// TRIM(R658WH)||TRIM(R658LC)||TRIM(R658PN) AS FULLID FROM EWOBJTST.ICM658M
// ) t2 ON t1.REFKEY = t2.FULLID WHERE t1.REFCAT = '658'";
// $REFCAT658 = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt);
// dd($REFCAT658);
// dd( Datatables::of($REFCAT658)->addIndexColumn()->make(true) );
return Datatables::of($REFCAT658)->addIndexColumn()->make(true);
}
@@ -92,7 +92,6 @@ class ShipToController extends Controller
$model = new ShipTo;
$model->fill($validated);
$success = $model->save();
// ShipTo::create($validated);
if ($success) {
return redirect()->route('m3.ship-to.index')->with('success', 'Record created successfully.');
} else {
@@ -1,107 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Log;
use Storage;
use Str;
class WhsPerfMetrics extends Controller
{
public static function index(Request $request)
{
$context = self::defaultContext();
try {
$context = array_merge($context, self::loadUserContext());
$context['IC670M'] = self::loadWarehouses();
$context['WHDDA'] = $context['COMPANY'] . $context['PLANT'] . $context['WHS'];
$context['allReportsUrls'] = self::loadReportUrls($context['WHS']);
} catch (\Throwable $exception) {
Log::error('Unable to load warehouse performance metrics.', [
'exception' => $exception,
]);
}
return view('m3::liberty-theme.pages.WhsPerfMetrics', $context);
}
public static function downloadFiles(Request $request)
{
$validated = $request->validate([
'filename' => ['required', 'string'],
]);
$fileName = ltrim($validated['filename'], '/');
$disk = Storage::disk('publicLabels');
if (! $disk->exists($fileName)) {
abort(404, 'Warehouse performance file not found.');
}
return $disk->download($fileName, basename($fileName));
}
private static function defaultContext(): array
{
return [
'IC670M' => collect(),
'WHDDA' => '',
'COMPANY' => '',
'PLANT' => '',
'WHS' => '',
'allReportsUrls' => [],
];
}
private static function loadUserContext(): array
{
$connection = config('m3.connection', 'pgsql');
$user = Str::upper(trim((string) m3_user()));
if ($user === '' || ! Schema::connection($connection)->hasTable('icm428m')) {
return ['COMPANY' => '', 'PLANT' => '', 'WHS' => ''];
}
$profile = DB::connection($connection)->table('icm428m')
->select('R428CO', 'R428PL', 'R428WH')
->where('R428US', $user)
->first();
return [
'COMPANY' => trim((string) ($profile->R428CO ?? '')),
'PLANT' => trim((string) ($profile->R428PL ?? '')),
'WHS' => trim((string) ($profile->R428WH ?? '')),
];
}
private static function loadWarehouses()
{
$connection = config('m3.connection', 'pgsql');
if (! Schema::connection($connection)->hasTable('ic670m')) {
return collect();
}
return DB::connection($connection)->table('ic670m')->get();
}
private static function loadReportUrls(string $warehouse): array
{
if ($warehouse === '') {
return [];
}
$disk = Storage::disk('publicLabels');
$urls = [];
foreach ($disk->allFiles('WhsPerf/' . $warehouse) as $file) {
$urls[$file] = $disk->url($file);
}
return $urls;
}
}
@@ -1,13 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers;
class authController extends Controller
{
public static function logout()
{
return view('m3::liberty-theme.pages.logout');
}
}
@@ -37,7 +37,6 @@ class carrierMaintController extends Controller
{
$currentUser = Helper::getUserCOWHSPLT();
$UserCO = $currentUser['UserCO'] ?? '';
// $UserWHS = $currentUser['UserWHS'] ?? '';
// $UserPL = $currentUser['UserPL'] ?? '';
// Insert record to ICM160M
@@ -66,7 +65,6 @@ class carrierMaintController extends Controller
{
$currentUser = Helper::getUserCOWHSPLT();
$UserCO = $currentUser['UserCO'] ?? '';
// $UserWHS = $currentUser['UserWHS'] ?? '';
// $UserPL = $currentUser['UserPL'] ?? '';
// Insert record to ICM160M
@@ -1,12 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers;
class dashboardController extends Controller
{
public static function index()
{
return view('m3::liberty-theme.pages.dashboard');
// , compact('data','whs','whs_array','starting','ending')
}
}
@@ -21,12 +21,10 @@ class execSummaryController extends Controller
try {
// Ajax Call
if ($request->ajax()) {
// dump($request->all());
$WHDDA = isset($request->WHDDA) ? $request->WHDDA : [];
$WHArr = [];
foreach ($WHDDA as $key => $WHDDAV) {
$CO = substr($WHDDAV, 0, 3);
// $R428PL = substr($WHDDAV, 3, 3);
$WHArr[] = substr($WHDDAV, 6, 3);
}
@@ -108,7 +106,6 @@ class execSummaryController extends Controller
$reportDate = $firstDay->modify('first 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)) : '';
// $toreportDate =$lastDay->modify('last day of this month')->format('Ymd');
// Build SQL
@@ -129,7 +126,6 @@ class execSummaryController extends Controller
$selectContent = '';
break;
}
// dump($reportDate);
// dump($toreportDate);
// dump($selectContent);
@@ -137,7 +133,6 @@ class execSummaryController extends Controller
} else {
$execSummaryRes = collect();
}
// dump($execSummaryRes);
return response()->json(['success' => true, 'reportPeriod' => $reportPeriod, 'result' => $execSummaryRes, 'checkSales' => $checkSales,
'checkWeight' => $checkWeight, 'checkLines' => $checkLines]);
@@ -145,7 +140,6 @@ class execSummaryController extends Controller
// Init Page
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER);
if ($SHUSER != '') {
// Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
@@ -19,12 +19,10 @@ class execSummaryLineController extends Controller
try {
// Ajax Call
if ($request->ajax()) {
// dump($request->all());
$WHDDA = isset($request->WHDDA) ? $request->WHDDA : [];
$WHArr = [];
foreach ($WHDDA as $key => $WHDDAV) {
$CO = substr($WHDDAV, 0, 3);
// $R428PL = substr($WHDDAV, 3, 3);
$WHArr[] = substr($WHDDAV, 6, 3);
}
@@ -178,7 +176,6 @@ class execSummaryLineController extends Controller
// Init Page
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
// dd($SHUSER);
if ($SHUSER != '') {
// Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
@@ -1,226 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers;
use Illuminate\Http\Request;
use Modules\M3\Services\BillOfLadingService;
class fillBOL2Controller extends Controller
{
protected $bolService;
public function __construct(BillOfLadingService $bolService)
{
$this->bolService = $bolService;
}
public static function index(Request $request)
{
return view('m3::liberty-theme.pages.fillBOL2');
}
public function fillBOL(Request $request)
{
// # $BOL = BOL::findOrFail($request);
$BOL = $request;
$data = [
'bol_number' => $request->input('BOL_number') ?? '1234567890',
'shipper_no' => $request->input('shipper_no') ?? '1234567890',
'date' => now()->format('m/d/Y') ?? '01/01/2000',
'master_bill_no' => $request->input('master_bill_no') ? 'X' : 'X',
'master_bill_yes' => $request->input('master_bill_yes') ? 'X' : '',
'master_bill_drops' => $request->input('master_bill_drops') ?? '',
'consignor_name' => $request->input('consignor_name') ?? 'ERICO INTERNATIONAL CORP',
'consignor_address1' => $request->input('consignor_address1') ?? '6800 ARNOLD MILLER PARKWAY',
'consignor_address2' => $request->input('consignor_address2') ?? 'SOLON, OH 44139',
'consignor_address3' => $request->input('consignor_address3') ?? 'USA',
'consignee_name' => $request->input('consignee_name') ?? 'ERICO EUROPE BV',
'consignee_address1' => $request->input('consignee_address1') ?? 'JULES VERNEWEG 75',
'consignee_address2' => $request->input('consignee_address2') ?? '',
'consignee_address3' => $request->input('consignee_address3') ?? 'TILBURG . 5015 BG',
'freight_collect' => $request->input('freight_collect') ? 'X' : 'X',
'carrier_name' => $request->input('carrier_name') ?? 'ICL / Expeditors',
'pieces' => $request->input('pieces') ?? '20',
'line_class' => $request->input('line_class') ?? '50',
'line_weight' => $request->input('line_weight') ?? '8320',
'total_pieces' => $request->input('total_pieces') ?? '20',
'total_line_weight' => $request->input('total_line_weight') ?? '8320',
'description' => $request->input('description') ?? 'Package Description sfdfsdfasdfas dfasdfasdfcasdfvasfa clsdalcdfl
Line 2
Line 3
Line 4
Line 5',
'DTESHIPED.1' => date('d/m/Y'),
'invoice_number' => $BOL['BOL_number'],
'amount_due' => number_format($BOL['amount'], 2),
'TYPEANDESCPTN.1' => 'TOTAL: 20 SKIDS 8320 #',
'TYPEANDESCPTN.10' => 'ROTTERDAM ETA: 11/22',
'TYPEANDESCPTN.13' => 'CONTAINER:',
'TYPEANDESCPTN.2' => 'MECHANICAL / CADDY/ ELECTRICAL',
'TYPEANDESCPTN.4' => 'BOOKING: 150744100',
'TYPEANDESCPTN.5' => 'REFERENCE: 3140028046',
'TYPEANDESCPTN.6' => 'VESSEL: INDEPENDENT HORIZON V. 1023E',
'TYPEANDESCPTN.7' => 'SEAL: 637053',
'TYPEANDESCPTN.9' => 'CHESTER, PA ETD: 11/05',
'BOFLADNGAGYCD' => $BOL['BOL_number'],
'CLASSORATE1' => '50',
'CNMETRKLICNSE' => 'ICL / Expeditors',
'CONSIGTONMADDR' => 'ERICO EUROPE BV JULES VERNEWEG 75 TILBURG . 5015 BG',
'DATE' => date('d/m/Y'),
'FRMNMADDR' => 'ERICO INTERNATIONAL CORP 6800 ARNOLD MILLER PARKWAY SOLON, OH 44139 USA',
'LNITEMWT1' => '8320',
'PARTOFMSTRBILL' => 'No',
'PKGTYPECOUNT1' => '20',
'SHPRNMBR' => '3140028046',
'TOTALWT' => '8320',
'TOTPIECES' => '20',
'ckFREIGHTCOLECT' => 'Yes',
'ckPREPAY' => 'Off',
'DTESHIPED.2' => '',
'LNITEMWT24' => '',
'CLASSORATE24' => '',
'LNITEMCLAS24' => '',
'TYPEANDESCPTN.24' => '',
'PKGTYPECOUNT24' => '',
'LNITEMWT23' => '',
'CLASSORATE23' => '',
'LNITEMCLAS23' => '',
'TYPEANDESCPTN.23' => '',
'PKGTYPECOUNT23' => '',
'LNITEMWT22' => '',
'CLASSORATE22' => '',
'LNITEMCLAS22' => '',
'TYPEANDESCPTN.22' => '',
'PKGTYPECOUNT22' => '',
'LNITEMWT21' => '',
'CLASSORATE21' => '',
'LNITEMCLAS21' => '',
'TYPEANDESCPTN.21' => '',
'PKGTYPECOUNT21' => '',
'LNITEMWT20' => '',
'CLASSORATE20' => '',
'LNITEMCLAS20' => '',
'TYPEANDESCPTN.20' => '',
'PKGTYPECOUNT20' => '',
'LNITEMWT19' => '',
'CLASSORATE19' => '',
'LNITEMCLAS19' => '',
'TYPEANDESCPTN.19' => '',
'PKGTYPECOUNT19' => '',
'LNITEMWT18' => '',
'CLASSORATE18' => '',
'LNITEMCLAS18' => '',
'TYPEANDESCPTN.18' => '',
'PKGTYPECOUNT18' => '',
'LNITEMWT17' => '',
'CLASSORATE17' => '',
'LNITEMCLAS17' => '',
'TYPEANDESCPTN.17' => '',
'PKGTYPECOUNT17' => '',
'LNITEMWT16' => '',
'CLASSORATE16' => '',
'LNITEMCLAS16' => '',
'TYPEANDESCPTN.16' => '',
'PKGTYPECOUNT16' => '',
'LNITEMWT15' => '',
'CLASSORATE15' => '',
'LNITEMCLAS15' => '',
'TYPEANDESCPTN.15' => '',
'PKGTYPECOUNT15' => '',
'LNITEMWT14' => '',
'CLASSORAT14' => '',
'LNITEMCLAS14' => '',
'TYPEANDESCPTN.14' => '',
'PKGTYPECOUNT14' => '',
'LNITEMWT13' => '',
'CLASSORATE13' => '',
'LNITEMCLAS13' => '',
'PKGTYPECOUNT13' => '',
'LNITEMWT12' => '',
'CLASSORATE12' => '',
'LNITEMCLAS12' => '',
'TYPEANDESCPTN.12' => '',
'PKGTYPECOUNT12' => '',
'LNITEMWT11' => '',
'CLASSORATE11' => '',
'LNITEMCLAS11' => '',
'TYPEANDESCPTN.11' => '',
'PKGTYPECOUNT11' => '',
'LNITEMWT10' => '',
'CLASSORATE10' => '',
'LNITEMCLAS10' => '',
'PKGTYPECOUNT10' => '',
'LNITEMWT9' => '',
'CLASSORATE9' => '',
'LNITEMCLAS8' => '',
'PKGTYPECOUNT9' => '',
'LNITEMWT8' => '',
'CLASSORATE8' => '',
'TYPEANDESCPTN.8' => '',
'PKGTYPECOUNT8' => '',
'LNITEMWT7' => '',
'CLASSORATE7' => '',
'LNITEMCLAS7' => '',
'PKGTYPECOUNT7' => '',
'LNITEMWT6' => '',
'CLASSORATE6' => '',
'LNITEMCLAS6' => '',
'PKGTYPECOUNT6' => '',
'LNITEMWT5' => '',
'CLASSORATE5' => '',
'LNITEMCLAS5' => '',
'PKGTYPECOUNT5' => '',
'LNITEMWT4' => '',
'CLASSORATE4' => '',
'LNITEMCLAS4' => '',
'PKGTYPECOUNT4' => '',
'LNITEMWT3' => '',
'CLASSORATE3' => '',
'LNITEMCLAS3' => '',
'TYPEANDESCPTN.3' => '',
'PKGTYPECOUNT3' => '',
'LNITEMWT2' => '',
'CLASSORATE2' => '',
'LNITEMCLAS2' => '',
'PKGTYPECOUNT2' => '',
'LNITEMCLAS1' => '',
'HAZLNITEMWT3' => '',
'HAZCLASSORATE3' => '',
'HAZLNITEMCLAS3' => '',
'HAZMATERDESL3' => '',
'HAZMATERL3' => '',
'HAZLNITEMWT2' => '',
'HAZCLASSORATE2' => '',
'HAZLNITEMCLAS2' => '',
'HAZMATERDESL2' => '',
'HAZMATERL2' => '',
'HAZLNITEMWT1' => '',
'HAZCLASSORATE1' => '',
'HAZLNITEMCLAS1' => '',
'HAZMATERDESL1' => '',
'HAZMATERL1' => '',
'24HREMGCYRSPNS' => '',
'CARIERFEDEMPID' => '',
'BILLTOADDR' => '',
'NUMDROPS' => '',
];
try {
$filledPdf = $this->bolService->fillBillOfLading($data);
return response()->download($filledPdf)->deleteFileAfterSend(true);
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
}
@@ -6,7 +6,6 @@ use Illuminate\Http\Request;
use mikehaertl\pdftk\Pdf;
use Storage;
// use mikehaertl\tmp\File;
class fillBOLController extends Controller
{
@@ -33,7 +32,6 @@ class fillBOLController extends Controller
dd($error);
}
// $test = Storage::disk('public')->exists('ETN-BOL.pdf');
// dd($test);
$newfile = "BOL-{$BOL['BOL_number']}.pdf";
@@ -46,7 +44,6 @@ class fillBOLController extends Controller
dd($error);
}
// $test=$pdf->addFile(Storage::disk('public')->path($newfile), 'A');
// dd($test);
$result = $pdf->fillForm([
@@ -86,10 +86,8 @@ class palletQtyController extends Controller
public static function saveQtyEdit(Request $request)
{
// dump($request);
// console.log($request);
// $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'");
// var_dump($icm709m);
@@ -57,7 +57,6 @@ class pendingClosureController extends Controller
$ICM699Ma[$val2->SHMACPKR]['SHTIME'] = $val2->SHTIME;
}
}
// dump($ICM699Ma);
$sqlstmt = "select count(*) as COUNT1 from ICM699M
where SHCO='$co' and SHWHS='$whs' and SHTYPE like '%M3%' and SHERROR='X'
@@ -75,11 +74,9 @@ class pendingClosureController extends Controller
// dump($sqlstmt3);
$UproccessedOrders = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt3);
foreach ($UproccessedOrders as $key => $UproccessedOrder) {
// $unprocessedArr[] = $UproccessedOrder->APMANIFEST;
$unprocessedArr[] = '<a class="btn btn-link mb-1" target="_blank" href="' . url('MFOrders', ['id' => trim($UproccessedOrder->APMANIFEST)]) . '"> ' .
trim($UproccessedOrder->APMANIFEST) . '</a>';
}
// dump($unprocessedArr);
return view(
'm3::liberty-theme.pages.pendingClosure',
@@ -92,7 +89,6 @@ class pendingClosureController extends Controller
{
// Get URL PARAMS
$urlParams = count($request->all()) > 0 ? $request->all() : '';
// dd($urlParams);
// $SHUSER = isset($urlParams["SHUSER"]) ? $urlParams["SHUSER"] : '';
$MANIFEST = isset($urlParams['MANIFEST']) ? $urlParams['MANIFEST'] : '';
$APCO = isset($urlParams['APCO']) ? $urlParams['APCO'] : '';
@@ -112,7 +108,6 @@ class pendingClosureController extends Controller
'message' => 'Manifest Closing submitted',
]);
} catch (\Throwable $th) {
// throw $th;
}
}
@@ -1,65 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers;
use DB;
use Illuminate\Http\Request;
class sentinelController extends Controller
{
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) : '';
if ($AYINTBOX != '') {
// Get the record from ICM695M1
$ICM695M1Sel = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
->select()
->where('AYINTBOX', $AYINTBOX)
->where('AYCO', $AYCO)
->where('AYWHS', $AYWHS)
->where('AYSTATUS', '')
->first();
$allowDeletion = isset($ICM695M1Sel->AYSENTPKR) ? ($ICM695M1Sel->AYSENTPKR != '' ? true : false) : false;
if ($allowDeletion) {
$timestamp = date('Y-m-d H:i:s.u');
$date1 = date('Ymd');
$time1 = date('His');
// Delete Records from ICM695M1 And ICM695M2
$ICM695M1Del = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m1')
->where('AYINTBOX', $AYINTBOX)
->where('AYCO', $AYCO)
->where('AYWHS', $AYWHS)
->delete();
$ICM695M2Del = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m2')
->where('AZINTBOX', $AYINTBOX)
->where('AZCO', $AYCO)
->where('AZWHS', $AYWHS)
->delete();
// 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',
'$timestamp', '$date1', '$time1', '$AYUSER','$timestamp', '$date1', '$time1', '$AYUSER','$AYINTBOX'";
$ICM689MInsert = DB::connection(config('m3.connection', 'pgsql'))->insert("INSERT INTO ICM689M
(A7CO, A7WHS, A7SENTPKR, A7MACPKR, A7ONO, A7RLNO, A7SHNO, A7SOURCE, A7ERRMSG, A7DISRAITS, A7DISRAID, A7DISRAIT, A7DISRAIU, A7DISRESTS ,A7DISRESD ,A7DISREST ,A7DISRESU , A7SPR15A01)
values ($InsertValues)");
return response()->json(['success' => true, 'message' => 'Line Deleted']);
} else {
return response()->json(['success' => false, 'message' => 'Line already packed']);
}
} else {
return response()->json(['success' => false, 'message' => 'Line missing']);
}
}
}
@@ -76,7 +76,6 @@ class userControlController extends Controller
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)
@@ -100,7 +99,6 @@ class userControlController extends Controller
if (! $result) {
$PGMERRORS = self::PROGRAM_ERROR_PREFIX . $conn->getErrorCode() . self::MESSAGE_SEPARATOR . $conn->getErrorMsg();
// echo "<script>alert($PGMERRORS);</script>";
return 'error profile2';
} else {
// Successful Call : User profile created with default password
@@ -128,7 +126,6 @@ class userControlController extends Controller
public static function saveUserEdit(Request $request)
{
// dump($request);
if ($request->R428EMPCDE == '') {
$request->R428EMPCDE = 0;
}
@@ -149,7 +146,6 @@ class userControlController extends Controller
// Update record to ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->select("select * from ICM428M where R428US='$request->R428US'");
// var_dump($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',
@@ -197,7 +193,6 @@ class userControlController extends Controller
}
}
// $conn->setOptions(array('persistent' => false, 'stateless' => true, 'debug' => true,'debugLogFile' => '/www/sentm3test/htdocs/M3/storage/logs/toolkit_debug.log'));
// Add LIB
// $result = $conn->CLCommand('ADDLIBLE LIB(MPDAT10)');
@@ -214,12 +209,10 @@ class userControlController extends Controller
// Add Delivery Note Param
// $params[] = $conn->AddParameterPackDec('in', 11, 0, 'ParamIn','','00000087125');
// $params[] = $conn->AddParameterZoned('in', 11, 0, 'ParamIn');
// Start Time Tracking
// $start = microtime(true);
// dump('Calling: EWOBJ/ICMCHGPRF action='.$request->ACTION.' user='.$request->USERID);
// Config::get('eproconf.misc.PGM1'), Config::get('eproconf.misc.libname4')
// ICM700C EWOBJTST ICM700C ICM700CSBM
@@ -227,7 +220,6 @@ class userControlController extends Controller
if (! $result) {
$PGMERRORS = self::PROGRAM_ERROR_PREFIX . $conn->getErrorCode() . self::MESSAGE_SEPARATOR . $conn->getErrorMsg();
// dump($PGMERRORS);
echo "<script>alert($PGMERRORS);</script>";
return 'error';
@@ -235,7 +227,6 @@ class userControlController extends Controller
}
// Successful Call
else {
// dump($result);
// $AWREQN = $result['io_param']["var0"];
// return "success";
if ($request->ACTION == 'P') {
@@ -260,21 +251,18 @@ class userControlController extends Controller
public static function savePassword(Request $request)
{
// dd('B4');
ini_set('max_execution_time', Config::get('arrays.PHPTimeOut'));
ini_set('max_input_time', Config::get('arrays.PHPTimeOut'));
ini_set('default_socket_timeout', Config::get('arrays.PHPTimeOut'));
$PGMERRORS = '';
// console_log("request> ");
// echo "request="; var_dump($request);
// echo "B3<br>";
// connect to toolkit using DB2 credentials (can also leave blank for default authority)
try {
$conn = app(PostgresProgramBridge::class);
// dump($conn);
// echo "B4<br>";
} catch (\Throwable $e) {
// echo "B5<br>";
@@ -299,15 +287,12 @@ class userControlController extends Controller
}
}
// $params = [];
// $params[] = $conn->AddParameterChar('in', 10, 'userid','USRPRF',$request->USERID);
// $params[] = $conn->AddParameterChar('in', 10, 'pwd','PASSWORD',$request->PASSWORD);
// $params[] = $conn->AddParameterChar('in', 9, 'sts','STATUS','*ENABLED');
// $params[] = $conn->AddParameterChar('in', 4, 'pwdexp','PWDEXP','*NO');
// dump('Before CHGUSRPRF');
$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());
// echo "<script>alert('After CHGUSRPRF');</script>";
if (! $result) {
@@ -54,9 +54,7 @@ class userPickingStats4 extends Controller
// while($row = odbc_fetch_object($result)) {
$x = 0;
foreach ($ICM428M as $key => $row) {
// print_r($row);
$user_array[$x]['userprf'] = trim($row->USERPRF);
// $user_array[$x]['name']=trim($row->R428FIRST)+' '+trim($row->R428FAMILY);
$user_array[$x]['name'] = trim($row->NAME);
$user_array[$x]['empno'] = $row->EMPNO;
$x++;
@@ -65,7 +63,6 @@ class userPickingStats4 extends Controller
// fill array of Lines per Hour per Monitor
$lph_per_monitor_array = Config::get('arrays_custom.lph_per_code_array');
// echo "<pre>"; print_r($user_array); echo "</pre>";
if (isset($request->user)) {
$user = $request->user;
$empno = 0;
@@ -95,7 +92,6 @@ class userPickingStats4 extends Controller
and oppno in ($payrollCodes)
group by oppno";
// echo "$sqlstmt<br>";
$lbpf1 = $schema->hasTable('lbpf')
? DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt)
@@ -107,7 +103,6 @@ class userPickingStats4 extends Controller
}
$sql = "select * from perfstat where dt='$starting' and a5pickcomu='$user' ";
// @dd($sql);
if ((isset($request->dates) || isset($request->user)) && $schema->hasTable('perfstat')) {
$statistic4 = DB::connection(config('m3.connection', 'pgsql'))->select($sql);
@@ -115,9 +110,7 @@ class userPickingStats4 extends Controller
$statistic4 = [];
}
// echo "<pre>"; print_r($statistic4); echo "</pre>";
// $duration = microtime(true) - $start;
// initialize arrays
$monitor_array = $totals_array = $perf_array = [];
@@ -128,7 +121,6 @@ class userPickingStats4 extends Controller
$totals_array['entries'] = 0;
$diff = 0;
// echo "<pre>"; print_r($lbpf1); echo "</pre>";
foreach ($lbpf1 as $key => $val) {
$monitor_array[$val->OPPNO]['tot_hours'] = $val->HRS;
@@ -158,7 +150,6 @@ class userPickingStats4 extends Controller
$monitor_array[$val->CODE]['weight'] = 0;
$monitor_array[$val->CODE]['lines'] = 0;
}
// echo "after 1st init<br>";
// add another element (0) in monitor_array to capture the total blended lph value expected
$monitor_array[0]['lph_blended_per_activity'] = 0;
@@ -258,7 +249,6 @@ class userPickingStats4 extends Controller
}
// echo "<pre>";
// print_r($request);
// print_r($perf_array); print_r($monitor_array);
@@ -294,7 +284,6 @@ class userPickingStats4 extends Controller
'grossHours' => $grossHours,
];
// echo "<pre>"; print_r($json_data);
return json_encode($json_data);
} else {
@@ -305,7 +294,6 @@ class userPickingStats4 extends Controller
$no_data = 'Y';
}
// error_log("Time required to xyz: " . $duration . "\n", 3, "/temp/v4.log");
return view(
'm3::liberty-theme.pages.userPickingStats4',
@@ -1,140 +0,0 @@
<?php
namespace Modules\M3\Http\Controllers;
use DateTime;
use DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\HttpFoundation\Request;
class userPickingStats5 extends Controller
{
public static function index(Request $request)
{
[$userArray, $co, $whs] = self::loadUsers();
[$starting, $ending, $days] = self::dateRange($request);
$user = $request->user;
$statistics = [];
$totals = self::emptyTotals();
if (isset($request->dates)) {
[$statistics, $totals] = self::collectDailyStatistics($request, $starting, $days, $totals);
}
if ($request->format === 'json') {
return response()->json($statistics);
}
$statistic5 = $statistics;
$totals_array = $totals;
$user_array = $userArray;
return view('m3::liberty-theme.pages.userPickingStats5', compact(
'statistic5', 'totals_array', 'user_array', 'user', 'starting', 'ending', 'request'
));
}
private static function loadUsers(): array
{
$users = [];
$co = '';
$whs = '';
try {
$connection = config('m3.connection', 'pgsql');
if (! Schema::connection($connection)->hasTable('icm428m')) {
return [$users, $co, $whs];
}
$profile = DB::connection($connection)->table('icm428m')
->select('R428CO', 'R428WH')
->where('R428US', strtoupper((string) m3_user()))
->first();
$co = trim((string) ($profile->R428CO ?? ''));
$whs = trim((string) ($profile->R428WH ?? ''));
if ($co === '' || $whs === '') {
return [$users, $co, $whs];
}
$rows = DB::connection($connection)->table('icm428m')
->selectRaw("R428US as userprf, (trim(R428FIRST) || ' ' || trim(R428FAMILY)) as name, R428EMPCDE as empno")
->where('R428EMPCDE', '!=', 0)->where('R428CO', $co)->where('R428WH', $whs)->get();
foreach ($rows as $row) {
$users[] = ['userprf' => trim((string) $row->userprf), 'name' => trim((string) $row->name), 'empno' => $row->empno];
}
array_multisort(array_column($users, 'name'), SORT_ASC, $users);
} catch (\Throwable $e) {
Log::warning('M3 picking user list unavailable', ['exception' => $e->getMessage()]);
}
return [$users, $co, $whs];
}
private static function dateRange(Request $request): array
{
if (isset($request->dates)) {
$dates = explode(' - ', (string) $request->dates);
$starting = $dates[0] ?? date('Y-m-d');
$ending = $dates[1] ?? $starting;
} else {
$starting = date('Y-m-d', strtotime('-5 days'));
$ending = date('Y-m-d');
}
$days = (int) (new DateTime($starting))->diff(new DateTime($ending))->format('%a');
return [$starting, $ending, $days];
}
private static function emptyTotals(): array
{
return ['performance' => 0, 'blendedTargetLPH' => 0, 'actualLPH' => 0, 'grossHours' => 0];
}
private static function collectDailyStatistics(Request $request, string $starting, int $days, array $totals): array
{
$statistics = [];
$count = 0;
$url = 'http://' . $request->server('HTTP_HOST') . '/userPickingStats4';
for ($day = 0; $day <= $days; $day++) {
$date = date('Y-m-d', strtotime($starting . "+$day days"));
$statistics[$day] = self::fetchStatistic($request, $url, $date);
self::addTotals($totals, $statistics[$day]);
if (($statistics[$day]['performance'] ?? 0) > 0) {
$count++;
}
}
if ($count > 0) {
foreach (array_keys($totals) as $key) {
$totals[$key] /= $count;
}
}
return [$statistics, $totals];
}
private static function fetchStatistic(Request $request, string $url, string $date): array
{
try {
$response = Http::withBasicAuth((string) $request->header('php-auth-user'), (string) $request->header('php-auth-pw'))
->get($url, ['dates' => $date, 'user' => $request->user, 'format' => 'json']);
$data = $response->successful() ? (json_decode($response->body(), true) ?: []) : [];
} catch (\Throwable $e) {
Log::warning('M3 picking statistics unavailable', ['date' => $date, 'exception' => $e->getMessage()]);
$data = [];
}
$data['day'] = $data['day'] ?? $date;
$data['performance'] = $data['performance'] ?? 0;
return $data;
}
private static function addTotals(array &$totals, array $statistic): void
{
foreach (array_keys($totals) as $key) {
$totals[$key] += (float) ($statistic[$key] ?? 0);
}
}
}
@@ -33,7 +33,6 @@ class userProfileController extends Controller
public static function updateUserProfile(Request $request)
{
// dd($request->all());
$R428US = isset($request->R428US) ? trim($request->R428US) : '';
$R428DPW = isset($request->R428DPW) ? trim($request->R428DPW) : '';
@@ -41,7 +40,6 @@ class userProfileController extends Controller
$R428CO = substr($R428DPW, 0, 3);
$R428PL = substr($R428DPW, 3, 3);
$R428WH = substr($R428DPW, 6, 3);
// dd($R428US.'-'.$R428CO.'-'.$R428PL.'-'.$R428WH );
if ($R428US != '') {
// Update record to ICM428M
@@ -49,7 +47,6 @@ class userProfileController extends Controller
set R428CO='$R428CO', R428PL='$R428PL', R428WH='$R428WH'
where R428US='$R428US'");
// return "success";
return redirect('/userprofile')->with('success', 'Profile updated successfully!');
} else {
return redirect('/userprofile')->with('success', 'Profile updated successfully!');
@@ -59,7 +56,6 @@ class userProfileController extends Controller
public static function updateUserProfileAjax(Request $request)
{
// dd($request->all());
$R428US = isset($request->R428US) ? trim($request->R428US) : '';
$R428DPW = isset($request->R428DPW) ? trim($request->R428DPW) : '';
@@ -67,7 +63,6 @@ class userProfileController extends Controller
$R428CO = substr($R428DPW, 0, 3);
$R428PL = substr($R428DPW, 3, 3);
$R428WH = substr($R428DPW, 6, 3);
// dd($R428US.'-'.$R428CO.'-'.$R428PL.'-'.$R428WH );
if ($R428US != '') {
// Update record to ICM428M
@@ -3,7 +3,6 @@
namespace Modules\M3\Http\Controllers;
use Ayeo\Barcode;
// use Symfony\Component\HttpFoundation\Request;
use Cache;
use Config;
use DB;
@@ -58,7 +57,6 @@ class utilitiesContoller extends Controller
// define several input/output params
$params = [];
// $params[] = $conn->AddParameterChar('out',7,'eqNumber');
// AddParameterChar($io, $size, $comment, $varName, $value, $varying, $dimension)
// Add Warehouse Param
@@ -68,7 +66,6 @@ class utilitiesContoller extends Controller
// Add Delivery Note Param
$params[] = $conn->AddParameterPackDec('in', 11, 0, 'ParamIn', '', '00000087125');
// $params[] = $conn->AddParameterZoned('in', 11, 0, 'ParamIn');
// Start Time Tracking
$start = microtime(true);
@@ -85,14 +82,11 @@ class utilitiesContoller extends Controller
// Successful Call
else {
dump($result);
// $AWREQN = $result['io_param']["var0"];
}
if ($PGMERRORS != '') {
// return back()->withMessage('Can not Create PR: '.$PGMERRORS);
dump($PGMERRORS);
} else {
// return $AWREQN;
}
// Get Execution Time
$time = microtime(true) - $start;
@@ -108,13 +102,11 @@ class utilitiesContoller extends Controller
// Parse PDF file and build necessary objects.
$parser = new Parser;
// $pdf = $parser->parseFile('/www/sentm3test/htdocs/labels/E1232824-10826596.pdf');
// dump($pdf);
// $text = $pdf->getText();
// dump("Text Only");
// dump($text);
// $pdfFile = file_get_contents('/www/sentm3test/htdocs/labels/E1232824-10826596.pdf');
$pdfFile = File::get('/www/sentm3test/htdocs/labels/' . $pdfFileName . '.pdf');
// Transform content to base64
@@ -172,9 +164,7 @@ class utilitiesContoller extends Controller
->orderBy('A5PICKSTRD', 'ASC')
->get();
// $counter=0;
foreach ($ICM688M2SLTMP as $key => $ICM688M2SL) {
// $counter++;
// $counter == 10 ? exit : '';
$A5MACPKR = isset($ICM688M2SL->A5MACPKR) ? $ICM688M2SL->A5MACPKR : '';
@@ -206,7 +196,6 @@ class utilitiesContoller extends Controller
// Get Manifest Array
$GSArray = $request->query();
// dump($GSArray);
$SHUSER = isset($GSArray['User']) ? trim($GSArray['User']) : '';
@@ -374,7 +363,6 @@ class utilitiesContoller extends Controller
}
$html .= '</body> </html>';
// dump($html);
ob_start();
@@ -389,7 +377,6 @@ class utilitiesContoller extends Controller
// $dompdf->stream();
$pdfContent = $dompdf->output();
// dump($pdfContent);
$labelsPath = Config::get('arrays.PdfPath'); // '/www/sentm3live/htdocs/labels/';
// Put the PDF in labels/CarrierLabel
@@ -415,12 +402,10 @@ class utilitiesContoller extends Controller
// $ICM695M3SQLInsert = DB::connection(config('m3.connection', 'pgsql'))->table('icm695m3')
// ->insert(['A2CO'=> $COMPANY,'A2WHS'=> $WHS,'A2MACPKR'=> $Macpkr,'A2GS1LABEL'=> $gs1_128_bc]);
// Log::channel('LabelCron')->info("<<< GS1-128...End of Label Creation for Mackpkr: ".$Macpkr);
return json_encode(['result' => 'success', 'GS1File' => $GS1FileNameNoRoot]);
} catch (\Throwable $th) {
// Log::error($th);
Log::channel('LabelCron')->error($th);
return json_encode(['result' => 'error', 'GS1File' => $th]);
@@ -432,10 +417,8 @@ class utilitiesContoller extends Controller
{
print_r('>>> Generate PDF');
// $builder = new Barcode\Builder();
// $image = $builder->output('(10)123456(400)11(3906)333333');
// $builder = new Barcode\Builder();
// $builder->setBarcodeType('gs1-128');
// $builder->setFilename('barcode.png');
// $builder->setImageFormat('png');
@@ -536,7 +519,6 @@ class utilitiesContoller extends Controller
</body>
</html>';
// return ($html);
// Initialize Dompdf
$dompdf = new Dompdf;
@@ -615,7 +597,6 @@ class utilitiesContoller extends Controller
$response = $controller->processShipment($myRequest);
$responseData = $response->getData();
// dd($responseData);
// $responseJSON = json_encode($responseData);
// dump($responseJSON);
@@ -5,7 +5,6 @@ namespace Modules\M3\Http\Controllers;
use Config;
use DB;
use Illuminate\Http\Request;
// use Modules\M3\Models\ICM711M;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
@@ -27,7 +26,6 @@ class whsePerfController extends Controller
// **********************************************************************************
$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 = isset($request->date_in)?$request->date_in:date('Ymd');
$date_in = $date_in_yr . $date_in_mth . '01';
$sqlstmt = 'select AVDATE, AVANOTESCL,AVADLRCL,AVAWGTCL,AVANOTESCH,AVADLRCH,AVAWGTCH,AVANOTESOP,AVADLROP,AVAWGTOP,
AVLNOTESCL,AVLDLRCL,AVLWGTCL,AVLNOTESCH,AVLDLRCH,AVLWGTCH,AVLNOTESOP,AVLDLROP,AVLWGTOP,
@@ -51,7 +49,6 @@ class whsePerfController extends Controller
$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 = isset($request->date_in)?$request->date_in:date('Ymd');
$date_in = $date_in_yr . $date_in_mth . '01';
$sqlstmt = 'select AVDATE, AVANOTESCL,AVADLRCL,AVAWGTCL,AVANOTESCH,AVADLRCH,AVAWGTCH,AVANOTESOP,AVADLROP,AVAWGTOP,
AVLNOTESCL,AVLDLRCL,AVLWGTCL,AVLNOTESCH,AVLDLRCH,AVLWGTCH,AVLNOTESOP,AVLDLROP,AVLWGTOP,
@@ -11,7 +11,6 @@ class whsePerfDetailsController extends Controller
public static function index(Request $request)
{
// $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_minus_4_months = date('Y-m-d', strtotime($date_in . ' -4 months'));
$for = isset($request->for) ? $request->for : 'a';
@@ -76,11 +75,8 @@ class whsePerfDetailsController extends Controller
$stmt2 = $all;
break;
}
// phpinfo();
include $_SERVER['DOCUMENT_ROOT'] . '/../../KPI2_update711M_SQL_main.inc.php';
// var_dump($sqlstmt1.$stmt2);
$perfDetails = DB::connection(config('m3.connection', 'pgsql'))->select($sqlstmt1 . $stmt2);
// var_dump($perfDetails);
return view('m3::liberty-theme.pages.whsePerfDetails', compact('perfDetails', 'date_in', 'for'));
View File
@@ -1,23 +0,0 @@
<?php
namespace Modules\M3\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param Request $request
*
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('m3.login');
}
}
}
-57
View File
@@ -1,57 +0,0 @@
<?php
namespace Modules\M3\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class BasicAuth
{
public function handle(Request $request, Closure $next): mixed
{
$login = trim((string) m3_user());
$password = (string) m3_legacy_password();
if ($login !== '' && $this->checkPassword($login, $password, '%%SYSTEM%%')) {
return $next($request);
}
return $this->unauthorized();
}
private function checkPassword(string $login, string $password, string $passwordFile): bool
{
if (! is_readable($passwordFile)) {
return false;
}
$handle = fopen($passwordFile, 'rb');
if ($handle === false) {
return false;
}
try {
while (($line = fgets($handle)) !== false) {
$parts = explode(':', trim($line), 2);
if (count($parts) !== 2 || ! hash_equals($parts[0], $login)) {
continue;
}
$storedHash = trim($parts[1]);
return $storedHash !== '' && password_verify($password, $storedHash);
}
} finally {
fclose($handle);
}
return false;
}
private function unauthorized(): Response
{
return response('INVALID USERNAME OR PASSWORD. ACCESS DENIED', 401)
->header('WWW-Authenticate', 'Basic realm="RESTRICTED ACCESS"');
}
}
@@ -1,17 +0,0 @@
<?php
namespace Modules\M3\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}
@@ -1,17 +0,0 @@
<?php
namespace Modules\M3\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
//
];
}
@@ -1,33 +0,0 @@
<?php
namespace Modules\M3\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Modules\M3\Providers\RouteServiceProvider;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure $next
* @param string|null ...$guards
*
* @return mixed
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}
@@ -1,19 +0,0 @@
<?php
namespace Modules\M3\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}
-20
View File
@@ -1,20 +0,0 @@
<?php
namespace Modules\M3\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}
@@ -1,23 +0,0 @@
<?php
namespace Modules\M3\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers = Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO | Request::HEADER_X_FORWARDED_AWS_ELB;
}
@@ -1,17 +0,0 @@
<?php
namespace Modules\M3\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}
View File
View File
-29
View File
@@ -1,29 +0,0 @@
<?php
namespace Modules\M3\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ICM428M extends Model
{
use HasFactory;
protected $connection = 'pgsql';
protected $table;
public $incrementing = false;
public $timestamps = false;
public function __construct()
{
$this->table = 'ICM428M';
}
// R428DV R428PL R428WHS R428STS R428US R428FIRST R428FAMILY R428EMPCDE R428ADMUSR R428PWRUSR -->
protected $fillable = [
'R428CO', 'R428PL', 'R428WH', 'R428STS', 'R428US', 'R428FIRST', 'R428FAMILY', 'R428EMPCDE', 'R428ADMUSR', 'R428PWRUSR',
];
}
-28
View File
@@ -1,28 +0,0 @@
<?php
namespace Modules\M3\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ICM658M extends Model
{
use HasFactory;
protected $connection = 'pgsql';
protected $table;
public $incrementing = false;
public $timestamps = false;
public function __construct()
{
$this->table = 'ICM658M';
}
protected $fillable = [
'R658CO', 'R658PL', 'R658WH', 'R658LC', 'R658PN', 'R658MQ', 'R658RQ', 'R658TL', 'R658RMQ', 'R658IZLCF',
];
}
-2
View File
@@ -34,7 +34,6 @@ class ShipTo extends Model
return parent::save($options);
} else {
return false;
// return redirect()->back()
// ->withErrors(['unique' => 'The combination of AUSHSHZP and AUSHWHS must be unique'])
// ->withInput();
}
@@ -54,7 +53,6 @@ class ShipTo extends Model
}
if ($existingRecord->count() > 0) {
// throw new \Exception('Composite unique constraint violated for AUSHSHZP and AUSHWHS');
return false;
} else {
return true;
-42
View File
@@ -1,42 +0,0 @@
<?php
namespace Modules\M3\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
View File
-42
View File
@@ -1,42 +0,0 @@
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
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\ReplenAPI;
use Modules\M3\Http\Controllers\API\TransferAPI;
use Modules\M3\Http\Controllers\API\TwoShipAPIs;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth')->get('/user', function (Request $request) {
return $request->user();
});
Route::apiResource('m3receiver', M3Controller::class);
Route::any('/M3InventoryReport', [M3InventoryReport::class, 'M3InventoryReport'])->name('M3InventoryReport');
Route::any('/M3InventoryReportListURL', [M3InventoryReport::class, 'M3InventoryReportListURL'])->name('M3InventoryReportListURL');
Route::any('/TransferAPIURL', [TransferAPI::class, 'TransferAPIURL'])->name('TransferAPIURL');
Route::any('/UpdateShipmentNumber', [TransferAPI::class, 'UpdateShipmentNumber'])->name('UpdateShipmentNumber');
Route::any('/M3InventoryReportReplen', [ReplenAPI::class, 'M3InventoryReportReplen'])->name('M3InventoryReportReplen');
Route::any('/CloseShipmentCoChargeAPI', [CloseShipment::class, 'CloseShipmentCoChargeAPI'])->name('CloseShipmentCoChargeAPI');
Route::any('/PdfStorageAPI', [PdfStorage::class, 'PdfStorageAPI'])->name('PdfStorageAPI');
Route::any('/twoshipupdatehold', [TwoShipAPIs::class, 'TwoShipUpdateHold'])->name('twoshipupdatehold');
-1
View File
@@ -132,7 +132,6 @@ Route::post('/exporttoExcel699', 'Modules\M3\Http\Controllers\M3ErrorsDispContro
// M3 Cached PDF
Route::resource('/M3GetPDFFromCache', 'Modules\M3\Http\Controllers\M3GetPDFFromCacheController', ['except' => ['create', 'store', 'edit', 'update', 'destroy']]);
Route::any('/M3GetPDFFromCache', 'Modules\M3\Http\Controllers\M3GetPDFFromCacheController@index');
// Route::get('/M3GetPDFFromCacheDT', 'Modules\M3\Http\Controllers\M3GetPDFFromCacheController@datatables')->name('M3GetPDFFromCacheDT');
// M3 Call Close API
Route::any('/M3ManifestCloseAPI', [M3CallCloseAPIController::class, 'index'])->name('M3ManifestCloseAPI');
+82 -228
View File
@@ -7,240 +7,94 @@ use Storage;
class BillOfLadingService
{
public function fillBillOfLading($data, $outputPath = null)
public function fillBillOfLading(array $data, ?string $outputPath = null): string
{
$templatePath = Storage::disk('public')->path('ETN-BOL2.pdf'); // storage_path('app/templates/ETN-BOL.pdf');
$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');
$templatePath = Storage::disk('public')->path('ETN-BOL2.pdf');
$newFile = 'BOL_' . ($data['bol_number'] ?? 'unknown') . '.pdf';
$outputPath ??= Storage::disk('public')->path($newFile);
$pdf = new Fpdi;
$pdf->setSourceFile($templatePath);
// Set source file
$pageCount = $pdf->setSourceFile($templatePath);
// Import first page (you have 5 pages in your PDF)
$tplIdx = $pdf->importPage(1);
$pdf->AddPage();
$pdf->useTemplate($tplIdx);
// Set font
$pdf->SetFont('Helvetica', '', 10);
$pdf->SetTextColor(0, 0, 0);
// $pdf->SetLineWidth(50);
// Fill form fields at specific coordinates
// You'll need to adjust X,Y positions based on your PDF
// Bill of Lading No.
if (isset($data['bol_number'])) {
$pdf->SetXY(126, 44);
$pdf->Write(0, $data['bol_number']);
}
// Date
if (isset($data['date'])) {
$pdf->SetXY(171, 44);
$pdf->Write(0, $data['date']);
}
// Shipper No.
if (isset($data['shipper_no'])) {
$pdf->SetXY(126, 53);
$pdf->Write(0, $data['shipper_no']);
}
// Master Bill No
if (isset($data['master_bill_no'])) {
$pdf->SetXY(172, 54);
$pdf->Write(0, $data['master_bill_no']);
}
// Master Bill Yes
if (isset($data['master_bill_yes'])) {
$pdf->SetXY(183, 54);
$pdf->Write(0, $data['master_bill_yes']);
}
// Master Bill Drops
if (isset($data['master_bill_drops'])) {
$pdf->SetXY(194, 55);
$pdf->Write(0, $data['master_bill_drops']);
}
// Consignor (FROM)
if (isset($data['consignor_name'])) {
$pdf->SetXY(21, 44);
$pdf->Write(0, $data['consignor_name']);
}
if (isset($data['consignor_address1'])) {
$pdf->SetXY(21, 48);
$pdf->Write(0, $data['consignor_address1']);
}
if (isset($data['consignor_address2'])) {
$pdf->SetXY(21, 52);
$pdf->Write(0, $data['consignor_address2']);
}
if (isset($data['consignor_address3'])) {
$pdf->SetXY(21, 56);
$pdf->Write(0, $data['consignor_address3']);
}
// Consignee (TO)
if (isset($data['consignee_name'])) {
$pdf->SetXY(21, 72);
$pdf->Write(0, $data['consignee_name']);
}
if (isset($data['consignee_address1'])) {
$pdf->SetXY(21, 76);
$pdf->Write(0, $data['consignee_address1']);
}
if (isset($data['consignee_address2'])) {
$pdf->SetXY(21, 80);
$pdf->Write(0, $data['consignee_address2']);
}
if (isset($data['consignee_address3'])) {
$pdf->SetXY(21, 84);
$pdf->Write(0, $data['consignee_address3']);
}
// Freight Collect
if (isset($data['freight_collect'])) {
$pdf->SetXY(127, 90);
$pdf->Write(0, $data['freight_collect']);
}
// Carrier Name
if (isset($data['carrier_name'])) {
$pdf->SetXY(10, 100);
$pdf->Write(0, $data['carrier_name']);
}
// Pieces
if (isset($data['pieces'])) {
$pdf->SetXY(6, 142);
$pdf->Write(0, $data['pieces']);
}
// Line class
if (isset($data['line_class'])) {
$pdf->SetXY(145, 142);
$pdf->Write(0, $data['line_class']);
}
// Line weight
if (isset($data['line_weight'])) {
$pdf->SetXY(177, 142);
$pdf->Write(0, $data['line_weight']);
}
// Total pieces
if (isset($data['total_pieces'])) {
$pdf->SetXY(6, 244);
$pdf->Write(0, $data['total_pieces']);
}
// Total weight
if (isset($data['total_line_weight'])) {
$pdf->SetXY(177, 244);
$pdf->Write(0, $data['total_line_weight']);
}
// Description of articles
if (isset($data['description'])) {
$pdf->SetXY(28, 140);
$pdf->MultiCell(67, 4.5, $data['description'], 0, 'L');
}
// Add more pages if needed (pages 2-5)
// Repeat for other pages as needed
$tplIdx = $pdf->importPage(2);
$pdf->AddPage();
$pdf->useTemplate($tplIdx);
// Bill of Lading No.
if (isset($data['bol_number'])) {
$pdf->SetXY(126, 44);
$pdf->Write(0, $data['bol_number']);
}
// Date
if (isset($data['date'])) {
$pdf->SetXY(171, 44);
$pdf->Write(0, $data['date']);
}
// Shipper No.
if (isset($data['shipper_no'])) {
$pdf->SetXY(126, 53);
$pdf->Write(0, $data['shipper_no']);
}
// Master Bill No
if (isset($data['master_bill_no'])) {
$pdf->SetXY(172, 54);
$pdf->Write(0, $data['master_bill_no']);
}
// Master Bill Yes
if (isset($data['master_bill_yes'])) {
$pdf->SetXY(183, 54);
$pdf->Write(0, $data['master_bill_yes']);
}
// Master Bill Drops
if (isset($data['master_bill_drops'])) {
$pdf->SetXY(194, 55);
$pdf->Write(0, $data['master_bill_drops']);
}
// Consignor (FROM)
if (isset($data['consignor_name'])) {
$pdf->SetXY(21, 44);
$pdf->Write(0, $data['consignor_name']);
}
if (isset($data['consignor_address1'])) {
$pdf->SetXY(21, 48);
$pdf->Write(0, $data['consignor_address1']);
}
if (isset($data['consignor_address2'])) {
$pdf->SetXY(21, 52);
$pdf->Write(0, $data['consignor_address2']);
}
if (isset($data['consignor_address3'])) {
$pdf->SetXY(21, 56);
$pdf->Write(0, $data['consignor_address3']);
}
// Consignee (TO)
if (isset($data['consignee_name'])) {
$pdf->SetXY(21, 72);
$pdf->Write(0, $data['consignee_name']);
}
if (isset($data['consignee_address1'])) {
$pdf->SetXY(21, 76);
$pdf->Write(0, $data['consignee_address1']);
}
if (isset($data['consignee_address2'])) {
$pdf->SetXY(21, 80);
$pdf->Write(0, $data['consignee_address2']);
}
if (isset($data['consignee_address3'])) {
$pdf->SetXY(21, 84);
$pdf->Write(0, $data['consignee_address3']);
}
// Freight Collect
if (isset($data['freight_collect'])) {
$pdf->SetXY(127, 90);
$pdf->Write(0, $data['freight_collect']);
}
// Carrier Name
if (isset($data['carrier_name'])) {
$pdf->SetXY(10, 100);
$pdf->Write(0, $data['carrier_name']);
}
// KD : add fields as you need
// Save the PDF
$this->renderPage($pdf, $data, 1, true);
$this->renderPage($pdf, $data, 2, false);
$pdf->Output('F', $outputPath);
return $outputPath;
}
private function renderPage(Fpdi $pdf, array $data, int $pageNumber, bool $includeLineDetails): void
{
$template = $pdf->importPage($pageNumber);
$pdf->AddPage();
$pdf->useTemplate($template);
$pdf->SetFont('Helvetica', '', 10);
$pdf->SetTextColor(0, 0, 0);
foreach ($this->headerFields() as $field => [$x, $y]) {
$this->writeField($pdf, $data, $field, $x, $y);
}
if ($includeLineDetails) {
foreach ($this->lineFields() as $field => [$x, $y]) {
$this->writeField($pdf, $data, $field, $x, $y);
}
$this->writeDescription($pdf, $data);
}
}
private function writeField(Fpdi $pdf, array $data, string $field, float $x, float $y): void
{
if (! array_key_exists($field, $data) || $data[$field] === null || $data[$field] === '') {
return;
}
$pdf->SetXY($x, $y);
$pdf->Write(0, (string) $data[$field]);
}
private function writeDescription(Fpdi $pdf, array $data): void
{
$description = $data['description'] ?? null;
if ($description === null || $description === '') {
return;
}
$pdf->SetXY(28, 140);
$pdf->MultiCell(67, 4.5, (string) $description, 0, 'L');
}
private function headerFields(): array
{
return [
'bol_number' => [126, 44],
'date' => [171, 44],
'shipper_no' => [126, 53],
'master_bill_no' => [172, 54],
'master_bill_yes' => [183, 54],
'master_bill_drops' => [194, 55],
'consignor_name' => [21, 44],
'consignor_address1' => [21, 48],
'consignor_address2' => [21, 52],
'consignor_address3' => [21, 56],
'consignee_name' => [21, 72],
'consignee_address1' => [21, 76],
'consignee_address2' => [21, 80],
'consignee_address3' => [21, 84],
'freight_collect' => [127, 90],
'carrier_name' => [10, 100],
];
}
private function lineFields(): array
{
return [
'pieces' => [6, 142],
'line_class' => [145, 142],
'line_weight' => [177, 142],
'total_pieces' => [6, 244],
'total_line_weight' => [177, 244],
];
}
}
@@ -1,99 +0,0 @@
<?php
namespace Modules\M3\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
/**
* PostgreSQL replacement for the old IBM i Toolkit program-call transport.
*
* The legacy M3 code invokes IBM i programs after writing PostgreSQL-backed
* staging data. Core no longer connects to DB2. These requests are persisted
* so a PostgreSQL-native worker/integration can process them without making
* the web request depend on IBM i drivers.
*/
class PostgresProgramBridge
{
private string $errorCode = '';
private string $errorMessage = '';
public function setOptions(array $options): self
{
return $this;
}
public function AddParameterChar(string $io, int $size, string $comment = '', string $name = '', mixed $value = null, mixed ...$rest): array
{
return compact('io', 'size', 'comment', 'name', 'value');
}
public function AddParameterPackDec(string $io, int $length, int $scale, string $comment = '', string $name = '', mixed $value = null, mixed ...$rest): array
{
return compact('io', 'length', 'scale', 'comment', 'name', 'value');
}
public function AddParameterZoned(string $io, int $length, int $scale, string $comment = '', string $name = '', mixed $value = null, mixed ...$rest): array
{
return compact('io', 'length', 'scale', 'comment', 'name', 'value');
}
public function PgmCall(string $program, ?string $library = null, array $parameters = [], array $returnParameters = [], array $options = []): array|false
{
return $this->queue('program', $program, $library, [
'parameters' => $parameters,
'return_parameters' => $returnParameters,
'options' => $options,
]);
}
public function CLCommand(string $command): array|false
{
return $this->queue('command', $command, null, []);
}
public function getErrorCode(): string
{
return $this->errorCode;
}
public function getErrorMsg(): string
{
return $this->errorMessage;
}
private function queue(string $type, string $operation, ?string $library, array $payload): array|false
{
try {
$record = [
'type' => $type,
'operation' => $operation,
'library' => $library,
'payload' => json_encode($payload, JSON_THROW_ON_ERROR),
'requested_by' => function_exists('m3_user') ? m3_user() : null,
'status' => 'pending',
'created_at' => now(),
'updated_at' => now(),
];
if (Schema::connection(config('m3.connection', 'pgsql'))->hasTable('m3_program_requests')) {
$id = DB::connection(config('m3.connection', 'pgsql'))
->table('m3_program_requests')
->insertGetId($record);
} else {
Log::warning('M3 PostgreSQL program bridge table is not migrated; request logged only.', $record);
$id = null;
}
return ['success' => true, 'queued' => true, 'request_id' => $id, 'io_param' => []];
} catch (\Throwable $e) {
$this->errorCode = (string) $e->getCode();
$this->errorMessage = $e->getMessage();
Log::error('Unable to queue M3 program request.', ['exception' => $e]);
return false;
}
}
}
-80
View File
@@ -1,80 +0,0 @@
<?php
namespace Modules\M3\Services;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class SpreadsheetExport
{
private const EXPORT_DIRECTORY = 'app/m3-exports/';
public function download(Collection $rows, string $filename): BinaryFileResponse
{
$path = storage_path(self::EXPORT_DIRECTORY . uniqid('', true) . '-' . basename($filename));
$this->write($rows, $path);
return response()->download($path, basename($filename))->deleteFileAfterSend(true);
}
public function store(Collection $rows, string $filename, ?string $disk = null): string
{
$tmp = storage_path(self::EXPORT_DIRECTORY . uniqid('', true) . '-' . basename($filename));
$this->write($rows, $tmp);
if ($disk && config("filesystems.disks.$disk")) {
Storage::disk($disk)->put($filename, file_get_contents($tmp));
@unlink($tmp);
return $filename;
}
return $tmp;
}
public function storeSheets(array $sheets, string $filename, ?string $disk = null): string
{
$book = new Spreadsheet;
$book->removeSheetByIndex(0);
foreach ($sheets as $title => $rows) {
$sheet = $book->createSheet();
$sheet->setTitle(substr((string) $title, 0, 31));
$array = collect($rows)->map(fn ($row) => (array) $row)->values();
if ($array->isNotEmpty()) {
$sheet->fromArray($array->map(fn ($row) => array_values($row))->all(), null, 'A1');
}
}
$tmp = storage_path(self::EXPORT_DIRECTORY . uniqid('', true) . '-' . basename($filename));
if (! is_dir(dirname($tmp))) {
mkdir(dirname($tmp), 0775, true);
}
(new Xlsx($book))->save($tmp);
if ($disk && config("filesystems.disks.$disk")) {
Storage::disk($disk)->put($filename, file_get_contents($tmp));
@unlink($tmp);
return $filename;
}
return $tmp;
}
private function write(Collection $rows, string $path): void
{
if (! is_dir(dirname($path))) {
mkdir(dirname($path), 0775, true);
}
$sheet = (new Spreadsheet)->getActiveSheet();
$array = $rows->map(fn ($row) => (array) $row)->values();
$headers = $array->first() ? array_keys($array->first()) : [];
if ($headers) {
$sheet->fromArray($headers, null, 'A1');
$sheet->fromArray($array->map(fn ($row) => array_values($row))->all(), null, 'A2');
}
(new Xlsx($sheet->getParent()))->save($path);
}
}