Commit a8365c22 authored by Sarun Mungthanya's avatar Sarun Mungthanya
Browse files

issue gen masterfile , solve with encoding file TIS-620

parent a485da71
<?php
namespace App\Http\Controllers;
use App\Models\ConfFormatFile;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class MasterFileController extends Controller
{
public function index()
{
$menu = 'MasterFile';
$currentContent = 'MasterFile';
return view('home', compact('menu', 'currentContent'));
}
public function createPatch(Request $request)
{
// $request->validate([
// 'format_file_id' => 'required|exists:conf_format_file,formatservice_ID',
// 'file' => 'required|file|max:12209752',
// 'limit' => 'nullable|integer',
// 'noLimit' => 'nullable|boolean',
// 'genWithSmartUpdate' => 'nullable|boolean',
// 'createPatch' => 'nullable|boolean',
// 'sendToEec' => 'nullable|boolean',
// ]);
$file = $request->file('file');
$filePath = $file->getRealPath();
if(isset($request->truncateGoods) && ($request->format_file_id == 196)) {
$truncateGoods = true ;
}else{
$truncateGoods = false ;
}
$fileFormat = ConfFormatFile::where('formatservice_ID', $request->format_file_id)->first();
$jsonFilePath = storage_path(str_replace(".inc", ".json", $fileFormat->file));
if (!file_exists($jsonFilePath)) {
return redirect()->back()->withErrors(['error' => 'Format JSON file not found.']);
}
$formatData = json_decode(file_get_contents($jsonFilePath), true);
$message = '';
if ($request->createPatch) {
$sqlPackAll = $this->readTxt($filePath, $formatData, $fileFormat, $request->limit, $request->noLimit);
$this->processPatches($sqlPackAll, $fileFormat, $request->genWithSmartUpdate, $request->noLimit , $truncateGoods);
$message .= 'Patch master file created successfully. ';
}
if ($request->sendToEec && !empty($fileFormat->ac)) {
$timestamp = Carbon::now()->toDateString();
$response = $this->sendMasterFileToEcc(config('services.eec.url'), [
'type' => $fileFormat->ac,
'file' => fopen($filePath, 'r'),
'timestamp' => $timestamp,
]);
$responseStatus = $response->status();
$responseData = $response->json();
$this->keepTransactionToEcc(auth()->id(), $fileFormat->ac, $file->getClientOriginalName(), json_encode([
'type' => $fileFormat->ac,
'timestamp' => $timestamp,
]), Carbon::now(), $responseStatus, json_encode($responseData));
$message .= 'Send to EEC successfully.';
}
return redirect()->route('patch.index')->with('message', $message);
}
private function sendMasterFileToEcc($url, $postData)
{
return Http::attach('file', $postData['file'])
->asMultipart()
->post($url, [
'type' => $postData['type'],
'timestamp' => $postData['timestamp'],
]);
}
private function keepTransactionToEcc($uid, $type, $filename, $requestData, $datetime, $responseStatus, $responseData)
{
DB::table('log_send_master2eec')->insert([
'UID' => $uid,
'TYPE' => $type,
'FILENAME' => $filename,
'REQDATA' => $requestData,
'ACTDATETIME' => $datetime,
'RESPSTATUS' => $responseStatus,
'RESPDATA' => $responseData,
]);
}
function processPatches($sqlPackAll, $fileFormat, $genSpnSmartUpdateDecode, $noLimit , $truncateGoods)
{
$uid = auth()->user()->id;
$pLevel = "Critical";
$nameFormat = $fileFormat->name ?? 'Unknown Format';
$pDesc = $nameFormat;
$day = Date('j');
$month = Date('n');
$year = Date('Y');
$pApproveDate = date("Y-m-d h:i:s");
$partPatch = '';
$countSql = count($sqlPackAll);
$part = 1;
foreach ($sqlPackAll as $i__ => $sqlPack) {
if ($countSql != 1 && !$noLimit) {
$partPatch = 'Part ' . $part++;
}
// $utf8_encoded = mb_convert_encoding(var_export($sqlPack, true), 'UTF-8', 'auto');
// $utf8_encoded = mb_convert_encoding(var_export($sqlPack, true), 'UTF-8', 'auto');
dd($fileFormat->ac);
if($fileFormat->ac == 'discharge-port' || $fileFormat->ac == 'discharge-port') {
$tis620_encoded = var_export($sqlPack, true);
}else{
$tis620_encoded = iconv('UTF-8', 'Windows-874',var_export($sqlPack, true));
}
// $tis620_encoded = var_export($sqlPack, true);
// dd($tis620_encoded);
$patchCode = '';
if($truncateGoods) {
$patchCode .= '$sql = "truncate table master_permissiongoods";
exec_query($sql);
if ($DBTYPE == "MSSQL") {
$Count_CONSTRAINT = Query2ArrayVarPack("SELECT COUNT(TC.CONSTRAINT_NAME) AS count_CONSTRAINT,TC.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = "PRIMARY KEY"
AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
and ku.table_name="master_permissiongoods"
GROUP BY TC.CONSTRAINT_NAME");
if ($Count_CONSTRAINT["count_CONSTRAINT"][0] != 5) {
exec_query("ALTER TABLE [master_permissiongoods] DROP CONSTRAINT [" . $Count_CONSTRAINT["CONSTRAINT_NAME"][0] . "]");
exec_query("ALTER TABLE [master_permissiongoods] ADD CONSTRAINT [" . $Count_CONSTRAINT["CONSTRAINT_NAME"][0] . "] PRIMARY KEY([tariffClass],[tariffStat],[startDate],[permissionGoodsType],[companyTaxNo])");
}
};
';
}
$ALL64 = base64_encode(gzcompress($tis620_encoded));
$patchCode .= '$ALL64="' . $ALL64 . '";' . "\n";
if ($genSpnSmartUpdateDecode) {
$updatedecode = '$ALLVAR=gzuncompress(spnsmartupdatedecode($ALL64));' . "\n";
} else {
$updatedecode = '$ALLVAR=gzuncompress(base64_decode($ALL64));' . "\n";
}
$patchCode .= $updatedecode;
$patchCode .= "eval('\$SQL='." . '$ALLVAR.";");' . "\n";
$patchCode .= $this->generatePatchCode($countSql, $i__);
if ($noLimit && ($i__ == $countSql - 1)) {
$this->savePatch($patchCode, $nameFormat, $day, $month, $year, $partPatch, $pLevel, $pDesc, $uid, $pApproveDate);
} elseif (!$noLimit) {
$this->savePatch($patchCode, $nameFormat, $day, $month, $year, $partPatch, $pLevel, $pDesc, $uid, $pApproveDate);
}
}
}
private function generatePatchCode($countSql, $i__)
{
$patchCode = '';
$patchCode .= '$insert=$SQL["insert"];' . "\n";
$patchCode .= '$update=$SQL["update"];' . "\n";
$patchCode .= '$select=$SQL["select"];' . "\n";
$patchCode .= '$select2=$SQL["select2"];' . "\n";
$patchCode .= '$DATABASE=$SQL["DATABASE"];' . "\n";
$patchCode .= '$CountSQL_=count($insert);' . "\n";
$patchCode .= '$succ="0";' . "\n";
$patchCode .= '$succ2="0";' . "\n";
$patchCode .= 'for($i_=0;$i_<$CountSQL_;$i_++){' . "\n";
$patchCode .= ' $INSERT_ID="";' . "\n";
$patchCode .= ' if($DBTYPE=="MYSQL"){' . "\n";
$patchCode .= ' $sql=$insert[$i_]." ON DUPLICATE KEY UPDATE ".$update[$i_];' . "\n";
$patchCode .= ' }' . "\n";
$patchCode .= ' if($DBTYPE=="MSSQL"){' . "\n";
$patchCode .= ' $sql="IF EXISTS (".$select[$i_].") BEGIN UPDATE $DATABASE SET ".$update[$i_].$select2[$i_]." END ELSE ".$insert[$i_];' . "\n";
$patchCode .= ' }' . "\n";
$patchCode .= ' exec_query($sql);' . "\n";
$patchCode .= ' $succ++;' . "\n";
$patchCode .= ' if($INSERT_ID!=""){$succ2++;}' . "\n";
$patchCode .= '}' . "\n";
$patchCode .= 'unset($ALL64);' . "\n";
$patchCode .= 'unset($ALLVAR);' . "\n";
$patchCode .= 'unset($SQL);' . "\n";
$patchCode .= 'unset($insert);' . "\n";
$patchCode .= 'unset($update);' . "\n";
$patchCode .= 'unset($select);' . "\n";
$patchCode .= 'unset($select2);' . "\n";
$patchCode .= '$PRINT_ .= date("h:i:s")." Process ' . ($i__ + 1) . ' / ' . $countSql . ' Successful Update $succ data(s) (Added = $succ2) from $CountSQL_.</br>";' . "\n";
return $patchCode;
}
private function savePatch($patchCode, $nameformat, $day, $month, $year, $partPatch, $PLEVEL, $PDESC, $UID, $PAPPROVEDATE)
{
$patchCode .= '$PRINTOUT=$PRINT_;' . "\n";
$patchCode .= '$PATCH_STATUS="OK";' . "\n";
// $patchCode = str_replace("'", "''", $patchCode);
$data = [
'PATCHNAME' => "Update Master File $nameformat วันที่ $day เดือน $month ปี $year $partPatch",
'PDATE' => Carbon::now(),
'PLEVEL' => $PLEVEL,
'PCODE' => 'SHIPPINGNET',
'MAJOR_VERSION' => 'ALL',
'PDESC' => $PDESC,
'POWNER' => $UID,
'PTYPE' => 'UPDATE MASTER',
'PAPPROVEDATE' => $PAPPROVEDATE,
'PATCHCODE' => iconv("utf-8", "tis-620" ,$patchCode),
'UNINSTALL' => '$DONE=1;',
'PATCHCODE_SERVER' => '$DONE=1;',
];
DB::table('conf_smartupdate')->insert($data);
}
private function readTxt($filePath, $formatData, $fileFormat, $limit = 10000, $noLimit = true)
{
// header("Content-Type: text/html; charset=TIS-620");
ini_set('memory_limit', '-1');
$sqlPackAll = [];
$sqlPack = [];
$count = 0;
$fileHandle = fopen($filePath, "r");
while (!feof($fileHandle)) {
$text = fgets($fileHandle);
if($fileFormat->ac != 'discharge-port') {
try {
$text = iconv('TIS-620', 'UTF-8', $text);
} catch (\Throwable $th) {
$encoding = mb_detect_encoding($text, ['UTF-8', 'ISO-8859-1', 'ASCII'], true);
$text = iconv('Windows-874', 'UTF-8', $text);
}
}
Log::info($text);
$X = $Y = $Z = 0;
$primaryKeyConditions = [];
foreach ($formatData['primary_key'] as $keyIndex => $primaryKey) {
$fieldFormat = $formatData['format'][$keyIndex];
$type = $fieldFormat['TYPE'];
if (strpos($type, 'DE') !== false) {
$type = str_replace('DE', '', $type);
$type = (int) $type + 1;
}
$type = (int) filter_var($type, FILTER_SANITIZE_NUMBER_INT);
if($fileFormat->ac != 'discharge-port') {
$fieldValue = mb_substr($text, $Y, $type, 'UTF-8');
}else{
$fieldValue = substr($text, $Y, $type);
}
// $fieldValue = substr($text, $Y, $type);
$Y += $type;
if(isset($fieldFormat['format'])) {
if ($fieldFormat['format'] === 'date') {
$fieldValue = $this->convertDate($fieldValue);
}
}
$primaryKeyConditions[] = $primaryKey['FILD'] . " = '" . trim($fieldValue) . "'";
}
$select2[] = " WHERE " . implode(' AND ', $primaryKeyConditions);
$select[] = "SELECT * FROM " . $formatData['database'] . " " . " WHERE " . implode(' AND ', $primaryKeyConditions);
$insertFields = [];
$insertValues = [];
foreach ($formatData['format'] as $fieldFormat) {
$type = $fieldFormat['TYPE'];
if (strpos($type, 'DE') !== false) {
$type = str_replace('DE', '', $type);
$type = (int) $type + 1;
}
$type = (int) filter_var($type, FILTER_SANITIZE_NUMBER_INT);
if($fileFormat->ac != 'discharge-port') {
$fieldValue = mb_substr($text, $X, $type, 'UTF-8');
}else{
$fieldValue = substr($text, $X, $type);
}
// $fieldValue = substr($text, $Y, $type);
$X += $type;
if(isset($fieldFormat['format'])) {
if ($fieldFormat['format'] === 'date') {
$fieldValue = $this->convertDate($fieldValue);
}
}
$insertFields[] = "`" . $fieldFormat['FILD'] . "`";
$insertValues[] = "'" . str_replace("'", "''", trim($fieldValue)) . "'";
}
$insert[] = "INSERT INTO " . $formatData['database'] . " (" . implode(',', $insertFields) . ") VALUES (" . implode(',', $insertValues) . ")";
$update[] = $this->generateUpdateQuery($formatData['format'], $text, $Z, $formatData['primary_key']);
$sqlPack = [
'insert' => $insert,
'update' => $update,
'select' => $select,
'select2' => $select2,
'DATABASE' => $formatData['database'],
'counter' => $count += 1
];
if ($count >= $limit && !$noLimit) {
$sqlPackAll[] = $sqlPack;
$count = 0;
unset($sqlPack);
}
}
fclose($fileHandle);
$sqlPackAll[] = $sqlPack;
return $sqlPackAll;
}
private function generateUpdateQuery($formatData, $text, &$Z, $primaryKeys)
{
$update = "";
foreach ($formatData as $index => $fieldFormat) {
$type = $fieldFormat['TYPE'];
if (strpos($type, 'DE') !== false) {
$type = str_replace('DE', '', $type);
$type = (int) $type + 1;
}
$type = (int) filter_var($type, FILTER_SANITIZE_NUMBER_INT);
$fieldValue = substr($text, $Z, $type);
$Z += $type;
if(isset($fieldFormat['format'])) {
if ($fieldFormat['format'] === 'date') {
$fieldValue = $this->convertDate($fieldValue);
}
}
if (!in_array($fieldFormat['FILD'], array_column($primaryKeys, 'FILD'))) {
if ($update != "") {
$update .= ", ";
}
$update .= "`" . $fieldFormat['FILD'] . "` = '" . str_replace("'", "''", trim($fieldValue)) . "'";
}
}
return $update;
}
}
<?php <?php
/*
-----------------------------------------
Only this file encoding with TIS-620 !!!!
-----------------------------------------
*/
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\ConfFormatFile; use App\Models\ConfFormatFile;
...@@ -21,7 +25,7 @@ class MasterFileController extends Controller ...@@ -21,7 +25,7 @@ class MasterFileController extends Controller
public function createPatch(Request $request) public function createPatch(Request $request)
{ {
// $request->validate([ // $request->validate([
// 'format_file_id' => 'required|exists:conf_format_file,formatservice_ID', // 'format_file_id' => 'required|exists:conf_format_file,formatservice_ID',
// 'file' => 'required|file|max:12209752', // 'file' => 'required|file|max:12209752',
...@@ -33,30 +37,29 @@ class MasterFileController extends Controller ...@@ -33,30 +37,29 @@ class MasterFileController extends Controller
// ]); // ]);
$file = $request->file('file'); $file = $request->file('file');
$filePath = $file->getRealPath(); $filePath = $file->getRealPath();
if(isset($request->truncateGoods) && ($request->format_file_id == 196)) { if (isset($request->truncateGoods) && ($request->format_file_id == 196)) {
$truncateGoods = true ; $truncateGoods = true;
}else{ } else {
$truncateGoods = false ; $truncateGoods = false;
} }
$fileFormat = ConfFormatFile::where('formatservice_ID', $request->format_file_id)->first(); $fileFormat = ConfFormatFile::where('formatservice_ID', $request->format_file_id)->first();
$jsonFilePath = storage_path(str_replace(".inc", ".json", $fileFormat->file)); $jsonFilePath = storage_path(str_replace(".inc", ".json", $fileFormat->file));
if (!file_exists($jsonFilePath)) { if (!file_exists($jsonFilePath)) {
return redirect()->back()->withErrors(['error' => 'Format JSON file not found.']); return redirect()->back()->withErrors(['error' => 'Format JSON file not found.']);
} }
$formatData = json_decode(file_get_contents($jsonFilePath), true); $formatData = json_decode(file_get_contents($jsonFilePath), true);
$message = ''; $message = '';
if ($request->createPatch) { if ($request->createPatch) {
$sqlPackAll = $this->readTxt($filePath, $formatData, $fileFormat, $request->limit, $request->noLimit); $sqlPackAll = $this->readTxt($filePath, $formatData, $fileFormat, $request->limit, $request->noLimit);
$this->processPatches($sqlPackAll, $fileFormat, $request->genWithSmartUpdate, $request->noLimit , $truncateGoods); $this->processPatches($sqlPackAll, $fileFormat, $request->genWithSmartUpdate, $request->noLimit, $truncateGoods);
$message .= 'Patch master file created successfully. '; $message .= 'Patch master file created successfully. ';
} }
...@@ -105,7 +108,7 @@ class MasterFileController extends Controller ...@@ -105,7 +108,7 @@ class MasterFileController extends Controller
]); ]);
} }
function processPatches($sqlPackAll, $fileFormat, $genSpnSmartUpdateDecode, $noLimit , $truncateGoods) function processPatches($sqlPackAll, $fileFormat, $genSpnSmartUpdateDecode, $noLimit, $truncateGoods)
{ {
$uid = auth()->user()->id; $uid = auth()->user()->id;
$pLevel = "Critical"; $pLevel = "Critical";
...@@ -124,31 +127,26 @@ class MasterFileController extends Controller ...@@ -124,31 +127,26 @@ class MasterFileController extends Controller
$partPatch = 'Part ' . $part++; $partPatch = 'Part ' . $part++;
} }
// $utf8_encoded = mb_convert_encoding(var_export($sqlPack, true), 'UTF-8', 'auto');
// $utf8_encoded = mb_convert_encoding(var_export($sqlPack, true), 'UTF-8', 'auto');
$tis620_encoded = iconv('UTF-8', 'Windows-874',var_export($sqlPack, true));
// $tis620_encoded = var_export($sqlPack, true);
// dd($tis620_encoded);
$patchCode = ''; $patchCode = '';
if($truncateGoods) { if ($truncateGoods) {
$patchCode .= '$sql = "truncate table master_permissiongoods"; $patchCode .= '$sql = "truncate table master_permissiongoods";
exec_query($sql); exec_query($sql);
if ($DBTYPE == "MSSQL") { if ($DBTYPE == "MSSQL") {
$Count_CONSTRAINT = Query2ArrayVarPack("SELECT COUNT(TC.CONSTRAINT_NAME) AS count_CONSTRAINT,TC.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC $Count_CONSTRAINT = Query2ArrayVarPack("SELECT COUNT(TC.CONSTRAINT_NAME) AS count_CONSTRAINT,TC.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = "PRIMARY KEY" INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = \'PRIMARY KEY\'
AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
and ku.table_name="master_permissiongoods" and ku.table_name=\'master_permissiongoods\'
GROUP BY TC.CONSTRAINT_NAME"); GROUP BY TC.CONSTRAINT_NAME");
if ($Count_CONSTRAINT["count_CONSTRAINT"][0] != 5) { if ($Count_CONSTRAINT[\'count_CONSTRAINT\'][0] != 5) {
exec_query("ALTER TABLE [master_permissiongoods] DROP CONSTRAINT [" . $Count_CONSTRAINT["CONSTRAINT_NAME"][0] . "]"); exec_query("ALTER TABLE [master_permissiongoods] DROP CONSTRAINT [" . $Count_CONSTRAINT[\'CONSTRAINT_NAME\'][0] . "]");
exec_query("ALTER TABLE [master_permissiongoods] ADD CONSTRAINT [" . $Count_CONSTRAINT["CONSTRAINT_NAME"][0] . "] PRIMARY KEY([tariffClass],[tariffStat],[startDate],[permissionGoodsType],[companyTaxNo])"); exec_query("ALTER TABLE [master_permissiongoods] ADD CONSTRAINT [" . $Count_CONSTRAINT[\'CONSTRAINT_NAME\'][0] . "] PRIMARY KEY([tariffClass],[tariffStat],[startDate],[permissionGoodsType],[companyTaxNo])");
} }
}'; }
';
} }
$ALL64 = base64_encode(gzcompress($tis620_encoded)); $ALL64 = base64_encode(gzcompress(var_export($sqlPack, true)));
$patchCode .= '$ALL64="' . $ALL64 . '";' . "\n"; $patchCode .= '$ALL64="' . $ALL64 . '";' . "\n";
...@@ -215,7 +213,7 @@ class MasterFileController extends Controller ...@@ -215,7 +213,7 @@ class MasterFileController extends Controller
// $patchCode = str_replace("'", "''", $patchCode); // $patchCode = str_replace("'", "''", $patchCode);
$data = [ $data = [
'PATCHNAME' => "Update Master File $nameformat วันที่ $day เดือน $month ปี $year $partPatch", 'PATCHNAME' => iconv("TIS-620", "UTF-8","Update Master File $nameformat ѹ $day ͹ $month $year $partPatch"),
'PDATE' => Carbon::now(), 'PDATE' => Carbon::now(),
'PLEVEL' => $PLEVEL, 'PLEVEL' => $PLEVEL,
'PCODE' => 'SHIPPINGNET', 'PCODE' => 'SHIPPINGNET',
...@@ -224,7 +222,7 @@ class MasterFileController extends Controller ...@@ -224,7 +222,7 @@ class MasterFileController extends Controller
'POWNER' => $UID, 'POWNER' => $UID,
'PTYPE' => 'UPDATE MASTER', 'PTYPE' => 'UPDATE MASTER',
'PAPPROVEDATE' => $PAPPROVEDATE, 'PAPPROVEDATE' => $PAPPROVEDATE,
'PATCHCODE' => iconv("utf-8", "tis-620" ,$patchCode), 'PATCHCODE' => $patchCode,
'UNINSTALL' => '$DONE=1;', 'UNINSTALL' => '$DONE=1;',
'PATCHCODE_SERVER' => '$DONE=1;', 'PATCHCODE_SERVER' => '$DONE=1;',
]; ];
...@@ -232,109 +230,124 @@ class MasterFileController extends Controller ...@@ -232,109 +230,124 @@ class MasterFileController extends Controller
DB::table('conf_smartupdate')->insert($data); DB::table('conf_smartupdate')->insert($data);
} }
private function readTxt($filePath, $formatData, $ac, $limit = 10000, $noLimit = true) private function readTxt($filePath, $formatData, $fileFormat, $limit = 10000, $noLimit = true)
{ {
// header("Content-Type: text/html; charset=TIS-620");
ini_set('memory_limit', '-1'); ini_set('memory_limit', '-1');
$sqlPackAll = []; $sqlPackAll = [];
$sqlPack = [];
$count = 0;
$fileHandle = fopen($filePath, "r"); $fileHandle = fopen($filePath, "r");
$count = 0;
$batch = [];
while (!feof($fileHandle)) { while (!feof($fileHandle)) {
$line = fgets($fileHandle);
Log::info($line);
$processedLine = $this->processLine($line, $formatData, $fileFormat);
$text = fgets($fileHandle); $batch[] = $processedLine;
try {
$text = iconv('TIS-620', 'UTF-8', $text);
} catch (\Throwable $th) {
$encoding = mb_detect_encoding($text, ['UTF-8', 'ISO-8859-1', 'ASCII'], true);
$text = iconv('Windows-874', 'UTF-8', $text);
}
// Log::info($text);
$X = $Y = $Z = 0;
$primaryKeyConditions = []; if (count($batch) >= $limit && !$noLimit) {
$sqlPackAll[] = $this->generateSqlPack($batch, $formatData);
$batch = [];
}
}
foreach ($formatData['primary_key'] as $keyIndex => $primaryKey) { if (!empty($batch)) {
$fieldFormat = $formatData['format'][$keyIndex]; $sqlPackAll[] = $this->generateSqlPack($batch, $formatData);
$type = $fieldFormat['TYPE']; }
if (strpos($type, 'DE') !== false) { fclose($fileHandle);
$type = str_replace('DE', '', $type); // dd($sqlPackAll);
return $sqlPackAll;
}
$type = (int) $type + 1; private function processLine($line, $formatData, $fileFormat)
} {
$X = 0;
$Y = 0;
$primaryKeyConditions = [];
$insertFields = [];
$insertValues = [];
$type = (int) filter_var($type, FILTER_SANITIZE_NUMBER_INT);
$fieldValue = mb_substr($text, $Y, $type, 'UTF-8');
// $fieldValue = substr($text, $Y, $type);
$Y += $type;
if(isset($fieldFormat['format'])) { foreach ($formatData['primary_key'] as $keyIndex => $primaryKey) {
if ($fieldFormat['format'] === 'date') { $fieldFormat = $formatData['format'][$keyIndex];
$fieldValue = $this->convertDate($fieldValue); $type = $this->getFieldType($fieldFormat['TYPE']);
} // $fieldValue = mb_substr($line, $Y, $type, 'UTF-8');
} $fieldValue = substr($line, $Y, $type);
$Y += $type;
$primaryKeyConditions[] = $primaryKey['FILD'] . " = '" . trim($fieldValue) . "'"; if (isset($fieldFormat['format']) && $fieldFormat['format'] === 'date') {
$fieldValue = $this->convertDate($fieldValue);
} }
$select2[] = " WHERE " . implode(' AND ', $primaryKeyConditions); $primaryKeyConditions[] = $primaryKey['FILD'] . " = '" . trim($fieldValue) . "'";
$select[] = "SELECT * FROM " . $formatData['database'] . " " . " WHERE " . implode(' AND ', $primaryKeyConditions); }
$select = "SELECT * FROM " . $formatData['database'] . " WHERE " . implode(' AND ', $primaryKeyConditions);
$select2 = " WHERE " . implode(' AND ', $primaryKeyConditions);
$insertFields = []; foreach ($formatData['format'] as $fieldFormat) {
$insertValues = []; $type = $this->getFieldType($fieldFormat['TYPE']);
foreach ($formatData['format'] as $fieldFormat) { $fieldValue = substr($line, $X, $type);
$type = $fieldFormat['TYPE'];
$X += $type;
if (strpos($type, 'DE') !== false) { if (isset($fieldFormat['format']) && $fieldFormat['format'] === 'date') {
$type = str_replace('DE', '', $type); $fieldValue = $this->convertDate($fieldValue);
$type = (int) $type + 1; }
}
$type = (int) filter_var($type, FILTER_SANITIZE_NUMBER_INT);
$fieldValue = mb_substr($text, $X, $type, 'UTF-8');
// $fieldValue = substr($text, $Y, $type);
$X += $type;
if(isset($fieldFormat['format'])) {
if ($fieldFormat['format'] === 'date') {
$fieldValue = $this->convertDate($fieldValue);
}
}
$insertFields[] = "`" . $fieldFormat['FILD'] . "`";
$insertValues[] = "'" . str_replace("'", "''", trim($fieldValue)) . "'";
}
$insertFields[] = "`" . $fieldFormat['FILD'] . "`"; $insert = "INSERT INTO " . $formatData['database'] . " (" . implode(',', $insertFields) . ") VALUES (" . implode(',', $insertValues) . ")";
$insertValues[] = "'" . str_replace("'", "''", trim($fieldValue)) . "'";
}
$insert[] = "INSERT INTO " . $formatData['database'] . " (" . implode(',', $insertFields) . ") VALUES (" . implode(',', $insertValues) . ")"; $update = $this->generateUpdateQuery($formatData['format'], $line, $X, $formatData['primary_key']);
$update[] = $this->generateUpdateQuery($formatData['format'], $text, $Z, $formatData['primary_key']); return [
'insert' => $insert,
'update' => $update,
'select' => $select,
'select2' => $select2,
'DATABASE' => $formatData['database'],
];
}
$sqlPack = [ private function getFieldType($type)
'insert' => $insert, {
'update' => $update,
'select' => $select, if (strpos($type, 'DE') !== false) {
'select2' => $select2, $type = str_replace('DE', '', $type);
'DATABASE' => $formatData['database'], $type = (int)$type + 1;
'counter' => $count += 1 }
]; return (int)filter_var($type, FILTER_SANITIZE_NUMBER_INT);
}
private function generateSqlPack($batch, $formatData)
if ($count >= $limit && !$noLimit) { {
$sqlPackAll[] = $sqlPack; $sqlPack = [
$count = 0; 'insert' => [],
unset($sqlPack); 'update' => [],
} 'select' => [],
'select2' => [],
'DATABASE' => $formatData['database'],
];
foreach ($batch as $lineData) {
$sqlPack['insert'][] = $lineData['insert'];
$sqlPack['update'][] = $lineData['update'];
$sqlPack['select'][] = $lineData['select'];
$sqlPack['select2'][] = $lineData['select2'];
} }
fclose($fileHandle);
$sqlPackAll[] = $sqlPack; return $sqlPack;
return $sqlPackAll;
} }
private function generateUpdateQuery($formatData, $text, &$Z, $primaryKeys) private function generateUpdateQuery($formatData, $text, &$Z, $primaryKeys)
{ {
...@@ -348,10 +361,10 @@ class MasterFileController extends Controller ...@@ -348,10 +361,10 @@ class MasterFileController extends Controller
$type = (int) $type + 1; $type = (int) $type + 1;
} }
$type = (int) filter_var($type, FILTER_SANITIZE_NUMBER_INT); $type = (int) filter_var($type, FILTER_SANITIZE_NUMBER_INT);
$fieldValue = mb_substr($text, $Z, $type); $fieldValue = substr($text, $Z, $type);
$Z += $type; $Z += $type;
if(isset($fieldFormat['format'])) { if (isset($fieldFormat['format'])) {
if ($fieldFormat['format'] === 'date') { if ($fieldFormat['format'] === 'date') {
$fieldValue = $this->convertDate($fieldValue); $fieldValue = $this->convertDate($fieldValue);
} }
...@@ -368,5 +381,4 @@ class MasterFileController extends Controller ...@@ -368,5 +381,4 @@ class MasterFileController extends Controller
return $update; return $update;
} }
} }
<?php
namespace App\Http\Controllers;
use App\Models\ConfFormatFile;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class MasterFileController extends Controller
{
public function index()
{
$menu = 'MasterFile';
$currentContent = 'MasterFile';
return view('home', compact('menu', 'currentContent'));
}
public function createPatch(Request $request)
{
// $request->validate([
// 'format_file_id' => 'required|exists:conf_format_file,formatservice_ID',
// 'file' => 'required|file|max:12209752',
// 'limit' => 'nullable|integer',
// 'noLimit' => 'nullable|boolean',
// 'genWithSmartUpdate' => 'nullable|boolean',
// 'createPatch' => 'nullable|boolean',
// 'sendToEec' => 'nullable|boolean',
// ]);
$file = $request->file('file');
$filePath = $file->getRealPath();
if (isset($request->truncateGoods) && ($request->format_file_id == 196)) {
$truncateGoods = true;
} else {
$truncateGoods = false;
}
$fileFormat = ConfFormatFile::where('formatservice_ID', $request->format_file_id)->first();
$jsonFilePath = storage_path(str_replace(".inc", ".json", $fileFormat->file));
if (!file_exists($jsonFilePath)) {
return redirect()->back()->withErrors(['error' => 'Format JSON file not found.']);
}
$formatData = json_decode(file_get_contents($jsonFilePath), true);
$message = '';
if ($request->createPatch) {
$sqlPackAll = $this->readTxt($filePath, $formatData, $fileFormat, $request->limit, $request->noLimit);
$this->processPatches($sqlPackAll, $fileFormat, $request->genWithSmartUpdate, $request->noLimit, $truncateGoods);
$message .= 'Patch master file created successfully. ';
}
if ($request->sendToEec && !empty($fileFormat->ac)) {
$timestamp = Carbon::now()->toDateString();
$response = $this->sendMasterFileToEcc(config('services.eec.url'), [
'type' => $fileFormat->ac,
'file' => fopen($filePath, 'r'),
'timestamp' => $timestamp,
]);
$responseStatus = $response->status();
$responseData = $response->json();
$this->keepTransactionToEcc(auth()->id(), $fileFormat->ac, $file->getClientOriginalName(), json_encode([
'type' => $fileFormat->ac,
'timestamp' => $timestamp,
]), Carbon::now(), $responseStatus, json_encode($responseData));
$message .= 'Send to EEC successfully.';
}
return redirect()->route('patch.index')->with('message', $message);
}
private function sendMasterFileToEcc($url, $postData)
{
return Http::attach('file', $postData['file'])
->asMultipart()
->post($url, [
'type' => $postData['type'],
'timestamp' => $postData['timestamp'],
]);
}
private function keepTransactionToEcc($uid, $type, $filename, $requestData, $datetime, $responseStatus, $responseData)
{
DB::table('log_send_master2eec')->insert([
'UID' => $uid,
'TYPE' => $type,
'FILENAME' => $filename,
'REQDATA' => $requestData,
'ACTDATETIME' => $datetime,
'RESPSTATUS' => $responseStatus,
'RESPDATA' => $responseData,
]);
}
function processPatches($sqlPackAll, $fileFormat, $genSpnSmartUpdateDecode, $noLimit, $truncateGoods)
{
$uid = auth()->user()->id;
$pLevel = "Critical";
$nameFormat = $fileFormat->name ?? 'Unknown Format';
$pDesc = $nameFormat;
$day = Date('j');
$month = Date('n');
$year = Date('Y');
$pApproveDate = date("Y-m-d h:i:s");
$partPatch = '';
$countSql = count($sqlPackAll);
$part = 1;
foreach ($sqlPackAll as $i__ => $sqlPack) {
if ($countSql != 1 && !$noLimit) {
$partPatch = 'Part ' . $part++;
}
// $utf8_encoded = mb_convert_encoding(var_export($sqlPack, true), 'UTF-8', 'auto');
// $utf8_encoded = mb_convert_encoding(var_export($sqlPack, true), 'UTF-8', 'auto');
// $sqlPackWindows874 = iconv("UTF-8", "windows-874", $sqlPack);
// $utf8_encoded = iconv('UTF-8', 'TIS-620', var_export($sqlPack, true));
// $tis620_encoded = iconv('UTF-8', 'Windows-874//IGNORE',var_export($sqlPack, true));
// if($fileFormat->ac == 'discharge-port' || $fileFormat->ac == 'country') {
// $tis620_encoded = var_export($sqlPack , true);
// }else{
// $tis620_encoded = iconv('UTF-8', 'Windows-874',var_export($sqlPack, true));
// }
$tis620_encoded = iconv('UTF-8', 'Windows-874',var_export($sqlPack, true));
dd($tis620_encoded);
// $tis620_encoded = var_export($sqlPack, true);
$patchCode = '';
if ($truncateGoods) {
$patchCode .= '$sql = "truncate table master_permissiongoods";
exec_query($sql);
if ($DBTYPE == "MSSQL") {
$Count_CONSTRAINT = Query2ArrayVarPack("SELECT COUNT(TC.CONSTRAINT_NAME) AS count_CONSTRAINT,TC.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = "PRIMARY KEY"
AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
and ku.table_name="master_permissiongoods"
GROUP BY TC.CONSTRAINT_NAME");
if ($Count_CONSTRAINT["count_CONSTRAINT"][0] != 5) {
exec_query("ALTER TABLE [master_permissiongoods] DROP CONSTRAINT [" . $Count_CONSTRAINT["CONSTRAINT_NAME"][0] . "]");
exec_query("ALTER TABLE [master_permissiongoods] ADD CONSTRAINT [" . $Count_CONSTRAINT["CONSTRAINT_NAME"][0] . "] PRIMARY KEY([tariffClass],[tariffStat],[startDate],[permissionGoodsType],[companyTaxNo])");
}
};
';
}
$ALL64 = base64_encode(gzcompress($tis620_encoded));
$patchCode .= '$ALL64="' . $ALL64 . '";' . "\n";
if ($genSpnSmartUpdateDecode) {
$updatedecode = '$ALLVAR=gzuncompress(spnsmartupdatedecode($ALL64));' . "\n";
} else {
$updatedecode = '$ALLVAR=gzuncompress(base64_decode($ALL64));' . "\n";
}
$patchCode .= $updatedecode;
$patchCode .= "eval('\$SQL='." . '$ALLVAR.";");' . "\n";
$patchCode .= $this->generatePatchCode($countSql, $i__);
if ($noLimit && ($i__ == $countSql - 1)) {
$this->savePatch($patchCode, $nameFormat, $day, $month, $year, $partPatch, $pLevel, $pDesc, $uid, $pApproveDate);
} elseif (!$noLimit) {
$this->savePatch($patchCode, $nameFormat, $day, $month, $year, $partPatch, $pLevel, $pDesc, $uid, $pApproveDate);
}
}
}
private function generatePatchCode($countSql, $i__)
{
$patchCode = '';
$patchCode .= '$insert=$SQL["insert"];' . "\n";
$patchCode .= '$update=$SQL["update"];' . "\n";
$patchCode .= '$select=$SQL["select"];' . "\n";
$patchCode .= '$select2=$SQL["select2"];' . "\n";
$patchCode .= '$DATABASE=$SQL["DATABASE"];' . "\n";
$patchCode .= '$CountSQL_=count($insert);' . "\n";
$patchCode .= '$succ="0";' . "\n";
$patchCode .= '$succ2="0";' . "\n";
$patchCode .= 'for($i_=0;$i_<$CountSQL_;$i_++){' . "\n";
$patchCode .= ' $INSERT_ID="";' . "\n";
$patchCode .= ' if($DBTYPE=="MYSQL"){' . "\n";
$patchCode .= ' $sql=$insert[$i_]." ON DUPLICATE KEY UPDATE ".$update[$i_];' . "\n";
$patchCode .= ' }' . "\n";
$patchCode .= ' if($DBTYPE=="MSSQL"){' . "\n";
$patchCode .= ' $sql="IF EXISTS (".$select[$i_].") BEGIN UPDATE $DATABASE SET ".$update[$i_].$select2[$i_]." END ELSE ".$insert[$i_];' . "\n";
$patchCode .= ' }' . "\n";
$patchCode .= ' exec_query($sql);' . "\n";
$patchCode .= ' $succ++;' . "\n";
$patchCode .= ' if($INSERT_ID!=""){$succ2++;}' . "\n";
$patchCode .= '}' . "\n";
$patchCode .= 'unset($ALL64);' . "\n";
$patchCode .= 'unset($ALLVAR);' . "\n";
$patchCode .= 'unset($SQL);' . "\n";
$patchCode .= 'unset($insert);' . "\n";
$patchCode .= 'unset($update);' . "\n";
$patchCode .= 'unset($select);' . "\n";
$patchCode .= 'unset($select2);' . "\n";
$patchCode .= '$PRINT_ .= date("h:i:s")." Process ' . ($i__ + 1) . ' / ' . $countSql . ' Successful Update $succ data(s) (Added = $succ2) from $CountSQL_.</br>";' . "\n";
return $patchCode;
}
private function savePatch($patchCode, $nameformat, $day, $month, $year, $partPatch, $PLEVEL, $PDESC, $UID, $PAPPROVEDATE)
{
$patchCode .= '$PRINTOUT=$PRINT_;' . "\n";
$patchCode .= '$PATCH_STATUS="OK";' . "\n";
// $patchCode = str_replace("'", "''", $patchCode);
$data = [
'PATCHNAME' => "Update Master File $nameformat วันที่ $day เดือน $month ปี $year $partPatch",
'PDATE' => Carbon::now(),
'PLEVEL' => $PLEVEL,
'PCODE' => 'SHIPPINGNET',
'MAJOR_VERSION' => 'ALL',
'PDESC' => $PDESC,
'POWNER' => $UID,
'PTYPE' => 'UPDATE MASTER',
'PAPPROVEDATE' => $PAPPROVEDATE,
'PATCHCODE' => iconv("utf-8", "tis-620", $patchCode),
'UNINSTALL' => '$DONE=1;',
'PATCHCODE_SERVER' => '$DONE=1;',
];
DB::table('conf_smartupdate')->insert($data);
}
private function readTxt($filePath, $formatData, $fileFormat, $limit = 10000, $noLimit = true)
{
// เพิ่ม memory_limit และปรับ encoding filter
ini_set('memory_limit', '-1');
$sqlPackAll = [];
$fileHandle = fopen($filePath, "r");
if ($fileFormat->ac == 'discharge-port' || $fileFormat->ac == 'country') {
// No conversion needed for 'discharge-port'
} else {
try {
stream_filter_append($fileHandle, 'convert.iconv.TIS-620//IGNORE/UTF-8');
} catch (\Exception $e) {
Log::error('Stream filter failed to apply.', ['error' => $e->getMessage()]);
}
}
// stream_filter_append($fileHandle, 'convert.iconv.Windows-1252/UTF-8');
// $contents = stream_get_contents($fileHandle);
// $contents = iconv('UTF-8',"Windows-874", $contents);
$count = 0;
$batch = [];
while (!feof($fileHandle)) {
$line = fgets($fileHandle);
$encoding = mb_detect_encoding($line, ['UTF-8', 'ISO-8859-1', 'ASCII'], true);
if ($encoding !== 'UTF-8') {
try {
if($encoding == 'ISO-8859-1') {
$line = iconv("Windows-874", 'UTF-8', $line);
}else{
$line = iconv($encoding, 'UTF-8//IGNORE', $line);
}
} catch (\Exception $e) {
Log::error('Failed to convert line encoding.', ['line' => $line, 'error' => $e->getMessage()]);
continue; // Skip problematic line
}
}
if (!mb_check_encoding($line, 'UTF-8')) {
Log::warning('Skipping invalid UTF-8 sequence.', ['line' => $line]);
continue; // Skip the line
}
Log::info($line);
// ประมวลผลแต่ละบรรทัด
$processedLine = $this->processLine($line, $formatData, $fileFormat);
$batch[] = $processedLine;
if (count($batch) >= $limit && !$noLimit) {
$sqlPackAll[] = $this->generateSqlPack($batch, $formatData);
$batch = [];
}
}
// ประมวลผล batch ที่เหลือ
if (!empty($batch)) {
$sqlPackAll[] = $this->generateSqlPack($batch, $formatData);
}
fclose($fileHandle);
// dd($sqlPackAll);
return $sqlPackAll;
}
private function processLine($line, $formatData, $fileFormat)
{
$X = 0;
$Y = 0;
$primaryKeyConditions = [];
$insertFields = [];
$insertValues = [];
// ประมวลผล Primary Key
foreach ($formatData['primary_key'] as $keyIndex => $primaryKey) {
$fieldFormat = $formatData['format'][$keyIndex];
$type = $this->getFieldType($fieldFormat['TYPE']);
// $fieldValue = mb_substr($line, $Y, $type, 'UTF-8');
$fieldValue = substr($line, $Y, $type);
$Y += $type;
if (isset($fieldFormat['format']) && $fieldFormat['format'] === 'date') {
$fieldValue = $this->convertDate($fieldValue);
}
$primaryKeyConditions[] = $primaryKey['FILD'] . " = '" . trim($fieldValue) . "'";
}
// สร้าง SQL สำหรับ Select
$select = "SELECT * FROM " . $formatData['database'] . " WHERE " . implode(' AND ', $primaryKeyConditions);
$select2 = " WHERE " . implode(' AND ', $primaryKeyConditions);
// ประมวลผลฟิลด์ที่เหลือ
foreach ($formatData['format'] as $fieldFormat) {
$type = $this->getFieldType($fieldFormat['TYPE']);
// $fieldValue = mb_substr($line, $X, $type);
if(strpos($line, 'หัสประเทศ') !== false && $type == 72) {
$encoding = mb_detect_encoding($line, ['UTF-8', 'ISO-8859-1', 'ASCII'], true);
$fieldValue = mb_substr($line, $X, $type, 'UTF-8');
// $fieldValue = iconv("UTF-8" , "TIS-620", trim($fieldValue));
// dd($fieldValue);
}
$fieldValue = mb_substr($line, $X, $type, 'UTF-8');
$X += $type;
if (isset($fieldFormat['format']) && $fieldFormat['format'] === 'date') {
$fieldValue = $this->convertDate($fieldValue);
}
$insertFields[] = "`" . $fieldFormat['FILD'] . "`";
$insertValues[] = "'" . str_replace("'", "''", trim($fieldValue)) . "'";
}
$insert = "INSERT INTO " . $formatData['database'] . " (" . implode(',', $insertFields) . ") VALUES (" . implode(',', $insertValues) . ")";
$update = $this->generateUpdateQuery($formatData['format'], $line, $X, $formatData['primary_key']);
// คืนค่าข้อมูลที่ประมวลผล
return [
'insert' => $insert,
'update' => $update,
'select' => $select,
'select2' => $select2,
'DATABASE' => $formatData['database'],
];
}
private function getFieldType($type)
{
// ประมวลผลประเภทฟิลด์
if (strpos($type, 'DE') !== false) {
$type = str_replace('DE', '', $type);
$type = (int)$type + 1;
}
return (int)filter_var($type, FILTER_SANITIZE_NUMBER_INT);
}
private function generateSqlPack($batch, $formatData)
{
// รวมข้อมูลใน batch เป็น SQL Pack
$sqlPack = [
'insert' => [],
'update' => [],
'select' => [],
'select2' => [],
'DATABASE' => $formatData['database'],
];
foreach ($batch as $lineData) {
$sqlPack['insert'][] = $lineData['insert'];
$sqlPack['update'][] = $lineData['update'];
$sqlPack['select'][] = $lineData['select'];
$sqlPack['select2'][] = $lineData['select2'];
}
return $sqlPack;
}
private function generateUpdateQuery($formatData, $text, &$Z, $primaryKeys)
{
$update = "";
foreach ($formatData as $index => $fieldFormat) {
$type = $fieldFormat['TYPE'];
if (strpos($type, 'DE') !== false) {
$type = str_replace('DE', '', $type);
$type = (int) $type + 1;
}
$type = (int) filter_var($type, FILTER_SANITIZE_NUMBER_INT);
$fieldValue = substr($text, $Z, $type);
$Z += $type;
if (isset($fieldFormat['format'])) {
if ($fieldFormat['format'] === 'date') {
$fieldValue = $this->convertDate($fieldValue);
}
}
if (!in_array($fieldFormat['FILD'], array_column($primaryKeys, 'FILD'))) {
if ($update != "") {
$update .= ", ";
}
$update .= "`" . $fieldFormat['FILD'] . "` = '" . str_replace("'", "''", trim($fieldValue)) . "'";
}
}
return $update;
}
}
...@@ -28,7 +28,7 @@ class SmartUpdateController extends Controller ...@@ -28,7 +28,7 @@ class SmartUpdateController extends Controller
// if ($serviceName !== 'SMARTUPDATE' || $action !== 'HISTORY_PATCH') { // if ($serviceName !== 'SMARTUPDATE' || $action !== 'HISTORY_PATCH') {
// return response()->json(['error' => 'Invalid request'], 400); // return response()->json(['error' => 'Invalid request'], 400);
// } // }
if ($action === 'HISTORY_PATCH') { if ($action === 'HISTORY_PATCH') {
$this->historyPatch($serverKeyClient); $this->historyPatch($serverKeyClient);
} else if ($action === 'LIST_PATCH') { } else if ($action === 'LIST_PATCH') {
...@@ -37,6 +37,8 @@ class SmartUpdateController extends Controller ...@@ -37,6 +37,8 @@ class SmartUpdateController extends Controller
$this->updatePatch($request); $this->updatePatch($request);
} else if ($action === 'FINISH_PATCH') { } else if ($action === 'FINISH_PATCH') {
$this->finishPatch($request); $this->finishPatch($request);
} else if ($action === 'GET_ALLPATCH') {
$this->getAllPatch($request);
} }
} }
...@@ -93,13 +95,12 @@ class SmartUpdateController extends Controller ...@@ -93,13 +95,12 @@ class SmartUpdateController extends Controller
->join('conf_smartupdate as t1', 't0.PatchID', '=', 't1.PID') ->join('conf_smartupdate as t1', 't0.PatchID', '=', 't1.PID')
->where('t0.ServerId', $serverId) ->where('t0.ServerId', $serverId)
->where('t0.TaskStatus', '<', 999) ->where('t0.TaskStatus', '<', 999)
->where('t1.PAPPROVEDATE', '<', now()) ->whereDate('t1.PAPPROVEDATE', '<', date('Y-m-d H:i:s'))
->where('t1.PAPPROVEDATE', '<>', '0000-00-00 00:00:00') ->whereDate('t1.PAPPROVEDATE', '<>', '0000-00-00 00:00:00')
->where('t0.TaskDate', '<', now()) ->whereDate('t0.TaskDate', '<', date('Y-m-d H:i:s'))
->where('t0.TaskDate', '<>', '0000-00-00 00:00:00') ->whereDate('t0.TaskDate', '<>', '0000-00-00 00:00:00')
->orderBy('t0.PatchID', 'ASC') ->orderBy('t0.PatchID', 'ASC')
->get(); ->get();
$cannotUpdateAll = false; $cannotUpdateAll = false;
foreach ($pendingUpdates as $index => $update) { foreach ($pendingUpdates as $index => $update) {
if ($index > 0 && $update->Action == 'Update') { if ($index > 0 && $update->Action == 'Update') {
...@@ -195,10 +196,10 @@ class SmartUpdateController extends Controller ...@@ -195,10 +196,10 @@ class SmartUpdateController extends Controller
->where('t1.PLEVEL', 'AUTO') ->where('t1.PLEVEL', 'AUTO')
->where('t0.ServerId', $serverId) ->where('t0.ServerId', $serverId)
->where('t0.TaskStatus', '<', 999) ->where('t0.TaskStatus', '<', 999)
->where('t1.PAPPROVEDATE', '<', now()) ->whereDate('t1.PAPPROVEDATE', '<', date('Y-m-d H:i:s'))
->where('t1.PAPPROVEDATE', '<>', '0000-00-00 00:00:00') ->whereDate('t1.PAPPROVEDATE', '<>', '0000-00-00 00:00:00')
->where('t0.TaskDate', '<', now()) ->whereDate('t0.TaskDate', '<', date('Y-m-d H:i:s'))
->where('t0.TaskDate', '<>', '0000-00-00 00:00:00') ->whereDate('t0.TaskDate', '<>', '0000-00-00 00:00:00')
->value('PID'); ->value('PID');
$mode = 'AUTO'; $mode = 'AUTO';
} }
...@@ -208,10 +209,10 @@ class SmartUpdateController extends Controller ...@@ -208,10 +209,10 @@ class SmartUpdateController extends Controller
->where('t1.PID', $patchId) ->where('t1.PID', $patchId)
->where('t0.ServerId', $serverId) ->where('t0.ServerId', $serverId)
->where('t0.TaskStatus', '<', 999) ->where('t0.TaskStatus', '<', 999)
->where('t1.PAPPROVEDATE', '<', now()) ->whereDate('t1.PAPPROVEDATE', '<', date('Y-m-d H:i:s'))
->where('t1.PAPPROVEDATE', '<>', '0000-00-00 00:00:00') ->whereDate('t1.PAPPROVEDATE', '<>', '0000-00-00 00:00:00')
->where('t0.TaskDate', '<', now()) ->whereDate('t0.TaskDate', '<', date('Y-m-d H:i:s'))
->where('t0.TaskDate', '<>', '0000-00-00 00:00:00') ->whereDate('t0.TaskDate', '<>', '0000-00-00 00:00:00')
->first(['PATCHCODE_SERVER', 'PATCHCODE', 'MAJOR_VERSION']); ->first(['PATCHCODE_SERVER', 'PATCHCODE', 'MAJOR_VERSION']);
if ($patchDetails && $clientVersion > $patchDetails->MAJOR_VERSION) { if ($patchDetails && $clientVersion > $patchDetails->MAJOR_VERSION) {
...@@ -491,10 +492,47 @@ class SmartUpdateController extends Controller ...@@ -491,10 +492,47 @@ class SmartUpdateController extends Controller
echo $th;die(); echo $th;die();
} }
$patchName = DB::table('conf_smartupdate')->where('pid', $patchId)->value('PATCHNAME'); $patchName = DB::table('conf_smartupdate')->where('pid', $patchId)->value('PATCHNAME');
$patchName = iconv("UTF-8" , "TIS-620" , $patchName);
echo base64_encode("\$PATCHNAME=\"$patchName\";"); echo base64_encode("\$PATCHNAME=\"$patchName\";");
} }
public function getAllPatch($request)
{
$serverKeyClient = $request->input('SERVERKEYCLIENT');
$patchId = $request->input('PATCHID');
$updateAll = $request->input('UPDATEALL');
$clientVersion = $request->input('CLIENTVERSION');
$serverId = DB::table('conf_server_license')
->where('SNKEY', $serverKeyClient)
->value('ID');
$pendingUpdates = ConfServerPendding::select(
't0.PatchID as PatchID' )
->from('conf_server_pendding as t0')
->join('conf_smartupdate as t1', 't0.PatchID', '=', 't1.PID')
->where('t0.ServerId', $serverId)
->where('t0.TaskStatus', '<', 999)
->where('t1.PAPPROVEDATE', '<', now())
->where('t1.PAPPROVEDATE', '<>', '0000-00-00 00:00:00')
->where('t0.TaskDate', '<', now())
->where('t0.TaskDate', '<>', '0000-00-00 00:00:00')
->orderBy('t0.PatchID', 'ASC')
->get();
$patchIdArr = [];
if(isset($pendingUpdates)) {
foreach($pendingUpdates as $pendding) {
array_push($patchIdArr, $pendding->PatchID);
}
$patchStr = implode(",", $patchIdArr);
}
echo base64_encode('$PATCHID_STR="'.$patchStr.'";');
DB::table('log_history')->insert([
'HDATE' => now(),
'HSID' => $serverId,
'HACTION' => 'GET ALL PATCH',
]);
}
public static function processPatchCode($patchCode) public static function processPatchCode($patchCode)
{ {
$patchCode = str_replace('$', '#', $patchCode); $patchCode = str_replace('$', '#', $patchCode);
......
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
}, },
{ {
"NAME": "Name", "NAME": "Name",
"TYPE": "35A", "TYPE": "72A",
"FILD": "name", "FILD": "name",
"FORMAT": "" "FORMAT": ""
}, },
...@@ -23,12 +23,6 @@ ...@@ -23,12 +23,6 @@
"TYPE": "3A", "TYPE": "3A",
"FILD": "currency", "FILD": "currency",
"FORMAT": "" "FORMAT": ""
},
{
"NAME": "wtocountry",
"TYPE": "1A",
"FILD": "wtocountry",
"FORMAT": ""
} }
] ]
} }
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment