SmartCane/laravel_app/app/Models/Project.php
Martin Folkerts f60fb7e46d wip
2023-12-05 13:55:11 +01:00

110 lines
3 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use HasFactory;
protected $fillable = [
'name',
'mail_template',
'mail_subject',
'mail_frequency',
'mail_day',
];
public static function saveWithFormData(mixed $formData)
{
$uniqueIdentifier = ['id' => $formData['id'] ?? null];
$project = Project::updateOrCreate($uniqueIdentifier, $formData);
$project->upsertBoundingBox($formData);
$project->upsertMailRecipients($formData);
}
private function upsertBoundingBox($formData)
{
$boundingBoxesData = array_map(function ($boundingBox) {
$boundingBox['project_id'] = $this->id;
unset($boundingBox['created_at']);
unset($boundingBox['updated_at']);
$boundingBox['id'] ??= null;
return $boundingBox;
}, $formData['boundingBoxes'] ?? []);
ProjectBoundingBox::upsert(
$boundingBoxesData,
['id', 'project_id'],
[
'name',
'top_left_latitude',
'top_left_longitude',
'bottom_right_latitude',
'bottom_right_longitude'
]
);
}
private function upsertMailRecipients($formData)
{
$mailRecipientsData = array_map(function ($mailRecipient) {
$mailRecipient['project_id'] = $this->id;
unset($mailRecipient['created_at']);
unset($mailRecipient['updated_at']);
$mailRecipient['id'] ??= null;
return $mailRecipient;
}, $formData['mail_recipients'] ?? []);
ProjectEmailRecipient::upsert(
$mailRecipientsData,
['id', 'project_id'],
['name', 'email',]
);
}
protected static function boot()
{
parent::boot(); // TODO: Change the autogenerated stub
static::deleting(function ($project) {
$project->boundingBoxes()->delete();
$project->emailRecipients()->delete();
$project->mailings()->each(function ($mailing) {
$mailing->attachments()->delete();
$mailing->recipients()->delete();
});
$project->mailings()->delete();
});
}
public function getAttachmentPathAttribute()
{
return storage_path(sprintf('%s/attachments', $this->download_path));
return '/storage/' . $this->download_path . '/attachments';
}
public function boundingBoxes()
{
return $this->hasMany(ProjectBoundingBox::class);
}
public function emailRecipients()
{
return $this->hasMany(ProjectEmailRecipient::class);
}
public function mailings()
{
return $this->hasMany(ProjectMailing::class);
}
public function downloads()
{
return $this->hasMany(ProjectDownload::class);
}
}