281 lines
14 KiB
PHP
281 lines
14 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Department;
|
|
use App\Models\Requisition;
|
|
use App\Models\RequisitionItem;
|
|
use App\Models\SupplyRecord;
|
|
use App\Models\User;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
/** Documentary production/maintenance orders owned by Compras; no production scheduling or SGF writes. */
|
|
final class OperationalOrders
|
|
{
|
|
private const REGISTRY_READERS = ['admin', 'procurement', 'requester', 'production_order_prepare', 'maintenance_order_prepare'];
|
|
|
|
public function ready(): bool
|
|
{
|
|
$db = DB::connection();
|
|
|
|
return config('operational-orders.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())))
|
|
&& Schema::hasTable('supply_records');
|
|
}
|
|
|
|
private function actor(User $actor): User
|
|
{
|
|
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);
|
|
|
|
return $actor;
|
|
}
|
|
|
|
private function policy(): ?SupplyRecord
|
|
{
|
|
return app(SupplyPlanning::class)->latest('op_order_policy')->first();
|
|
}
|
|
|
|
/** @return Builder<SupplyRecord> */
|
|
private function registryOrders(User $actor): Builder
|
|
{
|
|
return app(SupplyPlanning::class)->latest('op_order')->where('tenant_id', $actor->tenant_id)
|
|
->when(! $actor->hasFunctions(['admin', 'procurement']), fn ($q) => $q->where('data->department_id', $actor->department_id));
|
|
}
|
|
|
|
/** Current native registry scope for read-only cross-module search.
|
|
* @return Builder<SupplyRecord>|null
|
|
*/
|
|
public function searchQuery(User $actor): ?Builder
|
|
{
|
|
if (! $this->ready() || auth()->id() !== $actor->id || $actor->tenant_id === null
|
|
|| app(OrganizationAccess::class)->maintenanceOnly($actor) || ! $actor->hasFunctions(self::REGISTRY_READERS)) {
|
|
return null;
|
|
}
|
|
|
|
return $this->registryOrders($actor);
|
|
}
|
|
|
|
/** @return list<string> */
|
|
private function types(User $actor, ?SupplyRecord $policy): array
|
|
{
|
|
if ($policy === null) {
|
|
return [];
|
|
}
|
|
if ($policy->data['mode'] === 'procurement') {
|
|
return $actor->hasFunctions(['procurement']) ? ['production', 'maintenance'] : [];
|
|
}
|
|
|
|
return array_values(array_filter(['production', 'maintenance'], fn ($type) => $actor->hasFunctions([$type.'_order_prepare'])));
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function workspace(User $actor, ?Requisition $request = null, ?int $selectedOrderId = null): array
|
|
{
|
|
return DB::transaction(function () use ($actor, $request, $selectedOrderId) {
|
|
$actor = $this->actor($actor);
|
|
$policy = $this->policy();
|
|
if ($request !== null) {
|
|
$request = Requisition::query()->visibleTo($actor)->findOrFail($request->id);
|
|
} else {
|
|
abort_unless($actor->hasFunctions(self::REGISTRY_READERS), 403);
|
|
}
|
|
$canLink = $request !== null && $request->status === 'draft' && $request->requester_id === $actor->id
|
|
&& app(OrganizationAccess::class)->canRequest($actor) && ! app(ConflictGuard::class)->participationBlocked($actor, $request);
|
|
$links = $request === null ? collect() : app(SupplyPlanning::class)->latest('op_order_link')->where('data->requisition_id', $request->id)->get();
|
|
$linkedIds = [];
|
|
foreach ($links as $link) {
|
|
$linkedIds[] = $link->data['order_id'];
|
|
}
|
|
$allDepartments = $actor->hasFunctions(['admin', 'procurement']);
|
|
$orders = $request === null ? $this->registryOrders($actor)
|
|
: app(SupplyPlanning::class)->latest('op_order')->where('data->department_id', $request->department_id)
|
|
->when(! $canLink, fn ($q) => $q->whereIn('id', $linkedIds));
|
|
if ($selectedOrderId !== null) {
|
|
(clone $orders)->findOrFail($selectedOrderId);
|
|
$orders->whereKey($selectedOrderId);
|
|
}
|
|
|
|
return ['actorId' => $actor->id, 'tenantId' => $actor->tenant_id, 'policy' => $policy,
|
|
'canConfigure' => $actor->hasFunctions(['admin']), 'allowedTypes' => $this->types($actor, $policy),
|
|
'departments' => Department::query()->when(! $allDepartments, fn ($q) => $q->whereKey($actor->department_id))->orderBy('name')->get(['id', 'name']),
|
|
'orders' => $orders->latest('id')->paginate(15, ['*'], 'page', $selectedOrderId === null ? null : 1)->withQueryString(),
|
|
'selectedOrderId' => $selectedOrderId,
|
|
'requisition' => $request?->only(['id', 'number', 'status']),
|
|
'items' => $request?->items()->get(['id', 'description']) ?? [],
|
|
'links' => $links, 'canLink' => $canLink,
|
|
];
|
|
});
|
|
}
|
|
|
|
/** @param array<string,mixed> $input */
|
|
public function configure(User $actor, array $input): SupplyRecord
|
|
{
|
|
$data = Validator::make($input, ['version' => 'required|integer|min:0', 'mode' => 'required|in:utilisation,procurement',
|
|
'reason' => 'required|string|min:10|max:4000', 'operation_key' => 'required|uuid'])->validate();
|
|
|
|
return DB::transaction(function () use ($actor, $data) {
|
|
$actor = $this->actor($actor);
|
|
abort_unless($actor->hasFunctions(['admin']), 403);
|
|
$retry = $this->retry($actor, 'op_order_policy', $data);
|
|
if ($retry !== null) {
|
|
return $retry;
|
|
}
|
|
$old = $this->policy();
|
|
abort_unless((int) $data['version'] === ($old->version ?? 0), 409);
|
|
|
|
return $this->record($actor, 'op_order_policy', $data, ['mode' => $data['mode']], [], $old);
|
|
});
|
|
}
|
|
|
|
/** @param array<string,mixed> $input */
|
|
public function save(User $actor, array $input): SupplyRecord
|
|
{
|
|
$data = Validator::make($input, ['type' => 'required|in:production,maintenance', 'reference' => 'required|string|min:3|max:120',
|
|
'department_id' => 'required|integer|min:1', 'utilisation_location' => 'required|string|min:3|max:300',
|
|
'description' => 'required|string|min:10|max:4000', 'reason' => 'required|string|min:10|max:4000',
|
|
'policy_version' => 'required|integer|min:1', 'operation_key' => 'required|uuid'])->validate();
|
|
|
|
return DB::transaction(function () use ($actor, $data) {
|
|
$actor = $this->actor($actor);
|
|
$policy = $this->policy();
|
|
abort_unless(in_array($data['type'], $this->types($actor, $policy), true), 403);
|
|
$retry = $this->retry($actor, 'op_order', $data);
|
|
if ($retry !== null) {
|
|
return $retry;
|
|
}
|
|
abort_unless((int) $data['policy_version'] === $policy?->version, 409, 'A origem das ordens mudou. Reveja a configuração.');
|
|
$department = Department::query()->whereKey($data['department_id'])
|
|
->when($policy->data['mode'] === 'utilisation', fn ($q) => $q->whereKey($actor->department_id))->firstOrFail();
|
|
abort_if(SupplyRecord::query()->where('kind', 'op_order')->where('data->type', $data['type'])
|
|
->where('data->department_id', $department->id)->where('data->reference', trim($data['reference']))->exists(), 409, 'Esta referência já está registada neste departamento.');
|
|
|
|
return $this->record($actor, 'op_order', $data, ['type' => $data['type'], 'reference' => trim($data['reference']),
|
|
'department_id' => $department->id, 'utilisation_location' => $data['utilisation_location'], 'description' => $data['description']],
|
|
['policy' => $policy->only(['id', 'version', 'data']), 'author' => $actor->only(['id', 'name']), 'department' => $department->only(['id', 'name'])]);
|
|
});
|
|
}
|
|
|
|
/** @param array<string,mixed> $input */
|
|
public function link(User $actor, Requisition $request, array $input): SupplyRecord
|
|
{
|
|
$data = Validator::make($input, ['item_id' => 'required|integer|min:1', 'order_id' => 'required|integer|min:1',
|
|
'version' => 'required|integer|min:0', 'reason' => 'required|string|min:10|max:4000', 'operation_key' => 'required|uuid'])->validate();
|
|
$data['requisition_id'] = $request->id;
|
|
|
|
return DB::transaction(function () use ($actor, $request, $data) {
|
|
$actor = $this->actor($actor);
|
|
$request = Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($request->id);
|
|
abort_unless($request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor), 403);
|
|
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
|
$retry = $this->retry($actor, 'op_order_link', $data);
|
|
if ($retry !== null) {
|
|
return $retry;
|
|
}
|
|
abort_unless($request->status === 'draft', 409);
|
|
$item = $request->items()->whereKey($data['item_id'])->firstOrFail();
|
|
$order = app(SupplyPlanning::class)->latest('op_order')->whereKey($data['order_id'])->where('data->department_id', $request->department_id)->firstOrFail();
|
|
$old = app(SupplyPlanning::class)->latest('op_order_link')->where('data->requisition_item_id', $item->id)->first();
|
|
abort_unless((int) $data['version'] === ($old->version ?? 0), 409);
|
|
|
|
return $this->record($actor, 'op_order_link', $data, ['requisition_id' => $request->id, 'requisition_item_id' => $item->id, 'order_id' => $order->id],
|
|
['item' => $this->item($item), 'source' => $order->toArray()], $old, $request);
|
|
});
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
private function item(RequisitionItem $item): array
|
|
{
|
|
return $item->only(['id', 'description', 'quantity', 'unit', 'equipment_id', 'spare_part_id', 'category_context']);
|
|
}
|
|
|
|
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 (! $this->ready() || $this->policy() === null) {
|
|
return;
|
|
}
|
|
foreach ($items as $item) {
|
|
$expected = match ($item->category_context['category'] ?? null) {
|
|
'production_input' => 'production', 'spare_part' => 'maintenance', default => null,
|
|
};
|
|
if ($expected !== null && ($frozen[$item->id]['snapshot']['source']['data']['type'] ?? null) !== $expected) {
|
|
throw ValidationException::withMessages(['op_order' => 'Ligue cada insumo de produção ou peça à ordem de produção/manutenção correspondente 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 [];
|
|
}
|
|
$links = app(SupplyPlanning::class)->latest('op_order_link')->whereIn('data->requisition_item_id', $ids)->get();
|
|
if ($links->isEmpty()) {
|
|
return [];
|
|
}
|
|
abort_unless($this->ready() && auth()->id() === $actor->id, 503);
|
|
$result = [];
|
|
foreach ($links as $link) {
|
|
$item = RequisitionItem::query()->whereKey($link->data['requisition_item_id'])->firstOrFail();
|
|
Requisition::query()->visibleTo($actor)->findOrFail($item->requisition_id);
|
|
abort_unless($link->snapshot['item'] === $this->item($item), 409, 'A linha mudou. Reveja a ordem de origem.');
|
|
$result[$item->id] = $link->only(['id', 'version', 'data', 'snapshot', 'reason']);
|
|
}
|
|
ksort($result, SORT_NUMERIC);
|
|
|
|
return $result;
|
|
}
|
|
|
|
/** @param array<string,mixed> $input */
|
|
private function retry(User $actor, string $kind, array $input): ?SupplyRecord
|
|
{
|
|
$record = SupplyRecord::query()->where('operation_key', strtolower($input['operation_key']))->first();
|
|
if ($record !== null) {
|
|
abort_unless($record->kind === $kind && $record->created_by === $actor->id && hash_equals($record->input_hash, $this->hash($input)), 409);
|
|
}
|
|
|
|
return $record;
|
|
}
|
|
|
|
/** @param array<string,mixed> $input */
|
|
private function hash(array $input): string
|
|
{
|
|
$input['operation_key'] = strtolower($input['operation_key']);
|
|
|
|
return hash('sha256', json_encode($input, JSON_THROW_ON_ERROR));
|
|
}
|
|
|
|
/** @param array<string,mixed> $input
|
|
* @param array<string,mixed> $data
|
|
* @param array<string,mixed> $snapshot
|
|
*/
|
|
private function record(User $actor, string $kind, array $input, array $data, array $snapshot, ?SupplyRecord $old = null, ?Requisition $request = null): SupplyRecord
|
|
{
|
|
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => $kind, 'record_key' => $old->record_key ?? (string) Str::uuid(),
|
|
'version' => ($old->version ?? 0) + 1, 'state' => 'recorded', 'data' => $data, 'snapshot' => $snapshot,
|
|
'created_by' => $actor->id, 'created_at' => now(), 'reason' => $input['reason'], 'operation_key' => strtolower($input['operation_key']), 'input_hash' => $this->hash($input)]);
|
|
app(RequisitionWorkflow::class)->audit($actor, $kind.'.recorded', $request, $old?->toArray(), ['record' => $record->toArray()]);
|
|
|
|
return $record;
|
|
}
|
|
}
|