SmartCane/laravel_app/app/Livewire/Projects/Tabs/Mosaic.php

96 lines
2.5 KiB
PHP

<?php
namespace App\Livewire\Projects\Tabs;
use App\Jobs\ProjectMosiacGeneratorJob;
use App\Models\Project;
use Livewire\Component;
use Livewire\WithPagination;
class Mosaic extends Component
{
use WithPagination;
public Project $project;
public $formData = [
'week' => '',
'year' => '',
];
public $showCreateModal = false;
public $search = "";
public function mount(Project $project)
{
$this->path = $project->download_path;
}
public function saveMosaic()
{
$this->validate([
'formData.year' => 'required',
'formData.week' => 'required',
]);
$mosaic = $this->project->mosaics()->updateOrCreate([
'name' => sprintf('Week %s, %s', $this->formData['week'], $this->formData['year']),
'year' => $this->formData['year'],
'week' => $this->formData['week'],
], [
'path' => $this->project->getMosaicPath(),
]);
ProjectMosiacGeneratorJob::dispatch($mosaic);
$this->showCreateModal = false;
}
public function openCreateMosiacsModal()
{
$this->showCreateModal = true;
}
public function getDateRangeProperty()
{
if (empty($this->formData['week']) || strlen($this->formData['year']) !== 4) {
return '<span class="text-red-500">Invalid week or year</span>';
}
$begin = now()
->setISODate($this->formData['year'], $this->formData['week'])
->startOfWeek();
$end = now()
->setISODate($this->formData['year'], $this->formData['week'])
->endOfWeek();
return $begin->format('Y-m-d').' - '.$end->format('Y-m-d');
}
private function applySearch($query)
{
return $query->when($this->search !== '', function ($q){
$q->where('name', 'like', '%'.$this->search.'%')
->orWhere('year', 'like', '%' . $this->search . '%')
->orWhere('week', 'like', '%' . $this->search . '%');
});
}
public function update($property)
{
if ($property === 'search') {
$this->resetPage('mosaicPage');
}
}
public function render()
{
$query = $this->project->mosaics()
->orderBy('year', 'desc')
->orderBy('week', 'desc');
$query = $this->applySearch($query);
$mosaics = $query->paginate(10, pageName: 'mosaicPage');
return view('livewire.projects.tabs.mosaic', [
'mosaics' => $mosaics
]);
}
}