<?php
namespace App\Http\Livewire\Pages\Company;
use Livewire\Component;
use App\Models\Company;
class CompanyCreate extends Component
{
public $companyTypes ;
public $companyType = '1';
public $name;
public $tax;
public $branch;
public $name_en;
public $address;
public $district;
public $sub_province;
public $province;
public $postcode;
public $phone;
public $fax;
public $tax_incentive;
public $action ;
protected $rules = [
'companyType' => 'required|exists:company_types,id',
'name' => 'required|string|max:255',
'tax' => 'required|string|max:13',
'branch' => 'required|string|max:6',
'name_en' => 'required|string|max:255',
'address' => 'nullable|string|max:255',
'district' => 'nullable|string|max:255',
'sub_province' => 'nullable|string|max:255',
'province' => 'nullable|string|max:255',
'postcode' => 'nullable|string|max:10',
'phone' => 'nullable|string|max:15',
'fax' => 'nullable|string|max:15',
'tax_incentive' => 'nullable|string|max:255',
];
protected $messages = [
'companyType.required' => 'The company type field is required.',
'companyType.exists' => 'The selected company type is invalid.',
'name.required' => 'The name field is required.',
'name.string' => 'The name must be a string.',
'name.max' => 'The name may not be greater than 255 characters.',
'tax.required' => 'The tax field is required.',
'tax.integer' => 'The tax must be a integer.',
'tax.max' => 'The tax field must not exceed 13 characters.',
'branch.required' => 'The branch field is required.',
'branch.integer' => 'The branch must be a integer.',
'branch.max' => 'The branch field must not exceed 6 characters.',
'name_en.required' => 'The English name field is required.',
'name_en.string' => 'The English name must be a string.',
'name_en.max' => 'The English name may not be greater than 255 characters.',
'address.required' => 'The address field is required.',
'address.string' => 'The address must be a string.',
'address.max' => 'The address may not be greater than 255 characters.',
'district.required' => 'The district field is required.',
'district.string' => 'The district must be a string.',
'district.max' => 'The district may not be greater than 255 characters.',
'sub_province.required' => 'The sub-province field is required.',
'sub_province.string' => 'The sub-province must be a string.',
'sub_province.max' => 'The sub-province may not be greater than 255 characters.',
'province.required' => 'The province field is required.',
'province.string' => 'The province must be a string.',
'province.max' => 'The province may not be greater than 255 characters.',
'postcode.required' => 'The postcode field is required.',
'postcode.string' => 'The postcode must be a string.',
'postcode.max' => 'The postcode may not be greater than 10 characters.',
'phone.required' => 'The phone field is required.',
'phone.string' => 'The phone must be a string.',
'phone.max' => 'The phone may not be greater than 15 characters.',
'fax.string' => 'The fax must be a string.',
'fax.max' => 'The fax may not be greater than 15 characters.',
'tax_incentive.string' => 'The tax incentive must be a string.',
'tax_incentive.max' => 'The tax incentive may not be greater than 255 characters.',
];
public function mount($companyTypes)
{
$this->companyTypes = $companyTypes;
}
public function render()
{
return view('livewire.pages.company.company-create');
}
public function submitForm()
{
$validatedData = $this->validate();
// Create a new company instance
$newCompany = new Company();
$newCompany->company_type_id = $this->companyType;
$newCompany->name = $this->name;
$newCompany->tax = $this->tax;
$newCompany->branch = $this->branch;
$newCompany->name_en = $this->name_en ??' ';
$newCompany->address = $this->address ??' ';
$newCompany->district = $this->district ??' ';
$newCompany->sub_province = $this->sub_province ??' ';
$newCompany->province = $this->province ??' ';
$newCompany->postcode = $this->postcode ??' ';
$newCompany->phone = $this->phone ??' ';
$newCompany->fax = $this->fax ??' ';
$newCompany->tax_incentive = $this->tax_incentive ??' ';
// Save the new company to the database
$newCompany->save();
// Reset form fields
$this->reset([
'companyType', 'name', 'tax', 'branch', 'name_en', 'address', 'district',
'sub_province', 'province', 'postcode', 'phone', 'fax', 'tax_incentive'
]);
$this->emit('showCompanyList' , 'Company successfully created.');
}
public function goBack()
{
$this->emit('showCompanyList', '');
}
}
<?php
namespace App\Http\Livewire\Pages\Company;
use Livewire\Component;
use App\Models\Company;
class CompanyEdit extends Component
{
public $editCompanyId;
public $companyTypes;
public $company;
protected $rules = [
'company.company_type_id' => 'required|exists:company_types,id',
'company.name' => 'required|string|max:255',
'company.tax' => 'required|string|max:13',
'company.branch' => 'required|string|max:6',
'company.name_en' => 'required|string|max:255',
'company.address' => 'nullable|string|max:255',
'company.district' => 'nullable|string|max:255',
'company.sub_province' => 'nullable|string|max:255',
'company.province' => 'nullable|string|max:255',
'company.postcode' => 'nullable|string|max:10',
'company.phone' => 'nullable|string|max:15',
'company.fax' => 'nullable|string|max:15',
'company.tax_incentive' => 'nullable|string|max:255',
];
protected $messages = [
'company.company_type_id.required' => 'The company type field is required.',
'company.company_type_id.exists' => 'The selected company type is invalid.',
'company.name.required' => 'The name field is required.',
'company.name.string' => 'The name must be a string.',
'company.name.max' => 'The name may not be greater than 255 characters.',
'company.tax.required' => 'The tax field is required.',
'company.tax.integer' => 'The tax must be an integer.',
'company.tax.max' => 'The tax field must not exceed 13 characters.',
'company.branch.required' => 'The branch field is required.',
'company.branch.integer' => 'The branch must be an integer.',
'company.branch.max' => 'The branch field must not exceed 6 characters.',
'company.name_en.required' => 'The English name field is required.',
'company.name_en.string' => 'The English name must be a string.',
'company.name_en.max' => 'The English name may not be greater than 255 characters.',
'company.address.required' => 'The address field is required.',
'company.address.string' => 'The address must be a string.',
'company.address.max' => 'The address may not be greater than 255 characters.',
'company.district.required' => 'The district field is required.',
'company.district.string' => 'The district must be a string.',
'company.district.max' => 'The district may not be greater than 255 characters.',
'company.sub_province.required' => 'The sub-province field is required.',
'company.sub_province.string' => 'The sub-province must be a string.',
'company.sub_province.max' => 'The sub-province may not be greater than 255 characters.',
'company.province.required' => 'The province field is required.',
'company.province.string' => 'The province must be a string.',
'company.province.max' => 'The province may not be greater than 255 characters.',
'company.postcode.required' => 'The postcode field is required.',
'company.postcode.string' => 'The postcode must be a string.',
'company.postcode.max' => 'The postcode may not be greater than 10 characters.',
'company.phone.required' => 'The phone field is required.',
'company.phone.string' => 'The phone must be a string.',
'company.phone.max' => 'The phone may not be greater than 15 characters.',
'company.fax.string' => 'The fax must be a string.',
'company.fax.max' => 'The fax may not be greater than 15 characters.',
'company.tax_incentive.string' => 'The tax incentive must be a string.',
'company.tax_incentive.max' => 'The tax incentive may not be greater than 255 characters.',
];
public function mount($editCompanyId, $companyTypes)
{
$this->editCompanyId = $editCompanyId;
$this->companyTypes = $companyTypes;
$this->company = Company::find($editCompanyId);
}
public function render()
{
return view('livewire.pages.company.company-edit');
}
public function submitEditForm()
{
$this->validate();
$this->company->save();
$this->emit('showCompanyList', 'Company successfully updated.');
}
public function goBack()
{
$this->emit('showCompanyList', '');
}
}
<?php
namespace App\Http\Livewire\Pages\Company;
use Livewire\Component;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\Company;
use App\Models\CompanyType;
use Livewire\WithPagination;
class CompanyIndex extends Component
{
use WithPagination;
public $perPage = 10;
public $url;
public $searchSelected = 'name';
public $editCompanyId;
public $deleteCompanyId;
public $keyword = '';
public $route = '';
protected $paginationTheme = 'bootstrap';
public $selectedOption = 'name';
public $searchBy;
public $menu;
public $action = 'list';
public $message;
public $selectedCompanies = [];
public $showDeleteListModal = false;
public $showNoPermissionModal = false;
public $showMessage = false;
public $totalItems;
protected $listeners = ['showCompanyList', 'deleteItem', 'deleteSelected'];
public function mount()
{
$this->searchBy = [
'name' => 'Name',
'name_en' => 'Name English',
'tax_branch' => 'Tax:Branch'
];
$this->message = session('message');
}
public function render()
{
$query = Company::query();
if ($this->searchSelected && $this->keyword) {
if ($this->searchSelected === 'tax_branch') {
$parts = explode(':', $this->keyword);
if (count($parts) == 2) {
[$tax, $branch] = $parts;
$query->where('tax', 'LIKE', '%' . trim($tax) . '%')
->where('branch', 'LIKE', '%' . trim($branch) . '%');
} else {
$query->where('tax', 'LIKE', '%' . $this->keyword . '%')
->orWhere('branch', 'LIKE', '%' . $this->keyword . '%');
}
} else {
$query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
}
}
$results = $query->paginate($this->perPage);
$companyTypes = CompanyType::all();
$this->totalItems = $results->total();
return view('livewire.pages.company.company-index', [
'results' => $results,
'searchBy' => $this->searchBy,
'route' => $this->route,
'url' => $this->url,
'companyTypes' => $companyTypes,
'selectedCompanies' => $this->selectedCompanies,
'showDeleteListModal' => $this->showDeleteListModal
]);
}
public function updatedPerPage($value)
{
$this->adjustPageForNewPerPage();
}
public function adjustPageForNewPerPage()
{
$lastPage = ceil($this->totalItems / $this->perPage);
if ($this->page > $lastPage) {
$this->setPage($lastPage);
}
}
public function showCompanyCreateForm()
{
if (!\Auth::user()->hasPermissions(['add-company'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$this->action = 'create';
}
public function showCompanyEditForm($companyId)
{
if (!\Auth::user()->hasPermissions(['edit-company'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$this->action = 'edit';
$this->editCompanyId = $companyId;
}
public function showCompanyList($message = null)
{
$this->action = 'list';
$this->keyword = '';
$this->resetPage();
$this->message = $message;
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
public function paginationView()
{
return 'paginate-custom';
}
public function deleteItem($deleteCompanyId)
{
if (!\Auth::user()->hasPermissions(['delete-company'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$company = Company::find($deleteCompanyId);
if ($company) {
$company->delete();
$message = "Deleted Successfully";
$this->message = $message;
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
}
public function deleteSelected($selectedCompanies)
{
if (!\Auth::user()->hasPermissions(['delete-company'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$companyDeleted = Company::whereIn("id", $selectedCompanies)->pluck('name')->toArray();
$companyStr = implode(",", $companyDeleted);
Company::destroy($selectedCompanies);
$message = "Deleted : (" . $companyStr . " )Successfully";
$this->message = $message;
$this->selectedCompanies = [];
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
}
<?php
namespace App\Http\Livewire\Pages\Dischargeport;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\MasterDischargePort;
class DischargeportIndex extends Component
{
use WithPagination;
public $action = 'list';
public $searchBy, $message, $keyword, $perPage = 20, $searchSelected = 'isocode';
public $totalItems;
protected $listeners = [
'showdischargeportListForm',
'loadPage'
];
public function mount()
{
$this->searchBy = [
'isocode' => 'ISO Code',
'portname' => 'Port Name',
'cntrycode' => 'Country Code',
'flagstatus' => 'Flag Status',
'lastupdate' => 'Last Update'
];
$this->showdischargeportListForm();
$this->message = null;
}
public function render()
{
$query = MasterDischargePort::select(
'isocode',
'portname',
'cntrycode',
'startdate',
'finishdate',
'usrname',
'flagstatus',
'lastupdate'
);
if ($this->searchSelected && $this->keyword) {
$query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
}
$results = $query->paginate($this->perPage);
$this->totalItems = $results->total();
return view('livewire.pages.dischargeport.dischargeport-index', [
'results' => $results,
'action' => $this->action,
]);
}
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 showdischargeportListForm()
{
$this->action = 'list';
}
public function loadPage($page)
{
$this->action = $page;
}
}
<?php
namespace App\Http\Livewire\Pages\Dischargeport;
use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\DB;
use App\Models\MasterDischargePort;
use App\Models\MasterDischargePortCompare;
class DischargeportUpload extends Component
{
use WithFileUploads;
public $file;
public $fileUploaded = false;
// public function startUpload()
// {
// $this->fileUploaded = true;
// }
public function removeFile()
{
$this->file = null;
$this->fileUploaded = false;
}
public function uploadFile()
{
$this->validate([
'file' => 'required|file|mimes:txt,csv',
]);
$filePath = $this->file->getRealPath();
$file = fopen($filePath, 'r');
MasterDischargePortCompare::truncate();
while (($line = fgets($file)) !== false) {
$isocode = substr($line, 0, 5);
$portname = substr($line, 5, 100);
$cntrycode = substr($line, 0, 2);
$lastupdate = now();
MasterDischargePortCompare::updateOrCreate(
['isocode' => $isocode],
[
'portname' => htmlspecialchars(trim($portname)),
'cntrycode' => $cntrycode,
'usrname' => auth()->user()->name,
'lastupdate' => $lastupdate,
]
);
}
fclose($file);
$lastupdate = now();
// update portname
$updatePorts = DB::table('master_discharge_port_compare as c')
->leftJoin('master_discharge_port as p', 'c.isocode', '=', 'p.isocode')
->whereRaw("REPLACE(REPLACE(REPLACE(TRIM(c.portname),'&#039;','\''),'&amp;', '&'),'&quot;', '\"') <> p.portname")
->select('c.isocode', 'c.portname')
->get();
foreach ($updatePorts as $updatePort) {
DB::table('master_discharge_port')
->where('isocode', $updatePort->isocode)
->update([
'portname' => $updatePort->portname,
'lastupdate' => $lastupdate,
]);
}
// update flag
$updateFlags = DB::table('master_discharge_port as p')
->leftJoin('master_discharge_port_compare as c', 'p.isocode', '=', 'c.isocode')
->where('p.flagstatus', 'Y')
->whereNotNull('c.isocode')
->select('c.isocode')
->get();
foreach ($updateFlags as $updateFlag) {
DB::table('master_discharge_port')
->where('isocode', $updateFlag->isocode)
->update([
'flagstatus' => null,
'lastupdate' => $lastupdate,
]);
}
// update delete flagstatus (Y is delete)
$isoAll = DB::table('master_discharge_port')
->whereNotIn('isocode', function ($query) {
$query->select('isocode')
->from('master_discharge_port_compare');
})
->pluck('isocode');
if ($isoAll->isNotEmpty()) {
DB::table('master_discharge_port')
->whereIn('isocode', $isoAll)
->update([
'flagstatus' => 'Y',
'lastupdate' => $lastupdate,
]);
}
// INSERT not have
DB::table('master_discharge_port')
->insertUsing(['isocode', 'portname', 'cntrycode', 'usrname', 'lastupdate'], function ($query) {
$query->select('t2.*')
->from('master_discharge_port_compare as t2')
->leftJoin('master_discharge_port as t1', 't1.isocode', '=', 't2.isocode')
->whereNull('t1.isocode');
});
DB::table('master_discharge_port')
->where(function ($query) {
$query->where('usrname', '')
->orWhereNotNull('usrname');
})
->update(['usrname' => null]);
session()->flash('message', 'Upload File Success');
return redirect()->route('main');
}
public function render()
{
return view('livewire.pages.dischargeport.dischargeport-upload');
}
}
<?php
namespace App\Http\Livewire\Pages\Exchangerate;
use Livewire\Component;
use App\Models\CenterConfExchangerate;
use App\Models\CenterConfExchangerateExport;
use Carbon\Carbon;
class ExchangerateCreate extends Component
{
public $currency, $exdate, $finishdate, $rate, $baht, $exbaht, $pageCode = [];
public $searchByPage = [];
public function mount()
{
// Initial setup if necessary
}
public function addExchangerate()
{
$this->validate([
'currency' => 'required',
'exdate' => 'required',
'finishdate' => 'nullable',
'rate' => 'nullable|numeric',
'baht' => 'nullable|numeric',
'exbaht' => 'nullable|numeric',
]);
//$exdate = Carbon::createFromFormat('m/d/Y', $this->exdate)->format('Y-m-d');
//$finishdate = $this->finishdate ? Carbon::createFromFormat('m/d/Y', $this->finishdate)->format('Y-m-d') : null;
CenterConfExchangerate::create([
'currency' => $this->currency,
'exdate' => $this->exdate,
'finishdate' => $this->finishdate,
'rate' => $this->rate,
'baht' => $this->baht,
]);
CenterConfExchangerateExport::create([
'currency' => $this->currency,
'exdate' => $this->exdate,
'finishdate' => $this->finishdate,
'rate' => $this->rate,
'baht' => $this->exbaht,
]);
$this->reset(['currency', 'exdate', 'finishdate', 'rate', 'baht', 'exbaht']);
$this->emit('showexchangerateListForm');
session()->flash('message', 'Exchangerate added successfully!');
}
public function render()
{
return view('livewire.pages.exchangerate.exchangerate-create');
}
public function loadPage($page)
{
$this->action = $page;
}
}
<?php
namespace App\Http\Livewire\Pages\Exchangerate;
use Livewire\Component;
use App\Models\CenterConfExchangerate;
use App\Models\CenterConfExchangerateExport;
class ExchangerateEdit extends Component
{
public $currency, $exdate, $finishdate, $rate, $baht, $exbaht;
public function mount($currency, $exdate)
{
$exchangerate = CenterConfExchangerate::where('currency', $currency)
->where('exdate', $exdate)
->first();
if ($exchangerate) {
$this->currency = $exchangerate->currency;
$this->exdate = $exdate;
$this->finishdate = $exchangerate->finishdate;
$this->rate = $exchangerate->rate;
$this->baht = $exchangerate->baht;
$export = CenterConfExchangerateExport::where('currency', $currency)
->where('exdate', $exdate)
->first();
$this->exbaht = $export ? $export->baht : null;
}
}
public function updateExchangerate()
{
$this->validate([
'currency' => 'required',
'exdate' => 'required',
'finishdate' => 'nullable',
'rate' => 'nullable|numeric',
'baht' => 'nullable|numeric',
'exbaht' => 'nullable|numeric',
]);
CenterConfExchangerate::where('currency', $this->currency)
->where('exdate', $this->exdate)
->update([
'finishdate' => $this->finishdate,
'rate' => $this->rate,
'baht' => $this->baht,
]);
$export = CenterConfExchangerateExport::where('currency', $this->currency)
->where('exdate', $this->exdate)
->first();
if ($export) {
CenterConfExchangerateExport::where('currency', $this->currency)
->where('exdate', $this->exdate)
->update([
'finishdate' => $this->finishdate,
'rate' => $this->rate,
'baht' => $this->exbaht,
]);
} else {
CenterConfExchangerateExport::create([
'currency' => $this->currency,
'exdate' => $this->exdate,
'finishdate' => $this->finishdate,
'rate' => $this->rate,
'baht' => $this->exbaht,
]);
}
$this->emit('showexchangerateListForm');
session()->flash('message', 'Exchangerate updated successfully!');
}
public function render()
{
return view('livewire.pages.exchangerate.exchangerate-edit');
}
public function loadPage($page)
{
$this->action = $page;
}
}
<?php
namespace App\Http\Livewire\Pages\Exchangerate;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\CenterConfExchangerate;
use App\Models\CenterConfExchangerateExport;
class ExchangerateIndex extends Component
{
use WithPagination;
public $action = 'list';
public $searchBy, $editCurrency, $editExdate, $deleteCurrency, $deleteExdate, $message, $keyword, $perPage = 20, $searchSelected = 'center_conf_exchangerate.currency';
public $selectedExchangerates = [];
public $totalItems;
protected $listeners = [
'deleteItem',
'deleteSelected',
'showexchangerateListForm',
'loadPage'
];
public function mount()
{
$this->searchBy = [
'center_conf_exchangerate.currency' => 'By Currency',
'center_conf_exchangerate.exdate' => 'By Expired date',
'center_conf_exchangerate.finishdate' => 'By Finish date'
];
$this->showexchangerateListForm();
$this->message = null;
}
public function render()
{
$query = CenterConfExchangerate::select(
'center_conf_exchangerate.currency',
'center_conf_exchangerate.exdate',
'center_conf_exchangerate.finishdate',
'center_conf_exchangerate.rate',
'center_conf_exchangerate.baht',
'center_conf_exchangerate.amenddate',
'center_conf_exchangerate_export.baht as exbaht'
)
->join('center_conf_exchangerate_export', function ($join) {
$join->on('center_conf_exchangerate.currency', '=', 'center_conf_exchangerate_export.currency')
->on('center_conf_exchangerate.exdate', '=', 'center_conf_exchangerate_export.exdate')
->on('center_conf_exchangerate.finishdate', '=', 'center_conf_exchangerate_export.finishdate');
});
if ($this->searchSelected && $this->keyword) {
$query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
}
$query->orderBy('center_conf_exchangerate.exdate', 'DESC')
->orderBy('center_conf_exchangerate_export.exdate', 'DESC')
->orderBy('center_conf_exchangerate.currency', 'DESC')
->orderBy('center_conf_exchangerate_export.currency', 'DESC');
$results = $query->paginate($this->perPage);
$this->totalItems = $results->total();
return view('livewire.pages.exchangerate.exchangerate-index', compact('results'));
}
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 showexchangerateListForm()
{
$this->action = 'list';
}
public function showexchangerateAddForm()
{
$this->action = 'add';
}
public function showexchangerateEditForm($currency, $exdate)
{
$this->editCurrency = $currency;
$this->editExdate = $exdate;
$this->action = 'edit';
}
public function deleteExchangerate($currency, $exdate)
{
CenterConfExchangerate::where('currency', $currency)
->where('exdate', $exdate)
->delete();
CenterConfExchangerateExport::where('currency', $currency)
->where('exdate', $exdate)
->delete();
session()->flash('message', 'Exchangerate deleted successfully!');
$this->showexchangerateListForm();
}
public function deleteSelectedExchangerates()
{
foreach ($this->selectedExchangerates as $exchangerate) {
$parts = explode(',', $exchangerate);
CenterConfExchangerate::where('currency', $parts[0])
->where('exdate', $parts[1])
->delete();
CenterConfExchangerateExport::where('currency', $parts[0])
->where('exdate', $parts[1])
->delete();
}
session()->flash('message', 'Selected Exchangerates deleted successfully!');
$this->selectedExchangerates = [];
$this->showexchangerateListForm();
}
public function deleteItem($currency, $exdate)
{
$this->deleteExchangerate($currency, $exdate);
}
public function deleteSelected()
{
$this->deleteSelectedExchangerates();
}
public function loadPage($page)
{
$this->action = $page;
}
}
<?php
namespace App\Http\Livewire\Pages\Exchangerate;
use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Storage;
use App\Models\CenterConfExchangerate;
use App\Models\CenterConfExchangerateExport;
use App\Models\ConfSmartupdate;
use Illuminate\Support\Facades\DB;
class ExchangerateUpload extends Component
{
use WithFileUploads;
public $file;
public $createPatch = false;
public $updatePatch = false;
public $sendToEec = false;
public function upload()
{
$this->validate([
'file' => 'required|mimes:csv,txt|max:2048',
]);
$temporaryFilePath = 'livewire-tmp/' . $this->file->getFilename();
if ($this->sendToEec) {
$absolutePath = Storage::disk('public')->path($temporaryFilePath);
$absolutePath = str_replace('/', '\\', $absolutePath);
$resultEEC = $this->sendMasterFileToEcc($absolutePath);
}
if ($this->createPatch && $this->updatePatch) {
session()->flash('message', 'กรุณาเลือกอย่างใดอย่างหนึ่ง Create หรือ Update.');
return;
}
if ($this->createPatch || $this->updatePatch) {
$absolutePath = Storage::disk('public')->path($temporaryFilePath);
$absolutePath = str_replace('/', '\\', $absolutePath);
$this->processFileForPatch($absolutePath);
}
}
private function sendMasterFileToEcc($filePath)
{
$url = env('URL_MASTERFILE_EEC');
$postData = [
'type' => 'exchange-rate',
'file' => curl_file_create(Storage::path($filePath)),
'timestamp' => now()->format('Y-m-d')
];
$curl = curl_init();
$options = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => [
"cache-control: no-cache",
"content-type: multipart/form-data"
],
];
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$err = curl_error($curl);
$info = curl_getinfo($curl);
curl_close($curl);
return $info;
}
private function processFileForPatch($filePath)
{
$fileContent = file_get_contents($filePath);
$lines = explode("\n", $fileContent);
$needChkDup = true;
$array_cur = [];
$Loop_pathcode = '';
foreach ($lines as $line) {
$CUR = substr($line, 0, 3);
if ($CUR != '') {
if (!in_array($CUR, $array_cur, true)) {
$array_cur[] = $CUR;
}
$DATE1 = substr($line, 3, 8);
$d1 = substr($DATE1, 0, 2);
$m1 = substr($DATE1, 2, 2);
$y1 = substr($DATE1, 4, 4);
$DATE1 = "$y1-$m1-$d1";
$DATE2 = substr($line, 11, 8);
$d2 = substr($DATE2, 0, 2);
$m2 = substr($DATE2, 2, 2);
$y2 = substr($DATE2, 4, 4);
$DATE2 = "$y2-$m2-$d2";
$EXRATE = trim(substr($line, 19, 13));
$IMRATE = trim(substr($line, 32, 13));
$FACT = trim(substr($line, 45, 7));
$AMMENDDATE = now()->format('Ymd') + 543;
if ($needChkDup && $this->createPatch) {
$latestRecord = CenterConfExchangerate::selectRaw('MONTH(MAX(center_conf_exchangerate.exdate)) as month, YEAR(MAX(center_conf_exchangerate.exdate)) as year')
->join('center_conf_exchangerate_export', function($join) {
$join->on('center_conf_exchangerate.currency', '=', 'center_conf_exchangerate_export.currency')
->on('center_conf_exchangerate.exdate', '=', 'center_conf_exchangerate_export.exdate')
->on('center_conf_exchangerate.finishdate', '=', 'center_conf_exchangerate_export.finishdate');
})->first();
//DB::enableQueryLog();
$chk = ConfSmartupdate::whereMonth('PDATE', $m2)
->whereYear('PDATE', $y2)
->where('PTYPE', 'UPDATE MASTER NEW')
->exists();
//dd(DB::getQueryLog());
if ($chk === true) {
session()->flash('message', 'ไม่สามารถเพิ่ม Patch เดือน '.$m2.' ปี '.$y2.' ได้เนื่องจากได้มีการเพิ่มข้อมูลไว้ในระบบเรียบร้อยแล้ว.');
return false;
}
// session()->forget('message');
$needChkDup = false;
}
CenterConfExchangerate::updateOrInsert(
[
'currency' => $CUR,
'exdate' => $DATE1,
],
[
'finishdate' => $DATE2,
'baht' => $IMRATE,
'rate' => $FACT,
'amenddate' => $AMMENDDATE
]
);
CenterConfExchangerateExport::updateOrInsert(
[
'currency' => $CUR,
'exdate' => $DATE1,
],
[
'finishdate' => $DATE2,
'baht' => $EXRATE,
'rate' => $FACT,
'amenddate' => $AMMENDDATE
]
);
if ($this->updatePatch) {
$y2 = str_pad($y2, 4, '0', STR_PAD_LEFT);
$m2 = str_pad($m2, 2, '0', STR_PAD_LEFT);
$UPDATECODE_update = $y2 . $m2;
$countExist = CenterConfExchangerate::where('exdate', $DATE1)
->where('currency', $CUR)
->count();
if ($countExist != 0) {
CenterConfExchangerate::where('currency', $CUR)
->where('exdate', $DATE1)
->update(['finishdate' => $DATE2]);
}
$countExistEx = CenterConfExchangerateExport::where('exdate', $DATE1)
->where('currency', $CUR)
->count();
if ($countExistEx != 0) {
CenterConfExchangerateExport::where('currency', $CUR)
->where('exdate', $DATE1)
->update(['finishdate' => $DATE2]);
}
$countExist = CenterConfExchangerate::where('exdate', $DATE1)
->where('currency', $CUR)
->count();
if ($countExist == 0) {
CenterConfExchangerate::create([
'currency' => $CUR,
'exdate' => $DATE1,
'finishdate' => $DATE2,
'rate' => $FACT,
'baht' => $IMRATE,
'amenddate' => $UPDATECODE_update
]);
CenterConfExchangerateExport::create([
'currency' => $CUR,
'exdate' => $DATE1,
'finishdate' => $DATE2,
'rate' => $FACT,
'baht' => $EXRATE,
'amenddate' => $UPDATECODE_update
]);
}
if ($this->updatePatch) {
while(strlen($y2)<4){$y2="0".$y2;}
while(strlen($m2)<2){$m2="0".$m2;}
$UPDATECODE_update= $y2.$m2;
$Loop_pathcode .= '
Query2Var("select count(*) as countExist from conf_exchangerate where exdate=\''.$DATE1.'\' and currency =\''.$CUR.'\'");
if($countExist!=0){
exec_query("update conf_exchangerate SET finishdate=\''.$DATE2.'\'
where currency=\''.$CUR.'\' and exdate =\''.$DATE1.'\'");
}
Query2Var("select count(*) as countExistEx from conf_exchangerate_export where exdate=\''.$DATE1.'\' and currency =\''.$CUR.'\'");
if($countExistEx!=0){
exec_query("update conf_exchangerate_export SET finishdate=\''.$DATE2.'\'
where currency=\''.$CUR.'\' and exdate =\''.$DATE1.'\'");
}
Query2Var("select count(*) as countExist from conf_exchangerate where exdate=\''.$DATE1.'\' and currency =\''.$CUR.'\'");
if($countExist==0){
if($DBTYPE==\'MYSQL\'){
exec_query("insert into conf_exchangerate (currency,exdate,finishdate,rate,baht,amenddate)
VALUES (\''.$CUR.'\',\''.$DATE1.'\',\''.$DATE2.'\',\''.$FACT.'\',\''.$IMRATE.'\',\''.$UPDATECODE_update.'\')");
exec_query("insert into conf_exchangerate_export (currency,exdate,finishdate,rate,baht,amenddate)
VALUES (\''.$CUR.'\',\''.$DATE1.'\',\''.$DATE2.'\',\''.$FACT.'\',\''.$EXRATE.'\',\''.$UPDATECODE_update.'\')");
}
}
Query2Var("select count(*) as countExist from conf_exchangerate where exdate=\''.$DATE1.'\' and currency =\''.$CUR.'\'");
if($countExist==0){
if($DBTYPE==\'MSSQL\'){
exec_query("insert into conf_exchangerate ([currency],[exdate],[finishdate],[rate],[baht],[amenddate])
VALUES (\''.$CUR.'\',\''.$DATE1.'\',\''.$DATE2.'\',\''.$FACT.'\',\''.$IMRATE.'\',\''.$UPDATECODE_update.'\')");
exec_query("insert into conf_exchangerate_export ([currency],[exdate],[finishdate],[rate],[baht],[amenddate])
VALUES (\''.$CUR.'\',\''.$DATE1.'\',\''.$DATE2.'\',\''.$FACT.'\',\''.$EXRATE.'\',\''.$UPDATECODE_update.'\')");
}
}
';
}
}
}
}
//GEN Patch
$ins_addMonth = $m2;
$ins_addYear = $y2;
$ins_addDay = $d1;
if ($this->updatePatch) {
$PDESC = "(UPDATE) อัตราแลกเปลี่ยนของขาเข้า และขาออก เดือน ". $this->monthToThai($m2) ."ปี $y2";
$PTYPE = "Specific Customer";
$PDATE = now()->format('Y-m-d H:i:s');
$PLEVEL = "Critical";
$PCODE = "";
$MAJOR_VERSION = 'All';
$POWNER = auth()->user()->id;
$PATCHCODE = $Loop_pathcode.' $PATCH_STATUS="OK";';
// $PATCHCODE = str_replace("'", "\'", $PATCHCODE);
$UNINSTALL='$b=1';
$next_PID = DB::table('information_schema.tables')
->where('table_name', 'conf_smartupdate')
->value('AUTO_INCREMENT');
// Using Eloquent to get the data
$patchFiles = DB::table('tab_patch_file')->where('ptid', $next_PID)->get();
$PATCHCODE_SERVER = "$"."a=1;\nQuery2Array(\"select * from tab_patch_file where ptid='".$next_PID."'\");\nfor("."$"."i=0;"."$"."i<count("."$"."fid);"."$"."i++){\n"."$"."{'file_name_'."."$"."i}="."$"."file_name["."$"."i];\n"."$"."{'file_data_'."."$"."i}="."$"."file_data["."$"."i];\n}\n"."$"."max=count("."$"."fid);";
// $PATCHCODE_SERVER=str_replace("'","''",$PATCHCODE_SERVER);
$PATCHCODE_SERVER=str_replace("\\","\\\\",$PATCHCODE_SERVER);
$arr_cur_str = "[".implode(",",$array_cur)."]";
$PATCHNAME="Update : Exchange Rate Import & Export $m2 / $y2 ".$arr_cur_str;
ConfSmartupdate::create([
'PATCHNAME' => $PATCHNAME,
'PDATE' => $PDATE,
'PLEVEL' => $PLEVEL,
'PCODE' => $PCODE,
'MAJOR_VERSION' => $MAJOR_VERSION,
'PDESC' => $PDESC,
'POWNER' => $POWNER,
'PTYPE' => $PTYPE,
'PATCHCODE' => $PATCHCODE,
'UNINSTALL' => $UNINSTALL,
'PATCHCODE_SERVER' => $PATCHCODE_SERVER,
'PAPPROVEDATE' => now()
]);
session()->flash('message', 'อัพเดท Patch เดือน '.$m2.' ปี '.$y2.' ในระบบเรียบร้อยแล้ว.');
}
if ($this->createPatch) {
$PDESC = "อัตราแลกเปลี่ยนของขาเข้า และขาออก เดือน ". $this->monthToThai($ins_addMonth) ."ปี $ins_addYear";
$PTYPE = "UPDATE MASTER NEW";
$PDATE = "$ins_addYear-$ins_addMonth-$ins_addDay 00:00:00";
$PLEVEL = "AUTO";
$PCODE = "SHIPPINGNET";
$MAJOR_VERSION = 'All';
$POWNER = auth()->user()->id;
$PATCHCODE = Storage::get('patchcode_new.txt');
// $PATCHCODE = str_replace("'", "''", $PATCHCODE);
$UNINSTALL = Storage::get('uninstall_new.txt');
// $UNINSTALL = str_replace("'", "''", $UNINSTALL);
$i=0;
$PATCHCODE_SERVER = '';
$filePath = 'patchcode_server_new.txt';
$fileContent = Storage::get($filePath);
foreach (explode("\n", $fileContent) as $tmp) {
if ($i==0) {
$PATCHCODE_SERVER .= '$MONTH="'.$ins_addYear.'-'.$ins_addMonth.'-%";';
} else if ($i==1) {
$PATCHCODE_SERVER .= '$UPDATECODE="'.$ins_addYear.$ins_addMonth.'";';
} else {
$PATCHCODE_SERVER .= $tmp;
}
$i++;
}
// $PATCHCODE_SERVER = str_replace("'", "''", $PATCHCODE_SERVER);
$PATCHNAME = "Exchange Rate Import & Export $ins_addMonth / $ins_addYear";
ConfSmartupdate::create([
'PATCHNAME' => $PATCHNAME,
'PDATE' => $PDATE,
'PLEVEL' => $PLEVEL,
'PCODE' => $PCODE,
'MAJOR_VERSION' => $MAJOR_VERSION,
'PDESC' => $PDESC,
'POWNER' => $POWNER,
'PTYPE' => $PTYPE,
'PATCHCODE' => $PATCHCODE,
'UNINSTALL' => $UNINSTALL,
'PATCHCODE_SERVER' => $PATCHCODE_SERVER,
'PAPPROVEDATE' => now()
]);
session()->flash('message', 'สร้าง Patch เดือน '.$ins_addMonth.' ปี '.$ins_addYear.' ในระบบเรียบร้อยแล้ว.');
}
}
private function monthToThai($m)
{
$thai_n = ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"];
$m = (int) $m;
return $thai_n[$m-1];
}
private function findHTX($filename)
{
// Implement findHTX logic based on your requirements
return $filename;
}
public function render()
{
return view('livewire.pages.exchangerate.exchangerate-upload');
}
}
?>
<?php
namespace App\Http\Livewire\Pages\FormatFileMaster;
use Livewire\Component;
use App\Models\ConfFormatFile;
use Livewire\WithFileUploads;
class FileCreate extends Component
{
use WithFileUploads;
public $name;
public $file;
protected $rules = [
'name' => 'required|string|max:255',
];
public function updatedFile()
{
$this->validate([
'file' => 'required|file|mimes:txt|max:10240', // 10MB max file size
]);
}
public function save()
{
$this->validate();
if ($this->file) {
$filePath = $this->file->store('runtime/format', 'public');
}
$date = date("Ymd");
$timestamp = date("His");
$fileFormat = new ConfFormatFile;
$fileFormat->name = $this->name;
$fileFormat->file = $filePath;
$fileFormat->date = $date;
$fileFormat->timestamp = $timestamp;
$fileFormat->save();
$this->reset(['name', 'file']);
return redirect()->route('format-file-master.index')->with('message', 'Format File saved successfully.');
}
public function render()
{
return view('livewire.pages.format-file-master.file-create');
}
}
<?php
namespace App\Http\Livewire\Pages\FormatFileMaster;
use App\Models\ConfFormatFile;
use Livewire\Component;
use App\Models\Role;
use App\Models\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class FileEdit extends Component
{
public $editId;
public $file;
public $name;
protected $rules = [
'role.name' => 'required',
];
public function mount($editId)
{
$this->editId = $editId;
$fileFormat = ConfFormatFile::findOrFail($this->editId);
$this->name = $fileFormat->name;
}
public function render()
{
return view('livewire.pages.format-file-master.file-edit');
}
public function submitEditForm()
{
$this->validate();
$filePath = null;
if ($this->file) {
if ($this->isEditMode && $this->editId) {
$oldFile = ConfFormatFile::find($this->editId)->file;
if ($oldFile && Storage::disk('public')->exists($oldFile)) {
Storage::disk('public')->delete($oldFile);
}
}
$filePath = $this->file->store('runtime/format', 'public');
}
$date = date("Ymd");
$timestamp = date("His");
if ($this->isEditMode && $this->editId) {
$fileFormat = ConfFormatFile::findOrFail($this->editId);
} else {
$fileFormat = new ConfFormatFile;
}
$fileFormat->name = $this->name;
if ($filePath) {
$fileFormat->file = $filePath;
}
$fileFormat->date = $date;
$fileFormat->timestamp = $timestamp;
$fileFormat->save();
$this->reset(['name', 'file']);
return redirect()->route('format-file-master.index')->with('message', 'Format File saved successfully.');
}
public function goBack()
{
$this->emit('showRoleList', '');
}
}
<?php
namespace App\Http\Livewire\Pages\FormatFileMaster;
use App\Models\ConfFormatFile;
use Livewire\Component;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\Role;
use App\Models\Permission;
use Livewire\WithPagination;
class FileIndex extends Component
{
use WithPagination;
public $perPage = 10;
public $searchSelected = 'name';
public $editId;
public $deleteId;
public $keyword = '';
public $route = '';
public $selectedOption = 'name';
public $searchBy;
public $menu;
public $action = 'list';
public $message;
public $showDeleteListModal = false;
public $showMessage = false;
protected $listeners = [ 'showRoleList', 'deleteItem' , 'deleteSelected'];
public function mount()
{
$this->searchBy = [
'name' => 'Name',
'fiel' => 'File'
];
$this->message = session('message');
}
public function render()
{
$query = ConfFormatFile::select('formatservice_ID', 'name', 'file', 'date', 'timestamp', 'ac');
if ($this->searchSelected && $this->keyword) {
$query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
}
$query->orderBy('formatservice_ID', 'DESC');
$results = $query->paginate($this->perPage);
return view('livewire.pages.format-file-master.file-index', compact('results'));
}
public function search()
{
$this->resetPage();
}
public function showListForm()
{
$this->action = 'list';
}
public function showAddForm()
{
$this->action = 'add';
}
public function showEditForm($id)
{
$this->editId= $id;
$this->action = 'edit';
}
public function showDeleteModal($patchFileId)
{
$this->emit('showDeleteModal' ,$patchFileId);
}
public function deleteItem($id) {
$file = ConfFormatFile::where("formatservice_ID", $id)->delete();
$message = "Deleted Patch ID : " . json_encode($file) . " Successfully";
$this->message = $message;
}
}
<?php
namespace App\Http\Livewire\Pages\Group;
use Livewire\Component;
use App\Models\Group;
class GroupCreate extends Component
{
public $name ,$companies , $company;
public $description;
public $action;
public $role_lists;
public $user_lists;
protected $rules = [
'name' => 'required',
];
public function mount($companies)
{
$this->companies = $companies;
}
public function render()
{
return view('livewire.pages.group.group-create');
}
public function submitForm()
{
$validatedData = $this->validate([
'name' => 'required'
]);
$this->company = isset($this->company) && $this->company != null ? $this->company : $this->companies->first()->id ?? null;
$groupeData = [
'name' => $this->name,
'company_id' => $this->company
];
$group = Group::create($groupeData);
$arr_role_lists = explode(",",$this->role_lists);
$arr_user_lists = explode(",",$this->user_lists);
if (!empty($this->role_lists)) {
$group->roles()->sync($arr_role_lists);
}
// dd($group->roles);
if (!empty($this->user_lists)) {
$group->users()->sync($arr_user_lists);
}
// Reset form fields
$this->reset([
'name', 'company' ,'description', 'role_lists' , 'user_lists'
]);
$this->emit('showGroupList', 'Group successfully created.');
}
public function goBack()
{
$this->emit('showGroupList', '');
}
}
<?php
namespace App\Http\Livewire\Pages\Group;
use Livewire\Component;
use App\Models\Group;
use App\Models\Permission;
class GroupEdit extends Component
{
public $editGroupId;
public $permissions;
public $groupId;
public $group;
public $name ,$companies , $company;
public $role_lists;
public $user_lists;
protected $rules = [
'name' => 'required',
// 'group.company_id' => 'required',
];
public function mount($editGroupId, $roles, $users, $companies)
{
$this->editGroupId = $editGroupId;
$this->group = Group::findOrFail($editGroupId);
$this->name = $this->group->name;
$this->company = $this->group->company_id;
}
public function render()
{
$groupRoles = $this->group->roles()->pluck('role_id')->toArray();
$groupUsers = $this->group->users()->pluck('user_id')->toArray();
return view('livewire.pages.group.group-edit' , [
'groupRoles' => $groupRoles,
'groupUsers' => $groupUsers
]);
}
public function submitEditForm()
{
$this->validate();
$this->company = isset($this->company) && $this->company != null ? $this->company : $this->companies->first()->id ?? null;
$groupeData = [
'name' => $this->name,
'company_id' => $this->company
];
$this->group->update($groupeData);
$arr_role_lists = explode(",",$this->role_lists);
$arr_user_lists = explode(",",$this->user_lists);
$this->group->roles()->sync($arr_role_lists);
$this->group->users()->sync($arr_user_lists);
$this->emit('showGroupList', 'Group successfully updated.');
}
public function goBack()
{
$this->emit('showGroupList', '');
}
}
<?php
namespace App\Http\Livewire\Pages\Group;
use Livewire\Component;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\Group;
use App\Models\Role;
use App\Models\User;
use App\Models\Company;
use Livewire\WithPagination;
class GroupIndex extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $perPage = 10;
public $url;
public $searchSelected = 'name';
public $editGroupId;
public $deleteGroupId;
public $keyword = '';
public $route = '';
public $selectedOption = 'name';
public $searchBy;
public $menu;
public $action = 'list';
public $message;
public $selectedGroups = [];
public $showDeleteListModal = false;
public $showNoPermissionModal = false;
public $showMessage = false;
public $totalItems;
protected $listeners = ['showGroupList', 'deleteItem', 'deleteSelected'];
public function mount()
{
$this->searchBy = [
'name' => 'Name',
];
$this->message = session('message');
}
public function render()
{
// \Log::info('searchSelected:', ['searchSelected' => $this->searchSelected]);
$results = $this->searchSelected && $this->keyword
? Group::where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%')->paginate($this->perPage)
: Group::paginate($this->perPage);
$roles = Role::all();
$users = User::all();
$companies = Company::all();
$this->totalItems = $results->total();
return view('livewire.pages.group.group-index', [
'results' => $results,
'route' => $this->route,
'url' => $this->url,
'roles' => $roles,
'users' => $users,
'companies' => $companies,
'selectedGroups' => $this->selectedGroups,
'showDeleteListModal' => $this->showDeleteListModal
]);
}
public function updatedPerPage($value)
{
$this->adjustPageForNewPerPage();
}
public function adjustPageForNewPerPage()
{
$lastPage = ceil($this->totalItems / $this->perPage);
if ($this->page > $lastPage) {
$this->setPage($lastPage);
}
}
public function showGroupCreateForm()
{
// if (!\Auth::user()->hasPermissions(['add-group'])) {
// $this->showNoPermissionModal = TRUE;
// return;
// }
$this->action = 'create';
}
public function showGroupEditForm($groupId)
{
if (!\Auth::user()->hasPermissions(['edit-group'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$this->action = 'edit';
$this->editGroupId = $groupId;
}
public function showGroupList($message)
{
$this->action = 'list';
$this->keyword = '';
$this->message = $message;
$this->resetPage();
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
public function paginationView()
{
return 'paginate-custom';
}
public function deleteItem($deleteGroupId)
{
if (!\Auth::user()->hasPermissions(['delete-group'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$group = Group::find($deleteGroupId);
if ($group) {
$group->delete();
$message = "Deleted Successfully";
$this->message = $message;
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
}
public function deleteSelected($selectedGroups)
{
if (!\Auth::user()->hasPermissions(['delete-group'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$groupDeleted = Group::whereIn("id", $selectedGroups)->pluck('name')->toArray();
$groupStr = implode(",", $groupDeleted);
Group::destroy($selectedGroups);
$message = "Deleted : (" . $groupStr . " )Successfully";
$this->message = $message;
$this->selectedGroups = [];
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
}
<?php
namespace App\Http\Livewire\Pages\ManualResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use App\Http\Controllers\ManualResponse\GenXmlController;
use App\Http\Controllers\ManualResponse\SpnConfigController;
use App\Models\ConfListProfile;
use App\Models\ManualResponse\MasterMessages;
use App\Models\ManualResponse\MasterResponseTemplates;
use App\Models\ManualResponse\MasterDocTypes;
use App\Models\ManualResponse\TabManualResponseLog;
use App\Models\ManualResponse\UsersConnectSpn;
use App\Models\MasterResponseMessageType;
use Carbon\Carbon;
use CURLFile;
class ManualResponse extends Component
{
public $displayCustomizeDiv = false;
public $masterMsg , $showSearch;
public $messageTypes = [];
public $messageId;
public $responseTemplates = [];
public $templateId;
public $templateList;
public $docTypes = [];
public $docType;
public $xmlContent;
public $xmlData = [];
public $xmlWithData = [];
public $activeLoader = false;
public $changeBtnColor;
public $lockData;
public $disableLockData = true;
public $structureXML;
public $disableDocType = false;
protected $rules = [
'messageId' => 'required|string',
'templateId' => 'required|string'
];
protected $messages = [
'messageId.required' => '*Message cannot be empty.',
'templateId.required' => '*Template cannot be empty.'
];
protected $listNonLockData = [
"MessageType",
"AuditDateTime",
"Message",
"Status"
];
public function mount()
{
$this->messageTypes = MasterMessages::pluck('value', 'id')->toArray();
$this->docTypes = MasterDocTypes::pluck('name', 'code')->toArray();
$this->changeBtnColor = "bg-[#A020F0] hover:bg-[#B34FEF] text-white font-bold";
$this->lockData = false;
$this->disableLockData = true;
}
public function render()
{
if ($this->messageId != '') {
$this->responseTemplates = MasterResponseTemplates::where('mid', $this->messageId)->get()->mapWithKeys(function ($record) {
$description = $record->description != '' ? ' ' . ' (' . $record->description . ')' : '';
return [$record->id => $record->code . ': ' . $record->name . $description];
})->toArray();
$this->docTypes = MasterDocTypes::where('mid', $this->messageId)->pluck('name', 'code')->toArray();
}
return view('livewire.pages.manual-response.manual-response-index');
}
public function updatedMessageId()
{
$this->templateId = '';
$this->responseTemplates = [];
$this->docTypes = [];
$this->docType = '';
$this->xmlData = [];
$this->xmlContent = '';
$this->displayCustomizeDiv = false;
if($this->messageId == 3 || $this->messageId == 4){
$this->disableDocType = true;
}else{
$this->disableDocType = false;
}
$this->lockData = false;
}
public function updatedXmlTagInputList()
{
if ($this->xmlData === null) {
$this->xmlContent = '';
}
}
public function gotoCustomize()
{
$this->disableLockData = false;
$tmp_xmlData = $this->xmlData;
$this->xmlData = [];
$this->xmlContent = '';
$this->validate();
//Default documentType in case messsage is export/import
if(empty($this->docType)){
if($this->messageId == 1){
$this->docType = 1;
}else if($this->messageId == 2){
$this->docType = 0;
}
}
$xmlGenerator = new GenXmlController();
$xml = $xmlGenerator->generateXML($this->templateId, $this->docType, $this->lockData);
if ($xml == null) {
session()->flash('templateNotFound', 'Template is not found!');
} else {
$this->displayCustomizeDiv = true;
$this->xmlContent = $xml['xmlContent'];
$this->xmlData = $xml['xmlWithData'];
//For response Export: 9904: Goods Transition Control Already Cancel Matching -> No auto-gen Declaration Number.
$messageCode = MasterResponseTemplates::where('id', $this->templateId)->value('code') ?? '';
if($messageCode == '9904'){
$this->xmlData['DeclarationNumber'] = '';
}
if($this->lockData){
foreach($this->xmlData as $key => $val){
if(isset($tmp_xmlData[$key]) && !in_array($key, $this->listNonLockData)){
$this->xmlData[$key] = $tmp_xmlData[$key];
}
if(isset($tmp_xmlData['ReferenceNumber']) && isset($this->xmlData['ReferenceNo'])){
$this->xmlData['ReferenceNo'] = $tmp_xmlData['ReferenceNumber'];
}else if(isset($tmp_xmlData['ReferenceNo']) && isset($this->xmlData['ReferenceNumber'])){
$this->xmlData['ReferenceNumber'] = $tmp_xmlData['ReferenceNo'];
}
}
}
$this->reGenerateXML();
}
$this->changeBtnColor = "bg-slate-150 font-medium text-slate-800 hover:bg-slate-200 focus:bg-slate-200 active:bg-slate-200/80 rounded-md border border-[#e5e7eb] ";
}
public function reGenerateXML()
{
$xmlGenerator = new GenXmlController();
$xml = $xmlGenerator->updateXmlValues($this->xmlContent, $this->xmlData);
$this->xmlContent = $xml;
}
public function mockUpXML()
{
$this->xmlData = $this->xmlWithData;
}
public function generateAndUploadXml()
{
$this->reGenerateXML();
$validateResult = $this->validateBeforeSend();
if(!$validateResult['success']){
$this->dispatchBrowserEvent('open-modal', [
'name' => 'alert-modal',
'message' => $validateResult['message'],
'status' => 'failed'
]);
return;
}
// Generate XML file from string
$now = Carbon::now();
$filename = 'manual_response_' . $now->format('Ymd_His') . ".xml";
Storage::disk('local')->put($filename, $this->xmlContent);
$filePath = storage_path('app/' . $filename);
$currentUser = Auth::user();
$userConnect = UsersConnectSpn::where('uid', $currentUser->id)->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'){
$uid = $spnConfig['uid'];
$ucode = $spnConfig['ucode'];
$ch = curl_init();
$cfile = new CURLFile($filePath, 'application/xml', $filename);
$postData = [
'UID' => $uid,
'UCODE' => $ucode,
'SERVICENAME' => 'imcoreservice',
'ACTION' => 'get_response_customs',
'profilecode' => '',
'API_PLACE_FILE' => 'Y',
'file' => $cfile
];
curl_setopt($ch, CURLOPT_URL, $userConnect->link . "/IE5DEV.shippingnet/data_defaulttemplate.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$error = curl_error($ch);
if ($error) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable peer verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Disable host verification
$result = curl_exec($ch);
$error = curl_error($ch); // Check for errors
}
curl_close($ch);
$messageType = MasterMessages::where('id', $this->messageId)->value('name') ?? '';
TabManualResponseLog::create([
'uid' => $currentUser->id,
'title' => 'Send Manual Response',
'detail' => "Username: " . $userConnect->username . "\nLink: " . $userConnect->link,
'message_type' => $messageType,
'xml_content' => base64_encode($this->xmlContent),
'reference_number' => $this->xmlData['ReferenceNumber'] ?? $this->xmlData['ReferenceNo'] ?? '',
'declaration_number' => $this->xmlData['DeclarationNumber'] ?? $this->xmlData['DocumentNumber'] ?? '',
'link' => $userConnect->link
]);
if ($error) {
//Cannot send response to SPN
$alertMessage = $error;
$alertStatus = 'failed';
} elseif(!$this->validateAfterSend($result)) {
$alertMessage = 'Unable to upload the file to SPN.<br>Please ensure the INBOX folder is properly set up before retrying.';
$alertStatus = 'failed';
} else {
$alertMessage = 'Send response successfully';
$alertStatus = 'success';
}
Storage::disk('local')->delete($filename);
}else if($spnConfig != null && $spnConfig['success'] == 'false'){
$alertMessage = $spnConfig['message'];
$alertStatus = 'failed';
}else{
//Cannot get UID/UCODE from SPN
$alertMessage = 'Cannot connect to SPN';
$alertStatus = 'failed';
}
$this->dispatchBrowserEvent('open-modal', [
'name' => 'alert-modal',
'message' => $alertMessage,
'status' => $alertStatus
]);
}
private function validateBeforeSend(){
$messageType = $this->xmlData['MessageType'] ?? '';
$referenceNo = $this->xmlData['ReferenceNumber'] ?? $this->xmlData['ReferenceNo'] ?? '';
$declarationNo = $this->xmlData['DeclarationNumber'] ?? $this->xmlData['DocumentNumber'] ?? '';
$profileProds = ConfListProfile::where('type', 'PROD')->pluck('name')->toArray();
//Validate reference number format
if (!preg_match('/^[A-Z]{4}[0-9]{9}$/', $referenceNo)) {
return [
"success" => false,
'message' => 'Reference Number is incorrect format.'
];
}
//Validate profile production
if(in_array(substr($referenceNo, 0, 1), $profileProds)){
return [
"success" => false,
'message' => 'Profile production is not allowed.'
];
}
//Validate profile production
if(in_array($messageType, ['XCDA', 'XCDR']) && $declarationNo == ''){
return [
"success" => false,
'message' => 'Cancel template is required "Declaration Number" field.'
];
}else if(in_array($messageType, ['SDCA', 'SDCR']) && $declarationNo == ''){
return [
"success" => false,
'message' => 'Short template is required "Declaration Number" field.'
];
}
if(str_starts_with($messageType, "XCDA_") && $declarationNo == ''){
return [
"success" => false,
'message' => 'Cancel template is required "Declaration Number" field.'
];
}
return ['success' => true, 'message' => ''];
}
private function validateAfterSend($result){
if(str_starts_with($result, 'Sorry, there was an error moving the file.')){
return false;
}
return true;
}
public function downloadXML(){
$tempCode = MasterResponseTemplates::find($this->templateId);
$fileName = $this->xmlData['DeclarationNumber']??''.'-'.$tempCode->code.'-'.str_replace("/","-",$this->xmlData['Message']).'.xml';
$xmlContent = $this->xmlContent;
Storage::disk('public')->put($fileName, $xmlContent);
$this->emit('fileManualDownload', asset('storage/' . $fileName));
}
public function selectMessage($masterMsgId) {
$message = MasterResponseMessageType::where('id', $masterMsgId)->first();
$this->xmlData["Message"] = $message->message;
$this->reGenerateXML();
$this->showSearch = false;
}
// public function updatedXmlData($value, $key)
// {
// if ($key === 'Message') {
// $this->showSearch = true;
// $tempCode = MasterResponseTemplates::find($this->templateId);
// $tempDoc = MasterMessages::find($this->messageId);
// if ($tempCode && $tempDoc) {
// $message = MasterResponseMessageType::where('doctype', strtoupper($tempDoc->name))
// ->where('codestatus', $tempCode->code)
// ->where('message', 'like', '%' . $value . '%')
// ->get();
// } else {
// $message = collect(); // Return an empty collection if no data is found
// }
// $this->masterMsg = $message;
// }
// }
}
<?php
namespace App\Http\Livewire\Pages\News;
use App\Models\Shippingnetnews;
use App\Models\Shippingnetnewstype;
use App\Models\Shippingnetservergroup;
use Livewire\Component;
use App\Models\User;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Hash;
use Str;
class NewsCreate extends Component
{
use WithFileUploads;
public $topic, $topicColor, $category = 1, $type, $content, $issueDate, $expireDate, $authorDate, $description;
public $image ,$imageTmp;
public $uploadFilePathName1;
public $uploadFilePathName2;
public $categories = [], $types = [];
protected $rules = [
'topic' => 'required|string|max:255',
'description' => 'required',
'category' => 'required',
'type'=> 'required',
'content' => 'required|string',
'issueDate' => 'required|date',
'expireDate' => 'required|date',
'topicColor' => 'required',
'uploadFilePathName1' => 'nullable|file|max:10240', // 10MB Max
'uploadFilePathName2' => 'nullable|file|max:10240', // 10MB Max
];
public function mount()
{
$this->types = Shippingnetnewstype::all()->pluck('newstype', 'id');
$this->categories = Shippingnetservergroup::all()->pluck('groupname', 'groupID');
$this->type = Shippingnetnewstype::first()->id;
}
// public function updatedContent($value)
// {
// $this->content = $value;
// }
public function uploadImage()
{
$this->validate([
'imageTmp' => 'image|max:2048', // ขนาดไฟล์สูงสุด 2MB
]);
$imagePath = $this->imageTmp->store('livewire-tmp', 'public');
$uploadedImageUrl = asset('storage/' . $imagePath); // สร้าง URL
// ส่ง URL กลับไปยัง JavaScript
$this->emit('imageUploaded', $uploadedImageUrl);
}
public function submitForm()
{
$this->validate();
if ($this->uploadFilePathName1) {
$filePath1 = $this->uploadFilePathName1->store('runtime/news', 'public');
}
if ($this->uploadFilePathName2) {
$filePath2 = $this->uploadFilePathName2->store('runtime/news', 'public');
}
Shippingnetnews::create([
'topic' => $this->topic,
'groupID' => $this->category,
'newstype' => $this->type,
'description' => $this->description,
'content' => $this->content, // Quill Editor HTML content
'issueDate' => $this->issueDate,
'expireDate' => $this->expireDate,
'authorDate' => date("Y-m-d"),
'topiccolor' => $this->topicColor,
'uploadFilePathName1' => $filePath1 ?? '',
'uploadFilePathName2' => $filePath2 ?? '',
'uploadFileName1' => $filePath1 ?? '',
'uploadFileName2' => $filePath2 ?? '',
]);
$this->resetForm();
if (auth()->guest()) {
return redirect()->route('login');
}
$this->emit('showNewsList', 'News successfully created.');
}
public function removeFile($fileName)
{
$this->$fileName = null;
}
public function resetForm()
{
$this->reset([
'topic',
'category',
'type',
'description',
'content',
'issueDate',
'expireDate',
'authorDate',
'topicColor',
'uploadFilePathName1',
'uploadFilePathName2'
]);
}
public function goBack()
{
if (auth()->guest()) {
return redirect()->route('login');
}
$this->emit('showNewsList');
}
public function render()
{
return view('livewire.pages.news.news-create');
}
}
<?php
namespace App\Http\Livewire\Pages\News;
use App\Models\Shippingnetnews;
use App\Models\Shippingnetnewstype;
use App\Models\Shippingnetservergroup;
use Livewire\Component;
use Livewire\WithFileUploads;
class NewsEdit extends Component
{
use WithFileUploads;
public $newsId, $topic, $topicColor, $category, $type, $content, $issueDate, $expireDate, $authorDate, $description;
public $uploadFilePathName1;
public $uploadFilePathName2;
public $categories = [], $types = [];
protected $rules = [
'topic' => 'required|string|max:255',
'description' => 'nullable|string',
'content' => 'nullable|string',
'issueDate' => 'nullable|date',
'expireDate' => 'nullable|date',
'topicColor' => 'nullable|string',
'uploadFilePathName1' => 'nullable|file|max:10240', // 10MB Max
'uploadFilePathName2' => 'nullable|file|max:10240', // 10MB Max
];
public function mount($editNewsId)
{
$news = Shippingnetnews::findOrFail($editNewsId);
$this->newsId = $editNewsId;
$this->topic = $news->topic;
$this->topicColor = $news->topiccolor;
$this->category = $news->groupID;
$this->type = $news->newstype;
$this->description = $news->description;
$this->content = $news->content;
$this->issueDate = $news->issueDate;
$this->expireDate = $news->expireDate;
$this->types = Shippingnetnewstype::all()->pluck('newstype', 'id');
$this->categories = Shippingnetservergroup::all()->pluck('groupname', 'groupID');
}
public function uploadImage($file)
{
$path = $file->store('images', 'public');
return asset('storage/' . $path);
}
public function submitForm()
{
$this->validate();
$news = Shippingnetnews::findOrFail($this->newsId);
if ($this->uploadFilePathName1) {
$filePath1 = $this->uploadFilePathName1->store('runtime/news', 'public');
}
if ($this->uploadFilePathName2) {
$filePath2 = $this->uploadFilePathName2->store('runtime/news', 'public');
}
// Update the existing record
$news->update([
'topic' => $this->topic,
'groupID' => $this->category,
'newstype' => $this->type,
'description' => $this->description,
'content' => $this->content,
'issueDate' => $this->issueDate,
'expireDate' => $this->expireDate,
'authorDate' => $this->authorDate ?? date("Y-m-d"),
'topiccolor' => $this->topicColor,
'uploadFilePathName1' => $filePath1 ?? $news->uploadFilePathName1,
'uploadFilePathName2' => $filePath2 ?? $news->uploadFilePathName2,
'uploadFileName1' => $filePath1 ?? $news->uploadFileName1,
'uploadFileName2' => $filePath2 ?? $news->uploadFileName2,
]);
$this->resetForm();
$this->emit('showNewsList', 'News successfully updated.');
}
public function removeFile($fileName)
{
$this->$fileName = null;
}
public function resetForm()
{
$this->reset([
'topic',
'category',
'type',
'description',
'content',
'issueDate',
'expireDate',
'authorDate',
'topicColor',
'uploadFilePathName1',
'uploadFilePathName2'
]);
}
public function goBack()
{
$this->emit('showNewsList');
}
public function render()
{
return view('livewire.pages.news.news-edit');
}
}
<?php
namespace App\Http\Livewire\Pages\News;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\Shippingnetnews;
use App\Models\Shippingnetnewstype;
use App\Models\Shippingnetservergroup;
use Illuminate\Support\Facades\Cache;
use Livewire\WithPagination;
class NewsIndex extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $perPage = 10;
public $url;
public $searchSelected = 'topic';
public $searchCateSelected;
public $searchTypeSelected;
public $editNewsId;
public $deleteNewsId;
public $keyword = '';
public $selectedOption = 'topic';
public $searchBy;
public $action = 'list';
public $message;
public $selectedNews = [];
public $searchCategory = [];
public $searchType = [];
public $showDeleteListModal = false;
public $showNoPermissionModal = false;
public $showMessage = false;
public $totalItems;
protected $listeners = ['showNewsList', 'deleteItem', 'deleteSelected', 'setShowMessageFalse'];
public function mount()
{
$this->searchBy = [
'topic' => 'Topic',
'issueDate' => 'Issue Date',
'expireDate' => 'Expire Date',
'authorDate' => 'Author Date',
];
$this->searchType = Cache::remember('shippingnetnewstype', 60, function () {
return Shippingnetnewstype::all()->pluck('newstype', 'id');
});
$this->searchCategory = Cache::remember('shippingnetservergroup', 60, function () {
return Shippingnetservergroup::all()->pluck('groupname', 'groupID');
});
}
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 showNewsAddForm()
{
$this->action = 'create';
}
public function showNewsEditForm($newsId)
{
$this->action = 'edit';
$this->editNewsId = $newsId;
}
public function hideMessage()
{
$this->showMessage = false;
}
public function showNewsList($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($deleteNewsId)
{
// if (!Auth::user()->hasPermissions(['delete-news'])) {
// $this->showNoPermissionModal = true;
// return;
// }
$news = Shippingnetnews::find($deleteNewsId);
if ($news) {
$news->delete();
$message = "Deleted Successfully";
$this->message = $message;
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
}
public function deleteSelected($selectedNews)
{
if (!\Auth::user()->hasPermissions(['delete-news'])) {
$this->showNoPermissionModal = TRUE;
return;
}
$newsDeleted = Shippingnetnews::whereIn("id", $selectedNews)->pluck('topic')->toArray();
$newsStr = implode(",", $newsDeleted);
Shippingnetnews::destroy($selectedNews);
$message = "Deleted : (" . $newsStr . " )Successfully";
$this->message = $message;
$this->selectedNews = [];
if ($this->message) {
$this->dispatchBrowserEvent('show-message', ['message' => $this->message]);
}
}
public function render()
{
$query = Shippingnetnews::with('group');
if (!empty($this->searchCateSelected)) {
$query->where('groupID', $this->searchCateSelected);
}
if (!empty($this->searchTypeSelected)) {
$query->where('newstype', $this->searchTypeSelected);
}
$results = $this->searchSelected && $this->keyword
? $query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%')->orderBy('shippingnetnews_ID', 'desc')->paginate($this->perPage)
: $query->orderBy('shippingnetnews_ID', 'desc')->paginate($this->perPage);
$this->totalItems = $results->total();
return view('livewire.pages.news.news-index', [
'results' => $results,
'selectedNews' => $this->selectedNews,
'showDeleteListModal' => $this->showDeleteListModal
]);
}
}
<?php
namespace App\Http\Livewire\Pages\Parameter;
use Livewire\Component;
use App\Models\ConfParameter;
use App\Models\TabParameterInfo;
use App\Models\TabSpnpage;
class ParameterCreate extends Component
{
public $name, $message, $value, $description, $active = 'Y', $detail, $pageCode = [];
public $searchByPage = [];
public function mount()
{
$this->searchByPage = TabSpnpage::select('pagecode', 'pagename')->get()->toArray();
}
public function addParameter()
{
$this->validate([
'name' => 'required|string|max:30',
'value' => 'required|string|max:50',
'description' => 'required|string|max:100',
'active' => 'required',
'detail' => 'required|string',
'pageCode' => 'required|array|min:1',
]);
ConfParameter::create([
'name' => $this->name,
'value' => $this->value,
'description' => $this->description,
'active' => $this->active,
]);
$pageCodesString = implode(',', $this->pageCode);
TabParameterInfo::create([
'parameterName' => $this->name,
'pageCode' => $pageCodesString,
'detail' => $this->detail,
]);
$this->reset(['name', 'value', 'description', 'active', 'pageCode', 'detail']);
$this->emit('showparameterListForm');
session()->flash('message', 'Parameter added successfully!');
}
public function render()
{
return view('livewire.pages.parameter.parameter-create');
}
public function loadPage($page)
{
$this->action = $page;
//$this->parameters = ConfParameter::all();
}
}