172 lines
12 KiB
PHP
172 lines
12 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Enums\PurchasingRole;
|
|
use App\Models\Requisition;
|
|
use App\Models\RequisitionItem;
|
|
use App\Models\StockItem;
|
|
use App\Models\SupplyRecord;
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Support\Str;
|
|
|
|
/** Documentary classification only. No tariff, exemption or financial calculation is activated. */
|
|
final class ImportTariffCodes
|
|
{
|
|
/** Freeze classifications only for explicitly marked imported lines; never rewrite an existing order.
|
|
* @param list<int> $itemIds
|
|
* @return array<int,array<string,mixed>>
|
|
*/
|
|
public function freezeForItems(User $actor, array $itemIds): array
|
|
{
|
|
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
|
if (! Schema::hasTable('supply_records')) {
|
|
return [];
|
|
}
|
|
$records = app(SupplyPlanning::class)->latest('import_tariff')->whereIn('data->requisition_item_id', $itemIds)->get();
|
|
if ($records->isEmpty()) {
|
|
return [];
|
|
}
|
|
abort_unless($this->ready(), 503, 'Preserve a capacidade de classificação dos artigos importados antes de emitir uma nova ordem.');
|
|
$result = [];
|
|
foreach ($records as $record) {
|
|
$item = RequisitionItem::query()->whereKey($record->data['requisition_item_id'])->firstOrFail();
|
|
Requisition::query()->visibleTo($actor)->whereKey($item->requisition_id)->firstOrFail();
|
|
abort_unless($record->state === 'confirmed' && $record->snapshot['item'] === $item->only(['id', 'description', 'unit', 'quantity']), 409,
|
|
'Confirme a classificação pautal actual de cada artigo importado antes de emitir a ordem.');
|
|
$result[$item->id] = ['record_id' => $record->id, 'version' => $record->version,
|
|
'requisition_item_id' => $item->id, 'item' => $record->snapshot['item'], 'data' => $record->data,
|
|
'source' => $record->snapshot['master'] ?? null, 'confirmed_by' => $record->snapshot['confirmed_by'], 'reason' => $record->reason];
|
|
}
|
|
ksort($result, SORT_NUMERIC);
|
|
|
|
return $result;
|
|
}
|
|
|
|
public function ready(): bool
|
|
{
|
|
$db = DB::connection();
|
|
|
|
return config('import-tariffs.qa_enabled') === true && app()->environment('testing')
|
|
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
|
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
|
|
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function workspace(User $actor, Requisition $request, string $search = ''): array
|
|
{
|
|
return DB::transaction(function () use ($actor, $request, $search): array {
|
|
[$actor, $request] = $this->context($actor, $request);
|
|
$materialsVisible = $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance]);
|
|
$history = SupplyRecord::query()->where('kind', 'import_tariff')->where('data->requisition_id', $request->id)
|
|
->latest('id')->paginate(20, ['id', 'version', 'state', 'reason', 'data', 'snapshot', 'created_at'], 'tariff_history_page')->withQueryString();
|
|
$latest = app(SupplyPlanning::class)->latest('import_tariff')->where('data->requisition_id', $request->id)
|
|
->get(['id', 'record_key', 'version', 'state', 'reason', 'data', 'snapshot']);
|
|
$stockItems = StockItem::query()->when(! $materialsVisible, fn ($q) => $q->whereRaw('1 = 0'))->when($search !== '', fn ($q) => $q->where(fn ($match) => $match
|
|
->where('code', 'like', '%'.addcslashes($search, '%_\\').'%')->orWhere('name', 'like', '%'.addcslashes($search, '%_\\').'%')))
|
|
->orderBy('id')->paginate(20, ['id', 'code', 'name', 'unit'], 'stock_page')->withQueryString();
|
|
$stockItems->through(fn ($item) => [...$item->only(['id', 'code', 'name', 'unit']),
|
|
'tariff' => app(SupplyPlanning::class)->latest('stock_tariff')->where('stock_item_id', $item->id)->first(['id', 'version', 'data'])]);
|
|
|
|
return ['requisition' => $request->only(['id', 'number', 'status']), 'items' => $request->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity']),
|
|
'latest' => $latest, 'history' => $history, 'stockItems' => $stockItems, 'canPropose' => ($actor->id === $request->requester_id && app(OrganizationAccess::class)->canRequest($actor)) || $actor->hasFunctions([PurchasingRole::Procurement]),
|
|
'canConfirm' => $actor->hasFunctions([PurchasingRole::Procurement]),
|
|
'masters' => app(SupplyPlanning::class)->latest('stock_tariff')->when(! $materialsVisible, fn ($q) => $q->whereRaw('1 = 0'))->whereIn('stock_item_id', StockItem::query()->select('id'))
|
|
->when($search !== '', fn ($q) => $q->whereRaw("LOWER(data->>'code') LIKE ? ESCAPE '!'", ['%'.str_replace(['!', '%', '_'], ['!!', '!%', '!_'], mb_strtolower($search)).'%']))
|
|
->latest('id')->paginate(20, ['id', 'version', 'stock_item_id', 'data', 'snapshot'], 'masters_page')->withQueryString(),
|
|
'masterSearch' => $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', 'action' => 'required|in:master,propose,confirm',
|
|
'version' => 'required|integer|min:0', 'reason' => 'required|string|min:10|max:4000',
|
|
'stock_item_id' => 'required_if:action,master|nullable|integer|min:1', 'requisition_item_id' => 'required_unless:action,master|nullable|integer|min:1',
|
|
'master_id' => 'nullable|integer|min:1', 'code' => 'required_unless:action,propose|nullable|string|max:40|not_regex:/[\x00-\x1F\x7F]/',
|
|
'source_reference' => 'required_unless:action,propose|nullable|string|max:2000'])->validate();
|
|
$data['operation_key'] = strtolower($data['operation_key']);
|
|
$hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
|
|
|
|
return DB::transaction(function () use ($actor, $request, $data, $hash): SupplyRecord {
|
|
[$actor, $request] = $this->context($actor, $request);
|
|
$buyer = $actor->hasFunctions([PurchasingRole::Procurement]);
|
|
abort_unless($buyer || ($data['action'] === 'propose' && $actor->id === $request->requester_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->created_by === $actor->id && in_array($retry->kind, ['stock_tariff', 'import_tariff'], true) && hash_equals($retry->input_hash, $hash), 409);
|
|
|
|
return $retry;
|
|
}
|
|
$code = trim($data['code'] ?? '');
|
|
$source = trim($data['source_reference'] ?? '');
|
|
$snapshot = ['calculations_activated' => false, 'legal_validity_certified' => false];
|
|
if ($data['action'] === 'master') {
|
|
abort_unless($code !== '' && $source !== '' && empty($data['requisition_item_id']) && empty($data['master_id']), 422, 'Indique código e fonte do cadastro do material.');
|
|
$item = StockItem::query()->whereKey($data['stock_item_id'] ?? null)->firstOrFail();
|
|
$kind = 'stock_tariff';
|
|
$old = app(SupplyPlanning::class)->latest($kind)->where('stock_item_id', $item->id)->first();
|
|
$payload = ['code' => $code, 'source_reference' => $source];
|
|
$snapshot['item'] = $item->only(['id', 'code', 'name', 'unit']);
|
|
$state = 'recorded';
|
|
} else {
|
|
abort_if(! empty($data['stock_item_id']), 422);
|
|
$item = $request->items()->whereKey($data['requisition_item_id'] ?? null)->firstOrFail();
|
|
$kind = 'import_tariff';
|
|
$old = app(SupplyPlanning::class)->latest($kind)->where('data->requisition_item_id', $item->id)->first();
|
|
$snapshot['item'] = $item->only(['id', 'description', 'unit', 'quantity']);
|
|
if ($data['action'] === 'propose') {
|
|
$payload = ['requisition_id' => $request->id, 'requisition_item_id' => $item->id,
|
|
'proposed_code' => $code === '' ? null : $code, 'source_reference' => $source === '' ? null : $source];
|
|
if (! empty($data['master_id'])) {
|
|
abort_unless($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance]), 403);
|
|
$master = SupplyRecord::query()->where('kind', 'stock_tariff')->whereKey($data['master_id'])->firstOrFail();
|
|
$currentMaster = app(SupplyPlanning::class)->latest('stock_tariff')->where('stock_item_id', $master->stock_item_id)->firstOrFail();
|
|
$material = StockItem::query()->whereKey($master->stock_item_id)->firstOrFail();
|
|
abort_unless($currentMaster->id === $master->id && $material->only(['id', 'code', 'name', 'unit']) === $master->snapshot['item'], 409, 'O cadastro do material mudou. Seleccione a versão actual.');
|
|
abort_unless($code === $master->data['code'] && $source === $master->data['source_reference'], 409, 'Aplique explicitamente o código e a fonte do cadastro ou conserve uma proposta manual.');
|
|
$snapshot['master'] = ['id' => $master->id, 'version' => $master->version, 'item' => $master->snapshot['item']];
|
|
}
|
|
$state = 'proposed';
|
|
} else {
|
|
abort_unless($old !== null && $old->state === 'proposed' && empty($data['master_id']) && $code !== '' && $source !== '', 409, 'Seleccione uma proposta actual e indique código e fonte da confirmação.');
|
|
abort_unless($old->snapshot['item'] === $snapshot['item'], 409, 'O artigo mudou. Prepare uma proposta actual.');
|
|
$payload = [...$old->data, 'confirmed_code' => $code, 'confirmation_source' => $source,
|
|
'deviation' => $code !== $old->data['proposed_code'], 'confirmed_by' => $actor->id];
|
|
$snapshot = [...$old->snapshot, 'confirmed_by' => ['id' => $actor->id, 'name' => $actor->name]];
|
|
$state = 'confirmed';
|
|
}
|
|
}
|
|
abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A classificação mudou. Preserve os seus valores e consulte a versão actual.');
|
|
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => $kind,
|
|
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
|
'stock_item_id' => $kind === 'stock_tariff' ? $item->id : null, 'state' => $state,
|
|
'created_by' => $actor->id, 'data' => $payload, 'snapshot' => $snapshot,
|
|
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
|
app(RequisitionWorkflow::class)->audit($actor, 'import.tariff_'.$data['action'], $kind === 'stock_tariff' ? null : $request, null,
|
|
['record_id' => $record->id, 'version' => $record->version, 'state' => $state, 'calculations_activated' => false]);
|
|
|
|
return $record;
|
|
});
|
|
}
|
|
|
|
/** @return array{User,Requisition} */
|
|
private function context(User $actor, Requisition $request): array
|
|
{
|
|
abort_unless($this->ready(), 503);
|
|
app(ConflictGuard::class)->lockCompany($actor);
|
|
$actor = app(CurrentActor::class)->lock($actor);
|
|
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
|
abort_unless(app(OrganizationAccess::class)->permissions($actor) !== [], 403);
|
|
$request = Requisition::query()->visibleTo($actor)->findOrFail($request->id);
|
|
|
|
return [$actor, $request];
|
|
}
|
|
}
|