SmartCane/laravel_app/app/Models/ProjectReport.php
Martin Folkerts da9d94880f wip
2024-01-09 10:49:25 +01:00

120 lines
3.1 KiB
PHP

<?php
namespace App\Models;
use App\Jobs\ProjectDownloadTiffJob;
use App\Jobs\ProjectMosiacGeneratorJob;
use Carbon\CarbonPeriod;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\File;
class ProjectReport extends Model
{
protected $fillable = ['name', 'path', 'week', 'year', 'status'];
public function setStatusSuccess()
{
$this->status = 'success';
$this->save();
}
public function setStatusFailed()
{
$this->status = 'failed';
$this->save();
}
public function project()
{
return $this->belongsTo(Project::class);
}
public function weeksAgo()
{
return $this->weeksAgoForYearAndWeek($this->year, $this->week);
}
public static function weeksAgoForYearAndWeek($year, $week)
{
return now()->diffInWeeks(now()->setISODate($year, $week));
}
public function getFileName()
{
return 'week_'.$this->week.'_'.$this->year;
}
public function getFullPathName()
{
return storage_path('app/'.$this->project->download_path.'/'.$this->path);
}
public function getReportDate()
{
return self::getReportDateForYearAndWeek(
$this->project,
$this->year,
$this->week
)->toDateString();
}
public static function getReportDateForYearAndWeek(Project $project, $year, $week)
{
$date = Carbon::now()->setISODate($year, $week);
$dayOfWeek = Carbon::parse($project->mail_day)->subDay(2)->dayOfWeek;
if ($dayOfWeek == 6) {
$reportDay = $date->startOfWeek()->subDay();
} else {
$reportDay = $date->startOfWeek()->addDays($dayOfWeek);
}
return $reportDay;
}
public function deleteMe()
{
if (File::exists($this->getFullPathName())) {
File::delete($this->getFullPathName());
}
$this->delete();
}
public static function schedule($year, $week)
{
Bus::chain([
Bus::batch(self::getFileDownloadsFor($year, $week)),
Bus::batch(self::getMosiacsFor($year, $week)),
Bus::batch(self::getReport($year, $week)),
]);
}
public static function getFileDownloadsFor($project, $year, $startWeekNumber)
{
$endOfRange = Carbon::now()->setISODate($year, $startWeekNumber)->endOfWeek();
$startOfRange = (clone $endOfRange)->subWeeks(2)->startOfWeek();
$dateRange = CarbonPeriod::create($startOfRange, $endOfRange);
return collect($dateRange)
->map(fn ($date) => ProjectDownloadTiffJob::handleForDate($project, $date))
->filter();
}
public static function getMosaicsFor($project, $year, $startWeekNumber)
{
$jobs = [];
foreach (range(0,2) as $weekDiff) {
$job = ProjectMosiacGeneratorJob::handleFor($project, $year, $startWeekNumber - $weekDiff);
if ($job) {
$jobs[] = $job;
}
}
return $jobs;
}
}