<?php
/*
-----------------------------------------
Only this file encoding with TIS-620 !!!!
-----------------------------------------
*/
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->truncate) && (($request->format_file_id == 32) || ($request->format_file_id == 63) || ($request->format_file_id == 196))) {
$truncate = true;
} else {
$truncate = 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, $truncate);
$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, $truncate)
{
$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++;
}
$patchCode = '';
if ($truncate && $i__ == 0 && $fileFormat->formatservice_ID == 196) {
$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])");
}
}
';
}else if ($truncate && $i__ == 0 && $fileFormat->formatservice_ID == 32) {
$patchCode .= '$sql="truncate table master_country";exec_query($sql);';
}else if ($truncate && $i__ == 0 && $fileFormat->formatservice_ID == 63) {
$patchCode .= '$sql="truncate table master_container_type";exec_query($sql);';
}
$ALL64 = base64_encode(gzcompress(var_export($sqlPack, true)));
$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_ = "";$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' => iconv("TIS-620", "UTF-8","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' => $patchCode,
'UNINSTALL' => '$DONE=1;',
'PATCHCODE_SERVER' => '$DONE=1;',
];
DB::table('conf_smartupdate')->insert($data);
}
private function readTxt($filePath, $formatData, $fileFormat, $limit = 10000, $noLimit = true)
{
ini_set('memory_limit', '-1');
$sqlPackAll = [];
$fileHandle = fopen($filePath, "r");
$count = 0;
$batch = [];
while (!feof($fileHandle)) {
$line = fgets($fileHandle);
Log::info($line);
$processedLine = $this->processLine($line, $formatData, $fileFormat);
$batch[] = $processedLine;
if (count($batch) >= $limit && !$noLimit) {
$sqlPackAll[] = $this->generateSqlPack($batch, $formatData);
$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;
$Z = 0;
$primaryKeyConditions = [];
$insertFields = [];
$insertValues = [];
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) . "'";
}
$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 = substr($line, $X, $type);
$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, $Z, $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)
{
$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 .= ", ";
}
Log::info( "`" . $fieldFormat['FILD'] . "` = '" . str_replace("'", "''", trim($fieldValue)) . "'");
$update .= "`" . $fieldFormat['FILD'] . "` = '" . str_replace("'", "''", trim($fieldValue)) . "'";
}
}
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;
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class NewsController extends Controller
{
public function index()
{
$menu = 'News';
$currentContent = 'News';
return view('home', compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ParameterController extends Controller
{
public function index() {
$menu = 'Parameter';
$currentContent = 'Parameter';
return view('home' ,compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PatchController extends Controller
{
public function index() {
$menu = 'Patch';
$currentContent = 'Patch';
return view('home' ,compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers;
use App\Models\ConfServerLicense;
use Illuminate\Http\Request;
class ReportController extends Controller
{
public function index() {
$menu = 'Report';
$currentContent = 'Report';
return view('home' ,compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class RoleController extends Controller
{
public function index() {
$menu = 'Role';
$currentContent = 'Role';
return view('home' ,compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers;
use App\Models\Group;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\Request;
class SelectListController extends Controller
{
public function getRoles()
{
$roles = Role::select('id', 'name')->get();
$formattedRoles = [];
foreach ($roles as $role) {
$formattedRoles[] = [
'id' => $role->id,
'name' => $role->name,
];
}
return response()->json(['roles' => $formattedRoles]);
}
public function getUsers()
{
$users = User::select('id', 'username', 'email')->get();
$formattedUsers = [];
foreach ($users as $user) {
$formattedUsers[] = [
'id' => $user->id,
'name' => $user->username,
'email' => $user->email,
];
}
return response()->json(['users' => $formattedUsers]);
}
public function getGroups()
{
$users = Group::select('id', 'name')->get();
$formattedGroups = [];
foreach ($users as $user) {
$formattedGroups[] = [
'id' => $user->id,
'name' => $user->name,
];
}
return response()->json(['groups' => $formattedGroups]);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SendPatchController extends Controller
{
public function index() {
$menu = 'SendPatch';
$currentContent = 'SendPatch';
return view('home' ,compact('menu', 'currentContent'));
}
public function indexMulti() {
$menu = 'SendMultiPatch';
$currentContent = 'SendMultiPatch';
return view('home' ,compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers;
use App\Models\ConfServerLicense;
use Illuminate\Http\Request;
class ServerLicenseController extends Controller
{
public function index() {
$menu = 'ServerLicense';
$currentContent = 'ServerLicense';
return view('home' ,compact('menu', 'currentContent'));
}
public function getAllServerKey()
{
$serverLicenses = ConfServerLicense::select('ID', 'SNKEY')->get();
$formattedserverLicenses = [];
foreach ($serverLicenses as $license) {
$formattedserverLicenses[] = [
'id' => $license->ID,
'name' => $license->SNKEY,
];
}
return response()->json(['serverLicenses' => $formattedserverLicenses]);
}
}
This diff is collapsed.
<?php
namespace App\Http\Controllers;
use App\Models\ConfSmartupdate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class TestController extends Controller
{
//
public function index() {
$numServerSubquery = DB::table('conf_server_pendding as p2')
->select(DB::raw('count(p2.ServerID) as NUMSERVER'), 'p2.PatchID')
->groupBy('p2.PatchID');
// Query หลัก
$query = ConfSmartupdate::from('conf_smartupdate as p1')
->select('p1.PID', 'p1.PATCHNAME', 'p1.PDESC', 'p1.PDATE', 'p1.PLEVEL', 'p1.Remark', 'p3.NUMSERVER')
->leftJoinSub($numServerSubquery, 'p3', function ($join) {
$join->on('p1.PID', '=', 'p3.PatchID');
});
// if ($this->searchSelected && $this->keyword) {
// $query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
// }
$query->orderBy('p1.PID', 'DESC');
$results = $query->paginate(10);
return view('test' , compact('results'));
}
}
\ No newline at end of file
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class TransferDataController extends Controller
{
public function transferUserData()
{
set_time_limit(0);
$batchSize = 100; // Number of records to process at a time
$offset = 0;
while (true) {
$oldUsers = DB::table('tab_user')->select([
'UID',
DB::raw('CONVERT(UCODE USING utf8) AS UCODE'),
DB::raw('CONVERT(USERNAME USING utf8) AS USERNAME'),
DB::raw('CONVERT(PASSWORD USING utf8) AS PASSWORD'),
DB::raw('CONVERT(FIRSTNAME USING utf8) AS FIRSTNAME'),
DB::raw('CONVERT(LASTNAME USING utf8) AS LASTNAME'),
DB::raw('CONVERT(EMAIL USING utf8) AS EMAIL'),
DB::raw('CONVERT(PHONE USING utf8) AS PHONE'),
'APPROVED',
'APPROVEDATE',
'STATUSLOGIN',
'LASTLOGIN',
DB::raw('CONVERT(ACTIVITY USING utf8) AS ACTIVITY'),
'ACTIVITY_TIME',
DB::raw('CONVERT(PAYMENT_USER USING utf8) AS PAYMENT_USER'),
DB::raw('CONVERT(PAYMENT_PASS USING utf8) AS PAYMENT_PASS'),
DB::raw('CONVERT(PAYMENT_ORG USING utf8) AS PAYMENT_ORG'),
DB::raw('CONVERT(BUCODE USING utf8) AS BUCODE'),
])->offset($offset)
->limit($batchSize)
->get();
if ($oldUsers->isEmpty()) {
break; // No more records to process
}
foreach ($oldUsers as $oldUser) {
// if (is_null($oldUser->EMAIL)) {
// // Skip this record if email is NULL
// continue;
// }
try {
DB::table('users')->insert([
'uid' => $oldUser->UID,
'user_code' => $oldUser->UCODE,
'username' => $oldUser->USERNAME,
'password' => Hash::make($oldUser->PASSWORD),
'first_name' => $oldUser->FIRSTNAME,
'last_name' => $oldUser->LASTNAME,
'email' => $oldUser->EMAIL ?? '',
'phone' => $oldUser->PHONE,
'is_approved' => $oldUser->APPROVED === 'Y' ? true : false,
'approved_at' => isset($oldUser->APPROVEDDATE) ? $oldUser->APPROVEDDATE : null,
'status_login' => $oldUser->STATUSLOGIN,
'last_login_at' => isset($oldUser->LASTLOGIN) ? $oldUser->LASTLOGIN : null,
'activity' => isset($oldUser->ACTIVITY) ? $oldUser->ACTIVITY : null,
'activity_time' => isset($oldUser->ACTIVITY_TIME) ? $oldUser->ACTIVITY_TIME : null,
'payment_username' => isset($oldUser->PAYMENT_USER) ? $oldUser->PAYMENT_USER : null,
'payment_password' => isset($oldUser->PAYMENT_PASS) ? Hash::make($oldUser->PAYMENT_PASS) : null,
'payment_organization' => isset($oldUser->PAYMENT_ORG) ? $oldUser->PAYMENT_ORG : null,
'bu_code' => isset($oldUser->BUCODE) ? $oldUser->BUCODE : null,
'created_at' => now(),
'updated_at' => now(),
'deleted_at' => null,
]);
} catch (\Illuminate\Database\QueryException $ex) {
if ($ex->getCode() == 23000) {
continue; // Skip to the next iteration if duplicate entry
} else {
throw $ex;
}
}
}
$offset += $batchSize; // Move to the next batch
}
return "Data transferred successfully!";
}
}
...@@ -2,131 +2,14 @@ ...@@ -2,131 +2,14 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Group;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
class UserController extends Controller class UserController extends Controller
{ {
public function index() {
protected $route = 'user'; $menu = 'User';
protected $url = '/user'; $currentContent = 'User';
protected $prefix_folder = 'components.users.'; return view('home' ,compact('menu', 'currentContent'));
public function index(Request $request)
{
$serchSelected = '';
$keyword = '';
if(isset($request->search) && isset($request->keyword)) {
$serchSelected = $request->search;
$keyword = $request->keyword;
$companies = User::where($serchSelected,'LIKE','%'.$keyword.'%')->paginate(10);
}else{
$companies = User::paginate(10);
}
$url = $this->url;
$route = $this->route;
$companies->withPath($url);
$searchBy = [
"name" => "Name",
"email" => "Email",
];
return view($this->prefix_folder . 'index', compact('users', 'url', 'route', 'searchBy', 'serchSelected', 'keyword'));
}
public function create()
{
$route = $this->route;
$groups = Group::all();
return view($this->prefix_folder . 'create', compact('route', 'groups'));
}
public function edit(user $user)
{
$route = $this->route;
$groups = Group::all();
return view($this->prefix_folder . 'edit', compact('user', 'groups', 'route'));
}
public function store(Request $request)
{
$rules = array(
'name' => 'required',
'tax' => 'required|unique:companies,tax'
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
} else {
$userData = $request->except('userType');
$userData['user_type_id'] = $request->input('userType');
$user = user::create($userData);
return redirect()->route($this->route . '.list')
->withSuccess(__('user created successfully.'));
}
}
public function update(Request $request, user $user)
{
$rules = array(
'name' => 'required',
'tax' => 'required'
);
$validator = Validator::make($request->all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
} else {
$userData = $request->except('userType');
$userData['user_type_id'] = $request->input('userType');
$user->update($userData);
return redirect()->route($this->route . '.list')
->withSuccess(__('user created successfully.'));
}
}
public function destroy(user $user)
{
$user->delete();
return redirect()->route($this->route . '.list')
->withSuccess(__('user deleted successfully.'));
}
public function getUsers()
{
$users = User::select('id', 'name', 'email')->get();
$formattedUsers = [];
foreach ($users as $user) {
$formattedUsers[] = [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
];
}
return response()->json(['users' => $formattedUsers]);
} }
} }
...@@ -63,6 +63,7 @@ class Kernel extends HttpKernel ...@@ -63,6 +63,7 @@ class Kernel extends HttpKernel
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'disableDebugbar' => \App\Http\Middleware\DisableDebugbar::class,
]; ];
protected $commands = [ protected $commands = [
......
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Jfcherng\Diff\Differ;
use Jfcherng\Diff\DiffHelper;
use Jfcherng\Diff\Factory\RendererFactory;
use Jfcherng\Diff\Renderer\RendererConstant;
use Jfcherng\Diff\Renderer\Html\Inline;
class CodeComparer extends Component
{
public $code;
public $gitCode;
public $gitCodeRaw;
public $comparisonResult;
public $diffResult;
public function mount()
{
$this->code = '';
$this->gitCodeRaw = $this->getCodeFromGit();
$this->gitCode = (iconv('TIS-620', 'UTF-8', $this->gitCodeRaw));
$this->diffResult = '';
}
public function compare()
{
try {
$this->gitCodeRaw = $this->getCodeFromGit();
$this->gitCode = (iconv('TIS-620', 'UTF-8', $this->gitCodeRaw));
$this->comparisonResult = 'GitLab connection successful.';
$this->diffResult = $this->getDiff($this->gitCode, $this->code);
// dd($this->diffResult);
$this->emit('diffResultUpdated');
} catch (RequestException $e) {
$this->comparisonResult = 'Error connecting to GitLab: ' . $e->getMessage();
$this->gitCode = '';
$this->gitCodeRaw = '';
}
}
public function getDiff($code1, $code2)
{
$diffOptions = [
'context' => 0,
'ignoreCase' => false,
'ignoreWhitespace' => true,
];
$rendererOptions = [
'detailLevel' => 'char',
'language' => 'eng',
'lineNumbers' => true,
'separateBlock' => true,
'showHeader' => true,
'spacesToNbsp' => false,
'outputFormat' => 'inline',
'mergeThreshold' => 0.8,
'originalFileName' => 'Original',
'newFileName' => 'New',
'cliColorization' => 'none',
];
$differ = new Differ(explode("\n", $code1), explode("\n", $code2), $diffOptions);
$renderer = RendererFactory::make('Inline', $rendererOptions);
$result = $renderer->render($differ);
$result = $this->convertDiffToPrismFormat($result);
return $result;
}
private function convertDiffToPrismFormat($diffHtml)
{
$diffHtml = str_replace('<tr data-type="-"', '<tr class="token deleted"', $diffHtml);
$diffHtml = str_replace('<tr data-type="+"', '<tr class="token inserted"', $diffHtml);
$diffHtml = str_replace('<td class="old">', '<td class="token deleted">', $diffHtml);
$diffHtml = str_replace('<td class="new">', '<td class="token inserted">', $diffHtml);
$diffHtml = str_replace('<th class="sign del">-</th>', '', $diffHtml);
$diffHtml = str_replace('<th class="sign ins">+</th>', '', $diffHtml);
return $diffHtml;
}
public function getCodeFromGit()
{
$projectId = 60; // ใช้ Project ID ที่ถูกต้อง
$filePath = 'IE5DEV.shippingnet/USERFUNC.inc'; // เส้นทางไฟล์ที่ถูกต้อง
$branch = 'master'; // หรือ branch ที่คุณต้องการ
$token = env('GITLAB_API_TOKEN');
$client = new Client([
'base_uri' => 'https://idemo.netbay.co.th/gitlab/api/v4/',
'headers' => [
'Authorization' => "Bearer $token",
'Accept' => 'application/json',
],
'verify' => false,
]);
try {
$response = $client->get("projects/$projectId/repository/files/" . urlencode($filePath) . "/raw", [
'query' => ['ref' => $branch]
]);
$statusCode = $response->getStatusCode();
$content = $response->getBody()->getContents();
if ($statusCode == 200) {
return $content;
} else {
throw new \Exception("Failed to fetch file. Status code: $statusCode");
}
} catch (RequestException $e) {
$this->comparisonResult = 'RequestException: ' . $e->getMessage();
throw $e;
} catch (\Exception $e) {
$this->comparisonResult = 'Exception: ' . $e->getMessage();
throw $e;
}
}
public function render()
{
//asdsda
return view('livewire.code-comparer');
}
}
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Company;
class DeleteItemModal extends Component
{
public $showModal = false;
public $deleteId;
protected $listeners = ['showDeleteItemModal'];
public function showDeleteItemModal($deleteId)
{
$this->deleteId = $deleteId;
$this->showModal = true;
}
public function closeModal()
{
$this->showModal = false;
}
public function render()
{
return view('livewire.delete-item-modal',['deleteId' => $this->deleteId]);
}
}
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Company;
class DeleteModal extends Component
{
public $showModal = false;
public $deleteId;
protected $listeners = ['showDeleteModal'];
public function showDeleteModal($deleteId)
{
$this->deleteId = $deleteId;
$this->showModal = true;
}
public function closeModal()
{
$this->showModal = false;
}
public function render()
{
return view('livewire.delete-modal',['deleteId' => $this->deleteId]);
}
}
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class MainContainer extends Component
{
public $currentContent = '';
public $loading = false;
public $pagePaginate = 1;
protected $listeners = ['menuChanged' => 'loadContent' , 'updatePagePaginate'];
public function loadContent($menu)
{
$this->loading = true;
$this->currentContent = $menu;
$this->loading = false;
}
public function updatePagePaginate($page) {
$this->pagePaginate = $page;
}
public function render()
{
return view('livewire.main-container');
}
}
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Navbar extends Component
{
public $currentMenu = 'DeleteMultiPatch';
public $navLoaded = false;
public $userName ;
public function mount() {
$this->userName = auth()->user()->username;
}
public function loadNav()
{
$this->navLoaded = true;
}
public function loadContent($menu)
{
$this->currentMenu = $menu;
$this->emit('menuChanged', $menu);
}
public function render()
{
return view('livewire.navbar');
}
}