Compare commits

..
4 Commits
Author SHA1 Message Date
Mark Gregory a9378cd309 M3 Security Fixes for scan command 2026-09-17 11:15:23 +01:00
Mark Gregory 59390d20c4 M3 Security Fixes for scan command 2026-09-17 11:01:10 +01:00
Mark Gregory e050b47a1c M3 Security Fixes for pass 30 2026-09-17 10:58:46 +01:00
Mark Gregory dca0f54109 M3 Security Fixes for pass 29 2026-09-17 10:54:04 +01:00
49 changed files with 2286 additions and 451 deletions
View File
+73
View File
@@ -0,0 +1,73 @@
<?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);
}
}
+101 -129
View File
@@ -41,139 +41,111 @@ class WHSMetricsSaveXls extends Command
* @return int
*/
public function handle()
{
$this->configureRuntime();
try {
Log::channel('dailyCron')->info('Cron...Start Save WHS Metrics to Excel');
$company = '110';
$warehouse = '321';
$plant = '143';
$file = 'WhsPerf/' . $warehouse . '/WhsPerfMetrics_' . date('Y-m-d') . '-' . $warehouse . '.xlsx';
Log::channel('dailyCron')->info('>>> File Name: ' . $file);
$this->info('Generate Today WHS Performance Report...');
[$summary, $details] = $this->reportCollections($company, $warehouse, $plant);
$this->storeReport($summary, $details, $file);
Log::channel('dailyCron')->info('Cron...End Save Today WHS Performance Report to Excel');
$this->info('Cron...End Save Today WHS Performance Report to Excel');
} catch (\Throwable $th) {
Log::channel('dailyCron')->error($th);
}
return self::SUCCESS;
}
private function configureRuntime(): void
{
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'));
ini_set('memory_limit', '1024M');
try {
Log::channel('dailyCron')->info('Cron...Start Save WHS Metrics to Excel');
// Get the Calling User
$userId = $this->argument('user');
$SHUSER = isset($userId) ? $userId : (m3_user() !== '' ? Str::upper(trim(m3_user())) : '');
$CO = $this->argument('co');
$COMPANY = '110';
$PWHS = $this->argument('whs');
$WHS = '321';
$PPL = $this->argument('pl');
$PLANT = '143';
$date = new \DateTime;
$DateToday = $date->format('Y-m-d');
// Define File Name
$whsPerfFile = 'WhsPerf/' . $WHS . '/WhsPerfMetrics_' . $DateToday . '-' . $WHS . '.xlsx';
Log::channel('dailyCron')->info('>>> File Name:');
Log::channel('dailyCron')->info($whsPerfFile);
$this->info('Generate Today WHS Performance Report...');
if ($COMPANY != '' && $WHS != '' && $PLANT != '') {
// Get Header Content
$ICM700MHeadSel = DB::connection(config('m3.connection', 'pgsql'))
->select("
WITH TEMPFILE AS (
SELECT A.*,A4TPCKWGHT,A4NOPICLNS,A4PICKSTS,
CASE WHEN UPPER(A4PICKSTS)<>'A' THEN 'Open' ELSE 'Closed' END AS STATUS,
CASE WHEN A4TPCKWGHT>16000 THEN 'FTL' ELSE A4SHIPTYPE END AS A4SHIPTYPE,
(SELECT SUM(A5RSVQTY*A5SLUNPR) FROM ICM688M2 WHERE A4MACPKR=A5MACPKR) AS DOLLARS
FROM ICM700M A LEFT JOIN ICM688M1 B ON A4MACPKR=A3MACPKR
WHERE A3MSMTDATE= (SELECT MAX(A3MSMTDATE) FROM ICM700M) AND A3CO='$COMPANY' AND A3WHS='$WHS' AND A3PLT='$PLANT'
)
SELECT A4SHIPTYPE,STATUS,SOURCE,COUNT(*) AS PICKERS, SUM(A4TPCKWGHT) AS WEIGHT,SUM(A4NOPICLNS) AS LINES,SUM(DOLLARS) AS DOLLARS
FROM TEMPFILE
GROUP BY A4SHIPTYPE,STATUS,SOURCE
ORDER BY 1,3,2
");
$newItem = ['A4SHIPTYPE' => 'Method', 'STATUS' => 'Status', 'SOURCE' => 'Source', 'PICKERS' => 'Pickers',
'WEIGHT' => 'Weight', 'LINES' => 'Lines', 'DOLLARS' => 'Dollars'];
// Trim All values
$ICM700MHeadCol = collect($ICM700MHeadSel)->map(function ($item) {
foreach ($item as $key => $value) {
if (is_string($value)) {
$item->{$key} = trim($value);
}
}
return $item;
});
// Prepend Header to Collection
$ICM700MHeadCol->prepend($newItem);
// Log::channel('dailyCron')->info(">>> Header Content");
// Log::channel('dailyCron')->info($ICM700MHeadCol);
// Count records before exporting to excel
$ICM700MHeadCount = $ICM700MHeadCol->count();
// Get Details Content
$ICM700MDetailsSel = DB::connection(config('m3.connection', 'pgsql'))
->select("
WITH TEMPFILE AS (
SELECT A3CO,A3WHS,A3PLT,A3MACPKR,A4PICKCRTS,SOURCE,
(SELECT TO_TIMESTAMP(CAST(SHDT AS TEXT) || ' ' || CAST(SHTIME AS TEXT), 'YYYY-MM-DD HH24:MI:SS') FROM ICM699M WHERE SHMACPKR=A4MACPKR AND SHTYPE='Lisnr-Hold' ORDER BY SHDT DESC, SHTIME DESC FETCH FIRST 1 ROWS ONLY) AS CARRIERASSIGNED,
A4ONO,A4SHSHNM,A4SCAC,A42SSVCNAM,A4PICKSTS,
CASE WHEN UPPER(A4PICKSTS)<>'A' THEN 'Open' ELSE 'Closed' END AS STATUS,
CASE WHEN A4TPCKWGHT>16000 THEN 'FTL' ELSE A4SHIPTYPE END AS A4SHIPTYPE,
A4TPCKWGHT,A4NOPICLNS,
(SELECT SUM(A5RSVQTY*A5SLUNPR) FROM ICM688M2 WHERE A4MACPKR=A5MACPKR) AS DOLLARS
FROM ICM700M A
LEFT JOIN ICM688M1 B ON A4MACPKR=A3MACPKR
WHERE A3MSMTDATE=(SELECT MAX(A3MSMTDATE) FROM ICM700M) AND A3CO='$COMPANY' AND A3WHS='$WHS' AND A3PLT='$PLANT'
)
SELECT * FROM TEMPFILE
");
$newItem2 = ['A3CO' => 'Co', 'A3WHS' => 'Whs', 'A3PLT' => 'Plt', 'A3MACPKR' => 'Delivery No', 'A4PICKCRTS' => 'Date Time Arrived in Sentinel',
'SOURCE' => 'Source', 'CARRIERASSIGNED' => 'Date carrier Assigned', 'A4ONO' => 'Order No', 'A4SHSHNM' => 'Customer name', 'A4SCAC' => 'Carrier',
'A42SSVCNAM' => 'Service', 'A4PICKSTS' => 'Picker Status', 'STATUS' => 'Open or Closed', 'A4SHIPTYPE' => 'Method',
'A4TPCKWGHT' => 'Weight', 'A4NOPICLNS' => 'Lines', 'DOLLARS' => 'Dollars'];
// Trim all values
$ICM700MDetailsCol = collect($ICM700MDetailsSel)->map(function ($item) {
foreach ($item as $key => $value) {
if (is_string($value)) {
$item->{$key} = trim($value);
}
}
return $item;
});
// Prepend Header
$ICM700MDetailsCol->prepend($newItem2);
// Count records before exporting to excel
$ICM700MDetailsCount = $ICM700MDetailsCol->count();
} else {
$ICM700MDetailsCol = collect();
}
// Log::channel('dailyCron')->info($ICM700MDetailsCol);
// Save Head and Details to XLS file
if ($ICM700MHeadCount > 0 && $ICM700MDetailsCount > 0) {
$this->info('Saving Today WHS Performance Report to Disk...');
Log::channel('dailyCron')->info('Saving Today WHS Performance Report to Disk...');
// Store both collections in one XLSX workbook using Core's PhpSpreadsheet dependency.
app(SpreadsheetExport::class)->storeSheets([
'Summary' => $ICM700MHeadCol,
'Details' => $ICM700MDetailsCol,
], $whsPerfFile, 'publicLabels');
} else {
Log::channel('dailyCron')->info('Today WHS Performance Report, no records found: Nothing to save...');
}
Log::channel('dailyCron')->info('Cron...End Save Today WHS Performance Report to Excel');
$this->info('Cron...End Save Today WHS Performance Report to Excel');
} catch (\Throwable $th) {
Log::channel('dailyCron')->error($th);
}
}
private function reportCollections(string $company, string $warehouse, string $plant): array
{
$summary = collect($this->summaryRows($company, $warehouse, $plant))->map(fn ($item) => $this->trimRow($item));
$summary->prepend([
'A4SHIPTYPE' => 'Method', 'STATUS' => 'Status', 'SOURCE' => 'Source', 'PICKERS' => 'Pickers',
'WEIGHT' => 'Weight', 'LINES' => 'Lines', 'DOLLARS' => 'Dollars',
]);
$details = collect($this->detailRows($company, $warehouse, $plant))->map(fn ($item) => $this->trimRow($item));
$details->prepend([
'A3CO' => 'Co', 'A3WHS' => 'Whs', 'A3PLT' => 'Plt', 'A3MACPKR' => 'Delivery No', 'A4PICKCRTS' => 'Date Time Arrived in Sentinel',
'SOURCE' => 'Source', 'CARRIERASSIGNED' => 'Date carrier Assigned', 'A4ONO' => 'Order No', 'A4SHSHNM' => 'Customer name',
'A4SCAC' => 'Carrier', 'A42SSVCNAM' => 'Service', 'A4PICKSTS' => 'Picker Status', 'STATUS' => 'Open or Closed',
'A4SHIPTYPE' => 'Method', 'A4TPCKWGHT' => 'Weight', 'A4NOPICLNS' => 'Lines', 'DOLLARS' => 'Dollars',
]);
return [$summary, $details];
}
private function trimRow(object $item): object
{
foreach ($item as $key => $value) {
if (is_string($value)) {
$item->{$key} = trim($value);
}
}
return $item;
}
private function summaryRows(string $company, string $warehouse, string $plant): array
{
return DB::connection(config('m3.connection', 'pgsql'))->select(<<<SQL
WITH TEMPFILE AS (
SELECT A.*,A4TPCKWGHT,A4NOPICLNS,A4PICKSTS,
CASE WHEN UPPER(A4PICKSTS)<>'A' THEN 'Open' ELSE 'Closed' END AS STATUS,
CASE WHEN A4TPCKWGHT>16000 THEN 'FTL' ELSE A4SHIPTYPE END AS A4SHIPTYPE,
(SELECT SUM(A5RSVQTY*A5SLUNPR) FROM ICM688M2 WHERE A4MACPKR=A5MACPKR) AS DOLLARS
FROM ICM700M A LEFT JOIN ICM688M1 B ON A4MACPKR=A3MACPKR
WHERE A3MSMTDATE=(SELECT MAX(A3MSMTDATE) FROM ICM700M) AND A3CO=? AND A3WHS=? AND A3PLT=?
)
SELECT A4SHIPTYPE,STATUS,SOURCE,COUNT(*) AS PICKERS,SUM(A4TPCKWGHT) AS WEIGHT,SUM(A4NOPICLNS) AS LINES,SUM(DOLLARS) AS DOLLARS
FROM TEMPFILE GROUP BY A4SHIPTYPE,STATUS,SOURCE ORDER BY 1,3,2
SQL, [$company, $warehouse, $plant]);
}
private function detailRows(string $company, string $warehouse, string $plant): array
{
return DB::connection(config('m3.connection', 'pgsql'))->select(<<<SQL
WITH TEMPFILE AS (
SELECT A3CO,A3WHS,A3PLT,A3MACPKR,A4PICKCRTS,SOURCE,
(SELECT TO_TIMESTAMP(CAST(SHDT AS TEXT) || ' ' || CAST(SHTIME AS TEXT), 'YYYY-MM-DD HH24:MI:SS') FROM ICM699M WHERE SHMACPKR=A4MACPKR AND SHTYPE='Lisnr-Hold' ORDER BY SHDT DESC,SHTIME DESC FETCH FIRST 1 ROWS ONLY) AS CARRIERASSIGNED,
A4ONO,A4SHSHNM,A4SCAC,A42SSVCNAM,A4PICKSTS,
CASE WHEN UPPER(A4PICKSTS)<>'A' THEN 'Open' ELSE 'Closed' END AS STATUS,
CASE WHEN A4TPCKWGHT>16000 THEN 'FTL' ELSE A4SHIPTYPE END AS A4SHIPTYPE,
A4TPCKWGHT,A4NOPICLNS,(SELECT SUM(A5RSVQTY*A5SLUNPR) FROM ICM688M2 WHERE A4MACPKR=A5MACPKR) AS DOLLARS
FROM ICM700M A LEFT JOIN ICM688M1 B ON A4MACPKR=A3MACPKR
WHERE A3MSMTDATE=(SELECT MAX(A3MSMTDATE) FROM ICM700M) AND A3CO=? AND A3WHS=? AND A3PLT=?
) SELECT * FROM TEMPFILE
SQL, [$company, $warehouse, $plant]);
}
private function storeReport($summary, $details, string $file): void
{
if ($summary->isEmpty() || $details->isEmpty()) {
Log::channel('dailyCron')->info('Today WHS Performance Report, no records found: Nothing to save...');
return;
}
$this->info('Saving Today WHS Performance Report to Disk...');
Log::channel('dailyCron')->info('Saving Today WHS Performance Report to Disk...');
app(SpreadsheetExport::class)->storeSheets(['Summary' => $summary, 'Details' => $details], $file, 'publicLabels');
}
}
@@ -0,0 +1,30 @@
<?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');
}
};
View File
+27
View File
@@ -0,0 +1,27 @@
<?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',
];
}
}
+36
View File
@@ -0,0 +1,36 @@
<?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 '';
}
}
@@ -0,0 +1,14 @@
<?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
@@ -0,0 +1,65 @@
<?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',
];
}
}
@@ -0,0 +1,150 @@
<?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]);
}
}
@@ -0,0 +1,119 @@
<?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];
}
}
@@ -69,153 +69,116 @@ class BoxPackToPalletController extends Controller
// Scan Boxes
public static function scanBoxes(Request $request)
{
$R659PALT = $request->R659PALT ?? abort(400, 'Pallet Not Found');
$R659BOX = trim($request->R659BOX) ?? abort(400, 'Box Not Found');
$SHUSER = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
$userWhsCoPlant = self::getUserWhsCoPlant();
$pallet = $request->R659PALT ?? abort(400, 'Pallet Not Found');
$box = trim((string) ($request->R659BOX ?? ''));
abort_if($box === '', 400, 'Box Not Found');
$boxMessage = '';
$user = m3_user() !== '' ? Str::upper(m3_user()) : 'WebUser';
$profile = self::getUserWhsCoPlant();
$validation = self::validateScannedBox($pallet, $box, $profile);
// Step 1: Check for duplicate — same pallet + box combo
$exists = DB::connection(config('m3.connection', 'pgsql'))
->table('icm659m')
->select('R659PALT')
->where('R659PALT', $R659PALT)
->where('R659BOX', $R659BOX)
->where('R659CO', trim($userWhsCoPlant['USERCO']))
->where('R659WHS', trim($userWhsCoPlant['USERWHS']))
->where('R659PLANT', trim($userWhsCoPlant['USERPL']))
->first();
if ($exists) {
$boxMessage = "&bull; Box {$R659BOX} is already assigned to Pallet {$exists->R659PALT}.";
if ($validation !== '') {
return response()->json(['success' => false, 'message' => $validation], 409);
}
// Step 2: Check if Box exists in ICM695M1 (with carrier + conveyor joined)
$ICM695M1Sel = DB::connection(config('m3.connection', 'pgsql'))
->table(self::CARTON_TABLE_ALIAS)
->select(
'c.AYINTBOX',
'c.AYSPR15A01',
'c.AYTYPE',
'c.AYMACPKR',
'cv.A4APR8N001',
self::CONVEYOR_SELECT,
)
->leftJoin(self::CONVEYOR_VALUE_ALIAS, 'c.AYMACPKR', '=', 'cv.A4MACPKR')
->leftJoin(self::CONVEYOR_TABLE_ALIAS, 'cv.A4APR8N001', '=', 'cnv.R652SEQ')
->where('c.AYINTBOX', $R659BOX)
->where('c.AYCO', trim($userWhsCoPlant['USERCO']))
->where('c.AYWHS', trim($userWhsCoPlant['USERWHS']))
->where('c.AYPLANT', trim($userWhsCoPlant['USERPL']))
->first();
$boxExistInICM695M = isset($ICM695M1Sel->AYINTBOX);
$boxisPalletICM695M = isset($ICM695M1Sel->AYTYPE) && $ICM695M1Sel->AYTYPE != 'BX';
if (! $boxExistInICM695M) {
$br = $boxMessage == '' ? '' : '<br>';
$boxMessage .= $br . "&bull; Box {$R659BOX} does not exist in ICM695M1 or it belongs to another Company.";
}
if ($boxExistInICM695M && $boxisPalletICM695M) {
$br = $boxMessage == '' ? '' : '<br>';
$boxMessage .= $br . "&bull; Scanned barcode {$R659BOX} is not a Box.";
}
// Step 3: Check that all boxes on the pallet share the same Carrier and Conveyor
if ($boxExistInICM695M && ! $boxisPalletICM695M && ! $exists) {
$firstPalletBox = DB::connection(config('m3.connection', 'pgsql'))
->table(self::PALLET_TABLE_ALIAS)
->select(
'c.AYSPR15A01',
self::CONVEYOR_SELECT,
)
->leftJoin(self::CARTON_TABLE_ALIAS, 'p.R659BOX', '=', 'c.AYINTBOX')
->leftJoin(self::CONVEYOR_VALUE_ALIAS, 'c.AYMACPKR', '=', 'cv.A4MACPKR')
->leftJoin(self::CONVEYOR_TABLE_ALIAS, 'cv.A4APR8N001', '=', 'cnv.R652SEQ')
->where('p.R659PALT', $R659PALT)
->where('p.R659CO', trim($userWhsCoPlant['USERCO']))
->where('p.R659WHS', trim($userWhsCoPlant['USERWHS']))
->where('p.R659PLANT', trim($userWhsCoPlant['USERPL']))
->first();
if ($firstPalletBox) {
$incomingCarrier = trim($ICM695M1Sel->AYSPR15A01 ?? '');
$incomingConveyor = trim($ICM695M1Sel->CONVEYOR_NAME ?? '');
$palletCarrier = trim($firstPalletBox->AYSPR15A01 ?? '');
$palletConveyor = trim($firstPalletBox->CONVEYOR_NAME ?? '');
if ($incomingCarrier !== $palletCarrier) {
$br = $boxMessage == '' ? '' : '<br>';
$boxMessage .= $br . "&bull; Box {$R659BOX} has a different Carrier ({$incomingCarrier}) than the boxes already on Pallet {$R659PALT} ({$palletCarrier}).";
}
if ($incomingConveyor !== $palletConveyor) {
$br = $boxMessage == '' ? '' : '<br>';
$boxMessage .= $br . "&bull; Box {$R659BOX} has a different Conveyor ({$incomingConveyor}) than the boxes already on Pallet {$R659PALT} ({$palletConveyor}).";
}
}
}
if ($exists || ! $boxExistInICM695M || $boxisPalletICM695M || $boxMessage !== '') {
return response()->json([
'success' => false,
'message' => $boxMessage,
], 409);
}
// Step 4: Insert new box record
DB::connection(config('m3.connection', 'pgsql'))
->table('icm659m')
->insert([
'R659PALT' => $R659PALT,
'R659BOX' => $R659BOX,
'R659LOADED' => '',
'R659USER' => $SHUSER,
'R659DATE' => date('Y-m-d'),
'R659TIME' => date('H:i:s'),
'R659CO' => trim($userWhsCoPlant['USERCO']),
'R659WHS' => trim($userWhsCoPlant['USERWHS']),
'R659PLANT' => trim($userWhsCoPlant['USERPL']),
]);
// Step 5: Return the full refreshed box list
$boxes = DB::connection(config('m3.connection', 'pgsql'))->table(self::PALLET_TABLE_ALIAS)
->select(
'p.R659PALT',
'p.R659BOX',
'p.R659LOADED',
'p.R659USER',
'p.R659DATE',
'p.R659TIME',
'c.AYMACPKR',
'c.AYSPR15A01',
'cv.A4APR8N001',
'cv.A4SHSHCT',
self::CONVEYOR_SELECT,
)
->leftJoin(self::CARTON_TABLE_ALIAS, 'p.R659BOX', '=', 'c.AYINTBOX')
->leftJoin(self::CONVEYOR_VALUE_ALIAS, 'c.AYMACPKR', '=', 'cv.A4MACPKR')
->leftJoin(self::CONVEYOR_TABLE_ALIAS, 'cv.A4APR8N001', '=', 'cnv.R652SEQ')
->where('p.R659PALT', $R659PALT)
->where('p.R659CO', trim($userWhsCoPlant['USERCO']))
->where('p.R659WHS', trim($userWhsCoPlant['USERWHS']))
->where('p.R659PLANT', trim($userWhsCoPlant['USERPL']))
->orderBy('p.R659DATE', 'desc')
->orderBy('p.R659TIME', 'desc')
->distinct()
->get()
->unique('R659BOX')
->values();
self::insertScannedBox($pallet, $box, $user, $profile);
return response()->json([
'success' => true,
'message' => "&bull; Box {$R659BOX} added to Pallet {$R659PALT}.",
'data' => $boxes,
'message' => "&bull; Box {$box} added to Pallet {$pallet}.",
'data' => self::boxesForPallet($pallet, $profile),
]);
}
private static function validateScannedBox($pallet, string $box, array $profile): string
{
$messages = [];
$existing = self::findExistingBox($pallet, $box, $profile);
if ($existing) {
$messages[] = "&bull; Box {$box} is already assigned to Pallet {$existing->R659PALT}.";
}
$boxRecord = self::findCarton($box, $profile);
if (! isset($boxRecord->AYINTBOX)) {
$messages[] = "&bull; Box {$box} does not exist in ICM695M1 or it belongs to another Company.";
} elseif (($boxRecord->AYTYPE ?? '') !== 'BX') {
$messages[] = "&bull; Scanned barcode {$box} is not a Box.";
} elseif (! $existing) {
$messages = array_merge($messages, self::palletCompatibilityMessages($pallet, $box, $boxRecord, $profile));
}
return implode('<br>', $messages);
}
private static function findExistingBox($pallet, string $box, array $profile): ?object
{
return DB::connection(config('m3.connection', 'pgsql'))->table('icm659m')
->select('R659PALT')->where('R659PALT', $pallet)->where('R659BOX', $box)
->where('R659CO', trim($profile['USERCO']))->where('R659WHS', trim($profile['USERWHS']))
->where('R659PLANT', trim($profile['USERPL']))->first();
}
private static function findCarton(string $box, array $profile): ?object
{
return DB::connection(config('m3.connection', 'pgsql'))->table(self::CARTON_TABLE_ALIAS)
->select('c.AYINTBOX', 'c.AYSPR15A01', 'c.AYTYPE', 'c.AYMACPKR', 'cv.A4APR8N001', self::CONVEYOR_SELECT)
->leftJoin(self::CONVEYOR_VALUE_ALIAS, 'c.AYMACPKR', '=', 'cv.A4MACPKR')
->leftJoin(self::CONVEYOR_TABLE_ALIAS, 'cv.A4APR8N001', '=', 'cnv.R652SEQ')
->where('c.AYINTBOX', $box)->where('c.AYCO', trim($profile['USERCO']))
->where('c.AYWHS', trim($profile['USERWHS']))->where('c.AYPLANT', trim($profile['USERPL']))->first();
}
private static function palletCompatibilityMessages($pallet, string $box, object $incoming, array $profile): array
{
$first = DB::connection(config('m3.connection', 'pgsql'))->table(self::PALLET_TABLE_ALIAS)
->select('c.AYSPR15A01', self::CONVEYOR_SELECT)
->leftJoin(self::CARTON_TABLE_ALIAS, 'p.R659BOX', '=', 'c.AYINTBOX')
->leftJoin(self::CONVEYOR_VALUE_ALIAS, 'c.AYMACPKR', '=', 'cv.A4MACPKR')
->leftJoin(self::CONVEYOR_TABLE_ALIAS, 'cv.A4APR8N001', '=', 'cnv.R652SEQ')
->where('p.R659PALT', $pallet)->where('p.R659CO', trim($profile['USERCO']))
->where('p.R659WHS', trim($profile['USERWHS']))->where('p.R659PLANT', trim($profile['USERPL']))->first();
if (! $first) {
return [];
}
$messages = [];
$incomingCarrier = trim($incoming->AYSPR15A01 ?? '');
$incomingConveyor = trim($incoming->CONVEYOR_NAME ?? '');
$palletCarrier = trim($first->AYSPR15A01 ?? '');
$palletConveyor = trim($first->CONVEYOR_NAME ?? '');
if ($incomingCarrier !== $palletCarrier) {
$messages[] = "&bull; Box {$box} has a different Carrier ({$incomingCarrier}) than the boxes already on Pallet {$pallet} ({$palletCarrier}).";
}
if ($incomingConveyor !== $palletConveyor) {
$messages[] = "&bull; Box {$box} has a different Conveyor ({$incomingConveyor}) than the boxes already on Pallet {$pallet} ({$palletConveyor}).";
}
return $messages;
}
private static function insertScannedBox($pallet, string $box, string $user, array $profile): void
{
DB::connection(config('m3.connection', 'pgsql'))->table('icm659m')->insert([
'R659PALT' => $pallet, 'R659BOX' => $box, 'R659LOADED' => '', 'R659USER' => $user,
'R659DATE' => date('Y-m-d'), 'R659TIME' => date('H:i:s'), 'R659CO' => trim($profile['USERCO']),
'R659WHS' => trim($profile['USERWHS']), 'R659PLANT' => trim($profile['USERPL']),
]);
}
private static function boxesForPallet($pallet, array $profile)
{
return DB::connection(config('m3.connection', 'pgsql'))->table(self::PALLET_TABLE_ALIAS)
->select('p.R659PALT', 'p.R659BOX', 'p.R659LOADED', 'p.R659USER', 'p.R659DATE', 'p.R659TIME',
'c.AYMACPKR', 'c.AYSPR15A01', 'cv.A4APR8N001', 'cv.A4SHSHCT', self::CONVEYOR_SELECT)
->leftJoin(self::CARTON_TABLE_ALIAS, 'p.R659BOX', '=', 'c.AYINTBOX')
->leftJoin(self::CONVEYOR_VALUE_ALIAS, 'c.AYMACPKR', '=', 'cv.A4MACPKR')
->leftJoin(self::CONVEYOR_TABLE_ALIAS, 'cv.A4APR8N001', '=', 'cnv.R652SEQ')
->where('p.R659PALT', $pallet)->where('p.R659CO', trim($profile['USERCO']))
->where('p.R659WHS', trim($profile['USERWHS']))->where('p.R659PLANT', trim($profile['USERPL']))
->orderBy('p.R659DATE', 'desc')->orderBy('p.R659TIME', 'desc')->distinct()->get()->unique('R659BOX')->values();
}
// Delete Box
public static function deleteBox(Request $request)
{
@@ -0,0 +1,13 @@
<?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;
}
@@ -0,0 +1,112 @@
<?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]);
}
}
@@ -0,0 +1,91 @@
<?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)
{
//
}
}
@@ -0,0 +1,70 @@
<?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';
}
}
@@ -256,52 +256,11 @@ class M3ErrorsDispController extends Controller
// Get Records Count only
$ICM699MC = DB::connection(config('m3.connection', 'pgsql'))->table('icm699m');
if ($R428US != '') {
$ICM699M->whereIn('SHCO', [$USERCO, '']);
$ICM699M->whereIn('SHWHS', [$USERWH, '']);
$ICM699MC->whereIn('SHCO', [$USERCO, '']);
$ICM699MC->whereIn('SHWHS', [$USERWH, '']);
} else {
$ICM699M->where('SHCO', null);
$ICM699M->where('SHWHS', null);
$ICM699MC->where('SHCO', null);
$ICM699MC->where('SHWHS', null);
}
if ($SHMACPKR != '') {
$ICM699M->where('SHMACPKR', $SHMACPKR);
$ICM699MC->where('SHMACPKR', $SHMACPKR);
}
if ($SHSOURCE != '') {
$ICM699M->where('SHSOURCE', $SHSOURCE);
$ICM699MC->where('SHSOURCE', $SHSOURCE);
}
// Disable PDFStorage Search
$ICM699M->where('SHSOURCE', '!=', 'PdfStorageAPI');
$ICM699MC->where('SHSOURCE', '!=', 'PdfStorageAPI');
if ($SHMACPKR == '' && $SKIPDATES == 'N') {
$ICM699M->whereBetween('SHDT', [$STARTDATE, $ENDDATE]);
$ICM699MC->whereBetween('SHDT', [$STARTDATE, $ENDDATE]);
}
if ($SHOWERRORS == 'Y') {
$ICM699M->where('SHERROR', 'X');
$ICM699MC->where('SHERROR', 'X');
}
// Get only M3 Logs
$ICM699M->where('SHTYPE', 'like', '%M3%');
$ICM699MC->where('SHTYPE', 'like', '%M3%');
self::applyExportFilters($ICM699M, $ICM699MC, [
'profileUser' => $R428US, 'company' => $USERCO, 'warehouse' => $USERWH,
'manifest' => $SHMACPKR, 'source' => $SHSOURCE, 'startDate' => $STARTDATE,
'endDate' => $ENDDATE, 'skipDates' => $SKIPDATES, 'showErrors' => $SHOWERRORS,
]);
// Count records before exporting to excel : Max 20K records are allowed
$ICM699MCount = $ICM699MC->count();
@@ -357,4 +316,31 @@ class M3ErrorsDispController extends Controller
Log::error($th);
}
}
private static function applyExportFilters($query, $countQuery, array $filters): void
{
$queries = [$query, $countQuery];
foreach ($queries as $builder) {
if ($filters['profileUser'] !== '') {
$builder->whereIn('SHCO', [$filters['company'], ''])->whereIn('SHWHS', [$filters['warehouse'], '']);
} else {
$builder->whereNull('SHCO')->whereNull('SHWHS');
}
if ($filters['manifest'] !== '') {
$builder->where('SHMACPKR', $filters['manifest']);
}
if ($filters['source'] !== '') {
$builder->where('SHSOURCE', $filters['source']);
}
$builder->where('SHSOURCE', '!=', 'PdfStorageAPI');
if ($filters['manifest'] === '' && $filters['skipDates'] === 'N') {
$builder->whereBetween('SHDT', [$filters['startDate'], $filters['endDate']]);
}
if ($filters['showErrors'] === 'Y') {
$builder->where('SHERROR', 'X');
}
$builder->where('SHTYPE', 'like', '%M3%');
}
}
}
@@ -22,20 +22,7 @@ class OrderLinesOfClosedOrder extends Controller
$REPORTDATEDisp = today()->format('Ymd');
$allReportsUrls = [];
try {
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
if ($SHUSER != '') {
// Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US', '=', $SHUSER)
->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; // User
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : '110'; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : '144'; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : '322'; // WareHouse
}
[$COMPANY, $PLANT, $WHS] = self::userWarehouseContext('110', '144', '322');
// Warehouse Table
$IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
@@ -84,18 +71,7 @@ class OrderLinesOfClosedOrder extends Controller
}
// Get List of Files
$allReportsUrls = [];
if ($WHS == '321') {
$files = Storage::disk('publicCL')->files();
} else {
$files = Storage::disk('publicCL')->allFiles($WHS);
}
foreach ($files as $file) {
// Get the file URL (if URL is configured in filesystems.php)
$url = Storage::disk('publicCL')->url($file);
$allReportsUrls[$file] = $url;
}
$allReportsUrls = self::reportUrls($WHS);
} catch (\Throwable $th) {
Log::error($th);
@@ -112,20 +88,7 @@ class OrderLinesOfClosedOrder extends Controller
ini_set('memory_limit', '1024M');
try {
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
if ($SHUSER != '') {
// Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US', '=', $SHUSER)
->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; // User
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; // WareHouse
}
[$COMPANY, $PLANT, $WHS] = self::userWarehouseContext();
// Warehouse Table
$IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
@@ -209,20 +172,7 @@ class OrderLinesOfClosedOrder extends Controller
ini_set('memory_limit', '1024M');
try {
$SHUSER = m3_user() !== '' ? Str::upper(trim(m3_user())) : '';
if ($SHUSER != '') {
// Get User CO & WH from Table ICM428M
$ICM428M = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428US', 'R428CO', 'R428WH', 'R428PL')
->where('R428US', '=', $SHUSER)
->first();
$R428US = isset($ICM428M->R428US) ? $ICM428M->R428US : ''; // User
$COMPANY = isset($ICM428M->R428CO) ? $ICM428M->R428CO : ''; // Company
$PLANT = isset($ICM428M->R428PL) ? $ICM428M->R428PL : ''; // Plant
$WHS = isset($ICM428M->R428WH) ? $ICM428M->R428WH : ''; // WareHouse
}
[$COMPANY, $PLANT, $WHS] = self::userWarehouseContext();
// Warehouse Table
$IC670M = DB::connection(config('m3.connection', 'pgsql'))->table('ic670m')->get();
@@ -288,11 +238,7 @@ class OrderLinesOfClosedOrder extends Controller
$ICM688M2Col = '';
}
if ($WHS == '321') {
$prevMonthFile = 'Closedorderlinesreport_' . $reportDateWD . '-' . $toreportDateWD . self::XLSX_EXTENSION;
} else {
$prevMonthFile = $WHS . '/Closedorderlinesreport_' . $reportDateWD . '-' . $toreportDateWD . '-' . $WHS . self::XLSX_EXTENSION;
}
$prevMonthFile = self::storedReportName($WHS, $reportDateWD, $toreportDateWD);
// MAK Store the File to Storage
app(SpreadsheetExport::class)->store($ICM688M2Col, $prevMonthFile, 'publicCL');
@@ -305,6 +251,47 @@ class OrderLinesOfClosedOrder extends Controller
}
}
private static function userWarehouseContext(string $defaultCompany = '', string $defaultPlant = '', string $defaultWarehouse = ''): array
{
$user = trim((string) m3_user());
if ($user === '') {
return [$defaultCompany, $defaultPlant, $defaultWarehouse];
}
$profile = DB::connection(config('m3.connection', 'pgsql'))->table('icm428m')
->select('R428CO', 'R428WH', 'R428PL')
->where('R428US', Str::upper($user))
->first();
return [
$profile->R428CO ?? $defaultCompany,
$profile->R428PL ?? $defaultPlant,
$profile->R428WH ?? $defaultWarehouse,
];
}
private static function reportUrls(string $warehouse): array
{
$disk = Storage::disk('publicCL');
$files = $warehouse === '321' ? $disk->files() : $disk->allFiles($warehouse);
$urls = [];
foreach ($files as $file) {
$urls[$file] = $disk->url($file);
}
return $urls;
}
private static function storedReportName(string $warehouse, string $from, string $to): string
{
$name = 'Closedorderlinesreport_' . $from . '-' . $to;
return $warehouse === '321'
? $name . self::XLSX_EXTENSION
: $warehouse . '/' . $name . '-' . $warehouse . self::XLSX_EXTENSION;
}
// Download File
public static function downloadFiles(Request $request)
{
@@ -0,0 +1,107 @@
<?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;
}
}
@@ -0,0 +1,13 @@
<?php
namespace Modules\M3\Http\Controllers;
class authController extends Controller
{
public static function logout()
{
return view('m3::liberty-theme.pages.logout');
}
}
@@ -0,0 +1,12 @@
<?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')
}
}
@@ -0,0 +1,226 @@
<?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);
}
}
}
@@ -0,0 +1,65 @@
<?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']);
}
}
}
@@ -0,0 +1,140 @@
<?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);
}
}
}
View File
@@ -0,0 +1,23 @@
<?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
@@ -0,0 +1,57 @@
<?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"');
}
}
@@ -0,0 +1,17 @@
<?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 = [
//
];
}
@@ -0,0 +1,17 @@
<?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 = [
//
];
}
@@ -0,0 +1,33 @@
<?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);
}
}
@@ -0,0 +1,19 @@
<?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
@@ -0,0 +1,20 @@
<?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(),
];
}
}
@@ -0,0 +1,23 @@
<?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;
}
@@ -0,0 +1,17 @@
<?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
@@ -0,0 +1,29 @@
<?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
@@ -0,0 +1,28 @@
<?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',
];
}
+42
View File
@@ -0,0 +1,42 @@
<?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
@@ -0,0 +1,42 @@
<?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');
@@ -0,0 +1,99 @@
<?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
@@ -0,0 +1,80 @@
<?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);
}
}
+98 -3
View File
@@ -1,6 +1,101 @@
#!/bin/bash
set -euo pipefail
SONAR_URL="http://192.168.1.2:9001"
PROJECT="Warehouse-Management-System"
OUTPUT="sonarqube-issues.csv"
TMP=$(mktemp)
trap 'rm -f "$TMP" "$TMP.new"' EXIT
if [ -z "${SONAR_TOKEN:-}" ]; then
echo "ERROR: SONAR_TOKEN is not set"
exit 1
fi
# Delete previous report FIRST
echo "Removing previous SonarQube report..."
rm -f "$OUTPUT"
echo
echo "Running SonarQube scan..."
JAVA_HOME="/opt/homebrew/opt/openjdk" \
PATH="/opt/homebrew/opt/openjdk/bin:$PATH" \
sonar-scanner \
-Dsonar.projectKey=Warehouse-Management-System \
-Dsonar.sources=. \
-Dsonar.host.url=http://192.168.1.2:9001
-Dsonar.projectKey="$PROJECT" \
-Dsonar.sources=. \
-Dsonar.host.url="$SONAR_URL" \
-Dsonar.token="$SONAR_TOKEN"
echo
echo "Downloading SonarQube issues..."
echo '[]' > "$TMP"
PAGE=1
PAGE_SIZE=500
while true; do
echo "Fetching page $PAGE..."
RESPONSE=$(curl \
--connect-timeout 5 \
--max-time 60 \
-sS \
-u "$SONAR_TOKEN:" \
"$SONAR_URL/api/issues/search?componentKeys=$PROJECT&ps=$PAGE_SIZE&p=$PAGE")
COUNT=$(echo "$RESPONSE" | jq '.issues | length')
TOTAL=$(echo "$RESPONSE" | jq '.total')
echo " $COUNT issues received ($TOTAL total)"
jq -s '.[0] + .[1].issues' \
"$TMP" \
<(printf '%s' "$RESPONSE") > "$TMP.new"
mv "$TMP.new" "$TMP"
[ "$COUNT" -lt "$PAGE_SIZE" ] && break
PAGE=$((PAGE + 1))
done
jq -r --arg project "$PROJECT" '
[
"Severity",
"Type",
"Status",
"Rule",
"File",
"Line",
"Message",
"Effort",
"Assignee",
"Author",
"Created",
"Updated"
],
(.[] | [
.severity,
.type,
.status,
.rule,
(.component | sub("^" + $project + ":";"")),
(.line // ""),
.message,
(.effort // ""),
(.assignee // ""),
(.author // ""),
.creationDate,
.updateDate
]) | @csv
' "$TMP" > "$OUTPUT"
ISSUE_COUNT=$(($(wc -l < "$OUTPUT") - 1))
echo
echo "Complete."
echo "Report: $OUTPUT"
echo "Issues exported: $ISSUE_COUNT"
-77
View File
@@ -1,77 +0,0 @@
#!/bin/bash
set -euo pipefail
SONAR_URL="http://192.168.1.2:9001"
PROJECT="Warehouse-Management-System"
OUTPUT="sonarqube-issues.csv"
TMP=$(mktemp)
if [ -z "${SONAR_TOKEN:-}" ]; then
echo "SONAR_TOKEN is not set"
exit 1
fi
echo "Downloading SonarQube issues for $PROJECT..."
echo '[]' > "$TMP"
PAGE=1
PAGE_SIZE=500
while true; do
echo "Fetching page $PAGE..."
RESPONSE=$(curl --connect-timeout 5 --max-time 60 -sS \
-u "$SONAR_TOKEN:" \
"$SONAR_URL/api/issues/search?componentKeys=$PROJECT&ps=$PAGE_SIZE&p=$PAGE")
COUNT=$(echo "$RESPONSE" | jq '.issues | length')
TOTAL=$(echo "$RESPONSE" | jq '.total')
echo " $COUNT issues received ($TOTAL total)"
jq -s '.[0] + .[1].issues' "$TMP" <(echo "$RESPONSE") > "$TMP.new"
mv "$TMP.new" "$TMP"
[ "$COUNT" -lt "$PAGE_SIZE" ] && break
PAGE=$((PAGE + 1))
done
jq -r '
[
"Severity",
"Type",
"Status",
"Rule",
"File",
"Line",
"Message",
"Effort",
"Assignee",
"Author",
"Created",
"Updated"
],
(.[] | [
.severity,
.type,
.status,
.rule,
(.component | sub("^Warehouse-Management-System:";"")),
(.line // ""),
.message,
(.effort // ""),
(.assignee // ""),
(.author // ""),
.creationDate,
.updateDate
]) | @csv
' "$TMP" > "$OUTPUT"
rm "$TMP"
echo
echo "Complete."
echo "Report: $OUTPUT"
echo "Issues exported: $(($(wc -l < "$OUTPUT") - 1))"