akaunting/app/Jobs/Document/UpdateDocument.php

72 lines
2.3 KiB
PHP
Raw Normal View History

2020-12-24 01:28:38 +03:00
<?php
namespace App\Jobs\Document;
use App\Abstracts\Job;
use App\Events\Document\PaidAmountCalculated;
use App\Events\Document\DocumentUpdated;
use App\Events\Document\DocumentUpdating;
2021-09-06 11:53:57 +03:00
use App\Interfaces\Job\ShouldUpdate;
2020-12-24 01:28:38 +03:00
use App\Jobs\Document\CreateDocumentItemsAndTotals;
use App\Models\Document\Document;
use App\Traits\Relationships;
use Illuminate\Support\Str;
2021-09-06 11:53:57 +03:00
class UpdateDocument extends Job implements ShouldUpdate
2020-12-24 01:28:38 +03:00
{
use Relationships;
2021-09-06 11:53:57 +03:00
public function handle(): Document
2020-12-24 01:28:38 +03:00
{
if (empty($this->request['amount'])) {
$this->request['amount'] = 0;
}
2021-09-06 11:53:57 +03:00
event(new DocumentUpdating($this->model, $this->request));
2020-12-24 01:28:38 +03:00
\DB::transaction(function () {
// Upload attachment
if ($this->request->file('attachment')) {
2021-09-06 11:53:57 +03:00
$this->deleteMediaModel($this->model, 'attachment', $this->request);
2020-12-24 01:28:38 +03:00
2021-01-22 12:38:17 +03:00
foreach ($this->request->file('attachment') as $attachment) {
2021-09-06 11:53:57 +03:00
$media = $this->getMedia($attachment, Str::plural($this->model->type));
2021-01-22 12:38:17 +03:00
2021-09-06 11:53:57 +03:00
$this->model->attachMedia($media, 'attachment');
2021-01-22 12:38:17 +03:00
}
2022-10-31 15:29:45 +03:00
} elseif (! $this->request->file('attachment') && $this->model->attachment) {
2021-09-06 11:53:57 +03:00
$this->deleteMediaModel($this->model, 'attachment', $this->request);
2020-12-24 01:28:38 +03:00
}
$this->deleteRelationships($this->model, ['items', 'item_taxes', 'totals'], true);
2020-12-24 01:28:38 +03:00
2021-09-06 11:53:57 +03:00
$this->dispatch(new CreateDocumentItemsAndTotals($this->model, $this->request));
2020-12-24 01:28:38 +03:00
2021-09-06 11:53:57 +03:00
$this->model->paid_amount = $this->model->paid;
2021-09-06 11:53:57 +03:00
event(new PaidAmountCalculated($this->model));
2020-12-24 01:28:38 +03:00
2021-09-06 11:53:57 +03:00
if ($this->model->paid_amount > 0) {
if ($this->request['amount'] == $this->model->paid_amount) {
$this->request['status'] = 'paid';
}
2021-09-06 11:53:57 +03:00
if ($this->request['amount'] > $this->model->paid_amount) {
$this->request['status'] = 'partial';
}
2020-12-24 01:28:38 +03:00
}
2021-09-06 11:53:57 +03:00
unset($this->model->reconciled);
unset($this->model->paid_amount);
2020-12-24 01:28:38 +03:00
2021-09-06 11:53:57 +03:00
$this->model->update($this->request->all());
2020-12-24 01:28:38 +03:00
2021-09-06 11:53:57 +03:00
$this->model->updateRecurring($this->request->all());
2020-12-24 01:28:38 +03:00
});
2021-09-06 11:53:57 +03:00
event(new DocumentUpdated($this->model, $this->request));
2020-12-24 01:28:38 +03:00
2021-09-06 11:53:57 +03:00
return $this->model;
2020-12-24 01:28:38 +03:00
}
}