Commits (172)
......@@ -14,4 +14,7 @@ yarn-error.log
/.idea
/.vscode
composer.lock
package-lock.json
\ No newline at end of file
package-lock.json
bootstrap/cache/livewire-components.php
bootstrap/cache/packages.php
bootstrap/cache/services.php
stages:
- sonar_scan
sonar_scan:
stage: sonar_scan
only :
- test-sonar
image: maven:3.8.1-jdk-11 # Use an appropriate image
script:
- apt-get update && apt-get install -y wget unzip
- wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.6.2.2472-linux.zip
- unzip sonar-scanner-cli-4.6.2.2472-linux.zip
- export PATH="$PATH:$(pwd)/sonar-scanner-4.6.2.2472-linux/bin"
- sonar-scanner -D"sonar.projectKey=SpnPatchLaravel" -D"sonar.sources=." -D"sonar.host.url=https://sonarqube.netbay.co.th/sonarqube" -D"sonar.login=910cc03c818c8884525a2c3f2b1d19cd8d98104f"
\ No newline at end of file
projectKey=SpnPatch
serverUrl=http://localhost:9000
serverVersion=10.6.0.92116
dashboardUrl=http://localhost:9000/dashboard?id=SpnPatch
ceTaskId=3cb72c3b-d0f7-4dc9-93aa-c683752993ab
ceTaskUrl=http://localhost:9000/api/ce/task?id=3cb72c3b-d0f7-4dc9-93aa-c683752993ab
# ใช้ภาพพื้นฐานของ PHP เวอร์ชัน 8.2 พร้อมกับ FPM
FROM php:8.2-fpm
# ติดตั้งส่วนขยายและโปรแกรมที่จำเป็น
RUN apt-get update && apt-get install -y \
git \
curl \
libpng-dev \
libjpeg-dev \
libfreetype6-dev \
zip \
unzip \
libzip-dev \
pkg-config \
&& docker-php-ext-configure zip \
&& docker-php-ext-install pdo_mysql gd zip
# ติดตั้ง Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# กำหนด Working Directory
WORKDIR /var/www/html
# ลบ node_modules หากมีอยู่แล้ว
RUN rm -rf node_modules
# คัดลอกไฟล์ทั้งหมดจากโฟลเดอร์ปัจจุบันไปยัง Container
COPY . .
# กำหนดสิทธิ์ให้ถูกต้อง
RUN chown -R www-data:www-data /var/www/html
# ติดตั้ง Dependencies ของ PHP
RUN composer install --no-dev --optimize-autoloader
# ติดตั้ง Node.js และ Vite
RUN curl -sL https://deb.nodesource.com/setup_16.x | bash - \
&& apt-get install -y nodejs \
&& npm ci
# กำหนดสิทธิ์ให้กับโฟลเดอร์ .npm
RUN mkdir -p /var/www/.npm && chown -R www-data:www-data /var/www/.npm
# รัน build assets
USER www-data
RUN npm run build
# เปิดพอร์ต 9000 เพื่อใช้งาน PHP-FPM
EXPOSE 9000
CMD ["php-fpm"]
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class ExportProgressUpdated implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $progress;
public function __construct($progress)
{
$this->progress = $progress;
}
public function broadcastOn()
{
return new Channel('export-progress');
}
}
\ No newline at end of file
<?php
namespace App\Exports;
use App\Models\ConfServerLicense;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithMapping;
class ServerLicenseExport implements FromCollection, WithHeadings, WithColumnFormatting, WithMapping
{ public function collection()
{
$select = "
SELECT c.`SNKEY` as 'SNKEY', c.`COMPANY`, c.`STATUS`, c.`LICENSEDATE`, c.`BACKUP_DATE`,
c.`CUR_VERSION`, c.`INSTALL_DATE`, c.`INSTALL_VERSION`, c.`DATABASETYPE`, c.`OWNERTYPE`,
c.`NBTEAM`, c.`CUSTOMERSIZE`, c.`CUSTOMERTYPE`, c.`CUSTOMERBRANCH`, c.`CONTACTCUSTOMERNAME`,
c.`CONTACT`, c.`CUSTOMERURL`, c.`MESSAGETYPE`, c.`PHP_VERSION_ID`, j.`javaversion` as 'JAVA_VERSION'
FROM conf_server_license c
LEFT JOIN conf_server_license_javaversion j ON c.SNKEY = j.SNKEY
";
return collect(DB::select($select));
}
public function headings(): array
{
return [
'SNKEY', 'COMPANY', 'STATUS', 'LICENSEDATE', 'BACKUP_DATE', 'CUR_VERSION', 'INSTALL_DATE', 'INSTALL_VERSION',
'DATABASETYPE', 'OWNERTYPE', 'NBTEAM', 'CUSTOMERSIZE', 'CUSTOMERTYPE', 'CUSTOMERBRANCH', 'CONTACTCUSTOMERNAME',
'CONTACT', 'CUSTOMERURL', 'MESSAGETYPE', 'PHP_VERSION_ID', 'JAVA VERSION'
];
}
public function columnFormats(): array
{
return [
'A' => NumberFormat::FORMAT_TEXT,
];
}
public function map($row): array
{
return [
'`' . $row->SNKEY, // Add a backtick (`) to enforce text format in Excel
$row->COMPANY,
$row->STATUS,
$row->LICENSEDATE,
$row->BACKUP_DATE,
$row->CUR_VERSION,
$row->INSTALL_DATE,
$row->INSTALL_VERSION,
$row->DATABASETYPE,
$row->OWNERTYPE,
$row->NBTEAM,
$row->CUSTOMERSIZE,
$row->CUSTOMERTYPE,
$row->CUSTOMERBRANCH,
$row->CONTACTCUSTOMERNAME,
$row->CONTACT,
$row->CUSTOMERURL,
$row->MESSAGETYPE,
$row->PHP_VERSION_ID,
$row->JAVA_VERSION,
];
}
}
......@@ -17,6 +17,30 @@ class AuthController extends Controller
return view('login');
}
// public function login(Request $request)
// {
// $validator = Validator::make($request->all(), [
// 'username' => ['required'],
// 'password' => ['required'],
// ]);
// if ($validator->fails()) {
// return redirect()->back()->withErrors($validator)->withInput();
// }
// $credentials = [
// 'USERNAME' => $request->input('username'),
// 'password' => $request->input('password')
// ];
// $user = TabUser::where('USERNAME', 'sarun')->where('PASSWORD', 'sarun')->first();
// if (Auth::loginUsingId($user->UID)) {
// return redirect()->route('index');
// } else {
// $errors = new \Illuminate\Support\MessageBag();
// $errors->add('password', 'The password does not match with username');
// return redirect()->back()->withErrors($errors)->withInput();
// }
// }
public function login(Request $request)
{
......@@ -28,30 +52,37 @@ class AuthController extends Controller
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
$credentials = [
'USERNAME' => $request->input('username'),
'password' => $request->input('password')
];
$user = TabUser::where('USERNAME', 'sarun')->where('PASSWORD', 'sarun')->first();
if (Auth::loginUsingId($user->UID)) {
$validated = $validator->validated();
if (Auth::attempt(array('username' => $validated['username'], 'password' => $validated['password']))) {
// $token = auth()->user()->createToken('app1_token')->plainTextToken;
// session(['shared_user_id' => auth()->id()]);
return redirect()->route('index');
} else {
$errors = new \Illuminate\Support\MessageBag();
$errors->add('password', 'The password does not match with username');
return redirect()->back()->withErrors($errors)->withInput();
$validator->errors()->add(
'password',
'The password does not match with username'
);
return redirect()->back()->withErrors($validator)->withInput();
}
}
public function registerView(){
public function registerView()
{
return view('register');
}
public function register(Request $request){
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string'],
'email' => ['required', 'email','unique:users'],
'password' => ['required',"confirmed", Password::min(7)],
'email' => ['required', 'email', 'unique:users'],
'password' => ['required', "confirmed", Password::min(7)],
]);
$validated = $validator->validated();
......
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CompanyController extends Controller
{
public function index() {
$menu = 'Company';
$currentContent = 'Company';
return view('home' ,compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class ConvertToJsonController extends Controller
{
public function convert()
{
// Path ของโฟลเดอร์ที่เก็บไฟล์ .inc
$formatPath = storage_path('format');
// Path ของโฟลเดอร์ที่เก็บไฟล์ JSON
$jsonPath = storage_path('json');
// ตรวจสอบว่ามีโฟลเดอร์ JSON หรือไม่ ถ้าไม่มีให้สร้างขึ้นมา
if (!file_exists($jsonPath)) {
mkdir($jsonPath, 0777, true);
}
// อ่านไฟล์ทั้งหมดในโฟลเดอร์ format
$files = scandir($formatPath);
foreach ($files as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) === 'inc') {
// อ่านเนื้อหาของไฟล์ .inc
$fileContent = file_get_contents($formatPath . '/' . $file);
// ตรวจสอบว่ามีข้อมูลที่ไม่ต้องการหรือไม่
$DATABASE = '';
$PKEY = [];
$FORMAT = [];
// ใช้ eval เพื่อทำให้ PHP เข้าใจเนื้อหาในไฟล์ (ควรระวัง)
eval('?>' . $fileContent);
// สร้าง array จากข้อมูลในไฟล์
$data = [
'database' => $DATABASE,
'primary_key' => $PKEY,
'format' => $FORMAT,
];
// แปลง array เป็น JSON
$jsonContent = json_encode($data, JSON_PRETTY_PRINT);
// เขียน JSON ลงในไฟล์ใหม่ในโฟลเดอร์ json
$jsonFileName = pathinfo($file, PATHINFO_FILENAME) . '.json';
file_put_contents($jsonPath . '/' . $jsonFileName, $jsonContent);
}
}
return response()->json(['message' => 'Conversion complete!']);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DeletePatchController extends Controller
{
public function indexMulti() {
$menu = 'DeleteMultiPatch';
$currentContent = 'DeleteMultiPatch';
return view('home' ,compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DischargePortController extends Controller
{
public function index() {
$menu = 'DischargePort';
$currentContent = 'DischargePort';
return view('home' ,compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ExchangeRateController extends Controller
{
public function index() {
$menu = 'ExchangeRate';
$currentContent = 'ExchangeRate';
return view('home' ,compact('menu', 'currentContent'));
}
public function creatPatch() {
$menu = 'PatchExchangeRate';
$currentContent = 'PatchExchangeRate';
return view('home' ,compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FormatFileMasterContrller extends Controller
{
public function index()
{
$menu = 'FormatFileMaster';
$currentContent = 'FormatFileMaster';
return view('home', compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class GroupController extends Controller
{
public function index() {
$menu = 'Group';
$currentContent = 'Group';
return view('home' ,compact('menu', 'currentContent'));
}
}
......@@ -6,8 +6,11 @@ use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index() {
dd("ddd");
return view("home");
public function index()
{
$menu = '';
$currentContent = '';
return view('home', compact('menu', 'currentContent'));
}
}
<?php
namespace App\Http\Controllers\ManualResponse;
use App\Http\Controllers\Controller;
use App\Models\ManualResponse\MasterResponseTemplates;
use App\Models\ManualResponse\DeclarationRunning;
use Illuminate\Support\Facades\DB;
use SimpleXMLElement;
use DOMDocument;
use Carbon\Carbon;
class GenXmlController extends Controller
{
public function generateXML($templateId, $documentType, $lockData)
{
$template = MasterResponseTemplates::join('mr_master_messages as mm', 'mr_master_response_templates.mid', '=', 'mm.id')
->select('mm.name as messageName', 'mr_master_response_templates.id as templateId', 'mr_master_response_templates.template')
->where('mr_master_response_templates.id', $templateId)
->first();
if (empty($template)) {
return null;
}
$json = json_decode($template['template'], true);
if($json != null){
return $this->genXmlFromTemplate($json, $documentType, $lockData);
}
}
private function genXmlFromTemplate($json, $documentType = '0', $lockData = true, $xml = null, &$xmlData = [])
{
if ($xml === null) {
$rootElement = $json['root'];
$namespace = $json['namespace'];
unset($json['root'], $json['namespace']);
if($namespace !== ''){
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"UTF-8\"?><$rootElement xmlns=\"$namespace\"></$rootElement>");
}else{
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"UTF-8\"?><$rootElement></$rootElement>");
}
}
foreach ($json as $key => $value) {
if (is_array($value)) {
if (is_numeric($key)) {
$key = 'item' . $key; // dealing with <0/>..<n/> issues
}
$new_object = $xml->addChild($key);
$this->genXmlFromTemplate($value, $documentType, $lockData, $new_object, $xmlData); // Pass by reference
} else {
if (is_numeric($key)) {
$key = 'item' . $key; // dealing with <0/>..<n/> issues
}
if (empty($value)) {
if($key == 'DeclarationNumber' && ($documentType !== null && $documentType != '')){
$value = $this->generateDeclarationNo($documentType);
}else if($key == 'GoodsTransitionNumber'){
$value = $this->generateGCLNo();
}
if(in_array($key, ['AuditDateTime', 'ErrorDate'])){
$value = Carbon::now()->setTimezone('GMT+7')->format('Y-m-d\TH:i:s');
}
$child = $xml->addChild($key);
$child[0] = ''; // Ensure closed tag for empty value
} else {
$xml->addChild($key, htmlspecialchars($value));
}
$xmlData[$key] = $value; // Collect all tags as editable input html
}
}
//$this->updateXmlValues($this->formatXml($xml->asXML()), $xmlNoData)
return ['xmlContent' => $this->formatXml($xml->asXML()),
'xmlWithData' => $xmlData
];
}
//Convert short tag in case of value is empty to closed tag
private function formatXml($xmlString)
{
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xmlString);
// Ensure empty tags are closed
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('//*[not(*) and not(text())]') as $node) {
$node->nodeValue = ''; // Set node value to empty string to ensure closed tag
}
return $dom->saveXML();
}
public function updateXmlValues($xmlString, $tagsToUpdate)
{
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadXML($xmlString);
foreach ($tagsToUpdate as $tag => $value) {
$nodes = $dom->getElementsByTagName($tag);
foreach ($nodes as $node) {
$node->nodeValue = htmlspecialchars($value);
}
}
return $dom->saveXML();
}
private function generateDeclarationNo($documentType)
{
$currentDate = Carbon::now()->toDateString();
$maxRunningNumber = 999999;
$running = DB::transaction(function () use ($currentDate, $maxRunningNumber, $documentType) {
$runningNumberRecord = DeclarationRunning::lockForUpdate()->where('document_type', $documentType)->first();
if ($runningNumberRecord) {
if ($runningNumberRecord->last_updated_date !== $currentDate) {
// Reset the running number if the date has changed
$runningNumberRecord->running_number = 1;
$runningNumberRecord->last_updated_date = $currentDate;
} elseif ($runningNumberRecord->running_number >= $maxRunningNumber) {
// Reset the running number if it reaches the max value
$runningNumberRecord->running_number = 1;
} else {
// Increment the running number
$runningNumberRecord->running_number += 1;
}
$runningNumberRecord->save();
} else {
// Create a new record if none exists
$runningNumberRecord = DeclarationRunning::create([
'running_number' => 1,
'last_updated_date' => $currentDate,
'document_type' => $documentType,
]);
}
return str_pad($runningNumberRecord->running_number, 6, '0', STR_PAD_LEFT);
});
$tmp_declarationNo = [
"A",
substr($running, 0, 1),
Carbon::now()->format('d'),
$documentType,
substr(Carbon::now()->year + 543, -2),
Carbon::now()->format('m'),
substr($running, -5)
];
return implode('', $tmp_declarationNo);
}
function generateGCLNo(){
$currentDate = Carbon::now()->toDateString();
$maxRunningNumber = 9999999;
$running = DB::transaction(function () use ($currentDate, $maxRunningNumber) {
$runningNumberRecord = DeclarationRunning::lockForUpdate()->where('document_type', "GCL")->first();
if ($runningNumberRecord) {
if ($runningNumberRecord->last_updated_date !== $currentDate) {
// Reset the running number if the date has changed
$runningNumberRecord->running_number = 1;
$runningNumberRecord->last_updated_date = $currentDate;
} elseif ($runningNumberRecord->running_number >= $maxRunningNumber) {
// Reset the running number if it reaches the max value
$runningNumberRecord->running_number = 1;
} else {
// Increment the running number
$runningNumberRecord->running_number += 1;
}
$runningNumberRecord->save();
} else {
// Create a new record if none exists
$runningNumberRecord = DeclarationRunning::create([
'running_number' => 1,
'last_updated_date' => $currentDate,
'document_type' => "GCL",
]);
}
return str_pad($runningNumberRecord->running_number, 7, '0', STR_PAD_LEFT);
});
$tmp_GCLNo = [
substr(Carbon::now()->year + 543, -2),
Carbon::now()->format('m'),
"A",
$running
];
return implode('', $tmp_GCLNo);
}
}
<?php
namespace App\Http\Controllers\ManualResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ManualResponseController extends Controller
{
public function index()
{
//return view('manual-response/index');
$currentContent = 'ManualResponse';
return view('.home', compact('currentContent'));
}
}
<?php
namespace App\Http\Controllers\ManualResponse;
use App\Models\ManualResponse\UsersConnectSpn;
use App\Http\Controllers\Controller;
class SpnConfigController extends Controller
{
public function init_connection(UsersConnectSpn $user)
{
$username = $user->username;
$password = $user->password;
$link = $user->link;
// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$link/spn/login_api.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the Authorization header for Basic Auth
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Basic ' . base64_encode("$username:$password"),
]);
// Execute cURL request
$response = curl_exec($ch);
$error = curl_error($ch); // Check for errors
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//dd($response, $error, $httpCode); //Debug response of cURL
if ($error) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable peer verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Disable host verification
$response = curl_exec($ch);
$error = curl_error($ch); // Check for errors
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
curl_close($ch); // Close the cURL handle
if($httpCode == '404'){
return [
'success' => 'false',
'message' => 'This endpoint is invaid or not support this feature. Please revise or update patch before submit.'
];
}
if ($error) {
return [
'success' => 'false',
'message' => 'cURL Error: ' . $error
];
}
// Process the response
$decodedResponse = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
session()->flash('error', 'Invalid JSON response');
return null; // Handle invalid JSON appropriately
}
return $decodedResponse; // Return the decoded response
}
}
<?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;
}
}