@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\PurchaseOrderItem;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\RequisitionItem;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/** All-or-nothing access to consolidated documents, preserving each native origin. */
|
||||
final class OrderPartsAccess
|
||||
{
|
||||
public static function applies(PurchaseOrder $order): bool
|
||||
{
|
||||
return $order->getAttribute('order_key') !== null || isset($order->snapshot['order_parts']);
|
||||
}
|
||||
|
||||
/** @return list<int> */
|
||||
public function origins(PurchaseOrder $order): array
|
||||
{
|
||||
if (! self::applies($order)) {
|
||||
return [$order->requisition_id];
|
||||
}
|
||||
abort_unless(Schema::hasTable('purchase_order_sources'), 503, 'Preserve as origens da ordem antes de a utilizar.');
|
||||
$ids = DB::table('purchase_order_sources')->where('tenant_id', $order->tenant_id)->where('purchase_order_id', $order->id)
|
||||
->orderBy('requisition_id')->pluck('requisition_id')->all();
|
||||
$expected = array_column($order->snapshot['order_parts']['sources'] ?? [], 'requisition_id');
|
||||
sort($expected, SORT_NUMERIC);
|
||||
abort_unless($ids !== [] && $ids === $expected, 503, 'As origens documentais da ordem estão incompletas.');
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/** Validates every source before a native writer operates on the shared document. */
|
||||
public function assertProcess(User $actor, PurchaseOrder $order, bool $participation = false, bool $receipt = false): void
|
||||
{
|
||||
abort_unless(auth()->id() === $actor->id && $actor->tenant_id === $order->tenant_id, 403);
|
||||
foreach ($this->origins($order) as $id) {
|
||||
$query = Requisition::query()->whereKey($id);
|
||||
if (! $receipt) {
|
||||
$query->visibleTo($actor);
|
||||
} elseif ($actor->departmentScoped()) {
|
||||
$query->where('department_id', $actor->department_id);
|
||||
}
|
||||
$request = $query->firstOrFail();
|
||||
if ($participation) {
|
||||
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
||||
}
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
|
||||
}
|
||||
}
|
||||
|
||||
public function requestForLine(PurchaseOrder $order, PurchaseOrderItem $line): Requisition
|
||||
{
|
||||
abort_unless($line->purchase_order_id === $order->id && $line->tenant_id === $order->tenant_id, 409);
|
||||
$id = RequisitionItem::query()->whereKey($line->requisition_item_id)->value('requisition_id');
|
||||
abort_unless(in_array($id, $this->origins($order), true), 503, 'Linha sem origem documental preservada.');
|
||||
|
||||
return Requisition::query()->whereKey($id)->firstOrFail();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user