107 lines
6.6 KiB
PHP
107 lines
6.6 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\SupplyRecord;
|
|
use App\Models\User;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\Schema;
|
|
|
|
/** Current approved versions only. Dates describe vigency, never renewal or purchase authority. */
|
|
final class AgreementFollowup
|
|
{
|
|
public function authorize(User $actor): User
|
|
{
|
|
$current = User::query()->findOrFail($actor->id);
|
|
abort_unless(auth()->id() === $current->id && $current->tenant_id !== null && $current->tenant_id === $actor->tenant_id, 403);
|
|
$planning = app(SupplyPlanning::class);
|
|
abort_unless(collect(['supply_read', 'supply_prepare', 'supply_review'])->contains(fn (string $permission) => $planning->allows($current, $permission)), 403);
|
|
abort_unless(Schema::hasTable('supply_records'), 503, 'Instalação do fornecimento pendente.');
|
|
|
|
return $current;
|
|
}
|
|
|
|
/** @return array{search:string,validity:string,expires_by:string} */
|
|
public function filters(Request $request): array
|
|
{
|
|
$v = $request->validate(['search' => 'nullable|string|max:100', 'validity' => 'nullable|in:all,current,expired,future,unknown',
|
|
'expires_by' => 'nullable|date_format:Y-m-d', 'page' => 'nullable|integer|min:1|max:1000000']);
|
|
|
|
return ['search' => trim($v['search'] ?? ''), 'validity' => $v['validity'] ?? 'all', 'expires_by' => $v['expires_by'] ?? ''];
|
|
}
|
|
|
|
/** @param array{search:string,validity:string,expires_by:string} $filters
|
|
* @return Builder<SupplyRecord>
|
|
*/
|
|
public function query(User $actor, array $filters, string $today, string $kind = 'agreement'): Builder
|
|
{
|
|
abort_unless(in_array($kind, ['agreement', 'contract'], true), 404);
|
|
if ($kind === 'contract') {
|
|
abort_unless(app(AgreementOrderLimits::class)->ready(), 503);
|
|
}
|
|
$query = app(SupplyPlanning::class)->latest($kind)->where('tenant_id', $actor->tenant_id)->where('state', 'approved');
|
|
if ($filters['search'] !== '') {
|
|
$query->where(fn (Builder $q) => $q->whereLike('data->reference', '%'.$filters['search'].'%')
|
|
->orWhereLike('snapshot->supplier->name', '%'.$filters['search'].'%')->orWhereLike('snapshot->item->code', '%'.$filters['search'].'%')
|
|
->orWhereLike('snapshot->item->name', '%'.$filters['search'].'%')->orWhereLike('snapshot->warehouse->name', '%'.$filters['search'].'%'));
|
|
}
|
|
if ($filters['validity'] === 'unknown') {
|
|
$query->where(fn (Builder $q) => $q->whereNull('data->valid_from')->orWhereNull('data->valid_until')->orWhere('data->valid_from', '')->orWhere('data->valid_until', ''));
|
|
} elseif ($filters['validity'] !== 'all') {
|
|
$query->whereNotNull('data->valid_from')->where('data->valid_from', '!=', '')->whereNotNull('data->valid_until')->where('data->valid_until', '!=', '');
|
|
match ($filters['validity']) {
|
|
'current' => $query->where('data->valid_from', '<=', $today)->where('data->valid_until', '>=', $today),
|
|
'expired' => $query->where('data->valid_until', '<', $today),
|
|
'future' => $query->where('data->valid_from', '>', $today),
|
|
default => throw new \InvalidArgumentException('Situação de vigência desconhecida.'),
|
|
};
|
|
}
|
|
if ($filters['expires_by'] !== '') {
|
|
$query->where('data->valid_until', '!=', '')->where('data->valid_until', '<=', $filters['expires_by']);
|
|
}
|
|
|
|
return $query;
|
|
}
|
|
|
|
/** @param Collection<int,SupplyRecord> $records
|
|
* @return list<array<string,mixed>>
|
|
*/
|
|
public function rows(Collection $records, string $today): array
|
|
{
|
|
$counts = app(SupplyPlanning::class)->latest('policy')->where('state', 'approved')->whereIn('data->agreement_key', $records->pluck('record_key'))
|
|
->select('data->agreement_key as agreement_key')->selectRaw('COUNT(*) as policy_count')->groupBy('data->agreement_key')->get()
|
|
->mapWithKeys(fn (SupplyRecord $record) => [(string) $record->getAttribute('agreement_key') => (int) $record->getAttribute('policy_count')]);
|
|
$articles = app(SupplyPlanning::class)->latest('agreement')->where('state', 'approved')->whereIn('data->contract_key', $records->where('kind', 'contract')->pluck('record_key'))
|
|
->select('data->contract_key as contract_key')->selectRaw('COUNT(*) as article_count')->groupBy('data->contract_key')->get()
|
|
->mapWithKeys(fn (SupplyRecord $record) => [(string) $record->getAttribute('contract_key') => (int) $record->getAttribute('article_count')]);
|
|
|
|
return array_values($records->map(function (SupplyRecord $record) use ($today, $counts, $articles) {
|
|
$from = $this->date($record->data['valid_from'] ?? null);
|
|
$until = $this->date($record->data['valid_until'] ?? null);
|
|
$validity = $from === null || $until === null ? 'unknown' : ($until < $from ? 'unknown' : ($until < $today ? 'expired' : ($from > $today ? 'future' : 'current')));
|
|
|
|
return ['id' => $record->id, 'record_key' => $record->record_key, 'version' => $record->version, 'reference' => $record->data['reference'] ?? null,
|
|
'supplier' => $record->snapshot['supplier']['name'] ?? null, 'item_code' => $record->snapshot['item']['code'] ?? null,
|
|
'item' => $record->snapshot['item']['name'] ?? null, 'warehouse' => $record->snapshot['warehouse']['name'] ?? null,
|
|
'valid_from' => $from, 'valid_until' => $until, 'validity' => $validity, 'approved_policies' => $counts->get($record->record_key, 0),
|
|
'kind' => $record->kind, 'currency' => $record->data['currency'] ?? null, 'max_order_value_minor' => $record->data['max_order_value_minor'] ?? null,
|
|
'periodicity_days' => $record->data['periodicity_days'] ?? null, 'approved_articles' => $articles->get($record->record_key, 0),
|
|
'articles_href' => '/compras/fornecimento?view=agreements&linked_contract_key='.$record->record_key,
|
|
'href' => '/compras/fornecimento?view='.($record->kind === 'contract' ? 'contracts' : 'agreements').'&record_id='.$record->id.'#supply-record-'.$record->id,
|
|
'policies_href' => '/compras/fornecimento?view=calendar&linked_agreement_key='.$record->record_key];
|
|
})->all());
|
|
}
|
|
|
|
private function date(mixed $value): ?string
|
|
{
|
|
if (! is_string($value)) {
|
|
return null;
|
|
}
|
|
$date = \DateTimeImmutable::createFromFormat('!Y-m-d', $value);
|
|
|
|
return $date !== false && $date->format('Y-m-d') === $value ? $value : null;
|
|
}
|
|
}
|