169 lines
10 KiB
PHP
169 lines
10 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Requisition;
|
|
use App\Models\RequisitionItem;
|
|
use App\Models\SupplyRecord;
|
|
use App\Models\User;
|
|
use Brick\Math\BigDecimal;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
/** Documentary account imputations; the common ledger remains the sole journal writer. */
|
|
final class RequisitionAccountAssignments
|
|
{
|
|
/** @return array{User,Requisition} */
|
|
private function context(User $actor, Requisition $request): array
|
|
{
|
|
abort_unless(app(RequisitionLedgerAccounts::class)->ready(), 503);
|
|
app(ConflictGuard::class)->lockCompany($actor);
|
|
$actor = app(CurrentActor::class)->lock($actor);
|
|
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
|
|
|
return [$actor, Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($request->id)];
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
private function basis(RequisitionItem $item, Requisition $request): array
|
|
{
|
|
return ['line' => $item->only(['id', 'description', 'category', 'purchase_type', 'quantity', 'unit', 'unit_price_minor', 'tax_rate',
|
|
'subtotal_minor', 'tax_minor', 'total_minor', 'equipment_id', 'spare_part_id', 'category_context', 'catalogue_entry_id']),
|
|
'cost_center_id' => $request->cost_center_id, 'budget_distribution_preparation' => $request->budget_distribution_preparation];
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function workspace(User $actor, Requisition $request, string $search = ''): array
|
|
{
|
|
return DB::transaction(function () use ($actor, $request, $search) {
|
|
[$actor, $request] = $this->context($actor, $request);
|
|
$write = $request->status === 'draft' && $request->getAttribute('draft_input') === null && $request->total_minor !== null
|
|
&& $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor)
|
|
&& ! app(ConflictGuard::class)->participationBlocked($actor, $request);
|
|
$items = $request->items()->orderBy('id')->get();
|
|
|
|
return ['requisition' => $request->only(['id', 'number', 'status']),
|
|
'items' => $items->map(fn ($line) => [...$this->basis($line, $request)['line'], 'subtotal_minor' => (string) $line->subtotal_minor,
|
|
'total_minor' => (string) $line->total_minor, 'basis_hash' => hash('sha256', json_encode($this->basis($line, $request), JSON_THROW_ON_ERROR))]),
|
|
'current' => app(SupplyPlanning::class)->latest('req_account')->where('data->requisition_id', $request->id)->get(),
|
|
'history' => SupplyRecord::query()->where('kind', 'req_account')->where('data->requisition_id', $request->id)
|
|
->latest('id')->paginate(15, ['*'], 'history_page')->withQueryString(),
|
|
'accounts' => $write ? app(RequisitionLedgerAccounts::class)->options($actor, $search) : null,
|
|
'canWrite' => $write, 'search' => $search, 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
|
});
|
|
}
|
|
|
|
/** @param array<string,mixed> $input */
|
|
public function save(User $actor, Requisition $request, array $input): SupplyRecord
|
|
{
|
|
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'item_id' => 'required|integer|min:1',
|
|
'basis_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'reason' => 'required|string|min:10|max:4000',
|
|
'allocations' => 'required|array|min:1|max:20', 'allocations.*.account_id' => 'required|integer|min:1|distinct',
|
|
'allocations.*.source_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'],
|
|
'allocations.*.subtotal' => ['required', 'regex:/^\d{1,18}(\.\d{1,2})?$/D'],
|
|
'allocations.*.total' => ['required', 'regex:/^\d{1,18}(\.\d{1,2})?$/D']])->validate();
|
|
$data['operation_key'] = strtolower($data['operation_key']);
|
|
usort($data['allocations'], fn ($a, $b) => $a['account_id'] <=> $b['account_id']);
|
|
$hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
|
|
|
|
return DB::transaction(function () use ($actor, $request, $data, $hash) {
|
|
[$actor, $request] = $this->context($actor, $request);
|
|
abort_unless($request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor), 403);
|
|
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
|
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
|
if ($retry !== null) {
|
|
abort_unless($retry->kind === 'req_account' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
|
|
|
return $retry;
|
|
}
|
|
abort_unless($request->status === 'draft', 409);
|
|
abort_unless($request->getAttribute('draft_input') === null && $request->total_minor !== null, 409, 'Complete primeiro as linhas e os campos da requisição.');
|
|
$item = $request->items()->whereKey($data['item_id'])->firstOrFail();
|
|
$basis = $this->basis($item, $request);
|
|
abort_unless(hash_equals(hash('sha256', json_encode($basis, JSON_THROW_ON_ERROR)), $data['basis_hash']), 409, 'A linha ou a distribuição mudou. Reveja a imputação.');
|
|
$old = app(SupplyPlanning::class)->latest('req_account')->where('data->requisition_item_id', $item->id)->first();
|
|
abort_unless((int) ($old->version ?? 0) === (int) $data['version'], 409);
|
|
$subtotal = BigDecimal::of(0);
|
|
$total = BigDecimal::of(0);
|
|
$allocations = [];
|
|
foreach ($data['allocations'] as $allocation) {
|
|
$account = app(RequisitionLedgerAccounts::class)->resolve($actor, (int) $allocation['account_id'], $allocation['source_hash']);
|
|
$net = BigDecimal::of($allocation['subtotal'])->multipliedBy(100)->toScale(0);
|
|
$gross = BigDecimal::of($allocation['total'])->multipliedBy(100)->toScale(0);
|
|
if ($gross->isLessThan($net)) {
|
|
throw ValidationException::withMessages(['allocations' => 'O total de cada parcela não pode ser inferior à base sem IVA.']);
|
|
}
|
|
$subtotal = $subtotal->plus($net);
|
|
$total = $total->plus($gross);
|
|
$allocations[] = ['account' => $account, 'subtotal_minor' => (string) $net, 'total_minor' => (string) $gross];
|
|
}
|
|
if (! $subtotal->isEqualTo($item->subtotal_minor) || ! $total->isEqualTo($item->total_minor)) {
|
|
throw ValidationException::withMessages(['allocations' => 'As parcelas devem corresponder exactamente à base sem IVA e ao total da linha.']);
|
|
}
|
|
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'req_account',
|
|
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
|
'state' => 'assigned', 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'reason' => $data['reason'],
|
|
'data' => ['requisition_id' => $request->id, 'requisition_item_id' => $item->id, 'allocations' => $allocations],
|
|
'snapshot' => $basis, 'created_by' => $actor->id, 'created_at' => now()]);
|
|
app(RequisitionWorkflow::class)->audit($actor, 'requisition.accounts_assigned', $request, $old?->toArray(), ['record' => $record->toArray()]);
|
|
|
|
return $record;
|
|
});
|
|
}
|
|
|
|
public function assertSubmission(User $actor, Requisition $request): void
|
|
{
|
|
$items = $request->items()->get();
|
|
$ids = [];
|
|
foreach ($items as $item) {
|
|
$ids[] = $item->id;
|
|
}
|
|
$frozen = $this->freezeForItems($actor, $ids);
|
|
if (! app(RequisitionLedgerAccounts::class)->ready()) {
|
|
abort_if(config('requisition-accounts.qa_enabled') === true && $items->isNotEmpty(),
|
|
503, 'Plano de contas indisponível. Não foram criadas reservas ou aprovações.');
|
|
|
|
return;
|
|
}
|
|
foreach ($items as $item) {
|
|
if (! isset($frozen[$item->id])) {
|
|
throw ValidationException::withMessages(['account_assignment' => 'Indique a conta contabilística de cada linha antes de submeter. Não foram criadas reservas ou aprovações.']);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** @param list<int> $ids
|
|
* @return array<int,array<string,mixed>>
|
|
*/
|
|
public function freezeForItems(User $actor, array $ids): array
|
|
{
|
|
if (! Schema::hasTable('supply_records')) {
|
|
return [];
|
|
}
|
|
$records = app(SupplyPlanning::class)->latest('req_account')->whereIn('data->requisition_item_id', $ids)->get();
|
|
if ($records->isEmpty()) {
|
|
return [];
|
|
}
|
|
abort_unless(app(RequisitionLedgerAccounts::class)->ready(), 503, 'Preserve a origem das contas atribuídas antes de prosseguir.');
|
|
$result = [];
|
|
foreach ($records as $record) {
|
|
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $record->data['requisition_id'])
|
|
->where('action', 'requisition.accounts_assigned')->where('user_id', $record->created_by)->where('after->record->id', $record->id)->first();
|
|
$saved = $audit === null ? null : json_decode($audit->after, true, 64, JSON_THROW_ON_ERROR)['record'] ?? null;
|
|
abort_unless(is_array($saved) && ($saved['data'] ?? null) === $record->data && ($saved['snapshot'] ?? null) === $record->snapshot
|
|
&& ($saved['version'] ?? null) === $record->version && ($saved['input_hash'] ?? null) === $record->input_hash, 409,
|
|
'A imputação não corresponde ao registo auditado. Confira a origem antes de prosseguir.');
|
|
$item = RequisitionItem::query()->whereKey($record->data['requisition_item_id'])->firstOrFail();
|
|
$request = Requisition::query()->visibleTo($actor)->whereKey($item->requisition_id)->firstOrFail();
|
|
abort_unless($record->snapshot === $this->basis($item, $request), 409, 'A linha ou a distribuição mudou. Reveja a imputação contabilística.');
|
|
$result[$item->id] = $record->only(['id', 'version', 'data', 'snapshot', 'reason']);
|
|
}
|
|
ksort($result, SORT_NUMERIC);
|
|
|
|
return $result;
|
|
}
|
|
}
|