<?php
namespace App\Http\Livewire\Pages\ServerLicense;
use App\Models\ConfServerLicense;
use App\Models\ConfServerPendding;
use Livewire\Component;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use ZipArchive;
use Livewire\WithPagination;
class ServerLicenseEdit extends Component
{
use WithPagination;
public $perPage = 10;
public $tab = 'form';
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;
public $customerUrl;
public $contact;
public $contactCustomerName;
public $licenseId;
public $message, $messages = [];
protected $listeners = ['gotoModal', 'setMessage'];
public $modalLoaded = false;
public $SNKEY;
public $selectDateOrg;
public $orgList = [];
public $allDate;
public $mappingList = [], $labelList = [], $userInterfaceList = [], $globalList = [], $parameterList = [], $onloadList = [], $validateList = [], $mapToList = [], $fileNameList = [];
protected $historyPatchList;
public $sortHistoryField = 'TaskDate';
public $sortHistoryDirection = 'asc';
public $globalListGroup = [];
public $fieldList = ['mapId', 'mapName', 'mapType', 'mapTo', 'mapConfig'];
public $backupFeedback, $info = [];
public $mainvarCode;
public $fileDownloads = [];
protected $rules = [
'serverKey' => 'required|string|max:255',
'teamId' => 'required|integer|not_in:0',
'customerSize' => 'required|integer|not_in:0',
'customerType' => 'required|not_in:0',
'company' => 'required|string|max:255',
// 'branch' => 'nullable|string|max:255',
'status' => 'required|in:Y,N',
'licenseDate' => 'nullable',
'phpVersionId' => 'required|integer',
'currentVersion' => 'nullable|string|max:255',
'installDate' => 'nullable',
'installVersion' => 'nullable|string|max:255',
'databaseType' => 'required|not_in:0',
'ownerType' => 'nullable',
'customerUrl' => 'nullable|string|max:255',
'contact' => 'nullable|string|max:255',
'contactCustomerName' => 'nullable|string|max:255',
// 'hscodeMethod' => 'required|integer|in:1,2',
];
public function loadModal()
{
$this->modalLoaded = true;
}
public function mount($editId)
{
$this->licenseId = $editId;
$this->loadData();
$this->fileDownloads = $this->info['FileDownload'] ?? [];
}
public function loadData()
{
$license = ConfServerLicense::find($this->licenseId);
if ($license) {
$this->serverKey = $license->SNKEY;
$this->teamId = $license->NBTEAM;
$this->customerSize = $license->CUSTOMERSIZE;
$this->customerType = $license->CUSTOMERTYPE;
$this->company = $license->COMPANY;
$this->branch = $license->BRANCH;
$this->status = $license->STATUS;
$this->licenseDate = $license->LICENSEDATE;
$this->phpVersionId = $license->PHP_VERSION_ID;
$this->currentVersion = $license->CUR_VERSION;
$this->installDate = $license->INSTALL_DATE;
$this->installVersion = $license->INSTALL_VERSION;
$this->databaseType = $license->DATABASETYPE;
$this->ownerType = $license->OWNERTYPE;
$this->hscodeMethod = $license->HSCODEMETHOD;
$this->customerUrl = $license->CUSTOMERURL;
$this->contact = $license->CONTACT;
$this->contactCustomerName = $license->CONTACTCUSTOMERNAME;
if ($license && !empty($license->BACKUP_FEEDBACK)) {
$compressedData = gzuncompress(base64_decode($license->BACKUP_FEEDBACK));
$this->backupFeedback = $compressedData;
$currentEncoding = mb_detect_encoding($compressedData, mb_detect_order(), true);
$this->info = null;
eval('$this->info = ' . trim($compressedData) . ';');
}
}
$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();
}
public function updateLicense()
{
$customMessages = [
'customerType.not_in' => 'Please select customer type.',
];
$this->validate($this->rules,$customMessages);
$license = ConfServerLicense::find($this->licenseId);
if ($license) {
$license->update([
'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,
]);
$message = 'Server License updated successfully!';
$this->setMessage($message);
// session()->flash('message', 'Server License updated successfully!');
}
}
public function loadPage($page)
{
$this->emit('menuChanged', $page);
}
public function updatedSelectDateOrg()
{
$this->loadOrganize();
}
public function loadOrganize()
{
$this->tab = 'organize';
$license = ConfServerLicense::find($this->licenseId);
$this->SNKEY = $license->SNKEY;
$this->allDate = DB::table('conf_server_license_orgcontrol')
->select('id', 'createDate')
->where('SNKEY', $this->SNKEY)
->orderByDesc('id')
->get();
if (empty($this->selectDateOrg)) {
if (isset($this->allDate)) {
foreach ($this->allDate as $date) {
$this->selectDateOrg = $date->id ?? '';
break;
}
}
}
$this->orgList = DB::table('conf_server_license_orglist')
->where('controlId', $this->selectDateOrg)
->orderBy('id')
->get()
->toArray();
foreach ($this->orgList as $orgData) {
$profileList = DB::table('conf_server_license_orglist_profile')
->where('orglistId', $orgData->id)
->get();
$orgData->profileList = $profileList ? $profileList : '';
// Fetch document type by org
$docTypeList = DB::table('conf_server_license_orglist_doctype as a')
->join('u01r_doctype as b', 'a.docType', '=', 'b.DTNAME')
->where('a.orglistId', $orgData->id)
->get();
$orgData->docTypeList = $docTypeList ? $docTypeList : '';
}
}
public function loadMapping()
{
$this->tab = 'csvMapping';
if ($this->info && isset($this->info['DATA']['conf_mapping'])) {
$this->mappingList = $this->info['DATA']['conf_mapping'];
foreach ($this->mappingList['mapConfig'] as $index => $config) {
$this->mappingList['mapConfig'][$index] = base64_decode($config);
}
}
}
public function saveMapping()
{
$fieldList = ['mapId', 'mapName', 'mapType', 'mapTo', 'mapConfig'];
$DATA = [];
foreach ($fieldList as $field) {
foreach ($this->mappingList[$field] as $index => $value) {
if ($field == 'mapConfig') {
$DATA[$field][] = base64_encode(htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $value), ENT_QUOTES));
} else {
$DATA[$field][] = htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $value), ENT_QUOTES);
}
}
}
$this->info['DATA']['conf_mapping'] = $DATA;
$newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));
$license = ConfServerLicense::find($this->licenseId);
if ($license) {
$updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
if ($updatedRows > 0) {
$message = 'Mapping data saved successfully!';
} else {
$message = 'No changes were made.';
}
}
$this->loadData();
$this->loadMapping();
$message = 'CSV Mapping updated successfully!';
$this->setMessage($message);
}
public function loadPrintForm()
{
$this->tab = 'printForm';
if ($this->info && isset($this->info['DATA']['conf_label_form'])) {
$this->labelList = $this->info['DATA']['conf_label_form'];
}
}
public function savePrintForm()
{
$fieldList = array('lid', 'form_name', 'l_name', 'l_value', 'x', 'y', 'parentId', 'editLayout', 'width', 'height', 'type', 'format');
$DATA = [];
foreach ($fieldList as $field) {
foreach ($this->mappingList[$field] as $index => $value) {
$DATA[$field][] = htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $value), ENT_QUOTES);
}
}
$this->info['DATA']['conf_label_form'] = $DATA;
$newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));
$license = ConfServerLicense::find($this->licenseId);
if ($license) {
$updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
if ($updatedRows > 0) {
$message = 'Print form saved successfully!';
} else {
$message = 'No changes were made.';
}
}
$this->loadData();
$this->loadPrintForm();
$message = 'Print form updated successfully!';
// $this->message = $message;
$this->setMessage($message);
}
public function loadUserInterface()
{
$this->tab = 'userInterface';
if ($this->info && isset($this->info['DATA']['conf_ui'])) {
$this->userInterfaceList = $this->info['DATA']['conf_ui'];
}
}
public function saveUserInterface()
{
$fieldList = array('pageCode', 'name', 'tname', 'required', 'type', 'spec', 'manual', 'user_note', 'js_before_focus', 'cannotImport', 'fname', 'reportFlag', 'reportOrderBy', 'reportCondition', 'reportTable', 'reportType', 'reportFormat', 'reportAlign', 'user_default');
$DATA = [];
foreach ($fieldList as $field) {
foreach ($this->userInterfaceList[$field] as $index => $value) {
if ($field == 'user_default') {
$DATA[$field][] = base64_encode(htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $value), ENT_QUOTES));
} else {
$DATA[$field][] = htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $value), ENT_QUOTES);
}
}
}
$this->info['DATA']['conf_ui'] = $DATA;
$newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));
$license = ConfServerLicense::find($this->licenseId);
if ($license) {
$updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
if ($updatedRows > 0) {
$message = 'User Interface saved successfully!';
} else {
$message = 'No changes were made.';
}
}
$this->loadData();
$this->loadPrintForm();
$message = 'User Interface updated successfully!';
// $this->message = $message;
$this->setMessage($message);
}
public function loadGlobal()
{
$this->tab = 'global';
if ($this->info && isset($this->info['DATA']['conf_global'])) {
$this->globalList = $this->info['DATA']['conf_global'];
}
$groupedData = [];
$globalTemp = $this->globalList;
if (!empty($globalTemp)) {
foreach ($globalTemp['profilecode'] as $index => $profileCode) {
if (isset($globalTemp['name'][$index]) && isset($globalTemp['value'][$index])) {
if (!isset($groupedData[$profileCode])) {
$groupedData[$profileCode] = [];
}
$groupedData[$profileCode][] = [
'name' => $globalTemp['name'][$index],
'value' => $globalTemp['value'][$index],
'profilecode' => $profileCode
];
}
}
}
$this->globalListGroup = $groupedData;
}
public function saveGlobal()
{
$fieldList = array('name', 'value', 'profilecode');
$DATA = [];
foreach ($this->globalListGroup as $profileCode => $profileData) {
foreach ($profileData as $index => $item) {
foreach ($fieldList as $field) {
if (isset($item[$field])) {
$DATA[$field][] = htmlspecialchars_decode(iconv("UTF-8", "TIS-620", $item[$field]), ENT_QUOTES);
}
}
}
}
$this->info['DATA']['conf_global'] = $DATA;
$newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));
$license = ConfServerLicense::find($this->licenseId);
if ($license) {
$updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
if ($updatedRows > 0) {
$message = 'Global saved successfully!';
} else {
$message = 'No changes were made.';
}
}
$this->loadData();
$this->loadPrintForm();
$message = 'Global updated successfully!';
// $this->message = $message;
$this->setMessage($message);
}
public function loadParameter()
{
$this->tab = 'parameter';
if ($this->info && isset($this->info['DATA']['conf_parameter'])) {
$this->parameterList = $this->info['DATA']['conf_parameter'];
}
// dd($this->parameterList);
}
public function saveParameter()
{
$fieldList = array('PID', 'name', 'value', 'description', 'active');
$DATA = [];
foreach ($fieldList as $field) {
foreach ($this->parameterList[$field] as $index => $value) {
$DATA[$field][] = htmlspecialchars_decode($value, ENT_QUOTES);
}
}
//
$this->info['DATA']['conf_parameter'] = $DATA;
$newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));
$license = ConfServerLicense::find($this->licenseId);
if ($license) {
$updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
if ($updatedRows > 0) {
$message = 'Parameter saved successfully!';
} else {
$message = 'No changes were made.';
}
}
$this->loadData();
$this->loadParameter();
$message = 'Parameter updated successfully!';
// $this->message = $message;
$this->setMessage($message);
}
public function loadOnload()
{
$this->tab = 'onload';
if ($this->info && isset($this->info['DATA']['conf_onload'])) {
$this->onloadList = $this->info['DATA']['conf_onload'];
}
// dd($this->onloadList);
}
public function saveOnload()
{
$fieldList = array('SKEY', 'SERVNAME', 'ACT', 'ONLOAD');
$DATA = [];
foreach ($fieldList as $field) {
foreach ($this->onloadList[$field] as $index => $value) {
$DATA[$field][] = htmlspecialchars_decode($value, ENT_QUOTES);
}
}
$this->info['DATA']['conf_onload'] = $DATA;
$newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));
$license = ConfServerLicense::find($this->licenseId);
if ($license) {
$updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
if ($updatedRows > 0) {
$message = 'Onload saved successfully!';
} else {
$message = 'No changes were made.';
}
}
$this->loadData();
$this->loadOnload();
$message = 'Onload updated successfully!';
// $this->message = $message;
$this->setMessage($message);
}
public function loadValidate()
{
$this->tab = 'validate';
if ($this->info && isset($this->info['DATA']['conf_validate'])) {
$this->validateList = $this->info['DATA']['conf_validate'];
}
// dd($this->validateList);
}
public function saveValidate()
{
$fieldList = array('id', 'step', 'level', 'name', 'desc', 'validateCode', 'doctype', 'active');
$DATA = [];
foreach ($fieldList as $field) {
foreach ($this->validateList[$field] as $index => $value) {
$DATA[$field][] = htmlspecialchars_decode($value, ENT_QUOTES);
}
}
$this->info['DATA']['conf_validate'] = $DATA;
$newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));
$license = ConfServerLicense::find($this->licenseId);
if ($license) {
$updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
if ($updatedRows > 0) {
$message = 'Validate saved successfully!';
} else {
$message = 'No changes were made.';
}
}
$this->loadData();
$this->loadValidate();
$message = 'Validate updated successfully!';
//
$this->setMessage($message);
}
public function loadMapTo()
{
$this->tab = 'mapTo';
if ($this->info && isset($this->info['DATA']['conf_mapto'])) {
$this->mapToList = $this->info['DATA']['conf_mapto'];
}
}
public function saveMapTo()
{
$fieldList = array('id', 'name', 'code', 'type');
$DATA = [];
foreach ($fieldList as $field) {
foreach ($this->mapToList[$field] as $index => $value) {
if ($field == 'code') {
$DATA[$field][] = base64_encode(htmlspecialchars_decode($value, ENT_QUOTES));
} else {
$DATA[$field][] = htmlspecialchars_decode($value, ENT_QUOTES);
}
}
}
$this->info['DATA']['conf_mapto'] = $DATA;
$newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));
$license = ConfServerLicense::find($this->licenseId);
if ($license) {
$updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
if ($updatedRows > 0) {
$message = 'Map To saved successfully!';
} else {
$message = 'No changes were made.';
}
}
$this->loadData();
$this->loadMapTo();
$message = 'MapTo updated successfully!';
// $this->message = $message;
$this->setMessage($message);
}
public function loadMainVar()
{
$this->tab = 'mainVar';
if ($this->info && isset($this->info['MAINVAR'])) {
$this->mainvarCode = $this->info['MAINVAR'];
}
}
public function saveMainVar()
{
$this->info['MAINVAR'] = $this->mainvarCode;
$newBackupFeedback = base64_encode(gzcompress(var_export($this->info, true)));
$license = ConfServerLicense::find($this->licenseId);
if ($license) {
$updatedRows = $license->update(['BACKUP_FEEDBACK' => $newBackupFeedback]);
if ($updatedRows > 0) {
$message = 'Main Var saved successfully!';
} else {
$message = 'No changes were made.';
}
}
$this->loadData();
$this->loadMainVar();
$message = 'Main Var updated successfully!';
$this->setMessage($message);
}
public function loadFileDownload()
{
$this->tab = 'fileDownload';
if ($this->info && isset($this->info['FileDownload'])) {
$this->fileNameList = $this->info['Filename'] ?? [];
}
}
public function downloadFile($index)
{
$this->loadData();
$codeFile =$this->info['FileDownload'][$index] ?? '';
$filename = $this->fileNameList[$index] ?? 'unknown_file' . $index . '.txt';
$codeFileUtf8 = iconv('TIS-620', 'UTF-8//IGNORE', $codeFile);
$filename = ltrim($filename, './');
$tempFilePath = storage_path('app/temp/' . $filename);
$dirname = dirname($tempFilePath);
if (!is_dir($dirname)) {
mkdir($dirname, 0777, true);
}
if (file_put_contents($tempFilePath, $codeFileUtf8) !== false) {
return response()->download($tempFilePath)->deleteFileAfterSend(true);
} else {
session()->flash('error', "Failed to create temporary file for $filename");
}
}
public function downloadAllFile()
{
$dateCurrent = now()->format('Y-m-d H:i:s');
$zip = new ZipArchive();
$dateExport = now()->format('Ymd');
$zipName = "{$this->SNKEY}_{$dateExport}.zip";
$zipFilePath = storage_path("app/temp/{$zipName}");
if (!Storage::exists('temp')) {
Storage::makeDirectory('temp');
}
if ($zip->open($zipFilePath, ZipArchive::CREATE) !== true) {
return response()->json(['error' => "Cannot open <$zipFilePath>"], 500);
}
$this->loadData();
$fileDownloads = $this->info['FileDownload'] ?? [];
$filenames = $this->info['Filename'] ?? [];
$textLog = "\n{$dateCurrent} {$this->SNKEY} ??TempUser?? [ ";
foreach ($fileDownloads as $key => $codeFile) {
// Convert $codeFile from TIS-620 to UTF-8
$codeFileUtf8 = iconv('TIS-620', 'UTF-8//IGNORE', $codeFile);
$filename = $filenames[$key] ?? 'unknown_file' . $key . '.txt';
$filename = ltrim($filename, './');
$tempFilePath = storage_path('app/temp/' . $filename);
$dirname = dirname($tempFilePath);
if (!is_dir($dirname)) {
mkdir($dirname, 0777, true);
}
if (file_put_contents($tempFilePath, $codeFileUtf8) !== false) {
$tempFiles[] = $tempFilePath;
if (!$zip->addFile($tempFilePath, $filename)) {
session()->flash('error', "Failed to add $filename to ZIP");
return;
}
} else {
session()->flash('error', "Failed to create temporary file for $filename");
return;
}
$textLog .= " {$filename} |";
}
$zip->close();
if(isset($tempFiles)){
foreach ($tempFiles as $file) {
if (file_exists($file)) {
unlink($file);
}
}
}
if (file_exists($zipFilePath)) {
$textLog = rtrim($textLog, '|') . " ]";
$logPath = storage_path("logs/patchGetFile_{$dateExport}.txt");
file_put_contents($logPath, $textLog, FILE_APPEND);
return response()->download($zipFilePath)->deleteFileAfterSend(true);
} else {
session()->flash('error', 'Zip file not found.');
}
}
public function loadHistoryPatch()
{
$this->tab = 'historyPatch';
}
public function loadHistoryPatchData()
{
$this->historyPatchList = DB::table('conf_server_pendding as cp')
->join('conf_smartupdate as cs', 'cp.PatchID', '=', 'cs.PID')
->select(
'cp.TaskDate',
'cp.TaskStatus',
'cp.TaskRunner',
'cp.TaskFinish',
'cs.PID',
'cs.PATCHNAME',
'cs.PAPPROVEDATE',
'cs.PDESC',
DB::raw("CASE WHEN cp.TaskStatus = 999 THEN 'Success'
WHEN cp.TaskStatus = 0 THEN 'Waiting Receive'
WHEN cp.TaskStatus = 1 THEN 'See Patch'
WHEN cp.TaskStatus = 2 THEN 'Error Recieved'
ELSE cp.TaskStatus END as TaskStatusLabel")
)
->where('cp.ServerID', $this->licenseId)
->orderBy($this->sortHistoryField, $this->sortHistoryDirection)
->paginate($this->perPage);
}
public function sortHistoryBy($field)
{
if ($this->sortHistoryField === $field) {
$this->sortHistoryDirection = $this->sortHistoryDirection === 'asc' ? 'desc' : 'asc';
} else {
$this->sortHistoryField = $field;
$this->sortHistoryDirection = 'asc';
}
}
public function setMessage($message)
{
$this->messages[] = $message;
}
public function render()
{
$this->loadHistoryPatchData();
return view('livewire.pages.server-license.server-license-edit', [
'historyPatchList' => $this->historyPatchList,
]);
}
}
<?php
namespace App\Http\Livewire\Pages\ServerLicense;
use App\Models\ConfServerLicense;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\ConfSmartUpdate;
use PDO;
use App\Exports\LicenseExport;
use App\Exports\ServerLicenseExport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\DB;
class ServerLicenseIndex extends Component
{
use WithPagination;
public $action = 'list';
public $searchBy, $editId, $message, $keyword, $perPage = 10, $searchSelected = 'COMPANY', $selectedPatch = [], $totalItems;
protected $listeners = ['deleteItem', 'deleteSelected', 'showpatchListForm'];
public function mount()
{
$this->searchBy = [
'COMPANY' => 'Company',
'SNKEY' => 'Serverkey',
'CUR_VERSION' => 'Current Version',
'STATUS' => 'Status',
'DATABASETYPE' => 'Database',
'PHP_VERSION_ID' => 'PHP Version'
];
}
public function render()
{
$query = ConfServerLicense::select('ID', 'SNKEY', 'COMPANY', 'STATUS', 'CUR_VERSION', 'DATABASETYPE', 'LICENSEDATE');
if ($this->searchSelected == 'PHP_VERSION_ID') {
if ($this->keyword == '32') {
if ($this->searchSelected && $this->keyword) {
$query->whereIn('PHP_VERSION_ID', [0, 1]);
}
} elseif ($this->keyword == '64') {
if ($this->searchSelected && $this->keyword) {
$query->whereIn('PHP_VERSION_ID', [0, 2]);
}
} else {
$query->whereIn('PHP_VERSION_ID', []);
}
} else {
if ($this->searchSelected && $this->keyword) {
$query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
}
}
$query->orderBy('ID', 'DESC');
$results = $query->paginate($this->perPage);
$this->totalItems = $results->total();
return view('livewire.pages.server-license.server-license-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 showServerLicenseListForm()
{
$this->action = 'list';
}
public function showServerLicenseAddForm()
{
$this->action = 'add';
}
public function showServerLicenseEditForm($id)
{
$this->editId = $id;
$this->action = 'edit';
// $this->emit('showpatchEditForm');
}
public function showDeleteModal($id)
{
$this->emit('showDeleteModal', $id);
}
public function deleteItem($id)
{
$serverlicense = ConfServerLicense::where("ID", $id)->first();
$serverlicense->status = 'N';
$serverlicense->save();
$message = "Serverlicense status updated successfully";
$this->message = $message;
}
public function exportLicense()
{
return Excel::download(new ServerLicenseExport(), 'conf_server_license.xlsx');
}
}
<?php
namespace App\Http\Livewire\Pages\User;
use App\Models\User;
use App\Models\ManualResponse\UsersConnectSpn;
use App\Http\Controllers\ManualResponse\SpnConfigController;
use Livewire\Component;
class ConfigManualResponse extends Component
{
public $editUserId;
public $editUsername;
public $usernameSPN;
public $passwordSPN;
public $linkSPN;
public $action;
public function mount($editUserId)
{
$this->editUserId = $editUserId;
$currentUser = User::find($editUserId);
$this->editUsername = $currentUser->first_name;
$userConnectSpn = UsersConnectSpn::where('uid', $editUserId)->first();
if($userConnectSpn){
$this->usernameSPN = $userConnectSpn->username;
$this->passwordSPN = "";
$this->linkSPN = $userConnectSpn->link;
}
}
public function updateConfig()
{
if(empty($this->usernameSPN)){
$this->dispatchBrowserEvent('open-modal', [
'name' => 'alert-modal',
'message' => 'Username must not be empty!',
'status' => 'warning'
]);
return;
}
$userConnectSpn = UsersConnectSpn::where('uid', $this->editUserId)->first();
if($userConnectSpn){
if(!empty($this->passwordSPN)){
$userConnectSpn->password = password_hash($this->passwordSPN, PASSWORD_BCRYPT);
}
$userConnectSpn->username = $this->usernameSPN;
$userConnectSpn->link = $this->linkSPN;
$userConnectSpn->save();
}else{
UsersConnectSpn::create([
'uid' => $this->editUserId,
'username' => $this->usernameSPN,
'password' => password_hash($this->passwordSPN, PASSWORD_BCRYPT),
'link' => $this->linkSPN
]);
}
$this->dispatchBrowserEvent('open-modal', [
'name' => 'alert-modal',
'message' => 'Update config successfully',
'status' => 'success'
]);
}
public function render()
{
return view('livewire.pages.user.config-manual-response');
}
public function backToMainList()
{
//Use emitTo() to call function on specific component, (emit() will call function on every loaded compoment)
$this->emitTo('pages.user.user-index', 'showUserList', '');
}
public function testConnection()
{
//Use emitTo() to call function on specific component, (emit() will call function on every loaded compoment)
$userConnect = UsersConnectSpn::where('uid', $this->editUserId)->first();
if(!isset($userConnect)){
$this->dispatchBrowserEvent('open-modal', [
'name' => 'alert-modal',
'message' => 'SPN config is not found!',
'status' => 'failed'
]);
return;
}
$spnConfigController = new SpnConfigController();
$spnConfig = $spnConfigController->init_connection($userConnect);
if($spnConfig != null && $spnConfig['success'] == 'true'){
$this->dispatchBrowserEvent('open-modal', [
'name' => 'alert-modal',
'message' => 'Connect to SPN successfully',
'status' => 'success'
]);
}else if($spnConfig != null && $spnConfig['success'] == 'false'){
$this->dispatchBrowserEvent('open-modal', [
'name' => 'alert-modal',
'message' => $spnConfig['message'],
'status' => 'failed'
]);
}else{
//Cannot get UID/UCODE from SPN
$this->dispatchBrowserEvent('open-modal', [
'name' => 'alert-modal',
'message' => 'Cannot connect to SPN',
'status' => 'failed'
]);
}
}
}
<?php
namespace App\Http\Livewire\Pages\User;
use Livewire\Component;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Str;
class UserCreate extends Component
{
public $username, $first_name , $last_name, $phone , $email ,$password , $password_confirmation;
public $description;
public $action;
public $group_lists;
protected $rules = [
'username' => 'required|string|max:255|unique:users,username',
'email' => 'required|string|email|max:255|unique:users,email',
'password' => 'required|string|min:8|confirmed',
];
protected $messages = [
'username.required' => 'The username field is required.',
'email.required' => 'The email field is required.',
'email.email' => 'The email must be a valid email address.',
'email.unique' => 'This email address is already taken.',
'password.required' => 'The password field is required.',
'password.min' => 'The password must be at least 8 characters.',
'password.confirmed' => 'The password confirmation does not match.',
];
public function mount()
{
}
public function render()
{
return view('livewire.pages.User.User-create');
}
public function submitForm()
{
$this->validate();
$UsereData = [
'username' => $this->username,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'phone' => $this->phone,
'uid' => Str::random(40),
'email' => $this->email,
'password' => Hash::make($this->password)
];
$User = User::create($UsereData);
if (!empty($this->group_lists)) {
$arr_group_lists = explode(",", $this->group_lists);
if (!empty($arr_group_lists)) {
$User->groups()->sync($arr_group_lists);
} else {
$User->groups()->sync([]);
}
} else {
$User->groups()->sync([]);
}
$this->reset([
'username', 'email', 'description', 'group_lists'
]);
if (auth()->guest()) {
return redirect()->route('login');
}
$this->emit('showUserList', 'User successfully created.');
}
public function goBack()
{
if (auth()->guest()) {
return redirect()->route('login');
}
$this->emit('showUserList');
}
}
<?php
namespace App\Http\Livewire\Pages\User;
use Livewire\Component;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class UserEdit extends Component
{
public $editUserId;
public $userId;
public $user;
public $username, $first_name , $last_name, $phone ,$email, $current_password, $new_password, $new_password_confirmation ,$changePassword = false ;
public $group_lists;
protected function rules()
{
$rules = [
'username' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users,email,' . $this->user->id,
];
if ($this->changePassword) {
$rules['current_password'] = 'required|string|min:8';
$rules['new_password'] = 'nullable|string|min:8|confirmed';
}
return $rules;
}
protected $messages = [
'username.required' => 'The username field is required.',
'email.required' => 'The email field is required.',
'email.email' => 'The email must be a valid email address.',
'email.unique' => 'This email address is already taken.',
'current_password.required' => 'The current password field is required.',
'current_password.min' => 'The current password must be at least 8 characters.',
'new_password.min' => 'The new password must be at least 8 characters.',
'new_password.confirmed' => 'The new password confirmation does not match.',
];
public function mount($editUserId)
{
$this->editUserId = $editUserId;
$this->user = User::findOrFail($editUserId);
$this->username = $this->user->username;
$this->first_name = $this->user->first_name;
$this->last_name = $this->user->last_name;
$this->phone = $this->user->phone;
$this->email = $this->user->email;
$this->group_lists = $this->user->groups()->pluck('group_id')->implode(',');
}
public function render()
{
$userGroups = $this->user->groups()->pluck('group_id')->toArray();
return view('livewire.pages.user.user-edit', [
'userGroups' => $userGroups,
]);
}
public function submitEditForm()
{
$this->validate();
if ($this->changePassword && !Hash::check($this->current_password, $this->user->password)) {
$this->addError('current_password', 'The current password is incorrect.');
return;
}
$this->user->username = $this->username;
$this->user->email = $this->email;
$this->user->first_name = $this->first_name;
$this->user->last_name = $this->last_name;
$this->user->phone = $this->phone;
if ($this->changePassword) {
$this->user->password = Hash::make($this->new_password);
}
$this->user->save();
if (!empty($this->group_lists)) {
if(!is_array($this->group_lists)) {
$arr_group_lists = explode(",", $this->group_lists);
}else{
$arr_group_lists = $this->group_lists;
}
if (!empty($arr_group_lists)) {
$this->user->groups()->sync($arr_group_lists);
} else {
$this->user->groups()->sync([]);
}
} else {
$this->user->groups()->sync([]);
}
$this->reset(['current_password']); // Clear the password field after saving
$this->emit('showUserList', 'User successfully updated.');
}
public function goBack()
{
$this->emit('showUserList', '');
}
}
<?php
namespace App\Http\Livewire\Pages\User;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use Livewire\WithPagination;
class UserIndex extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $perPage = 10;
public $url;
public $searchSelected = 'username';
public $editUserId;
public $deleteUserId;
public $keyword = '';
public $route = '';
public $selectedOption = 'username';
public $searchBy;
public $menu;
public $action = 'list';
public $message;
public $selectedUsers = [];
public $showDeleteListModal = false;
public $showNoPermissionModal = false;
public $showMessage = false;
public $totalItems;
protected $listeners = ['showUserList', 'deleteItem', 'deleteSelected', 'setShowMessageFalse'];
public function mount()
{
$this->searchBy = [
'username' => 'Username',
'id'=> 'ID',
];
// $this->message = session('message');
// $this->showMessage = true;
}
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 render()
{
// \Log::info('searchSelected:', ['searchSelected' => $this->searchSelected]);
$results = $this->searchSelected && $this->keyword
? User::where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%')->paginate($this->perPage)
: User::paginate($this->perPage);
$this->totalItems = $results->total();
return view('livewire.pages.user.user-index', [
'results' => $results,
'route' => $this->route,
'url' => $this->url,
'selectedUsers' => $this->selectedUsers,
'showDeleteListModal' => $this->showDeleteListModal
]);
}
public function showUserAddForm()
{
// if (!Auth::user()->hasPermissions(['add-user'])) {
// $this->showNoPermissionModal = TRUE;
// return;
// }
$this->action = 'create';
}
public function showUserEditForm($UserId)
{
if (!Auth::user()->hasPermissions(['edit-user'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$this->action = 'edit';
$this->editUserId = $UserId;
}
public function showConfigManualResponseForm($UserId)
{
if (!Auth::user()->hasPermissions(['edit-user'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$this->action = 'configManualResponse';
$this->editUserId = $UserId;
}
public function hideMessage()
{
$this->showMessage = false;
}
public function showUserList($message = null)
{
$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($deleteUserId)
{
// if (!Auth::user()->hasPermissions(['delete-user'])) {
// $this->showNoPermissionModal = TRUE;
// return;
// }
$user = User::find($deleteUserId);
if ($user) {
$user->delete();
$message = "Deleted Successfully";
$this->message = $message;
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
}
public function deleteSelected($selectedUsers)
{
// if (!Auth::user()->hasPermissions(['delete-user'])) {
// $this->showNoPermissionModal = TRUE;
// return;
// }
$userDeleted = User::whereIn("id", $selectedUsers)->pluck('name')->toArray();
$userStr = implode(",", $userDeleted);
User::destroy($selectedUsers);
$message = "Deleted : (" . $userStr . " )Successfully";
$this->message = $message;
$this->selectedUsers = [];
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
}
<?php
namespace App\Http\Middleware;
use Barryvdh\Debugbar\Facades\Debugbar;
use Closure;
class DisableDebugbar
{
public function handle($request, Closure $next)
{
if (app()->bound('debugbar')) {
Debugbar::disable();
}
return $next($request);
}
}
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ExportChunkJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $rows;
protected $fileName;
public function __construct($rows, $fileName)
{
$this->rows = $rows;
$this->fileName = $fileName;
}
public function handle()
{
// ประมวลผลข้อมูลใน $rows
// เช่น ใช้ Excel::store() เพื่อสร้างไฟล์สำหรับ chunk นั้น
\Maatwebsite\Excel\Facades\Excel::store(new \App\Exports\ServerLicenseExport($this->rows), $this->fileName, 'local');
}
}
\ No newline at end of file
<?php
namespace App\Jobs;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\ServerLicenseExport;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class ExportReportJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $fileName;
public $jobId;
public function __construct($fileName, $jobId)
{
$this->fileName = $fileName;
$this->jobId = $jobId;
}
public function handle()
{
$totalRows = DB::table('conf_server_license')->count(); // จำนวนข้อมูลทั้งหมด
$processedRows = 0;
// ใช้ chunk เพื่อแบ่งการประมวลผล
DB::table('conf_server_license')->chunk(100, function ($rows) use (&$processedRows, $totalRows) {
// ประมวลผลข้อมูลใน chunk
Excel::store(new ServerLicenseExport($rows), $this->fileName, 'local');
// เพิ่มจำนวนข้อมูลที่ถูกประมวลผล
$processedRows += count($rows);
// คำนวณเปอร์เซ็นต์ความคืบหน้า
$progress = ($processedRows / $totalRows) * 100;
// อัปเดต progress ลงใน cache แทนฐานข้อมูล
Cache::put("export_progress_{$this->jobId}", $progress);
});
// ลบค่า progress เมื่อประมวลผลเสร็จสิ้น
Cache::forget("export_progress_{$this->jobId}");
}
}
\ No newline at end of file
...@@ -8,30 +8,71 @@ class SidebarPanel ...@@ -8,30 +8,71 @@ class SidebarPanel
public static function MainMenu() public static function MainMenu()
{ {
return [ return [
'title' => 'Menu', 'title' => '',
'items' => [ 'items' => [
[ [
'company_management' => [ 'configuration' => [
'title' => 'Company', 'title' => 'Configuration',
'route_name' => 'company.list' 'submenu' => [
], 'User Management' => [
'user_management' => [ 'title' => 'User Management',
'title' => 'User', 'route_name' => 'configurations.user.index'
'route_name' => 'user.list' ],
], 'Company Management' => [
'group' => [ 'title' => 'Company Management',
'title' => 'Group', 'route_name' => 'configurations.company.index'
'route_name' => 'group.list' ],
], 'Group' => [
'role' => [ 'title' => 'Group',
'title' => 'Role', 'route_name' => 'configurations.group.index'
'route_name' => 'role.list' ],
'Menu' => [
'title' => 'Menu Management',
'route_name' => 'configurations.menu.index'
],
'Company Type' => [
'title' => 'Company Type',
'route_name' => 'configurations.company-type.index'
],
'Importer Management' => [
'title' => 'Importer Management',
'route_name' => 'index'
]
]
], ],
'company_profile' => [ 'Server License Management' => [
'title' => 'Company Profile', 'title' => 'Server License Management',
'route_name' => 'company-profile.list' 'submenu' => [
'Create Patch Exchange Rate' => [
'title' => 'Create Patch Exchange Rate',
'route_name' => 'index'
],
'Master File From Customs' => [
'title' => 'Master File From Customs',
'route_name' => 'index'
],
'Send Patch To Customer' => [
'title' => 'Send Patch To Customer',
'route_name' => 'send-patch'
],
'Send Multi Patch To Customer' => [
'title' => 'Menu Management',
'route_name' => 'index'
],
'Patch Management' => [
'title' => 'Patch Management',
'route_name' => 'index'
],
'News Update' => [
'title' => 'News Update',
'route_name' => 'index'
],
'Create Discharge Port' => [
'title' => 'Create Discharge Port',
'route_name' => 'index'
]
]
], ],
] ]
] ]
]; ];
......
...@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Model; ...@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Model;
class CenterConfExchangerate extends Model class CenterConfExchangerate extends Model
{ {
public $timestamps = false;
protected $table = 'center_conf_exchangerate'; protected $table = 'center_conf_exchangerate';
protected $fillable = [ protected $fillable = [
'currency', 'currency',
......
...@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Model; ...@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Model;
class CenterConfExchangerateExport extends Model class CenterConfExchangerateExport extends Model
{ {
public $timestamps = false;
protected $table = 'center_conf_exchangerate_export'; protected $table = 'center_conf_exchangerate_export';
protected $fillable = [ protected $fillable = [
'currency', 'currency',
......
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Company extends Model
{
use SoftDeletes;
protected $table = 'companies';
protected $fillable = [
'id',
'company_type_id',
'name',
'name_en',
'address',
'district',
'sub_province',
'province',
'postcode',
'contry_code',
'phone',
'fax',
'tax',
'branch',
'tax_incentive',
'created_at',
'updated_at',
];
public function companyType()
{
return $this->belongsTo(CompanyType::class, 'company_type_id');
}
public function groups()
{
return $this->hasMany(Group::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CompanyType extends Model
{
protected $table = 'company_types';
protected $fillable = [
'id',
'name',
'created_at',
'updated_at',
];
}
...@@ -7,6 +7,9 @@ use Illuminate\Database\Eloquent\Model; ...@@ -7,6 +7,9 @@ use Illuminate\Database\Eloquent\Model;
class ConfFormatFile extends Model class ConfFormatFile extends Model
{ {
protected $table = 'conf_format_file'; protected $table = 'conf_format_file';
public $timestamps = false;
protected $primaryKey ='formatservice_ID';
protected $fillable = [ protected $fillable = [
'formatservice_ID', 'formatservice_ID',
'name', 'name',
......
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ConfListProfile extends Model
{
use HasFactory;
protected $table = 'conf_list_profiles';
protected $fillable = [
'id',
'name',
'type',
'desc',
];
}
...@@ -6,7 +6,9 @@ use Illuminate\Database\Eloquent\Model; ...@@ -6,7 +6,9 @@ use Illuminate\Database\Eloquent\Model;
class ConfParameter extends Model class ConfParameter extends Model
{ {
public $timestamps = false;
protected $table = 'conf_parameter'; protected $table = 'conf_parameter';
protected $fillable = [ protected $fillable = [
'PID', 'PID',
'name', 'name',
......
...@@ -7,6 +7,8 @@ use Illuminate\Database\Eloquent\Model; ...@@ -7,6 +7,8 @@ use Illuminate\Database\Eloquent\Model;
class ConfServerLicense extends Model class ConfServerLicense extends Model
{ {
protected $table = 'conf_server_license'; protected $table = 'conf_server_license';
public $timestamps = false;
protected $primaryKey = 'ID';
protected $fillable = [ protected $fillable = [
'ID', 'ID',
'SNKEY', 'SNKEY',
...@@ -37,6 +39,6 @@ class ConfServerLicense extends Model ...@@ -37,6 +39,6 @@ class ConfServerLicense extends Model
'CONTACTCUSTOMERNAME', 'CONTACTCUSTOMERNAME',
'CONTACT', 'CONTACT',
'CUSTOMERURL', 'CUSTOMERURL',
'MESSAGETYPE', 'MESSAGETYPE',
]; ];
} }
...@@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Model; ...@@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Model;
class ConfServerLicenseJavaversion extends Model class ConfServerLicenseJavaversion extends Model
{ {
protected $table = 'conf_server_license_javaversion'; protected $table = 'conf_server_license_javaversion';
public $timestamps = false;
protected $fillable = [ protected $fillable = [
'id', 'id',
'SNKEY', 'SNKEY',
......
...@@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Model; ...@@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Model;
class ConfServerLicenseOrgcontrol extends Model class ConfServerLicenseOrgcontrol extends Model
{ {
protected $table = 'conf_server_license_orgcontrol'; protected $table = 'conf_server_license_orgcontrol';
public $timestamps = false;
protected $fillable = [ protected $fillable = [
'id', 'id',
'SNKEY', 'SNKEY',
......