Merge branch 'Feature/date-range-mosaic'

This commit is contained in:
guillaume91 2024-06-24 09:20:26 +02:00
commit 67466bd417
18 changed files with 395 additions and 191 deletions

View file

@ -2,18 +2,12 @@
namespace App\Jobs;
use App\Models\Project;
use App\Models\ProjectDownload;
use App\Models\ProjectMosaic;
use App\Models\ProjectReport;
use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Symfony\Component\Process\Process;
class NullJob implements ShouldQueue
{
@ -25,7 +19,7 @@ class NullJob implements ShouldQueue
*/
public function __construct()
{
logger('NullJob construct called');
logger('NullJob construct called');
}
/**

View file

@ -2,22 +2,23 @@
namespace App\Jobs;
use App\Enums\Status;
use App\Livewire\Projects\Tabs\Mosaic;
use App\Models\Project;
use App\Models\ProjectDownload;
use App\Models\ProjectMosaic;
use App\Models\ProjectReport;
use Carbon\Carbon;
use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Process\Exceptions\ProcessFailedException;
use Illuminate\Process\Exceptions\ProcessTimedOutException;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Symfony\Component\Process\Process;
use Illuminate\Support\Facades\Process as ProcessNew;
/**
*
*/
class ProjectMosiacGeneratorJob implements ShouldQueue
{
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
@ -37,15 +38,18 @@ public function __construct(ProjectMosaic $mosaic)
/**
* Execute the job.
*/
public function handle(): void
public function handleNew(): void
{
$weeksAgo = ProjectReport::weeksAgoForYearAndWeek($this->mosaic->year, $this->mosaic->week);
//$weeksAgo = ProjectReport::weeksAgoForYearAndWeek($this->mosaic->year, $this->mosaic->week);
//TODO change to end_date and offset
$projectFolder = base_path('../');
$command = [
sprintf('%sbuild_mosaic.sh', $projectFolder),
sprintf('--weeks_ago=%s', $weeksAgo),
sprintf('--end_date=%s', $this->mosaic->end_date),
sprintf('--offset=%s', $this->mosaic->offset),
sprintf('--data_dir=%s', $this->mosaic->project->download_path),
];
@ -56,7 +60,6 @@ public function handle(): void
$process->setEnv(['PATH' => $currentPath.':/usr/local/Cellar/pandoc/3.1.8/bin/pandoc']);
// $process->setTimeout(36000); // stel een geschikte timeout in
$process->start();
try {
$myOutput = [];
$process->wait(function ($type, $buffer) use (&$myOutput) {
@ -74,28 +77,93 @@ public function handle(): void
}
}
public static function handleFor(Project $project, $year, $startWeekNumber)
/**
* Execute the job.
*/
public function handle(): void
{
logger("ProjectMosiacGeneratorJob::handleFor(week $startWeekNumber, year $year)");
if ($project->hasInvalidMosaicFor($year, $startWeekNumber)) {
logger("ProjecMosaicGeneratorJob::handleFor(week $startWeekNumber, year $year): InvalidMosaic.");
//$weeksAgo = ProjectReport::weeksAgoForYearAndWeek($this->mosaic->year, $this->mosaic->week);
$projectFolder = base_path('../');
$command = [
sprintf('%sbuild_mosaic.sh', $projectFolder),
sprintf('--end_date=%s', $this->mosaic->end_date),
sprintf('--offset=%s', $this->mosaic->offset),
sprintf('--data_dir=%s', $this->mosaic->project->download_path),
];
$currentPath = '/usr/bin:/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin/Users/mfolkerts/anaconda3/bin:/Library/Apple/usr/bin';
try{
$process = ProcessNew::timeout(220)
->env(['PATH' => $currentPath . ':/usr/local/Cellar/pandoc/3.1.8/bin/pandoc'])
->start($command, function (string $type, string $output ) {
logger($output);
});
$results = $process->wait();
if($results->successful()){
$this->mosaic->setStatusSuccess();
}
}catch(\RuntimeException|ProcessTimedOutException|ProcessFailedException $e){
echo $e->getMessage();
$this->mosaic->setStatusFailed();
}
}
// public static function handleFor(Project $project, $year, $startWeekNumber)
// {
// logger("ProjectMosiacGeneratorJob::handleFor(week $startWeekNumber, year $year)");
// if ($project->hasInvalidMosaicFor($year, $startWeekNumber)) {
// logger("ProjecMosaicGeneratorJob::handleFor(week $startWeekNumber, year $year): InvalidMosaic.");
// return new NullJob();
// }
//
// $mosaic = $project->mosaics()->updateOrCreate(
// [
// 'year' => $year,
// 'week' => $startWeekNumber,
// ],
// [
// 'name' => sprintf('Week %d, %d', $startWeekNumber, $year),
// 'path' => sprintf('%s/%s/%s',
// $project->download_path,
// 'mosaics',
// ProjectMosaic::getFilenameForYearAndWeek($year, $startWeekNumber)
// ),
// 'year' => $year,
// 'week' => $startWeekNumber,
// ]);
// return new self($mosaic);
// }
/**
* Check if the project has a mosaic for given period.
*/
public static function handleFor(Project $project,Carbon $endDate, int $offset): NullJob|ProjectMosiacGeneratorJob
{
logger("ProjectMosiacGeneratorJob::handleFor($endDate, $offset)");
if ($project->hasInvalidMosaicFor($endDate,$offset)) {
logger("ProjecMosaicGeneratorJob::handleFor(end_date: $endDate, offset: $offset): InvalidMosaic.");
return new NullJob();
}
/**
* @var ProjectMosaic $mosaic
*/
$mosaic = $project->mosaics()->updateOrCreate(
[
'year' => $year,
'week' => $startWeekNumber,
'end_date' => $endDate,
'offset' => $offset,
],
[
'name' => sprintf('Week %d, %d', $startWeekNumber, $year),
'name' => sprintf('Period %s - %s', $endDate->format('Y-m-d'), $endDate->copy()->subDays($offset)->format('Y-m-d')),
'path' => sprintf('%s/%s/%s',
$project->download_path,
'mosaics',
ProjectMosaic::getFilenameForYearAndWeek($year, $startWeekNumber)
ProjectMosaic::getFilenameByPeriod($endDate,$offset)
),
'year' => $year,
'week' => $startWeekNumber,
'end_date' => $endDate->format('Y-m-d'),
'offset' => $offset,
]);
return new self($mosaic);
}

View file

@ -35,7 +35,8 @@ public function __construct(ProjectReport $projectReport, $sendMail = false)
*/
public function handle()
{
$this->projectReport->weeksAgo();
// TODO check the changements due to migration
//$this->projectReport->weeksAgo();
$projectFolder = base_path('../');

View file

@ -4,6 +4,8 @@
use App\Jobs\ProjectMosiacGeneratorJob;
use App\Models\Project;
use App\Models\ProjectMosaic;
use Carbon\Carbon;
use Livewire\Component;
use Livewire\WithPagination;
@ -14,8 +16,8 @@ class Mosaic extends Component
public Project $project;
public $formData = [
'week' => '',
'year' => '',
'end_date' => '',
'offset' => '7',
];
public $showCreateModal = false;
@ -27,18 +29,19 @@ class Mosaic extends Component
public function mount(Project $project)
{
$this->path = $project->download_path;
$this->formData['end_date'] = Carbon::yesterday()->toDateString();
}
public function saveMosaic()
{
$this->validate([
'formData.year' => 'required',
'formData.week' => 'required',
'formData.end_date' => ['required','date','before:today'],
'formData.offset' => 'required|integer|min:1|max:1000',
]);
$mosaic = $this->project->mosaics()->updateOrCreate([
'name' => sprintf('Week %s, %s', $this->formData['week'], $this->formData['year']),
'year' => $this->formData['year'],
'week' => $this->formData['week'],
'name' => ProjectMosaic::projectMosaicNameFormat(new Carbon($this->formData['end_date']),(int) $this->formData['offset']),
'offset' => $this->formData['offset'],
'end_date' => $this->formData['end_date'],
], [
'path' => $this->project->getMosaicPath(),
]);
@ -55,24 +58,20 @@ public function openCreateMosiacsModal()
public function getDateRangeProperty()
{
if (empty($this->formData['week']) || strlen($this->formData['year']) !== 4) {
return '<span class="text-red-500">Invalid week or year</span>';
if (!$this->formData['end_date'] || !$this->formData['offset']) {
return '<span class="text-red-500">Please give a correct date or offset</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');
$start = (new Carbon($this->formData['end_date']))->subDays($this->formData['offset']-1);
$end = new Carbon($this->formData['end_date']);
return 'from '.$start->format('Y-m-d').' to '.$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 . '%');
->orWhere('offset', 'like', '%' . $this->search . '%')
->orWhere('end_date', 'like', '%' . $this->search . '%');
});
}
@ -86,8 +85,8 @@ public function update($property)
public function render()
{
$query = $this->project->mosaics()
->orderBy('year', 'desc')
->orderBy('week', 'desc');
->orderBy('offset', 'desc')
->orderBy('end_date', 'desc');
$query = $this->applySearch($query);
$mosaics = $query->paginate(10, pageName: 'mosaicPage');

View file

@ -2,10 +2,14 @@
namespace App\Livewire\Projects\Tabs;
use App\Jobs\ProjectMosiacGeneratorJob;
use App\Jobs\ProjectReportGeneratorJob;
use App\Models\Project;
use App\Models\ProjectMosaic;
use App\Models\ProjectReport;
use App\Rules\AllMosaicsPresentRule;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Livewire\Attributes\Reactive;
use Livewire\Component;
use Livewire\WithPagination;
@ -14,7 +18,10 @@ class Report extends Component
{
use WithPagination;
public $formData = [];
public $formData = [
'end_date' => '',
'offset' => 7
];
public Project $project;
public $search = "";
@ -22,6 +29,11 @@ class Report extends Component
public $showReportModal = false;
public function mount()
{
$this->formData['end_date'] = Carbon::yesterday()->toDateString();
}
public function openCreateReportModal()
{
$this->resetFormData();
@ -29,24 +41,24 @@ public function openCreateReportModal()
}
private function resetFormData()
{
$this->formData['week'] = now()->weekOfYear;
$this->formData['year'] = now()->year;
$this->formData['end_date'] = Carbon::yesterday()->toDateString();
$this->formData['offset'] = 7;
}
public function saveProjectReport()
{
$this->validate([
'formData.week' => ['required', 'integer', 'min:1', 'max:53'],
'formData.year' => 'required|integer|min:2020|max:'.now()->addYear()->year,
'formData.end_date' => ['required','date','before:today'],
'formData.offset' => 'required|integer|min:1|max:1000',
'formData' => [new AllMosaicsPresentRule($this->project->id)],
]);
$newReport = Project::find($this->project->id)
->reports()->create([
'name' => 'Report for week '.$this->formData['week'].' of '.$this->formData['year'],
'week' => $this->formData['week'],
'year' => $this->formData['year'],
'path' => 'reports/week_'.$this->formData['week'].'_'.$this->formData['year'].'.docx',
'name' => ProjectReport::projectReportNameFormat(new Carbon($this->formData['end_date']),(int) $this->formData['offset']),
'end_date' => $this->formData['end_date'],
'offset' => $this->formData['offset'],
'path' => 'reports/'.ProjectReport::getFileName($this->formData['end_date'],$this->formData['offset']).'.docx',
]);
ProjectReportGeneratorJob::dispatch($newReport);
@ -58,17 +70,12 @@ public function saveProjectReport()
public function getDateRangeProperty()
{
if (empty($this->formData['week']) || strlen($this->formData['year']) !== 4) {
return '<span class="text-red-500">Invalid week or year</span>';
if (!$this->formData['end_date'] || !$this->formData['offset']) {
return '<span class="text-red-500">Please give a correct date or offset</span>';
}
// @TODO dit moet gecorrigeerd voor de project settings;
$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');
$start = (new Carbon($this->formData['end_date']))->subDays($this->formData['offset']-1);
$end = new Carbon($this->formData['end_date']);
return 'from '.$start->format('Y-m-d').' to '.$end->format('Y-m-d');
}
public function deleteReport(ProjectReport $report)
@ -81,8 +88,8 @@ 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.'%');
->orWhere('end_date', 'like', '%'.$this->search.'%')
->orWhere('offset', 'like', '%'.$this->search.'%');
});
}
@ -92,8 +99,8 @@ public function render()
$query = Project::find($this->project->id)
->reports()
->with('project')
->orderBy('year', 'desc')
->orderBy('week', 'desc');
->orderBy('end_date', 'desc')
->orderBy('offset', 'desc');
$query = $this->applySearch($query);
$reports = $query->paginate(10, pageName: 'reportPage');
@ -101,4 +108,11 @@ public function render()
return view('livewire.projects.tabs.report')
->with(compact('reports'));
}
public function getMissingMosaicsInFileSystem(Carbon $endDate,int $offset = 7)
{
$this->project->getMosaicsFor($endDate,$offset);
return redirect()->route('project.show',[$this->project->name,'mosaics']);
}
}

View file

@ -3,6 +3,7 @@
namespace App\Models;
use App\Events\ProjectMosaicStatus;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@ -11,17 +12,29 @@ class ProjectMosaic extends Model
use HasFactory;
use \App\Traits\HasStatus;
protected $casts = [
'end_date' => 'datetime',
];
protected $fillable = [
'name',
'path',
'week',
'year',
'end_date',
'offset',
'status'
];
public static function getFilenameForYearAndWeek($year, $startWeekNumber)
public static function getFilenameByPeriod(Carbon $endDate,int $offset)
{
return sprintf('week_%02d_%d.tif', $startWeekNumber, $year);
return sprintf('period_%s_%s.tif',(clone $endDate)->subdays($offset)->format('Y-m-d'),$endDate->format('Y-m-d'));
}
public static function projectMosaicNameFormat(Carbon $endDate,int $offset):string
{
return 'Period '.$endDate->copy()->subDays($offset)->toDateString().' - '.$endDate->toDateString();
}
public function project()
@ -29,6 +42,11 @@ public function project()
return $this->belongsTo(Project::class);
}
public function getStartDateAttribute()
{
return $this->end_date->subDay($this->offset);
}
protected static function booted(): void
{
parent::booted();

View file

@ -3,40 +3,34 @@
namespace App\Models;
use App\Events\ProjectReportStatus;
use App\Jobs\ProjectDownloadTiffJob;
use App\Jobs\ProjectMosiacGeneratorJob;
use App\Traits\HasStatus;
use Carbon\CarbonPeriod;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\File;
class ProjectReport extends Model
{
use HasStatus;
protected $fillable = ['name', 'path', 'week', 'year','status'];
protected $casts = [ 'end_date' => 'datetime'];
protected $fillable = ['name', 'path', 'week', 'year','status', 'end_date','offset'];
public function project()
{
return $this->belongsTo(Project::class);
}
public function weeksAgo()
public function getFileNameAttribute(): string
{
return $this->weeksAgoForYearAndWeek($this->year, $this->week);
return static::getFileName($this->end_date,$this->offset);
}
public static function getFileName(Carbon $endDate, int $offset): string
{
return 'period_'.$endDate->copy()->subDays($offset).'_'.$endDate;
}
public static function weeksAgoForYearAndWeek($year, $week)
public static function projectReportNameFormat(Carbon $endDate,int $offset):string
{
return (now()->week - now()->setISODate($year, $week)->week);
}
public function getFileName()
{
return 'week_'.$this->week.'_'.$this->year;
return 'Report from '.$endDate->copy()->subDays($offset)->toDateString().' to '.$endDate->toDateString();
}
public function getFullPathName()
@ -44,13 +38,10 @@ public function getFullPathName()
return storage_path('app/'.$this->project->download_path.'/'.$this->path);
}
public function getReportDate()
public function getReportDate():string
{
return self::getReportDateForYearAndWeek(
$this->project,
$this->year,
$this->week
)->toDateString();
// TODO remove year and week
return $this->end_date->format('Y-m-d');
}
public static function getReportDateForYearAndWeek(Project $project, $year, $week)

View file

@ -4,7 +4,7 @@
use Illuminate\Contracts\Validation\Rule;
use App\Models\Project;
use App\Models\ProjectReport;
use Carbon\Carbon;
class AllMosaicsPresentRule implements Rule
{
@ -27,9 +27,7 @@ public function passes($attribute, $value)
return false;
}
return $project->allMosaicsPresent(
ProjectReport::getReportDateForYearAndWeek($project, $value['year'], $value['week'])
);
return $project->allMosaicsPresent(new Carbon($value['end_date']));
} catch (\Exception $e) {
$this->errorMessage = $e->getMessage();
return false;

View file

@ -0,0 +1,57 @@
<?php
use App\Models\ProjectMosaic;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('project_mosaics', function (Blueprint $table) {
$table->date('end_date')->nullable();
$table->integer('offset')->default(7);
});
ProjectMosaic::all()->each(function (ProjectMosaic $project_mosaic) {
$end_date = Carbon::parse(sprintf('%s-W%02d',$project_mosaic->year,$project_mosaic->week))->addDay(Carbon::THURSDAY);
$project_mosaic->update(['end_date' => $end_date]);
});
Schema::table('project_mosaics', function (Blueprint $table) {
$table->dropColumn('week');
$table->dropColumn('year');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('project_mosaics', function (Blueprint $table) {
// Add back year and week columns
$table->integer('year');
$table->integer('week');
});
// Extract year and week from end_date (assuming logic applied in up() is reversible)
ProjectMosaic::all()->each(function (ProjectMosaic $project_mosaic) {
if (!$project_mosaic->end_date) {
return; // Skip if end_date is null
}
$project_mosaic->update(['year' => $project_mosaic->end_date->format('Y'), 'week' => $project_mosaic->end_date->format('W')]);
});
Schema::table('project_mosaics', function (Blueprint $table) {
// Drop end_date and offset columns
$table->dropColumn('end_date');
$table->dropColumn('offset');
});
}
};

View file

@ -0,0 +1,57 @@
<?php
use App\Models\ProjectReport;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('project_reports', function (Blueprint $table) {
$table->date('end_date')->nullable();
$table->integer('offset')->default(7);
});
ProjectReport::all()->each(function (ProjectReport $project_report) {
$end_date = Carbon::parse(sprintf('%s-W%02d',$project_report->year,$project_report->week))->addDay(Carbon::THURSDAY);
$project_report->update(['end_date' => $end_date]);
});
Schema::table('project_reports', function (Blueprint $table) {
$table->dropColumn('week');
$table->dropColumn('year');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('project_reports', function (Blueprint $table) {
// Add back year and week columns
$table->integer('year');
$table->integer('week');
});
// Extract year and week from end_date (assuming logic applied in up() is reversible)
ProjectReport::all()->each(function (ProjectReport $project_report) {
if (!$project_report->end_date) {
return; // Skip if end_date is null
}
$project_report->update(['year' => $project_report->end_date->format('Y'), 'week' => $project_report->end_date->format('W')]);
});
Schema::table('project_reports', function (Blueprint $table) {
// Drop end_date and offset columns
$table->dropColumn('end_date');
$table->dropColumn('offset');
});
}
};

View file

@ -17,13 +17,13 @@
<x-slot name="form">
<div class="col-span-6 sm:col-span-4">
<x-label for="year" value="{{ __('Year') }}"/>
<x-input id="year" type="number" min="1900" max="{{\Carbon\Carbon::now()->year}}" class="mt-1 block w-full" wire:model.live="formData.year" autofocus/>
<x-input-error for="formData.year" class="mt-2"/>
<x-label for="end_date" value="{{ __('Date') }}"/>
<x-input id="end_date" type="date" max="{{\Carbon\Carbon::yesterday()->toDateString()}}" class="mt-1 block w-full" wire:model.live="formData.end_date" autofocus/>
<x-input-error for="formData.end_date" class="mt-2"/>
</div><div class="col-span-6 sm:col-span-4">
<x-label for="week" value="{{ __('Week') }}"/>
<x-input id="week" type="number" min="1" max="53" class="mt-1 block w-full" wire:model.live="formData.week" autofocus/>
<x-input-error for="formData.week" class="mt-2"/>
<x-label for="offset" value="{{ __('Offset') }}"/>
<x-input id="offset" type="number" min="1" max="1000" placeholder="{{__('Number of days used to generate the mosaic (7 by default)')}}" class="mt-1 block w-full" wire:model.live="formData.offset" autofocus/>
<x-input-error for="formData.offset" class="mt-2"/>
<x-input-error for="formData" class="mt-2"/>
</div>
<div>

View file

@ -1,9 +1,3 @@
@props([
'formData',
/** @var \App\Livewire\Projects\ProjectManager */
'reportManager'
])
<x-modal wire:model.live="showReportModal" {{ $attributes }} >
<x-form-modal submit="saveProjectReport" wire:loading.class="opacity-50">
<x-slot name="title">
@ -16,13 +10,13 @@
<x-slot name="form">
<div class="col-span-6 sm:col-span-4">
<x-label for="year" value="{{ __('Year') }}"/>
<x-input id="year" type="text" class="mt-1 block w-full" wire:model.live="formData.year" autofocus/>
<x-input-error for="formData.year" class="mt-2"/>
<x-label for="end_date" value="{{ __('Date') }}"/>
<x-input id="end_date" type="date" max="{{\Carbon\Carbon::yesterday()->toDateString()}}" class="mt-1 block w-full" wire:model.live="formData.end_date" autofocus/>
<x-input-error for="formData.end_date" class="mt-2"/>
</div><div class="col-span-6 sm:col-span-4">
<x-label for="week" value="{{ __('Week') }}"/>
<x-input id="week" type="text" class="mt-1 block w-full" wire:model.live="formData.week" autofocus/>
<x-input-error for="formData.week" class="mt-2"/>
<x-label for="offset" value="{{ __('Offset') }}"/>
<x-input id="offset" type="number" min="1" max="1000" placeholder="{{__('Number of days used to generate the mosaic (7 by default)')}}" class="mt-1 block w-full" wire:model.live="formData.offset" autofocus/>
<x-input-error for="formData.offset" class="mt-2"/>
<x-input-error for="formData" class="mt-2"/>
</div>
<div>
@ -34,7 +28,13 @@
<x-action-message class="mr-3" on="saved">
{{ __('Saved.') }}
</x-action-message>
@error('formData')
<x-button
class="mr-3 flex justify-center rounded-md bg-indigo-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
x-on:click="$wire.call('getMissingMosaicsInFileSystem',parseInt($wire.formData.offset))"
>Download missing Mosaics</x-button>
@enderror
<x-secondary-button class="mr-3"
type="button"
x-on:click="$wire.showReportModal = false"

View file

@ -5,11 +5,6 @@
<td class="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6 lg:pl-8">{{ $report->name }}</td>
<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{{-- @if($report->status == \App\Enums\Status::Pending)--}}
{{-- <x-badge status="pending" wire:poll.1s=""></x-badge>--}}
{{-- @else--}}
{{-- <x-badge :status="$report->status"></x-badge>--}}
{{-- @endif--}}
<livewire:components.badge :status="$report->status" :id="$report->id" :type="'report'" wire:key="{{$report->id}}"></livewire:components.badge>
</td>
<td class="py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6 lg:pr-8 flex justify-end">

View file

@ -22,10 +22,16 @@ class="justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold t
<tr>
<th scope="col"
class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6 lg:pl-8">
Name
{{__('Name')}}
</th>
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
Year-Week
{{__('Start')}}
</th>
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
{{__('End')}}
</th>
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
{{__('Range (days)')}}
</th>
<th scope="col"
class="px-3 py-3.5 text-right text-sm font-semibold text-gray-900 sm:pr-8 lg:pr-8">
@ -38,7 +44,13 @@ class="px-3 py-3.5 text-right text-sm font-semibold text-gray-900 sm:pr-8 lg:pr-
<tr>
<td class="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6 lg:pl-8">{{ $mosaic->name }}</td>
<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{{ $mosaic->year }}-{{ $mosaic->week}}
{{ $mosaic->end_date->copy()->subDays($mosaic->offset)->format('Y-m-d') }}
</td>
<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{{ $mosaic->end_date->format('Y-m-d') }}
</td>
<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
{{ $mosaic->offset }}
</td>
<td class="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6 lg:pr-8">
<livewire:components.badge :status="$mosaic->status" :id="$mosaic->id" type="mosaic" wire:key="{{$mosaic->id}}"></livewire:components.badge>
@ -52,7 +64,6 @@ class="px-3 py-3.5 text-right text-sm font-semibold text-gray-900 sm:pr-8 lg:pr-
<div class="text-gray-700 text-sm">
Results: {{ \Illuminate\Support\Number::format($mosaics->total()) }}
</div>
{{ $mosaics->links('livewire.pagination') }}
</div>
</div>

View file

@ -52,6 +52,7 @@ class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6 lg
</div>
</div>
</div>
<x-report-manager-properties-modal :reportManager="$this"/>
</div>

View file

@ -24,19 +24,20 @@ class ProjectMosaicTest extends TestCase
* @test
* @dataProvider filenameProvider
* */
public function it_should_return_the_correct_attachment_path($year,$week, $expected)
public function it_should_return_the_correct_attachment_path($endDate,$offset, $expected)
{
$this->assertEquals(
$expected,
ProjectMosaic::getFilenameForYearAndWeek($year, $week)
ProjectMosaic::getFilenameByPeriod($endDate,$offset)
);
}
public static function filenameProvider(){
return [
[2022, 1, 'week_01_2022.tif'],
[2022, 10, 'week_10_2022.tif'],
[new Carbon('2022-01-01'), 10, 'period_2021-12-22_2022-01-01.tif'],
[new Carbon('2022-10-25'),7, 'period_2022-10-18_2022-10-25.tif'],
];
}

View file

@ -21,28 +21,28 @@ protected function setUp(): void
parent::setUp(); // TODO: Change the autogenerated stub
}
/**
* @test
* @dataProvider weeksAgoProvider
*/
public function it_can_calculatore_weeksAgo($year, $week, $expected)
{
Carbon::setTestNow(Carbon::now()->setISODate('2021', '41'));
$projectReport = ProjectReport::make([
'year' => $year,
'week' => $week,
]);
$this->assertEquals($expected, $projectReport->weeksAgo());
}
public static function weeksAgoProvider()
{
return [
'1 week ago' => [2021, 40, 1],
'2 weeks ago' => [2021, 39, 2],
'3 weeks ago' => [2021, 38, 3],
];
}
// /**
// * @test
// * @dataProvider weeksAgoProvider
// */
// public function it_can_calculatore_weeksAgo($endDate, $offset, $expected)
// {
// Carbon::setTestNow(Carbon::now()->setISODate('2021', '41'));
// $projectReport = ProjectReport::make([
// 'end_date' => $endDate,
// 'offset' => $offset,
// ]);
// $this->assertEquals($expected, $projectReport->weeksAgo());
// }
//
// public static function weeksAgoProvider()
// {
// return [
// '1 week ago' => [2021, 40, 1],
// '2 weeks ago' => [2021, 39, 2],
// '3 weeks ago' => [2021, 38, 3],
// ];
// }
/**
* @test
@ -55,8 +55,8 @@ public function it_can_get_the_full_path_name()
]);
$projectReport = $project->reports()->create([
'name' => 'name',
'year' => 2021,
'week' => 41,
'end_date' => new Carbon('2021-01-01'),
'offset' => 10,
'path' => 'path/doc.pdf',
]);
$projectReport->setStatusSuccess();
@ -67,7 +67,7 @@ public function it_can_get_the_full_path_name()
* @test
* @dataProvider reportDateProvider
*/
public function it_can_return_the_reportDate($expected, $mail_day, $week, $year)
public function it_can_return_the_reportDate($expected, $mail_day, $endDate, $offset)
{
$project = Project::create([
'name' => 'project_name',
@ -76,8 +76,8 @@ public function it_can_return_the_reportDate($expected, $mail_day, $week, $year)
]);
$projectReport = $project->reports()->create([
'name' => 'name',
'year' => $year,
'week' => $week,
'end_date' => $endDate,
'offset' => $offset,
'path' => 'path/doc.pdf',
]);
$projectReport->setStatusSuccess();
@ -88,13 +88,13 @@ public function it_can_return_the_reportDate($expected, $mail_day, $week, $year)
public static function reportDateProvider()
{
return [
'monday' => ['2023-12-10', 'monday', 50, 2023],
'tuesday' => ['2023-12-11', 'tuesday', 50, 2023],
'wednesday' => ['2023-12-12', 'wednesday', 50, 2023],
'thursday' => ['2023-12-13', 'thursday', 50, 2023],
'friday' => ['2023-12-14', 'friday', 50, 2023],
'saturday' => ['2023-12-15', 'saturday', 50, 2023],
'sunday' => ['2023-12-16', 'sunday', 50, 2023],
'monday' => ['2023-12-10', 'monday',new Carbon('2023-12-10'),10 ],
'tuesday' => ['2023-12-11', 'tuesday',new Carbon('2023-12-11'),10 ],
'wednesday' => ['2023-12-12', 'wednesday',new Carbon('2023-12-12'),10 ],
'thursday' => ['2023-12-13', 'thursday',new Carbon('2023-12-13'),10 ],
'friday' => ['2023-12-14', 'friday',new Carbon('2023-12-14'),10 ],
'saturday' => ['2023-12-15', 'saturday',new Carbon('2023-12-15'),10 ],
'sunday' => ['2023-12-16', 'sunday',new Carbon('2023-12-16'),10 ],
];
}

View file

@ -80,10 +80,9 @@ public function when_not_all_mosaics_are_present_it_should_return_an_exception()
$this->seed();
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Missing mosaics: week_52_2022.tif, week_51_2021.tif, week_50_2021.tif, week_49_2021.tif');
$this->expectExceptionMessage('Missing mosaics: period_2021-12-26_2022-01-01.tif, period_2021-12-19_2021-12-25.tif, period_2021-12-12_2021-12-18.tif, period_2021-12-05_2021-12-11.tif');
$project = Project::find(1);
$lastDate = Carbon::parse('2022-01-01');
//$lastDate->getWeekOfYear();
$project->allMosaicsPresent($lastDate);
}
@ -92,13 +91,13 @@ public function when_all_mosaics_are_present_it_should_return_true()
{
// TODO CHeck with Martin the Leading Zero test
$project = Mockery::mock(Project::class)->makePartial();
$lastDate = Carbon::parse('2021-01-22');
$lastDate = Carbon::parse('2022-01-01');
$project->shouldReceive('getMosaicList')->andReturn(
collect([
"chemba/weekly_mosaic/week_53_2020.tif",
"chemba/weekly_mosaic/week_03_2021.tif",
"chemba/weekly_mosaic/week_02_2021.tif",
"chemba/weekly_mosaic/week_01_2021.tif",
"chemba/weekly_mosaic/period_2021-12-26_2022-01-01.tif",
"chemba/weekly_mosaic/period_2021-12-19_2021-12-25.tif",
"chemba/weekly_mosaic/period_2021-12-12_2021-12-18.tif",
"chemba/weekly_mosaic/period_2021-12-05_2021-12-11.tif",
]));
$this->assertTrue($project->allMosaicsPresent($lastDate));
@ -108,16 +107,14 @@ public function when_all_mosaics_are_present_it_should_return_true()
public function when_not_mosaics_are_present_it_should_throw_an_exception_listing_the_missing_mosiacs()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Missing mosaics: week_53_2020.tif');
$this->expectExceptionMessage('Missing mosaics: period_2020-12-05_2020-12-11.tif');
$project = Mockery::mock(Project::class)->makePartial();
$lastDate = Carbon::parse('2021-01-01');
$project->shouldReceive('getMosaicList')->andReturn(
collect([
"chemba/weekly_mosaic/week_52_2020.tif",
"chemba/weekly_mosaic/week_51_2020.tif",
"chemba/weekly_mosaic/week_50_2020.tif",
"chemba/weekly_mosaic/week_49_2021.tif",
"chemba/weekly_mosaic/week_48_2021.tif",
"chemba/weekly_mosaic/period_2020-12-26_2021-01-01.tif",
"chemba/weekly_mosaic/period_2020-12-19_2020-12-25.tif",
"chemba/weekly_mosaic/period_2020-12-12_2020-12-18.tif",
]));
$project->allMosaicsPresent($lastDate);
@ -127,7 +124,7 @@ public function when_not_mosaics_are_present_it_should_throw_an_exception_listin
public function when_all_mosaics_are_present_is_called_with_future_date_it_should_throw_an_expection()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Mosaic can be generated for the future. Change the end date.');
$this->expectExceptionMessage('Mosaic can\'t be generated for the future. Change the end date.');
$this->seed();
$project = Project::find(1);
Carbon::setTestNow(Carbon::parse('2020-01-01'));
@ -143,14 +140,14 @@ public function getMosiacFileListByEndDate_should_return_four_filenames()
/* @var Project $project */
$project = Project::find(1);
$lastDate = Carbon::parse('2021-01-01');
$list = $project::getMosaicFilenameListByEndDate($lastDate);
$list = iterator_to_array($project::getMosaicFilenameListByEndDate($lastDate));
$this->assertCount(4, $list);
$this->assertEquals([
"week_53_2020.tif",
"week_52_2020.tif",
"week_51_2020.tif",
"week_50_2020.tif",
], $list->toArray());
"period_2020-12-26_2021-01-01.tif",
"period_2020-12-19_2020-12-25.tif",
"period_2020-12-12_2020-12-18.tif",
"period_2020-12-05_2020-12-11.tif",
], $list);
}
/** @test */
@ -162,8 +159,8 @@ public function when_getFileDownloadsFor_is_called_it_returns_a_collection_of_se
'download_path' => 'project_download_path',
]);
$downloads = $project->getFileDownloadsFor(2023, 22);
$this->assertCount(4 * 7, $downloads);
$downloads = $project->getFileDownloadsFor(new Carbon('2024-06-18'),7);
$this->assertCount(28, $downloads);
collect($downloads)->each(fn($job) => $this->assertInstanceOf(ProjectDownloadTiffJob::class, $job));
}
@ -176,7 +173,7 @@ public function when_getMosaicsFor_is_called_it_returns_a_collection_of_seven_do
'download_path' => 'project_download_path',
]);
$mosaics = $project->getMosaicsFor(2023, 2);
$mosaics = $project->getMosaicsFor(new Carbon('2023-01-01'));
$this->assertCount(4, $mosaics);
collect($mosaics)->each(fn($job) => $this->assertInstanceOf(ProjectMosiacGeneratorJob::class, $job));
}
@ -190,7 +187,7 @@ public function when_getReport_is_called_it_returns_a_jobs()
'download_path' => 'project_download_path',
]);
$job = $project->getReportFor(2023, 2);
$job = $project->getReportFor(new Carbon('2023-01-01'));
$this->assertInstanceOf(ProjectReportGeneratorJob::class, $job);
}
@ -198,15 +195,17 @@ public function when_getReport_is_called_it_returns_a_jobs()
/** @test */
public function it_can_create_a_chain_of_batches_that_result_in_a_report()
{
/* @var Project $project*/
$project = Project::create([
'name' => 'project_name',
'download_path' => 'project_download_path',
]);
Bus::fake();
$project->scheduleReport(2023, 50);
$project->scheduleReport(new Carbon('2023-01-01'),7);
Bus::assertChained([
Bus::chainedBatch(function (PendingBatch $batch) {
$batch;
return $batch->jobs->count() === 28;
}),
Bus::chainedBatch(function (PendingBatch $batch) {