<?php
namespace App\Http\Livewire\Pages\Parameter;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\ConfParameter;
use App\Models\TabParameterInfo;
use App\Models\TabSpnpage;
use App\Models\TabParameterImg;
use App\Models\TabUser;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
class ParameterEdit extends Component
{
use WithFileUploads;
public $parameterId;
public $name, $value, $description, $active, $detail, $pageCode = [];
public $searchByPage = [];
public $images = [];
public $newImage;
public $imgdetail, $category = '1';
protected $rules = [
'name' => 'required|string|max:30',
'value' => 'required|string|max:50',
'description' => 'required|string|max:100',
'active' => 'required',
'detail' => 'required',
'pageCode' => 'required|array',
'newImage' => 'nullable|image|max:1024',
'imgdetail' => 'nullable|string|max:255',
'category' => 'nullable|string|max:100',
];
public function mount($editPid)
{
$parameter = ConfParameter::where('PID', $editPid)->firstOrFail();
$this->parameterId = $parameter->PID;
$this->name = $parameter->name;
$this->value = $parameter->value;
$this->description = $parameter->description;
$this->active = $parameter->active;
$parameterInfo = TabParameterInfo::where('parameterName', $parameter->name)->first();
if ($parameterInfo) {
$this->detail = $parameterInfo->detail;
$this->pageCode = explode(',', $parameterInfo->pageCode);
} else {
$this->detail = '';
$this->pageCode = [];
}
$this->searchByPage = TabSpnpage::select('pagecode', 'pagename')->get()->toArray();
$this->images = TabParameterImg::where('parameterCode', $parameter->name)->get();
}
public function updateParameter()
{
$this->validate();
ConfParameter::where('PID', $this->parameterId)->update([
'name' => $this->name,
'value' => $this->value,
'description' => $this->description,
'active' => $this->active,
]);
$pageCodesString = implode(',', $this->pageCode);
$parameterInfo = TabParameterInfo::where('parameterName', ConfParameter::where('PID', $this->parameterId)->value('name'))->first();
if ($parameterInfo) {
$parameterInfo->update([
'parameterName' => $this->name,
'pageCode' => $pageCodesString,
'detail' => $this->detail,
]);
} else {
TabParameterInfo::create([
'parameterName' => $this->name,
'pageCode' => $pageCodesString,
'detail' => $this->detail,
]);
}
if ($this->newImage) {
$this->uploadImage();
}
session()->flash('message', 'Parameter updated successfully!');
$this->emit('loadPage', 'list');
}
public function uploadImage()
{
$this->validate([
'newImage' => 'nullable|image|max:1024',
'category' => 'nullable|string|max:100',
]);
$user = Auth::user();
if (!$user) {
session()->flash('error', 'User not authenticated.');
return;
}
if ($this->newImage) {
$imagePath = base64_encode(file_get_contents($this->newImage->getRealPath()));
TabParameterImg::create([
'parameterCode' => $this->name,
'imgdetail' => $imagePath,
'category' => $this->category,
'uploadBy' => $user->USERNAME,
'uploadTime' => now(),
]);
$this->images = TabParameterImg::where('parameterCode', $this->name)->get();
$this->reset(['newImage', 'category']); // Reset the input fields
$this->emit('clearFileInput');
}
}
public function deleteImage($imgid)
{
$image = TabParameterImg::where('imgid', $imgid)->first();
if ($image) {
$image->delete();
$this->images = TabParameterImg::where('parameterCode', $this->name)->get();
}
}
public function render()
{
return view('livewire.pages.parameter.parameter-edit');
}
}
<?php
namespace App\Http\Livewire\Pages\Parameter;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\ConfParameter;
use App\Models\TabParameterInfo;
use App\Models\TabSpnpage;
class ParameterIndex extends Component
{
use WithPagination;
public $action = 'list';
public $searchBy, $searchByPage, $editPid, $message, $keyword, $perPage = 20, $searchSelected = 'name', $searchSelectedPage = '';
public $selectedParameters = [];
public $deletePid;
public $totalItems;
protected $listeners = [
'deleteItem',
'deleteSelected',
'showparameterListForm',
'loadPage'
];
public function mount()
{
$this->searchBy = [
'name' => 'By Name',
'value' => 'By Value',
'description' => 'By Description'
];
$this->searchByPage = TabSpnpage::select('pagecode', 'pagename')->get()->toArray();
logger($this->searchByPage);
}
public function render()
{
$query = ConfParameter::select('conf_parameter.PID', 'conf_parameter.name', 'conf_parameter.value', 'conf_parameter.description', 'conf_parameter.active', 'tab_parameter_info.pageCode', 'tab_parameter_info.detail')
->leftJoin('tab_parameter_info', 'conf_parameter.name', '=', 'tab_parameter_info.parameterName');
if ($this->searchSelected && $this->keyword) {
$query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
}
if ($this->searchSelectedPage) {
$query->where('tab_parameter_info.pageCode', $this->searchSelectedPage);
}
$query->orderBy('PID', 'DESC');
$results = $query->paginate($this->perPage);
$this->totalItems = $results->total();
return view('livewire.pages.parameter.parameter-index', compact('results'));
}
public function updatedPerPage($value)
{
$this->adjustPageForNewPerPage();
}
public function adjustPageForNewPerPage()
{
$lastPage = ceil($this->totalItems / $this->perPage);
if ($this->page > $lastPage) {
$this->setPage($lastPage);
}
}
public function search()
{
$this->resetPage();
}
public function showparameterListForm()
{
$this->action = 'list';
}
public function showparameterAddForm()
{
$this->action = 'add';
}
public function showparameterEditForm($pid)
{
$this->editPid = $pid;
$this->action = 'edit';
}
public function showparameterDeleteForm($pid)
{
$this->deletePid = $pid;
$this->action = 'delete';
}
public function deleteParameter($pid)
{
$parameter = ConfParameter::where('PID', $pid)->firstOrFail();
$parameterName = $parameter->name;
ConfParameter::where('PID', $pid)->delete();
TabParameterInfo::where('parameterName', $parameterName)->delete();
session()->flash('message', 'Parameter deleted successfully!');
$this->showparameterListForm();
}
public function deleteSelectedParameters()
{
$parameters = ConfParameter::whereIn('PID', $this->selectedParameters)->get();
foreach ($parameters as $parameter) {
$parameterName = $parameter->name;
ConfParameter::where('PID', $parameter->PID)->delete();
TabParameterInfo::where('parameterName', $parameterName)->delete();
}
session()->flash('message', 'Selected parameters deleted successfully!');
$this->selectedParameters = [];
$this->showparameterListForm();
}
public function deleteItem($pid)
{
$this->deleteParameter($pid);
}
public function deleteSelected()
{
$this->deleteSelectedParameters();
}
public function loadPage($page)
{
$this->action = $page;
//$this->parameters = ConfParameter::all();
}
}
<?php
namespace App\Http\Livewire\Pages\Patch;
use App\Models\TabPatchFile;
use Livewire\Component;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Jfcherng\Diff\Differ;
use Jfcherng\Diff\DiffHelper;
use Jfcherng\Diff\Factory\RendererFactory;
class ModalEditCode extends Component
{
public $openModalEditCode = false;
public $patchFileId, $patchFile, $gitCode, $gitCodeRaw, $dbCode, $commit, $selectedProject, $comparisonResult, $diffResult, $message;
public $preImpHeader;
public $isOpenEditCode = false;
protected $listeners = ['openModalEditCode' , 'deleteSubItem'];
public function openModalEditCode($patchFileId, $selectedProject)
{
$this->selectedProject = $selectedProject;
$this->patchFileId = $patchFileId;
$patchFile = TabPatchFile::where('fid', $this->patchFileId)->first();
$this->patchFile = $patchFile->file_name;
$this->dbCode = base64_decode($patchFile->file_content); // Adjust accordingly based on your database schema
$this->gitCodeRaw = $this->getFileContentFromGit($this->patchFile, $this->commit);
try {
$this->gitCode = (iconv('TIS-620', 'UTF-8', $this->gitCodeRaw));
} catch (\Throwable $th) {
$this->gitCode = "This is image cannot show !";
}
$this->isOpenEditCode = true;
}
public function closeModal()
{
$this->isOpenEditCode = false;
}
public function updateCode()
{
}
private function getFileContentFromGit($filePath, $commit)
{
$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,
]);
if (strpos($filePath, "../SPN/") !== false) {
$filePath = str_replace("../SPN/", "SPN/", $filePath);
} else if (strpos($filePath, "../spn/") !== false) {
$filePath = str_replace("../spn/", "spn/", $filePath);
} else {
$filePath = str_replace("./", "IE5DEV.shippingnet/", $filePath);
}
try {
$response = $client->get("projects/{$this->selectedProject}/repository/files/" . urlencode($filePath) . "/raw", [
'query' => ['ref' => $commit]
]);
$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) {
throw $e;
} catch (\Exception $e) {
throw $e;
}
}
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;
}
public function compare()
{
try {
// $this->comparisonResult = 'GitLab connection successful.';
$this->diffResult = $this->getDiff($this->gitCode, $this->dbCode);
// dd($this->diffResult);
$this->emit('diffResultUpdated');
} catch (RequestException $e) {
$this->comparisonResult = 'Error connecting to GitLab: ' . $e->getMessage();
$this->gitCode = '';
$this->gitCodeRaw = '';
}
}
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 showDeleteItemModal($patchFileId)
{
$this->emit('showDeleteItemModal' ,$patchFileId);
}
public function deleteSubItem($patchFileId) {
$pathFile = TabPatchFile::where("fid", $patchFileId)->first();
$patchId = $pathFile->ptid;
$pathFile = TabPatchFile::where("fid", $patchFileId)->delete();
$message = "Deleted File ID : " . json_encode($patchFileId) . " Successfully";
$this->message = $message;
$this->emit('reloadComponent', $patchId);
$this->isOpenEditCode = false;
}
public function render()
{
return view('livewire.pages.patch.modal-edit-code');
}
}
<?php
namespace App\Http\Livewire\Pages\Patch;
use App\Models\TabPatchFile;
use Livewire\Component;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Jfcherng\Diff\Differ;
use Jfcherng\Diff\DiffHelper;
use Jfcherng\Diff\Factory\RendererFactory;
class ModalFormPatchFile extends Component
{
public $openModalFormPatchFile = false;
public $patchFileId, $patchId, $patchFile, $dbCode, $fileName, $commit, $comparisonResult, $diffResult, $message;
public $preImpHeader;
public $isOpenFormPatchFile = false;
protected $listeners = ['openModalFormPatchFile', 'deleteSubItem'];
public function openModalFormPatchFile($patchFileId = null, $patchId = null)
{
$this->patchFileId = $patchFileId;
$this->patchId = $patchId;
if (isset($patchFileId) && $patchFileId !== '') {
$patchFile = TabPatchFile::where('fid', $this->patchFileId)->first();
$this->patchFile = $patchFile->file_name;
$this->dbCode = base64_decode($patchFile->file_data);
$this->dbCode = (iconv('TIS-620', 'UTF-8', $this->dbCode));
}else{
$this->patchFile = '';
$this->dbCode = '';
}
$this->isOpenFormPatchFile = true;
}
public function closeModal()
{
$this->isOpenFormPatchFile = false;
}
public function updateCode()
{
}
private function getFileContentFromGit($filePath, $commit)
{
$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,
]);
if (strpos($filePath, "../SPN/") !== false) {
$filePath = str_replace("../SPN/", "SPN/", $filePath);
} else if (strpos($filePath, "../spn/") !== false) {
$filePath = str_replace("../spn/", "spn/", $filePath);
} else {
$filePath = str_replace("./", "IE5DEV.shippingnet/", $filePath);
}
try {
$response = $client->get("projects/{$this->selectedProject}/repository/files/" . urlencode($filePath) . "/raw", [
'query' => ['ref' => $commit]
]);
$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) {
throw $e;
} catch (\Exception $e) {
throw $e;
}
}
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;
}
public function compare()
{
try {
// $this->comparisonResult = 'GitLab connection successful.';
$this->diffResult = $this->getDiff($this->gitCode, $this->dbCode);
// dd($this->diffResult);
$this->emit('diffResultUpdated');
} catch (RequestException $e) {
$this->comparisonResult = 'Error connecting to GitLab: ' . $e->getMessage();
// $this->gitCode = '';
// $this->gitCodeRaw = '';
}
}
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 showDeleteItemModal($patchFileId)
{
$this->emit('showDeleteItemModal', $patchFileId);
}
public function deleteSubItem($patchFileId)
{
$pathFile = TabPatchFile::where("fid", $patchFileId)->first();
$patchId = $pathFile->ptid;
$pathFile = TabPatchFile::where("fid", $patchFileId)->delete();
$message = "Deleted File ID : " . json_encode($patchFileId) . " Successfully";
$this->message = $message;
$this->emit('reloadComponent', $patchId);
$this->isOpenFormPatchFile = false;
}
public function render()
{
return view('livewire.pages.patch.modal-form-patch-file');
}
public function saveCode($dbCode, $fileName)
{
$dbCode = (iconv('UTF-8', 'TIS-620', $dbCode));
if (isset($this->patchFileId) && $this->patchFileId !== '') {
$pathFile = TabPatchFile::where("fid", $this->patchFileId)->first();
$pathFile->file_name = $fileName;
$pathFile->file_data = base64_encode($dbCode);
$pathFile->save();
} else {
$filepath = new TabPatchFile;
$filepath->ptid = $this->patchId;
$filepath->file_name = $fileName;
$filepath->file_data = base64_encode($dbCode);
$filepath->save();
}
$this->isOpenFormPatchFile = false;
$this->emit('reloadComponent',$this->patchId );
}
}
<?php
namespace App\Http\Livewire\Pages\Patch;
use GuzzleHttp\Exception\RequestException;
use App\Models\ConfSmartupdate;
use App\Models\MasterPhpVer;
use App\Models\TabPatchFile;
use Livewire\Component;
use GuzzleHttp\Client;
use ZipArchive;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
class PatchCreate extends Component
{
public $projects = [];
public $branches = [];
public $selectedProject;
public $selectedBranch;
public $startCommit = '';
public $endCommit = '';
public $fileChanges = [], $filePathChanges = [];
public $searchProject = 'SPN64Bits';
public $UNINSTALL = '$b=1';
public $PATCHNAME, $PDATE, $PHP_VERSION = 0, $PLEVEL, $PCODE, $MAJOR_VERSION, $PDESC, $Remark, $POWNER,$POWNERNAME, $PAPPROVEDATE, $PTYPE, $SPECIFIC_CUSTOMER, $PATCHCODE, $PATCHCODE_SERVER;
public function mount()
{
$this->PDATE = date("Y-m-d H:i:s");
$this->PAPPROVEDATE = date("Y-m-d H:i:s");
$this->PLEVEL = 'High';
$this->POWNERNAME = auth()->user()->username??'';
$this->PATCHCODE = 'function updatePatchFile($PATH_APP,$content){
$handle = fopen($PATH_APP, "w");
fputs($handle,base64_decode($content));
fclose($handle);
}
updatePatchFile("$$file_name_0","$$file_data_0");
$PATCH_STATUS="OK";';
$nextPid = ConfSmartupdate::max('PID') + 1;
$this->PATCHCODE_SERVER = '$a=1;
Query2Array("select * from tab_patch_file where ptid=' . "'" . $nextPid . "'" . '");
for($i=0;$i<count($fid);$i++){
${\'file_name_\'.$i}=$file_name[$i];
${\'file_data_\'.$i}=$file_data[$i];
}
$max=count($fid);';
}
public function updatedSearchProject()
{
$this->fetchProjects();
}
public function fetchProjects()
{
$client = new Client([
'headers' => [
'Authorization' => 'Bearer ' . env('GITLAB_API_TOKEN'),
'Accept' => 'application/json',
],
'verify' => false,
]);
$page = 1;
$perPage = 100;
$response = $client->get(env('GITLAB_API_URL') . '/projects', [
'query' => [
'membership' => true,
'min_access_level' => 30,
'search' => $this->searchProject,
'per_page' => $perPage,
],
]);
$this->projects = json_decode($response->getBody(), true);
$this->dispatchBrowserEvent('projects-fetched');
}
public function updatedSelectedProject($value)
{
$this->fetchBranches($value);
}
public function fetchBranches($projectId)
{
$client = new Client([
'headers' => [
'Authorization' => 'Bearer ' . env('GITLAB_API_TOKEN'),
'Accept' => 'application/json',
],
'verify' => false,
]);
$response = $client->get(env('GITLAB_API_URL') . "/projects/{$projectId}/repository/branches");
$this->branches = json_decode($response->getBody(), true);
}
public function getChangedFiles()
{
$client = new Client([
'headers' => [
'Authorization' => 'Bearer ' . env('GITLAB_API_TOKEN'),
'Accept' => 'application/json',
],
'verify' => false,
]);
try {
$response = $client->get(env('GITLAB_API_URL') . "/projects/{$this->selectedProject}/repository/compare", [
'query' => [
'from' => $this->startCommit,
'to' => $this->endCommit,
],
]);
$data = json_decode($response->getBody(), true);
foreach ($data['diffs'] as $file) {
$this->filePathChanges[] = $file['new_path'];
}
$this->fileChanges = $this->buildTree($data['diffs']);
} catch (\Throwable $th) {
$data = '';
}
$this->dispatchBrowserEvent('files-fetched', ['fileChanges' => $this->fileChanges]);
}
private function buildTree($files)
{
$tree = [];
foreach ($files as $file) {
$path = explode('/', $file['new_path']);
$current = &$tree;
foreach ($path as $part) {
if (!isset($current[$part])) {
$current[$part] = [];
}
$current = &$current[$part];
}
// $current['id'] = $file['fid'];
}
return $tree;
}
// $changedFiles = [];
// foreach ($data['diffs'] as $file) {
// $changedFiles[] = $file['new_path'];
// }
// $zip = new ZipArchive;
// $zipFileName = storage_path('app/changed_files.zip');
// if ($zip->open($zipFileName, ZipArchive::CREATE) === TRUE) {
// foreach ($changedFiles as $file) {
// $fileResponse = $client->get(env('GITLAB_API_URL')."/projects/{$this->selectedProject}/repository/files/" . urlencode($file) . '/raw', [
// 'query' => [
// 'ref' => $this->endCommit,
// ],
// ]);
// $fileContent = $fileResponse->getBody();
// $zip->addFromString($file, $fileContent);
// }
// $zip->close();
// }
// return response()->download($zipFileName);
// }
public function save()
{
$this->validate([
'PATCHNAME' => 'required|string|max:255',
'PHP_VERSION' => 'required|in:0,1,2,3',
'PLEVEL' => 'required|string|max:255',
'MAJOR_VERSION' => 'required|string|max:255',
'PDESC' => 'required|string|max:255',
'PAPPROVEDATE' => 'required|date',
// 'PTYPE' => 'required|string|max:255',
// 'POWNER' => 'required|string|max:255',
// 'PATCHCODE' => 'required|string',
// 'UNINSTALL' => 'required|string|max:255',
// 'PATCHCODE_SERVER' => 'required|string',
]);
$codePhpVersion = MasterPhpVer::find($this->PHP_VERSION);
$confSmartUpdate = new ConfSmartUpdate();
$confSmartUpdate->PATCHNAME = $this->PATCHNAME;
$confSmartUpdate->PDATE = date("Y-m-d H:i:s");
$confSmartUpdate->PHP_VERSION_ID = $this->PHP_VERSION;
$confSmartUpdate->PLEVEL = $this->PLEVEL;
$confSmartUpdate->PCODE = $this->PCODE ?? $this->PATCHNAME;
$confSmartUpdate->MAJOR_VERSION = $this->MAJOR_VERSION;
$confSmartUpdate->PDESC = $this->PDESC;
$confSmartUpdate->Remark = $this->Remark;
$confSmartUpdate->POWNER = auth()->user()->id;
$confSmartUpdate->PAPPROVEDATE = $this->PAPPROVEDATE;
$confSmartUpdate->PTYPE = $this->PTYPE ?? ' ';
$confSmartUpdate->PATCHCODE = ($codePhpVersion->check_code ?? '') . " " . $this->PATCHCODE;
$confSmartUpdate->UNINSTALL = $this->UNINSTALL;
$confSmartUpdate->PATCHCODE_SERVER = $this->PATCHCODE_SERVER;
$confSmartUpdate->save();
if (count($this->filePathChanges) > 0) {
foreach ($this->filePathChanges as $file) {
$filedata = $this->getFileContentFromGit($file, $this->endCommit);
$filePath = $this->formatFilePath($file);
$filepath = new TabPatchFile;
$filepath->ptid = $confSmartUpdate->PID;
$filepath->file_name = $filePath;
$filepath->file_data = base64_encode($filedata);
$filepath->save();
}
}
// session()->flash('message', 'Patch details saved successfully.');
return redirect()->route('patch.index')->with('message', 'Patch details saved successfully.');
}
private function formatFilePath($file)
{
if (strpos($file, 'SPN/') !== false) {
return str_replace("SPN/", "../SPN/", $file);
} else if (strpos($file, 'spn/') !== false) {
return str_replace("spn/", "../spn/", $file);
} else {
return str_replace("IE5DEV.shippingnet", ".", $file);
}
}
private function getFileContentFromGit($filePath, $commit)
{
$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/$this->selectedProject/repository/files/" . urlencode($filePath) . "/raw", [
'query' => ['ref' => $commit]
]);
$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) {
return '';
// throw $e;
} catch (\Exception $e) {
return '';
// throw $e;
}
}
public function loadPage($page)
{
$this->emit('menuChanged', $page);
}
public function render()
{
return view('livewire.pages.patch.patch-create');
}
}
<?php
namespace App\Http\Livewire\Pages\Patch;
use Livewire\Component;
use App\Models\ConfSmartUpdate;
use App\Models\TabPatchFile;
use App\Models\User;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Cache;
class PatchEdit extends Component
{
public $patchId;
public $message;
public $progressSave = 0, $isProcessing = false, $progress = 0, $currentStep = 0;
public $searchProject = '';
public $selectedBranch, $selectedPatch, $showModal;
public $selectedProject;
public $projects = [];
public $branches = [];
public $fileGitChanges = [];
public $filePatchChanges = [];
public $filePatch = [];
public $fileChangesTemp = [];
public $fileChanges = [];
public $startCommit = '';
public $endCommit = '';
public $PATCHNAME;
public $PDATE;
public $PHP_VERSION;
public $PLEVEL;
public $PCODE;
public $MAJOR_VERSION;
public $PDESC;
public $Remark;
public $POWNER;
public $POWNERNAME;
public $PAPPROVEDATE;
public $PTYPE;
public $PATCHCODE;
public $UNINSTALL;
public $PATCHCODE_SERVER;
public $filePathChanges = [];
protected $listeners = ['gotoModal', 'reloadComponent', 'deletePatchFile'];
public $modalLoaded = false;
public $contentType = 'application/json';
public function loadModal()
{
$this->modalLoaded = true;
}
public function mount($editPid)
{
// $editPid = '15689'; // remove this when real
$this->patchId = $editPid;
$this->loadPatchData();
}
public function updatedSearchProject()
{
$this->fetchProjects();
}
public function fetchProjects()
{
$client = new Client([
'headers' => [
'Authorization' => 'Bearer ' . env('GITLAB_API_TOKEN'),
'Accept' => $this->contentType,
],
'verify' => false,
]);
$perPage = 100;
$response = $client->get(env('GITLAB_API_URL') . '/projects', [
'query' => [
'membership' => true,
'min_access_level' => 30,
'search' => $this->searchProject,
'per_page' => $perPage,
],
]);
$this->projects = json_decode($response->getBody(), true);
$this->dispatchBrowserEvent('projects-fetched');
}
public function getChangedFiles()
{
$this->fileChangesTemp = [];
$client = new Client([
'headers' => [
'Authorization' => 'Bearer ' . env('GITLAB_API_TOKEN'),
'Accept' => $this->contentType,
],
'verify' => false,
]);
try {
$response = $client->get(env('GITLAB_API_URL') . "/projects/{$this->selectedProject}/repository/compare", [
'query' => [
'from' => $this->startCommit,
'to' => $this->endCommit,
],
]);
$data = json_decode($response->getBody(), true);
foreach ($data['diffs'] as $file) {
$this->fileChangesTemp[] = $file['new_path'];
}
$this->fileGitChanges = $this->buildTreeEdit($data['diffs']);
} catch (\Throwable $th) {
$data = '';
}
}
private function buildTreeEdit($files)
{
$tree = [];
foreach ($files as $file) {
$path = explode('/', $file['new_path']);
$current = &$tree;
foreach ($path as $part) {
if (!isset($current[$part])) {
$current[$part] = [];
}
$current = &$current[$part];
}
}
return $tree;
}
public function reloadComponent($id)
{
$this->patchId = $id;
$this->loadPatchData();
$this->render();
}
public function loadPatchData()
{
$patch = ConfSmartUpdate::findOrFail($this->patchId);
if(!isset($patch->user)) {
$owner = User::where('id', $patch->POWNER)->first();
$this->POWNERNAME = $owner->username;
}else{
$this->POWNERNAME = $patch->user->username;
}
$this->PATCHNAME = $patch->PATCHNAME;
$this->PDATE = $patch->PDATE;
$this->PHP_VERSION = $patch->PHP_VERSION;
$this->PLEVEL = $patch->PLEVEL;
$this->PCODE = $patch->PCODE;
$this->MAJOR_VERSION = $patch->MAJOR_VERSION;
$this->PDESC = $patch->PDESC;
$this->Remark = $patch->Remark;
$this->POWNER = $patch->POWNER;
$this->PAPPROVEDATE = $patch->PAPPROVEDATE;
$this->PTYPE = $patch->PTYPE;
$this->PATCHCODE = $patch->PATCHCODE;
$this->UNINSTALL = $patch->UNINSTALL;
$this->PATCHCODE_SERVER = $patch->PATCHCODE_SERVER;
$filePath = TabPatchFile::select('fid','ptid','file_name')->where("ptid", $this->patchId)->get()->toArray();
$this->filePatch = $filePath;
$this->filePatchChanges = $this->buildTree($filePath);
}
public function startProcess()
{
$this->progress = 0;
$this->isProcessing = true;
$this->dispatchBrowserEvent('process-started');
}
public function getProgress()
{
return $this->progress;
}
public function processStep()
{
$confSmartUpdate = ConfSmartUpdate::findOrFail($this->patchId);
$confSmartUpdate->PATCHNAME = $this->PATCHNAME;
$confSmartUpdate->PDATE = $this->PDATE;
$confSmartUpdate->PHP_VERSION_ID = $this->PHP_VERSION;
$confSmartUpdate->PLEVEL = $this->PLEVEL;
$confSmartUpdate->PCODE = $this->PCODE;
$confSmartUpdate->MAJOR_VERSION = $this->MAJOR_VERSION;
$confSmartUpdate->PDESC = $this->PDESC;
$confSmartUpdate->Remark = $this->Remark;
$confSmartUpdate->POWNER = $this->POWNER;
$confSmartUpdate->PAPPROVEDATE = $this->PAPPROVEDATE;
$confSmartUpdate->PTYPE = $this->PTYPE;
$confSmartUpdate->PATCHCODE = $this->PATCHCODE;
$confSmartUpdate->UNINSTALL = $this->UNINSTALL;
$confSmartUpdate->PATCHCODE_SERVER = $this->PATCHCODE_SERVER;
$confSmartUpdate->save();
if ($this->isProcessing && count($this->fileChangesTemp) > 0) {
$totalFiles = count($this->fileChangesTemp);
$this->currentStep = $totalFiles - ($totalFiles - $this->currentStep);
if ($this->currentStep < $totalFiles) {
$file = $this->fileChangesTemp[$this->currentStep];
$filedata = $this->getFileContentFromGit($file, $this->endCommit);
$filePath = $this->formatFilePath($file , 'SPN');
$existingFile = TabPatchFile::where('file_name', $filePath)
->where('ptid', $confSmartUpdate->PID)
->first();
if (!$existingFile) {
$filepath = new TabPatchFile;
$filepath->ptid = $confSmartUpdate->PID;
$filepath->file_name = $filePath;
$filepath->file_data = base64_encode($filedata);
$filepath->save();
}
$this->currentStep += 1;
$this->progress = round(($this->currentStep / $totalFiles) * 100, 2);
if ($this->progress == 100) {
$this->message = 'Patch details and file changes updated successfully.';
$this->emit('reloadComponent', $this->patchId);
$this->reset(['fileChangesTemp', 'fileGitChanges', 'currentStep']);
}
}
}
return $this->progress;
}
private function formatFilePath($file ,$project)
{
$lowerProject = strtolower($project);
$upperProject = strtoupper($project);
if (strpos($file, $upperProject.'/') !== false) {
return str_replace("$upperProject/", "../$upperProject/", $file);
} elseif (strpos($file, '$lowerProject/') !== false) {
return str_replace("$lowerProject/", "../$lowerProject/", $file);
} else {
return str_replace("IE5DEV.shippingnet", ".", $file);
}
}
private function getFileContentFromGit($filePath, $commit)
{
$token = env('GITLAB_API_TOKEN');
$client = new Client([
'base_uri' => 'https://idemo.netbay.co.th/gitlab/api/v4/',
'headers' => [
'Authorization' => "Bearer $token",
'Accept' => $this->contentType,
],
'verify' => false,
]);
try {
$response = $client->get("projects/$this->selectedProject/repository/files/" . urlencode($filePath) . "/raw", [
'query' => ['ref' => $commit]
]);
$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) {
throw $e;
} catch (\Exception $e) {
throw $e;
}
}
private function buildTree($files)
{
$tree = [];
foreach ($files as $file) {
$filePath = $this->generateFilePath($file['file_name']);
$pathParts = explode('/', $filePath);
$current = &$tree;
foreach ($pathParts as $part) {
if (!isset($current[$part])) {
$current[$part] = [];
}
$current = &$current[$part];
}
$current['id'] = $file['fid'] ?? 0;
}
return $tree;
}
private function generateFilePath($fileName)
{
if (strpos($fileName, "IE5DEV.shippingnet") !== false) {
return $this->processShippingNetPath($fileName);
} elseif (strpos($fileName, "IE5DEV.seamanifest") !== false) {
return $this->processSeaManifestPath($fileName);
}
return $fileName;
}
private function processShippingNetPath($fileName)
{
if (strpos($fileName, "../SPN/") !== false) {
return str_replace("../SPN/", "SPN/", $fileName);
} elseif (strpos($fileName, "../spn/") !== false) {
return str_replace("../spn/", "spn/", $fileName);
}
return "IE5DEV.shippingnet" . substr($fileName, 1);
}
private function processSeaManifestPath($fileName)
{
if (strpos($fileName, "../seamanifest/") !== false) {
return str_replace("../seamanifest/", "seamanifest/", $fileName);
} elseif (strpos($fileName, "../SEAMANIFEST/") !== false) {
return str_replace("../SEAMANIFEST/", "SEAMANIFEST/", $fileName);
}
return "IE5DEV.seamanifest" . substr($fileName, 1);
}
public function loadPage($page)
{
$this->emit('menuChanged', $page);
}
public function deletePatchFile($patchFileId)
{
$pathFile = TabPatchFile::where("fid", $patchFileId)->first();
$patchId = $pathFile->ptid;
TabPatchFile::where("fid", $patchFileId)->delete();
$message = "Deleted File ID : " . json_encode($patchFileId) . " Successfully";
$this->message = $message;
$this->emit('reloadComponent', $patchId);
}
public function deleteSelectedPatchFiles($selectedFiles)
{
foreach ($selectedFiles as $patchFileId) {
$pathFile = TabPatchFile::where("fid", $patchFileId)->first();
$patchId = $pathFile->ptid;
TabPatchFile::where("fid", $patchFileId)->delete();
}
$this->emit('reloadComponent', $patchId);
}
public function render()
{
return view('livewire.pages.patch.patch-edit');
}
}
<?php
namespace App\Http\Livewire\Pages\Patch;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\ConfSmartUpdate;
use App\Models\TabPatchFile;
class PatchIndex extends Component
{
use WithPagination;
public $action = 'list';
public $searchBy, $editPid, $message, $keyword, $perPage = 10, $searchSelected = 'PID' , $selectedPatch = [] ;
public $totalItems;
protected $listeners = [ 'deleteItem', 'deleteSelected' ,'showpatchListForm'];
public function mount()
{
$this->searchBy = [
'PID' => 'PID',
'PATCHNAME' => 'Patch Name',
'PDESC' => 'Description',
'MAJOR_VERSION' => 'Major Version',
'Remark' => 'Remark'
];
}
public function render()
{
$query = ConfSmartUpdate::select('PID', 'PATCHNAME', 'PDESC', 'PDATE', 'PLEVEL', 'Remark', 'MAJOR_VERSION');
if ($this->searchSelected && $this->keyword) {
$query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
}
$query->orderBy('PID', 'DESC');
$results = $query->paginate($this->perPage);
$this->totalItems = $results->total();
return view('livewire.pages.patch.patch-index', compact('results'));
}
public function updatedPerPage($value)
{
$this->adjustPageForNewPerPage();
}
public function adjustPageForNewPerPage()
{
$lastPage = ceil($this->totalItems / $this->perPage);
if ($this->page > $lastPage) {
$this->setPage($lastPage);
}
}
public function search()
{
$this->resetPage();
}
public function showpatchListForm()
{
$this->action = 'list';
}
public function showpatchAddForm()
{
$this->action = 'add';
}
public function showpatchEditForm($pid)
{
$this->editPid = $pid;
$this->action = 'edit';
}
public function showDeleteModal($patchFileId)
{
$this->emit('showDeleteModal' ,$patchFileId);
}
public function deleteItem($pid) {
TabPatchFile::where("ptid", $pid)->delete();
ConfSmartUpdate::where("PID", $pid)->delete();
$message = "Deleted Patch ID : " . json_encode($pid) . " Successfully";
$this->message = $message;
}
}
<?php
namespace App\Http\Livewire\Pages\Patch;
use Livewire\Component;
use App\Models\ConfFormatFile;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Livewire\WithFileUploads;
use Illuminate\Http\UploadedFile;
use Facades\Livewire\GenerateSignedUploadUrl;
use Illuminate\Validation\ValidationException;
use Livewire\Exceptions\S3DoesntSupportMultipleFileUploads;
use Livewire\FileUploadConfiguration;
use Illuminate\Support\Facades\Storage;
use Livewire\TemporaryUploadedFile;
use App\Traits\CustomTemporaryFileUpload;
class PatchMasterFile extends Component
{
use WithFileUploads;
// use CustomTemporaryFileUpload;
public $file, $format_file_id, $messages, $formatFile, $limit, $noLimit, $genPatch, $createPatch = false, $sendToEec = false, $genWithSmartUpdate = false;
protected $formatFiles;
protected $rules = [
'name' => 'required|string|max:255',
'files.*' => 'required|file|max:12209752',
];
public function createPatch()
{
$fileData = $this->file->getRealPath();
$fileFormat = ConfFormatFile::where('formatservice_ID', $this->format_file_id)->first();
$jsonFilePath = storage_path(str_replace(".inc", ".json", $fileFormat->file));
if (!file_exists($jsonFilePath)) {
session()->flash('error', 'Format JSON file not found.');
return;
}
$formatData = json_decode(file_get_contents($jsonFilePath), true);
$message = '';
if ($this->createPatch) {
$sqlPackAll = $this->readTxt($fileData, $formatData, $fileFormat, $this->limit, $this->noLimit);
$this->processPatches($sqlPackAll, $fileFormat, $this->genWithSmartUpdate);
$message .= 'Patch master file created successfully.';
}
$timeStampEec = Carbon::now()->toDateString();
$datetime = Carbon::now()->toDateTimeString();
$typeEec = $fileFormat->ac ?? '';
if ($this->sendToEec && $typeEec !== '') {
$uid = auth()->user()->id;
$response = $this->sendMasterFileToEcc(config('services.eec.url'), [
'type' => $typeEec,
'file' => fopen($fileData, 'r'),
'timestamp' => $timeStampEec,
]);
$reponseStatus = $response->status();
$responseDate = $response->json();
$requestData = json_encode([
'type' => $typeEec,
'file' => $fileData,
'timestamp' => $timeStampEec,
]);
$this->keepTransactionToEcc($uid, $typeEec, basename($fileData), $requestData, $datetime, $reponseStatus, json_encode($responseDate));
$message .= 'Send EEC successfully.';
// if ($RESPSTATUS == 200) {
// return response()->json(['message' => 'Send MasterFile To EEC'], 200);
// } else {
// return response()->json(['message' => 'Can Not Send MasterFile To EEC'], 500);
// }
} else {
// return response()->json(['message' => 'MasterFile Not config to EEC'], 400);
}
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, $REQDATA, $ACTDATETIME, $RESPSTATUS, $RESPDATA)
{
DB::table('log_send_master2eec')->insert([
'UID' => $UID,
'TYPE' => $TYPE,
'FILENAME' => $FILENAME,
'REQDATA' => $REQDATA,
'ACTDATETIME' => $ACTDATETIME,
'RESPSTATUS' => $RESPSTATUS,
'RESPDATA' => $RESPDATA,
]);
}
function processPatches($sqlPackAll, $fileFormat, $genSpnSmartUpdateDecode)
{
$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 && !$this->noLimit) {
$partPatch = 'Part ' . $part++;
}
$tis620_encoded = iconv('UTF-8', 'TIS-620', var_export($sqlPack, true));
$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 ($this->noLimit && ($i__ == $countSql - 1)) {
$this->savePatch($patchCode, $nameFormat, $day, $month, $year, $partPatch, $pLevel, $pDesc, $uid, $pApproveDate);
} elseif (!$this->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, $ac, $limit = 10000, $noLimit = false)
{
$sqlPackAll = [];
$count = 0;
$fileHandle = fopen($filePath, "r");
while (!feof($fileHandle)) {
$text = fgets($fileHandle);
$text = iconv('TIS-620', 'UTF-8', $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);
$fieldValue = mb_substr($text, $Y, $type, 'UTF-8');
$Y += $type;
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);
$fieldValue = mb_substr($text, $X, $type, 'UTF-8');
$X += $type;
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
];
$sqlPackAll[] = $sqlPack;
if ($this->noLimit && $this->limit > 10000) {
break;
} elseif ($this->limit >= $limit) {
break;
}
}
fclose($fileHandle);
return $sqlPackAll;
}
private function convertDate($datetime)
{
$year = substr($datetime, 4, 8) - 543;
$month = substr($datetime, 2, 2);
$day = substr($datetime, 0, 2);
return date("Y-m-d", mktime(0, 0, 0, $month, $day, $year));
}
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 = mb_substr($text, $Z, $type, 'UTF-8');
$Z += $type;
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;
}
public function render()
{
$this->formatFiles = ConfFormatFile::all();
return view('livewire.pages.patch.patch-master-file', with([
'formatFiles' => $this->formatFiles
]));
}
}
<?php
namespace App\Http\Livewire\Pages\Report;
use App\Exports\ServerLicenseExport;
use App\Jobs\ExportChunkJob;
use App\Jobs\ExportReportJob;
use App\Models\ConfServerLicense;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
use Throwable;
class ReportIndex extends Component
{
public $searchBy = [
'COMPANY' => 'Company',
'SNKEY' => 'Server Key',
'CUR_VERSION' => 'Current Version',
'STATUS' => 'Status',
'DATABASETYPE' => 'Database',
'PHP_VERSION_ID' => 'PHP Version'
];
public $searchSelected;
public $keyword;
protected $results;
public $progress = 0;
public $exporting = false;
public $fileName;
public $jobId;
public $batchId;
public $status = '';
public function filterReport()
{
$query = ConfServerLicense::select('ID', 'SNKEY', 'COMPANY', 'STATUS', 'CUR_VERSION', 'DATABASETYPE', 'LICENSEDATE');
if ($this->searchSelected && $this->keyword) {
$query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
}
$this->results = $query->orderBy('ID', 'DESC')->get();
}
public function exportReport()
{
$this->exporting = true;
$fileName = 'report_' . time() . '.xlsx';
$chunks = $this->getDataInChunks();
// สร้าง batch jobs โดยไม่ต้องใช้ withBatchId
$batch = Bus::batch(
collect($chunks)->map(fn($rows) => new ExportChunkJob($rows, $fileName))->toArray()
)->then(function (Batch $batch) {
// เมื่อ batch เสร็จสมบูรณ์
$this->progress = 100;
$this->status = 'Completed';
$this->exporting = false;
})->catch(function (Batch $batch, Throwable $e) {
// เมื่อ batch ล้มเหลว
$this->status = 'Failed';
$this->exporting = false;
})->finally(function (Batch $batch) {
$this->emit('checkProgress'); // เรียก Livewire เช็ค progress
})->dispatch();
$this->batchId = $batch->id; // เก็บ batchId ไว้เพื่อตรวจสอบ progress
$this->emit('startPolling'); // เริ่ม polling เพื่อติดตาม progress
}
public function checkProgress()
{
// เช็ค progress โดยใช้ batchId
if ($this->batchId) {
$batch = Bus::findBatch($this->batchId);
if ($batch) {
$this->progress = $batch->progress(); // อัปเดต progress
if ($batch->finished()) {
$this->status = 'Completed';
$this->exporting = false;
}
}
}
}
public function getDataInChunks()
{
$chunks = [];
// ใช้ chunk() โดยมี callback function เป็นพารามิเตอร์ที่สอง
ConfServerLicense::select('ID', 'SNKEY', 'COMPANY', 'STATUS', 'CUR_VERSION', 'DATABASETYPE', 'LICENSEDATE')
->orderBy('ID', 'DESC')
->chunk(100, function($rows) use (&$chunks) {
$chunks[] = $rows;
});
return $chunks;
}
public function render()
{
$this->filterReport();
return view('livewire.pages.report.report-index');
}
}
<?php
namespace App\Http\Livewire\Pages\Role;
use Livewire\Component;
use App\Models\Role;
class RoleCreate extends Component
{
public $name;
public $description;
public $permissions;
public $action;
public $permission_lists = [];
public $permission_lists_temp = [];
protected $rules = [
'name' => 'required',
'description' => 'required',
];
public function mount($permissions)
{
$this->permissions = $permissions;
}
public function render()
{
return view('livewire.pages.role.role-create');
}
public function submitForm($selectedList)
{
$validatedData = $this->validate([
'name' => 'required',
'description' => 'required',
'permission_lists' => 'array',
]);
$this->permission_lists = $selectedList;
$roleData = [
'name' => $this->name,
'description' => $this->description,
];
$role = Role::create($roleData);
if (!empty($this->permission_lists)) {
$role->permissions()->sync($this->permission_lists);
}
// Reset form fields
$this->reset([
'name', 'description', 'permission_lists'
]);
$this->emit('showRoleList', 'Role successfully created.');
}
public function goBack()
{
$this->emit('showRoleList', '');
}
}
<?php
namespace App\Http\Livewire\Pages\Role;
use Livewire\Component;
use App\Models\Role;
use App\Models\Permission;
use Illuminate\Http\Request;
class RoleEdit extends Component
{
public $editRoleId;
public $permissions;
public $roleId;
public $role;
public $name;
public $description;
public $permissionLists = [];
protected $rules = [
'role.name' => 'required',
'role.description' => 'required',
];
public function mount($editRoleId, $permissions)
{
$this->editRoleId = $editRoleId;
$this->permissions = $permissions;
$this->role = Role::findOrFail($editRoleId);
$this->name = $this->role->name;
$this->description = $this->role->description;
$this->permissionLists = $this->role->permissions->pluck('id')->toArray();
$this->permissions = Permission::all();
}
public function render()
{
$permissionLists = $this->permissionLists;
return view('livewire.pages.role.role-edit', compact('permissionLists'));
}
public function submitEditForm($selectedList)
{
// $this->validate();
$this->permissionLists = array_map('intval', $selectedList);
$this->role->name = $this->name;
$this->role->description = $this->description;
$this->role->permissions()->sync($this->permissionLists);
$this->role->save();
$this->emit('showRoleList', 'Role successfully updated.');
}
public function goBack()
{
$this->emit('showRoleList', '');
}
}
<?php
namespace App\Http\Livewire\Pages\Role;
use Livewire\Component;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\Role;
use App\Models\Permission;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Livewire\WithPagination;
use Illuminate\Support\FacadesAuth;
class RoleIndex extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $perPage = 10;
public $url;
public $searchSelected = 'name';
public $editRoleId;
public $deleteRoleId;
public $keyword = '';
public $route = '';
public $selectedOption = 'name';
public $searchBy;
public $menu;
public $action = 'list';
public $message;
public $selectedRoles ,$permission_lists= [];
public $showDeleteListModal = false;
public $showNoPermissionModal = false;
public $showMessage = false;
protected $listeners = [ 'showRoleList', 'deleteItem' , 'deleteSelected'];
public function mount()
{
$this->searchBy = [
'name' => 'Name',
];
$this->message = session('message');
}
public function updatedPerPage($value)
{
$this->adjustPageForNewPerPage();
}
public function adjustPageForNewPerPage()
{
$lastPage = ceil($this->totalItems / $this->perPage);
if ($this->page > $lastPage) {
$this->setPage($lastPage);
}
}
public function render()
{
$results = $this->searchSelected && $this->keyword
? Role::where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%')->paginate($this->perPage)
: Role::paginate($this->perPage);
$permissions = Permission::orderBy('permission_group_name', 'asc')->get();
$this->totalItems = $results->total();
return view('livewire.pages.role.role-index', [
'results' => $results,
'route' => $this->route,
'url' => $this->url,
'permissions' => $permissions,
'selectedRoles' => $this->selectedRoles,
'showDeleteListModal' => $this->showDeleteListModal
]);
}
public function showRoleCreateForm()
{
if (!Auth::user()->hasPermissions(['add-role'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$this->action = 'create';
}
public function showRoleEditForm($roleId)
{
if (!Auth::user()->hasPermissions(['edit-role'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$this->action = 'edit';
$this->editRoleId = $roleId;
}
public function showRoleList($message)
{
$this->action = 'list';
$this->resetPage();
$this->message = $message;
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
public function paginationView()
{
return 'paginate-custom';
}
public function deleteItem($deleteRoleId)
{
if (!Auth::user()->hasPermissions(['delete-role'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$role = Role::find($deleteRoleId);
if ($role) {
$role->delete();
$message = "Deleted Successfully";
$this->message = $message;
Log::info("Deleted Role ID : $deleteRoleId by User ".auth()->user()->id);
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
}
public function deleteSelected($selectedRoles)
{
if (!Auth::user()->hasPermissions(['delete-role'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$roleDeleted= Role::whereIn("id", $selectedRoles)->pluck('name')->toArray();
$roleStr = implode("," ,$roleDeleted);
Role::destroy($selectedRoles);
$message = "Deleted Role : (". $roleStr." ) Successfully";
Log::info("Deleted Role ID: $roleStr by User ".auth()->user()->id);
$this->message = $message;
$this->selectedRoles = [];
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
}
<?php
namespace App\Http\Livewire\Pages\SendPatch;
use App\Models\ConfServerLicense;
use App\Models\ConfServerPendding;
use App\Models\ConfSmartupdate;
use Livewire\Component;
use Livewire\WithPagination;
class DeleteMultiPatch extends Component
{
public $serverkey = '', $companyName, $showSearch, $searchInProgress, $results, $selectedPatches = [];
public function selectResult($key)
{
$this->serverkey = $key;
$this->results = [];
$this->showSearch = false;
$serverLicense = ConfServerLicense::where('SNKEY', $this->serverkey)->first();
if (isset($serverLicense)) {
$this->companyName = $serverLicense->COMPANY;
}
$this->emit('updateServerkey', $key);
}
public function updatedServerkey()
{
$this->showSearch = true;
if ($this->searchInProgress) {
$this->reset('results');
}
$this->searchInProgress = true;
$this->results = ConfServerLicense::where('SNKEY', 'LIKE', '%' . $this->serverkey . '%')->take(50)->get();
$this->searchInProgress = false;
}
public function render()
{
return view('livewire.pages.send-patch.delete-multi-patch', [
'selectedPatches' => ConfSmartUpdate::whereIn('PID', $this->selectedPatches)->get()
]);
}
}
<?php
namespace App\Http\Livewire\Pages\SendPatch;
use App\Models\ConfServerLicense;
use App\Models\ConfServerPendding;
use App\Models\ConfSmartupdate;
use App\Http\Livewire\Pages\SendPatch\SendPatchEdit;
use App\Models\LogSendPath2customer;
use Livewire\Component;
class DeleteMultiPatchBox extends Component
{
protected $listeners = ['updateServerkey' , 'updateDeletedPatches'];
public $isLoading = false;
public $selectedPatches = [];
public $selectedPatchName = [];
public $serverkey = '', $serverId, $showSearch = false, $searchInProgress, $reponseMessages = [];
public $showProgressModal = false;
public $results = [];
public function mount($selectedPatches)
{
$this->selectedPatches = $selectedPatches;
}
public function updateServerkey($serverkey)
{
$serverLicense = ConfServerLicense::where("SNKEY", $serverkey)->first();
if (isset($serverLicense)) {
$this->serverId = $serverLicense->ID;
$this->serverkey = $serverkey;
}
}
public function updateDeletedPatches($patchId, $allSelectPatchName)
{
if (is_array($patchId)) {
$this->selectedPatches = $patchId;
$this->selectedPatchName = $allSelectPatchName;
} else {
if (in_array($patchId, $this->selectedPatches)) {
$key = array_search($patchId, $this->selectedPatches);
if ($key !== false) {
unset($this->selectedPatches[$key]);
unset($this->allSelectPatchName[$key]);
}
} else {
$this->selectedPatches[] = $patchId;
$this->selectedPatchName[] = $allSelectPatchName;
}
}
}
public function removePatch($key)
{
$keyIndex = array_search($key, $this->selectedPatches);
if ($keyIndex !== false) {
unset($this->selectedPatches[$keyIndex]);
unset($this->selectedPatchName[$keyIndex]);
$this->selectedPatches = array_values($this->selectedPatches);
$this->selectedPatchName = array_values($this->selectedPatchName);
}
$this->emit('removePatchSelected', $key);
}
public function deleteSelectedPatches()
{
$this->reponseMessages = [];
if (count($this->selectedPatches) > 0 && !empty($this->serverkey)) {
foreach ($this->selectedPatches as $pId) {
$serverLicense = ConfServerLicense::where('SNKEY', $this->serverkey)->first();
if (isset($serverLicense)) {
ConfServerPendding::where("PatchID", $pId)->where('ServerID', $serverLicense->ID)->delete();
static::logSendPatch($pId, $serverLicense->ID, "Delete Patch");
$this->reponseMessages[] = "[Delete Patch] Send Success Serverkey : " . $this->serverkey . " and Patch : " . $pId;
} else {
$this->reponseMessages[] = '<span class="text-error">Serverkey : ' . $this->serverkey . ' not found</span>';
}
}
}
$this->showProgressModal = true;
$this->selectedPatchName = [];
$this->selectedPatches = [];
$this->emit('updateSelectPatchAfterDeleted');
}
public static function logSendPatch($patchId, $serverId, $logDesc)
{
$log = new LogSendPath2customer;
$log->UID = auth()->user()->uid;
$log->PATCHID = $patchId;
$log->SERVERKEYID = $serverId;
$log->ACTDATETIME = date("Y-m-d H:i:s");
$log->LOGDESC = $logDesc;
$log->IPACTIVE = request()->ip();
$log->save();
}
public function render()
{
return view('livewire.pages.send-patch.delete-multi-patch-box');
}
}
<?php
namespace App\Http\Livewire\Pages\SendPatch;
use App\Models\ConfServerLicense;
use App\Models\ConfServerPendding;
use App\Models\ConfSmartupdate;
use Livewire\Component;
use Livewire\WithPagination;
class DeleteMultiPatchList extends Component
{
use WithPagination;
public $serverkey = '';
public $searchBy, $serverId, $editPid, $message, $keyword, $perPage = 10, $searchSelected = 'PID';
public $selectedPatches = [];
protected $results;
public $totalItems;
protected $listeners = ['updateServerkey' , 'updateSelectPatchAfterDeleted', 'removePatchSelected'];
public function mount()
{
$this->searchBy = [
'PID' => 'PID',
'PATCHNAME' => 'Patch Name',
'PDESC' => 'Description',
'MAJOR_VERSION' => 'Major Version',
'Remark' => 'Remark'
];
// dd($results);
// $this->selectedPatches = [];
}
public function search()
{
$this->resetPage();
}
public function updatedPerPage($value)
{
$this->adjustPageForNewPerPage();
}
public function adjustPageForNewPerPage()
{
$lastPage = ceil($this->totalItems / $this->perPage);
if ($this->page > $lastPage) {
$this->setPage($lastPage);
}
}
public function updateServerkey($serverkey)
{
$serverLicense = ConfServerLicense::where("SNKEY", $serverkey)->first();
if (isset($serverLicense)) {
$this->serverId = $serverLicense->ID;
}
$this->render();
}
public function updateSelectPatchAfterDeleted()
{
$this->selectedPatches = [];
$this->render();
}
public function removePatchSelected($key)
{
$this->selectedPatches = array_filter($this->selectedPatches, function ($patch) use ($key) {
return $patch!== $key;
});
$this->resetPage();
}
public function render()
{
$query = ConfServerPendding::select('PID', 'PATCHNAME', 'PDESC', 'PDATE', 'PLEVEL', 'Remark', 'MAJOR_VERSION')
->join('conf_smartupdate', 'conf_smartupdate.PID', '=', 'conf_server_pendding.PatchID')
->where('conf_server_pendding.ServerID', $this->serverId)
->where('conf_server_pendding.TaskStatus' , '!=', '999');
if ($this->searchSelected && $this->keyword) {
$query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
}
$query->orderBy('PID', 'DESC');
$results = $query->paginate($this->perPage);
$this->totalItems = $results->total();
return view('livewire.pages.send-patch.delete-multi-patch-list', [
'results' => $results
]);
}
}
<?php
namespace App\Http\Livewire\Pages\SendPatch;
use App\Models\ConfServerLicense;
use App\Models\ConfServerPendding;
use App\Models\ConfSmartupdate;
use Livewire\Component;
class SendMultiPatchBox extends Component
{
protected $listeners = ['updateSelectedPatches'];
public $selectedPatches = [];
public $selectedPatchName = [];
public $serverkey = '', $showSearch = false, $searchInProgress, $reponseMessages = [];
public $showProgressModal = false;
public $results = [];
public function updatedServerkey()
{
$this->showSearch = true;
if ($this->searchInProgress) {
$this->reset('results');
}
$this->searchInProgress = true;
$this->results = ConfServerLicense::where('SNKEY', 'LIKE', '%' . $this->serverkey . '%')->take(50)->get();
$this->searchInProgress = false;
}
public function selectResult($key)
{
$this->serverkey = $key;
$this->results = [];
$this->showSearch = false;
}
public function mount($selectedPatches)
{
$this->selectedPatches = $selectedPatches;
}
public function updateSelectedPatches($patchId, $allSelectPatchName)
{
if (is_array($patchId)) {
$this->selectedPatches = $patchId;
$this->selectedPatchName = $allSelectPatchName;
} else {
if (in_array($patchId, $this->selectedPatches)) {
$key = array_search($patchId, $this->selectedPatches);
if ($key !== false) {
unset($this->selectedPatches[$key]);
unset($this->allSelectPatchName[$key]);
}
} else {
$this->selectedPatches[] = $patchId;
$this->selectedPatchName[] = $allSelectPatchName;
}
}
}
public function sendSelectedPatches()
{
$this->reponseMessages = [];
if (count($this->selectedPatches) > 0 && !empty($this->serverkey)) {
foreach ($this->selectedPatches as $pId) {
$serverLicense = ConfServerLicense::where('SNKEY', $this->serverkey)->first();
if (isset($serverLicense)) {
$serverPhpVersion = $serverLicense->PHP_VERSION_ID;
$patch = ConfSmartupdate::where('PID', $pId)->first();
$patchPhpVersion = $patch->PHP_VERSION_ID;
if ($serverPhpVersion != 0 && $patchPhpVersion != 0 && $serverPhpVersion != $patchPhpVersion) {
$this->reponseMessages[] = '<span class="text-error">Serverkey : ' . $this->serverkey . " and Patch : " . $pId . " PHP version conflict</span>";
continue;
}
$checkPendding = ConfServerPendding::where("PatchID", $pId)->where("ServerID", $serverLicense->ID)->first();
if (isset($checkPendding)) {
ConfServerPendding::where("PatchID", $pId)->where("ServerID", $serverLicense->ID)->update([
"TaskStatus" => "0",
"TaskFinish" => '0000_00_00 00:00:00'
]);
SendPatchEdit::logSendPatch($patch, $serverLicense->ID, "Reload Patch");
$this->reponseMessages[] = "[Reload Patch] Send Success Serverkey : " . $this->serverkey . " and Patch : " . $pId ;
} else {
$serverPedding = new ConfServerPendding;
$serverPedding->ServerID = $serverLicense->ID;
$serverPedding->PatchID = $pId;
$serverPedding->TaskDate = date("Y-m-d H:i:s");
$serverPedding->TaskType = "";
$serverPedding->TaskStatus = "0";
$serverPedding->TaskRunner = auth()->user()->username;
$serverPedding->save();
SendPatchEdit::logSendPatch($patch, $serverLicense->ID, "Add Patch");
$this->reponseMessages[] = "[Add Patch] Send Success Serverkey : " . $this->serverkey . " and Patch : " . $pId ;
}
} else {
$this->reponseMessages[] = '<span class="text-error">Serverkey : ' . $this->serverkey . ' not found</span>';
}
}
}
$this->showProgressModal = true;
}
public function render()
{
return view('livewire.pages.send-patch.send-multi-patch-box');
}
}
<?php
namespace App\Http\Livewire\Pages\SendPatch;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\ConfSmartUpdate;
class SendMultiPatchList extends Component
{
use WithPagination;
public $action = 'list';
public $searchBy, $editPid, $message, $keyword, $perPage = 10, $searchSelected = 'PID';
public $selectedPatches = [];
public $insertedIds = [];
public $totalItems;
protected $listeners = ['deleteItem', 'deleteSelected', 'showMultiPatchList'];
public function mount()
{
$this->searchBy = [
'PID' => 'PID',
'PATCHNAME' => 'Patch Name',
'PDESC' => 'Description',
'MAJOR_VERSION' => 'Major Version',
'Remark' => 'Remark'
];
$this->selectedPatches = [];
// $this->dispatchBrowserEvent('grandchild-component-loaded');
}
public function updatedPerPage($value)
{
$this->adjustPageForNewPerPage();
}
public function adjustPageForNewPerPage()
{
$lastPage = ceil($this->totalItems / $this->perPage);
if ($this->page > $lastPage) {
$this->setPage($lastPage);
}
}
public function search()
{
$this->resetPage();
}
public function showMultiPatchList()
{
$this->render();
}
public function loadPage($page)
{
$this->emit('menuChanged', $page);
}
public function render()
{
$query = ConfSmartUpdate::select('PID', 'PATCHNAME', 'PDESC', 'PDATE', 'PLEVEL', 'Remark', 'MAJOR_VERSION');
if ($this->searchSelected && $this->keyword) {
$query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
}
$query->orderBy('PID', 'DESC');
$results = $query->paginate($this->perPage);
$this->totalItems = $results->total();
return view('livewire.pages.send-patch.send-multi-patch-list', [
'results' => $results,
'selectedPatches' => ConfSmartUpdate::whereIn('PID', $this->selectedPatches)->get()
]);
}
}
<?php
namespace App\Http\Livewire\Pages\SendPatch;
use App\Models\ConfServerLicense;
use App\Models\ConfServerOwnertype;
use App\Models\ConfServerPendding;
use App\Models\ConfSmartupdate;
use App\Models\LogSendPath2customer;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\DB;
class SendPatchEdit extends Component
{
use WithPagination;
public $PID,$patchName , $serverKeyOption, $serverKeyOwnerType, $company, $db_type, $cur_ver;
public $perPage = 10;
public $search = '';
public $server_lists;
public $selectedOwnerType = '';
public $message;
public $searchSelected = 'SNKEY';
public $keyword = '';
public $selectedPenddings = [];
public $serverkey = '', $showSearch = false, $searchInProgress = false, $resultsServerkey = [] ,$resultsServerkeyArr= [];
public $serverKeyWaitingSend = [], $serverKeySuccess = [];
protected $listeners = ['deletePatch', 'refreshComponent' => '$refresh' , 'sendPatch' ,'deleteSelected'];
public function mount($editPid)
{
// $this->setPage(1);
$this->PID = $editPid;
$patch = ConfSmartupdate::where("PID", $editPid)->first();
$this->patchName = $patch->PATCHNAME;
// $this->PID = 15670;
// $this->updateServerLists();
}
public function updatedServerkey()
{
$this->searchResults();
}
public function updatedCompany()
{
$this->searchResults();
}
public function updatedDbType()
{
$this->searchResults();
}
public function updatedCurVer()
{
$this->searchResults();
}
public function selectAllResults()
{
$this->searchInProgress = true;
foreach ($this->resultsServerkey as $result) {
$this->selectResult($result->SNKEY);
}
$this->serverkey = '';
}
public function searchResults()
{
if ($this->searchInProgress) {
$this->reset('resultsServerkey');
$this->reset('resultsServerkeyArr');
}
$this->searchInProgress = true;
$query = ConfServerLicense::query();
if (!empty($this->serverkey)) {
$query->where('SNKEY', 'LIKE', '' . $this->serverkey . '%');
}
if (!empty($this->company)) {
$query->where('COMPANY', 'LIKE', '%' . $this->company . '%');
}
if (!empty($this->db_type)) {
$query->where('DATABASETYPE', 'LIKE', '%' . $this->db_type . '%');
}
if (!empty($this->cur_ver)) {
$query->where('CUR_VERSION', 'LIKE', '%' . $this->cur_ver . '%');
}
if (!empty($this->selectedOwnerType)) {
$query->where('OWNERTYPE', $this->selectedOwnerType);
}
$tmp = $query->get();
$this->resultsServerkey = $tmp;
$this->resultsServerkeyArr = $tmp->toArray();
$this->showSearch = true;
$this->searchInProgress = false;
}
public function selectResult($key)
{
$this->serverkey = $key;
$this->resultsServerkey = [];
$this->showSearch = false;
$temp = ConfServerLicense::where('SNKEY', $key)->first();
$keys = array_column($this->serverKeyWaitingSend, 'key');
if (!in_array($key, $keys)) {
$this->serverKeyWaitingSend[] = ['id' => $temp->ID, 'key' => $key, 'db' => $temp->DATABASE_TYPE, 'cur_ver' => $temp->CUR_VERSION];
}
}
public function removeServerKey($key)
{
$this->serverKeyWaitingSend = array_filter($this->serverKeyWaitingSend, function ($serverKey) use ($key) {
return $serverKey['key'] !== $key;
});
$this->serverKeyWaitingSend = array_values($this->serverKeyWaitingSend);
}
public function updatedSelectedOwnerType($value)
{
// if (!empty($value)) {
// $serverKeyOwnerType = $this->fetchServerKeyOption($value);
// if (count($serverKeyOwnerType) > 0) {
// foreach ($serverKeyOwnerType as $sk) {
// $this->selectResult($sk["name"]);
// }
// }
// } else {
// $this->serverKeyOwnerType = [];
// }
// $this->serverkey = '';
$this->searchResults();
}
protected function fetchServerKeyOption($ownerType)
{
$query = ConfServerLicense::query();
if ($ownerType) {
$query->where('OWNERTYPE', $ownerType);
}
if ($this->search) {
$query->where('SNKEY', 'like', '%' . $this->search . '%');
}
return $query->get(['ID as id', 'SNKEY as name'])->toArray();
}
public function sendPatch($serverKeyWaitingSend)
{
if (isset($serverKeyWaitingSend)) {
foreach ($serverKeyWaitingSend as $server) {
$serverPedding = new ConfServerPendding;
$serverPedding->ServerID = $server["id"];
$serverPedding->PatchID = $this->PID;
$serverPedding->TaskDate = date("Y-m-d H:i:s");
$serverPedding->TaskType = "";
$serverPedding->TaskStatus = "0";
$serverPedding->TaskRunner = auth()->user()->username;
$serverPedding->save();
static::logSendPatch($this->PID, $server["id"], "Add Patch");
array_push($this->serverKeySuccess , $server);
$this->emit('patchSent', $server);
}
}
// $this->serverKeyWaitingSend = [];
}
public function resendPatch($serverId)
{
$pendding = ConfServerPendding::where('ServerID', $serverId)->where('PatchID', $this->PID)->update([
"TaskStatus" => "0",
"TaskFinish" => '0000_00_00 00:00:00'
]);
// $pendding->TaskStatus = "0";
// $pendding->TaskFinish = '0000_00_00 00:00:00';
// $pendding->save();
static::logSendPatch($this->PID, $serverId, "Reload Patch");
}
public function deletePatch($serverId)
{
// if (!\Auth::user()->hasPermissions(['delete-pendding'])) {
// $this->showNoPermissionModal = TRUE;
// return;
// }
$pendding = ConfServerPendding::where("ServerID", $serverId)->where("PatchID", $this->PID,)->delete();
static::logSendPatch($this->PID, $serverId, "Delete Patch");
}
public function deleteSelected()
{
// if (!\Auth::user()->hasPermissions(['delete-user'])) {
// $this->showNoPermissionModal = TRUE;
// return;
// }
if(isset($this->selectedPenddings)){
foreach($this->selectedPenddings as $serverId) {
$pendding = ConfServerPendding::where("ServerID", $serverId)->where("PatchID", $this->PID,)->delete();
static::logSendPatch($this->PID, $serverId, "Delete Patch");
}
}
$message = "Deleted Successfully";
$this->message = $message;
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
$this->selectedPenddings = [];
}
public static function logSendPatch($patchId, $serverId, $logDesc)
{
$log = new LogSendPath2customer;
$log->UID = auth()->user()->uid;
$log->PATCHID = $patchId;
$log->SERVERKEYID = $serverId;
$log->ACTDATETIME = date("Y-m-d H:i:s");
$log->LOGDESC = $logDesc;
$log->IPACTIVE = request()->ip();
$log->save();
}
public function render()
{
$query = ConfServerLicense::query();
if ($this->selectedOwnerType) {
$query->where('OWNERTYPE', $this->selectedOwnerType);
}
if ($this->search) {
$query->where('SNKEY', 'like', '%' . $this->search . '%');
}
$this->serverKeyOption = $query->get(['ID as id', 'SNKEY as name'])->toArray();
$ownerType = ConfServerOwnertype::all();
$results = $this->searchSelected && $this->keyword
? ConfServerPendding::join('conf_server_license as p2', 'conf_server_pendding.ServerID', '=', 'p2.ID')
->where('PatchID', $this->PID)
->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%')
->paginate($this->perPage)
: ConfServerPendding::join('conf_server_license as p2', 'conf_server_pendding.ServerID', '=', 'p2.ID')
->where('PatchID', $this->PID)
->paginate($this->perPage);
return view('livewire.pages.send-patch.send-patch-edit', compact('ownerType', 'results'));
}
public function export()
{
$data = DB::table('log_send_path2customer as t1')
->join('tab_user as t2', 't1.UID', '=', 't2.UID')
->join('conf_server_license as t3', 't1.SERVERKEYID', '=', 't3.ID')
->join('conf_server_pendding as cp', function ($join) {
$join->on('cp.ServerID', '=', 't3.ID')
->on('cp.PatchID', '=', 't1.PATCHID');
})
->select([
't2.USERNAME',
't3.SNKEY',
't3.COMPANY',
't1.ACTDATETIME',
't1.LOGDESC',
't1.IPACTIVE',
'cp.PatchID',
DB::raw("CASE WHEN cp.TaskStatus = 999 THEN 'Yes' ELSE 'No' END as isReceive"),
])
->where('cp.PatchID', $this->PID)
->orderBy('t1.ACTDATETIME', 'DESC')
->get();
$dataArray = $data->map(function ($item) {
return (array) $item;
})->toArray();
$filename = "patch_pendding_" . now()->format('YmdHis') . ".csv";
$headers = [
'Content-Type' => 'text/csv',
'Content-Disposition' => "attachment; filename=$filename",
];
$callback = function () use ($dataArray) {
$file = fopen('php://output', 'w');
if (!empty($dataArray)) {
fputcsv($file, array_keys($dataArray[0]));
}
foreach ($dataArray as $row) {
$row["SNKEY"] = "'". $row["SNKEY"];
fputcsv($file, $row);
}
fclose($file);
};
return Response::stream($callback, 200, $headers);
}
}
<?php
namespace App\Http\Livewire\Pages\SendPatch;
use App\Models\ConfServerPendding;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Support\Facades\DB;
use App\Models\ConfSmartUpdate;
use Illuminate\Support\Facades\Cache;
class SendPatchIndex extends Component
{
use WithPagination;
public $searchBy;
public $editPid;
public $message;
public $keyword;
public $perPage = 10;
public $searchSelected = 'PID';
public $action = 'list';
public $totalItems;
public $showMessage= false;
protected $listeners = ['showGroupList', 'deleteItem'];
public function mount()
{
$this->searchBy = [
'PID' => 'PID',
'PATCHNAME' => 'Patch Name',
'PDESC' => 'Description',
'MAJOR_VERSION' => 'Major Version',
'Remark' => 'Remark'
];
$this->message = session('message');
}
public function updatedPerPage($value)
{
$this->adjustPageForNewPerPage();
}
public function adjustPageForNewPerPage()
{
$lastPage = ceil($this->totalItems / $this->perPage);
if ($this->page > $lastPage) {
$this->setPage($lastPage);
}
}
public function render()
{
$results = [];
if ($this->action == 'list') {
$query = ConfSmartUpdate::select('PID', 'PATCHNAME', 'PDESC', 'PDATE', 'PLEVEL', 'Remark')
->withCount(['confServerPendding as NUMSERVER']);
if ($this->searchSelected && $this->keyword) {
$query->where($this->searchSelected, 'LIKE', '%'.$this->keyword . '%');
}
// dd( $query->where($this->searchSelected, 'LIKE', $this->keyword . '%'));
$query->orderBy('PID', 'DESC');
$results = $query->paginate($this->perPage);
$this->totalItems = $results->total();
}
return view('livewire.pages.send-patch.send-patch-index', compact('results'));
}
public function search()
{
$this->resetPage();
}
public function showpatchEditForm($pid)
{
$this->editPid = $pid;
$this->action = 'edit';
}
}
<?php
namespace App\Http\Livewire\Pages\ServerLicense;
use GuzzleHttp\Exception\RequestException;
use App\Models\ConfSmartupdate;
use App\Models\MasterPhpVer;
use App\Models\TabPatchFile;
use Livewire\Component;
use GuzzleHttp\Client;
use App\Models\ConfServerLicense;
use Illuminate\Support\Facades\DB;
class ServerLicenseCreate extends Component
{
public $phpVersions = [];
public $teams;
public $sizings = [];
public $customerTypes = [];
public $dbTypes = [];
public $ownerTypes = [];
public $serverKey;
public $teamId;
public $customerSize;
public $customerType;
public $company;
public $branch;
public $status;
public $licenseDate;
public $phpVersionId;
public $currentVersion;
public $installDate;
public $installVersion;
public $databaseType;
public $ownerType;
public $hscodeMethod = 1;
public $customerUrl;
public $contact;
public $contactCustomerName;
protected $rules = [
'serverKey' => 'required|string|max:255',
'teamId' => 'required|integer',
'customerSize' => 'required|integer',
'customerType' => 'required|not_in:0',
'company' => 'required|string|max:255',
// 'branch' => 'nullable|string|max:255',
'status' => 'required|in:Y,N',
'licenseDate' => 'nullable|date',
'phpVersionId' => 'required|integer',
'currentVersion' => 'nullable|string|max:255',
'installDate' => 'nullable|date',
'installVersion' => 'nullable|string|max:255',
'databaseType' => 'required',
'ownerType' => 'nullable',
'customerUrl' => 'nullable|string|max:255',
'contact' => 'nullable|string|max:255',
'contactCustomerName' => 'nullable|string|max:255',
// 'hscodeMethod' => 'required|integer|in:1,2',
];
protected $messages = [
'customerType.not_in' => 'Please select customer type.',
];
public function mount()
{
$this->phpVersionId = DB::table('master_php_ver')
->orderBy('id', 'asc')
->first()->id;
$this->teamId = DB::table('master_team')
->orderBy('id', 'asc')
->first()->id;
$this->customerSize = DB::table('master_size')
->orderBy('id', 'asc')
->first()->id;
$this->customerType = DB::table('master_sizeType')
->orderBy('id', 'asc')
->first()->id;
$this->databaseType = DB::table('master_dbtype')
->orderBy('id', 'asc')
->first()->id;
$this->ownerType = DB::table('conf_server_ownertype')
->orderBy('owntypeid', 'asc')
->first()->owntypeid;
}
public function save()
{
$this->validate();
ConfServerLicense::create([
'SNKEY' => $this->serverKey,
'NBTEAM' => $this->teamId,
'CUSTOMERSIZE' => $this->customerSize,
'CUSTOMERTYPE' => $this->customerType,
'COMPANY' => $this->company,
'BRANCH' => $this->branch,
'STATUS' => $this->status,
'LICENSEDATE' => $this->licenseDate ?? ' ',
'PHP_VERSION_ID' => $this->phpVersionId ?? ' ',
'CUR_VERSION' => $this->currentVersion ?? ' ',
'INSTALL_DATE' => $this->installDate ?? ' ',
'INSTALL_VERSION' => $this->installVersion ?? ' ',
'DATABASETYPE' => $this->databaseType ?? ' ',
'OWNERTYPE' => $this->ownerType ?? ' ',
'HSCODEMETHOD' => $this->hscodeMethod ?? ' ',
'CUSTOMERURL' => $this->customerUrl ?? ' ',
'CONTACT' => $this->contact ?? ' ',
'CONTACTCUSTOMERNAME' => $this->contactCustomerName ?? ' ',
]);
return redirect()->route('server-license.index')->with('message', 'Server License saved successfully.');
}
public function loadPage($page)
{
$this->emit('menuChanged', $page);
}
public function render()
{
$this->phpVersions = DB::table('master_php_ver')
->orderBy('id', 'asc')
->get();
$this->teams = DB::table('master_team')
->orderBy('id', 'asc')
->get();
$this->sizings = DB::table('master_size')
->orderBy('id', 'asc')
->get();
$this->customerTypes = DB::table('master_sizeType')
->orderBy('id', 'asc')
->get();
$this->dbTypes = DB::table('master_dbtype')
->orderBy('id', 'asc')
->get();
$this->ownerTypes = DB::table('conf_server_ownertype')
->orderBy('owntypeid', 'asc')
->get();
return view('livewire.pages.server-license.server-license-create');
}
}