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; 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\Batchable;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Symfony\Component\Process\Process;
class NullJob implements ShouldQueue class NullJob implements ShouldQueue
{ {

View file

@ -2,22 +2,23 @@
namespace App\Jobs; namespace App\Jobs;
use App\Enums\Status;
use App\Livewire\Projects\Tabs\Mosaic;
use App\Models\Project; use App\Models\Project;
use App\Models\ProjectDownload;
use App\Models\ProjectMosaic; use App\Models\ProjectMosaic;
use App\Models\ProjectReport; use Carbon\Carbon;
use Illuminate\Bus\Batchable; use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Process\Exceptions\ProcessFailedException; use Illuminate\Process\Exceptions\ProcessFailedException;
use Illuminate\Process\Exceptions\ProcessTimedOutException;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
use Illuminate\Support\Facades\Process as ProcessNew;
/**
*
*/
class ProjectMosiacGeneratorJob implements ShouldQueue class ProjectMosiacGeneratorJob implements ShouldQueue
{ {
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels; use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
@ -37,15 +38,18 @@ public function __construct(ProjectMosaic $mosaic)
/** /**
* Execute the job. * 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('../'); $projectFolder = base_path('../');
$command = [ $command = [
sprintf('%sbuild_mosaic.sh', $projectFolder), 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), 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->setEnv(['PATH' => $currentPath.':/usr/local/Cellar/pandoc/3.1.8/bin/pandoc']);
// $process->setTimeout(36000); // stel een geschikte timeout in // $process->setTimeout(36000); // stel een geschikte timeout in
$process->start(); $process->start();
try { try {
$myOutput = []; $myOutput = [];
$process->wait(function ($type, $buffer) use (&$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)"); //$weeksAgo = ProjectReport::weeksAgoForYearAndWeek($this->mosaic->year, $this->mosaic->week);
if ($project->hasInvalidMosaicFor($year, $startWeekNumber)) {
logger("ProjecMosaicGeneratorJob::handleFor(week $startWeekNumber, year $year): InvalidMosaic.");
return new NullJob(); $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( $mosaic = $project->mosaics()->updateOrCreate(
[ [
'year' => $year, 'end_date' => $endDate,
'week' => $startWeekNumber, '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', 'path' => sprintf('%s/%s/%s',
$project->download_path, $project->download_path,
'mosaics', 'mosaics',
ProjectMosaic::getFilenameForYearAndWeek($year, $startWeekNumber) ProjectMosaic::getFilenameByPeriod($endDate,$offset)
), ),
'year' => $year, 'end_date' => $endDate->format('Y-m-d'),
'week' => $startWeekNumber, 'offset' => $offset,
]); ]);
return new self($mosaic); return new self($mosaic);
} }

View file

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

View file

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

View file

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

View file

@ -3,40 +3,34 @@
namespace App\Models; namespace App\Models;
use App\Events\ProjectReportStatus; use App\Events\ProjectReportStatus;
use App\Jobs\ProjectDownloadTiffJob;
use App\Jobs\ProjectMosiacGeneratorJob;
use App\Traits\HasStatus; use App\Traits\HasStatus;
use Carbon\CarbonPeriod; use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\File;
class ProjectReport extends Model class ProjectReport extends Model
{ {
use HasStatus; 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() public function project()
{ {
return $this->belongsTo(Project::class); 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); return 'Report from '.$endDate->copy()->subDays($offset)->toDateString().' to '.$endDate->toDateString();
}
public function getFileName()
{
return 'week_'.$this->week.'_'.$this->year;
} }
public function getFullPathName() public function getFullPathName()
@ -44,13 +38,10 @@ public function getFullPathName()
return storage_path('app/'.$this->project->download_path.'/'.$this->path); return storage_path('app/'.$this->project->download_path.'/'.$this->path);
} }
public function getReportDate() public function getReportDate():string
{ {
return self::getReportDateForYearAndWeek( // TODO remove year and week
$this->project, return $this->end_date->format('Y-m-d');
$this->year,
$this->week
)->toDateString();
} }
public static function getReportDateForYearAndWeek(Project $project, $year, $week) public static function getReportDateForYearAndWeek(Project $project, $year, $week)

View file

@ -4,7 +4,7 @@
use Illuminate\Contracts\Validation\Rule; use Illuminate\Contracts\Validation\Rule;
use App\Models\Project; use App\Models\Project;
use App\Models\ProjectReport; use Carbon\Carbon;
class AllMosaicsPresentRule implements Rule class AllMosaicsPresentRule implements Rule
{ {
@ -27,9 +27,7 @@ public function passes($attribute, $value)
return false; return false;
} }
return $project->allMosaicsPresent( return $project->allMosaicsPresent(new Carbon($value['end_date']));
ProjectReport::getReportDateForYearAndWeek($project, $value['year'], $value['week'])
);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->errorMessage = $e->getMessage(); $this->errorMessage = $e->getMessage();
return false; 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"> <x-slot name="form">
<div class="col-span-6 sm:col-span-4"> <div class="col-span-6 sm:col-span-4">
<x-label for="year" value="{{ __('Year') }}"/> <x-label for="end_date" value="{{ __('Date') }}"/>
<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 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.year" class="mt-2"/> <x-input-error for="formData.end_date" class="mt-2"/>
</div><div class="col-span-6 sm:col-span-4"> </div><div class="col-span-6 sm:col-span-4">
<x-label for="week" value="{{ __('Week') }}"/> <x-label for="offset" value="{{ __('Offset') }}"/>
<x-input id="week" type="number" min="1" max="53" class="mt-1 block w-full" wire:model.live="formData.week" autofocus/> <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.week" class="mt-2"/> <x-input-error for="formData.offset" class="mt-2"/>
<x-input-error for="formData" class="mt-2"/> <x-input-error for="formData" class="mt-2"/>
</div> </div>
<div> <div>

View file

@ -1,9 +1,3 @@
@props([
'formData',
/** @var \App\Livewire\Projects\ProjectManager */
'reportManager'
])
<x-modal wire:model.live="showReportModal" {{ $attributes }} > <x-modal wire:model.live="showReportModal" {{ $attributes }} >
<x-form-modal submit="saveProjectReport" wire:loading.class="opacity-50"> <x-form-modal submit="saveProjectReport" wire:loading.class="opacity-50">
<x-slot name="title"> <x-slot name="title">
@ -16,13 +10,13 @@
<x-slot name="form"> <x-slot name="form">
<div class="col-span-6 sm:col-span-4"> <div class="col-span-6 sm:col-span-4">
<x-label for="year" value="{{ __('Year') }}"/> <x-label for="end_date" value="{{ __('Date') }}"/>
<x-input id="year" type="text" class="mt-1 block w-full" wire:model.live="formData.year" autofocus/> <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.year" class="mt-2"/> <x-input-error for="formData.end_date" class="mt-2"/>
</div><div class="col-span-6 sm:col-span-4"> </div><div class="col-span-6 sm:col-span-4">
<x-label for="week" value="{{ __('Week') }}"/> <x-label for="offset" value="{{ __('Offset') }}"/>
<x-input id="week" type="text" class="mt-1 block w-full" wire:model.live="formData.week" autofocus/> <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.week" class="mt-2"/> <x-input-error for="formData.offset" class="mt-2"/>
<x-input-error for="formData" class="mt-2"/> <x-input-error for="formData" class="mt-2"/>
</div> </div>
<div> <div>
@ -34,7 +28,13 @@
<x-action-message class="mr-3" on="saved"> <x-action-message class="mr-3" on="saved">
{{ __('Saved.') }} {{ __('Saved.') }}
</x-action-message> </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" <x-secondary-button class="mr-3"
type="button" type="button"
x-on:click="$wire.showReportModal = false" 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 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"> <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> <livewire:components.badge :status="$report->status" :id="$report->id" :type="'report'" wire:key="{{$report->id}}"></livewire:components.badge>
</td> </td>
<td class="py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6 lg:pr-8 flex justify-end"> <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> <tr>
<th scope="col" <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"> 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>
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900"> <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>
<th scope="col" <th scope="col"
class="px-3 py-3.5 text-right text-sm font-semibold text-gray-900 sm:pr-8 lg:pr-8"> 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> <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 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"> <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>
<td class="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6 lg:pr-8"> <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> <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"> <div class="text-gray-700 text-sm">
Results: {{ \Illuminate\Support\Number::format($mosaics->total()) }} Results: {{ \Illuminate\Support\Number::format($mosaics->total()) }}
</div> </div>
{{ $mosaics->links('livewire.pagination') }} {{ $mosaics->links('livewire.pagination') }}
</div> </div>
</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> </div>
</div> </div>
<x-report-manager-properties-modal :reportManager="$this"/> <x-report-manager-properties-modal :reportManager="$this"/>
</div> </div>

View file

@ -24,19 +24,20 @@ class ProjectMosaicTest extends TestCase
* @test * @test
* @dataProvider filenameProvider * @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( $this->assertEquals(
$expected, $expected,
ProjectMosaic::getFilenameForYearAndWeek($year, $week) ProjectMosaic::getFilenameByPeriod($endDate,$offset)
); );
} }
public static function filenameProvider(){ public static function filenameProvider(){
return [ return [
[2022, 1, 'week_01_2022.tif'], [new Carbon('2022-01-01'), 10, 'period_2021-12-22_2022-01-01.tif'],
[2022, 10, 'week_10_2022.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 parent::setUp(); // TODO: Change the autogenerated stub
} }
/** // /**
* @test // * @test
* @dataProvider weeksAgoProvider // * @dataProvider weeksAgoProvider
*/ // */
public function it_can_calculatore_weeksAgo($year, $week, $expected) // public function it_can_calculatore_weeksAgo($endDate, $offset, $expected)
{ // {
Carbon::setTestNow(Carbon::now()->setISODate('2021', '41')); // Carbon::setTestNow(Carbon::now()->setISODate('2021', '41'));
$projectReport = ProjectReport::make([ // $projectReport = ProjectReport::make([
'year' => $year, // 'end_date' => $endDate,
'week' => $week, // 'offset' => $offset,
]); // ]);
$this->assertEquals($expected, $projectReport->weeksAgo()); // $this->assertEquals($expected, $projectReport->weeksAgo());
} // }
//
public static function weeksAgoProvider() // public static function weeksAgoProvider()
{ // {
return [ // return [
'1 week ago' => [2021, 40, 1], // '1 week ago' => [2021, 40, 1],
'2 weeks ago' => [2021, 39, 2], // '2 weeks ago' => [2021, 39, 2],
'3 weeks ago' => [2021, 38, 3], // '3 weeks ago' => [2021, 38, 3],
]; // ];
} // }
/** /**
* @test * @test
@ -55,8 +55,8 @@ public function it_can_get_the_full_path_name()
]); ]);
$projectReport = $project->reports()->create([ $projectReport = $project->reports()->create([
'name' => 'name', 'name' => 'name',
'year' => 2021, 'end_date' => new Carbon('2021-01-01'),
'week' => 41, 'offset' => 10,
'path' => 'path/doc.pdf', 'path' => 'path/doc.pdf',
]); ]);
$projectReport->setStatusSuccess(); $projectReport->setStatusSuccess();
@ -67,7 +67,7 @@ public function it_can_get_the_full_path_name()
* @test * @test
* @dataProvider reportDateProvider * @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([ $project = Project::create([
'name' => 'project_name', 'name' => 'project_name',
@ -76,8 +76,8 @@ public function it_can_return_the_reportDate($expected, $mail_day, $week, $year)
]); ]);
$projectReport = $project->reports()->create([ $projectReport = $project->reports()->create([
'name' => 'name', 'name' => 'name',
'year' => $year, 'end_date' => $endDate,
'week' => $week, 'offset' => $offset,
'path' => 'path/doc.pdf', 'path' => 'path/doc.pdf',
]); ]);
$projectReport->setStatusSuccess(); $projectReport->setStatusSuccess();
@ -88,13 +88,13 @@ public function it_can_return_the_reportDate($expected, $mail_day, $week, $year)
public static function reportDateProvider() public static function reportDateProvider()
{ {
return [ return [
'monday' => ['2023-12-10', 'monday', 50, 2023], 'monday' => ['2023-12-10', 'monday',new Carbon('2023-12-10'),10 ],
'tuesday' => ['2023-12-11', 'tuesday', 50, 2023], 'tuesday' => ['2023-12-11', 'tuesday',new Carbon('2023-12-11'),10 ],
'wednesday' => ['2023-12-12', 'wednesday', 50, 2023], 'wednesday' => ['2023-12-12', 'wednesday',new Carbon('2023-12-12'),10 ],
'thursday' => ['2023-12-13', 'thursday', 50, 2023], 'thursday' => ['2023-12-13', 'thursday',new Carbon('2023-12-13'),10 ],
'friday' => ['2023-12-14', 'friday', 50, 2023], 'friday' => ['2023-12-14', 'friday',new Carbon('2023-12-14'),10 ],
'saturday' => ['2023-12-15', 'saturday', 50, 2023], 'saturday' => ['2023-12-15', 'saturday',new Carbon('2023-12-15'),10 ],
'sunday' => ['2023-12-16', 'sunday', 50, 2023], '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->seed();
$this->expectException(\Exception::class); $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); $project = Project::find(1);
$lastDate = Carbon::parse('2022-01-01'); $lastDate = Carbon::parse('2022-01-01');
//$lastDate->getWeekOfYear();
$project->allMosaicsPresent($lastDate); $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 // TODO CHeck with Martin the Leading Zero test
$project = Mockery::mock(Project::class)->makePartial(); $project = Mockery::mock(Project::class)->makePartial();
$lastDate = Carbon::parse('2021-01-22'); $lastDate = Carbon::parse('2022-01-01');
$project->shouldReceive('getMosaicList')->andReturn( $project->shouldReceive('getMosaicList')->andReturn(
collect([ collect([
"chemba/weekly_mosaic/week_53_2020.tif", "chemba/weekly_mosaic/period_2021-12-26_2022-01-01.tif",
"chemba/weekly_mosaic/week_03_2021.tif", "chemba/weekly_mosaic/period_2021-12-19_2021-12-25.tif",
"chemba/weekly_mosaic/week_02_2021.tif", "chemba/weekly_mosaic/period_2021-12-12_2021-12-18.tif",
"chemba/weekly_mosaic/week_01_2021.tif", "chemba/weekly_mosaic/period_2021-12-05_2021-12-11.tif",
])); ]));
$this->assertTrue($project->allMosaicsPresent($lastDate)); $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() public function when_not_mosaics_are_present_it_should_throw_an_exception_listing_the_missing_mosiacs()
{ {
$this->expectException(\Exception::class); $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(); $project = Mockery::mock(Project::class)->makePartial();
$lastDate = Carbon::parse('2021-01-01'); $lastDate = Carbon::parse('2021-01-01');
$project->shouldReceive('getMosaicList')->andReturn( $project->shouldReceive('getMosaicList')->andReturn(
collect([ collect([
"chemba/weekly_mosaic/week_52_2020.tif", "chemba/weekly_mosaic/period_2020-12-26_2021-01-01.tif",
"chemba/weekly_mosaic/week_51_2020.tif", "chemba/weekly_mosaic/period_2020-12-19_2020-12-25.tif",
"chemba/weekly_mosaic/week_50_2020.tif", "chemba/weekly_mosaic/period_2020-12-12_2020-12-18.tif",
"chemba/weekly_mosaic/week_49_2021.tif",
"chemba/weekly_mosaic/week_48_2021.tif",
])); ]));
$project->allMosaicsPresent($lastDate); $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() public function when_all_mosaics_are_present_is_called_with_future_date_it_should_throw_an_expection()
{ {
$this->expectException(\Exception::class); $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(); $this->seed();
$project = Project::find(1); $project = Project::find(1);
Carbon::setTestNow(Carbon::parse('2020-01-01')); Carbon::setTestNow(Carbon::parse('2020-01-01'));
@ -143,14 +140,14 @@ public function getMosiacFileListByEndDate_should_return_four_filenames()
/* @var Project $project */ /* @var Project $project */
$project = Project::find(1); $project = Project::find(1);
$lastDate = Carbon::parse('2021-01-01'); $lastDate = Carbon::parse('2021-01-01');
$list = $project::getMosaicFilenameListByEndDate($lastDate); $list = iterator_to_array($project::getMosaicFilenameListByEndDate($lastDate));
$this->assertCount(4, $list); $this->assertCount(4, $list);
$this->assertEquals([ $this->assertEquals([
"week_53_2020.tif", "period_2020-12-26_2021-01-01.tif",
"week_52_2020.tif", "period_2020-12-19_2020-12-25.tif",
"week_51_2020.tif", "period_2020-12-12_2020-12-18.tif",
"week_50_2020.tif", "period_2020-12-05_2020-12-11.tif",
], $list->toArray()); ], $list);
} }
/** @test */ /** @test */
@ -162,8 +159,8 @@ public function when_getFileDownloadsFor_is_called_it_returns_a_collection_of_se
'download_path' => 'project_download_path', 'download_path' => 'project_download_path',
]); ]);
$downloads = $project->getFileDownloadsFor(2023, 22); $downloads = $project->getFileDownloadsFor(new Carbon('2024-06-18'),7);
$this->assertCount(4 * 7, $downloads); $this->assertCount(28, $downloads);
collect($downloads)->each(fn($job) => $this->assertInstanceOf(ProjectDownloadTiffJob::class, $job)); 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', 'download_path' => 'project_download_path',
]); ]);
$mosaics = $project->getMosaicsFor(2023, 2); $mosaics = $project->getMosaicsFor(new Carbon('2023-01-01'));
$this->assertCount(4, $mosaics); $this->assertCount(4, $mosaics);
collect($mosaics)->each(fn($job) => $this->assertInstanceOf(ProjectMosiacGeneratorJob::class, $job)); 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', 'download_path' => 'project_download_path',
]); ]);
$job = $project->getReportFor(2023, 2); $job = $project->getReportFor(new Carbon('2023-01-01'));
$this->assertInstanceOf(ProjectReportGeneratorJob::class, $job); $this->assertInstanceOf(ProjectReportGeneratorJob::class, $job);
} }
@ -198,15 +195,17 @@ public function when_getReport_is_called_it_returns_a_jobs()
/** @test */ /** @test */
public function it_can_create_a_chain_of_batches_that_result_in_a_report() public function it_can_create_a_chain_of_batches_that_result_in_a_report()
{ {
/* @var Project $project*/
$project = Project::create([ $project = Project::create([
'name' => 'project_name', 'name' => 'project_name',
'download_path' => 'project_download_path', 'download_path' => 'project_download_path',
]); ]);
Bus::fake(); Bus::fake();
$project->scheduleReport(2023, 50); $project->scheduleReport(new Carbon('2023-01-01'),7);
Bus::assertChained([ Bus::assertChained([
Bus::chainedBatch(function (PendingBatch $batch) { Bus::chainedBatch(function (PendingBatch $batch) {
$batch;
return $batch->jobs->count() === 28; return $batch->jobs->count() === 28;
}), }),
Bus::chainedBatch(function (PendingBatch $batch) { Bus::chainedBatch(function (PendingBatch $batch) {