@@ -24,7 +24,7 @@ class OperationsCheck extends Command
|
||||
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
} else {
|
||||
$this->line($result['ok'] ? 'Operação: verificações concluídas sem divergências observadas.' : 'Operação: verificações requerem atenção.');
|
||||
$labels = ['replenishment' => 'Reposição', 'receipt_documents' => 'Documentos da recepção'];
|
||||
$labels = ['replenishment' => 'Reposição', 'receipt_documents' => 'Documentos da recepção', 'import_cost_documents' => 'Documentos dos custos de importação'];
|
||||
$states = ['passed' => 'sem divergências observadas', 'attention' => 'requer atenção', 'incomplete' => 'verificação incompleta', 'unavailable' => 'consulta indisponível'];
|
||||
foreach ($result['checks'] as $key => $check) {
|
||||
$this->line($labels[$key].': '.$states[$check['status']].'.');
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use App\Services\ImportLandedCosts;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class ImportLandedCostController extends Controller
|
||||
{
|
||||
private function actor(Request $request): User
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
public function index(Request $request, SupplyRecord $import, ImportLandedCosts $service): Response
|
||||
{
|
||||
return $this->page($request, $import, $service);
|
||||
}
|
||||
|
||||
public function preview(Request $request, SupplyRecord $import, ImportLandedCosts $service): Response
|
||||
{
|
||||
return $this->page($request, $import, $service, $service->preview($this->actor($request), $import, $request->all()));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed>|null $preview */
|
||||
private function page(Request $request, SupplyRecord $import, ImportLandedCosts $service, ?array $preview = null): Response
|
||||
{
|
||||
$search = $request->validate(['invoice_search' => 'nullable|string|max:100'])['invoice_search'] ?? '';
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('supply/import-costs', [...$service->workspace($this->actor($request), $import, $search), 'preview' => $preview])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function document(Request $request, SupplyRecord $import, ImportLandedCosts $service): RedirectResponse
|
||||
{
|
||||
$request->validate(['file' => 'required|file']);
|
||||
$file = $request->file('file');
|
||||
abort_unless($file instanceof UploadedFile, 422);
|
||||
$service->recordDocument($this->actor($request), $import, $request->except('file'), $file);
|
||||
|
||||
return to_route('imports.costs', $import);
|
||||
}
|
||||
|
||||
public function save(Request $request, SupplyRecord $import, ImportLandedCosts $service): RedirectResponse
|
||||
{
|
||||
$service->save($this->actor($request), $import, $request->all());
|
||||
|
||||
return to_route('imports.costs', $import);
|
||||
}
|
||||
|
||||
public function financial(Request $request, SupplyRecord $import, SupplyRecord $plan, ImportLandedCosts $service): RedirectResponse
|
||||
{
|
||||
$service->financial($this->actor($request), $import, $plan, $request->all());
|
||||
|
||||
return to_route('imports.costs', $import);
|
||||
}
|
||||
|
||||
public function evidence(Request $request, SupplyRecord $import, int $document, ImportLandedCosts $service): Response
|
||||
{
|
||||
$source = $service->evidence($this->actor($request), $import, $document);
|
||||
$evidence = $source->snapshot['evidence'];
|
||||
|
||||
return Storage::disk('local')->download($evidence['path'], 'documento-importacao-'.$source->id.'.'.pathinfo($evidence['path'], PATHINFO_EXTENSION),
|
||||
['Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\ImportTariffCodes;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class ImportTariffController extends Controller
|
||||
{
|
||||
public function index(Request $request, Requisition $requisition, ImportTariffCodes $service): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$data = $request->validate(['search' => 'nullable|string|max:100', 'tariff_history_page' => 'nullable|integer|min:1|max:1000000',
|
||||
'stock_page' => 'nullable|integer|min:1|max:1000000', 'masters_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('supply/import-tariffs', $service->workspace($actor, $requisition, $data['search'] ?? ''))->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function store(Request $request, Requisition $requisition, ImportTariffCodes $service): RedirectResponse
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$service->save($actor, $requisition, $request->all());
|
||||
|
||||
return back()->with('success', 'Classificação documental registada.');
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ use App\Models\User;
|
||||
use App\Services\InventoryDispositions;
|
||||
use App\Services\InventoryReversals;
|
||||
use App\Services\InvoiceWorkflow;
|
||||
use App\Services\OrderPartsAccess;
|
||||
use App\Services\OrderPartsInvoices;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\RequisitionBudgetDistributions;
|
||||
use App\Services\SupplierPayables;
|
||||
@@ -36,7 +38,9 @@ class InvoiceController extends Controller
|
||||
'invoices' => Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))->when($focus !== null, fn ($q) => $q->whereKey($focus))->when($focusOrder !== null, fn ($q) => $q->where('purchase_order_id', $focusOrder))->with('items')->latest('id')->paginate(15)->withQueryString()
|
||||
->through(fn (Invoice $invoice) => [...$invoice->toArray(), 'canValidate' => app(InvoiceWorkflow::class)->reviewerEligible($actor, $invoice)]),
|
||||
'orders' => PurchaseOrder::query()->visibleTo($actor)->operational()->with('items')->latest('id')->get()->map(fn ($order) => ['id' => $order->id, 'number' => $order->number, 'currency' => $order->currency, 'supplier' => $order->snapshot['supplier']['name'], 'items' => $order->items,
|
||||
'budgetDistributionOptions' => app(RequisitionBudgetDistributions::class)->options($actor, Requisition::query()->findOrFail($order->requisition_id))]),
|
||||
'orderParts' => OrderPartsAccess::applies($order),
|
||||
'orderPartsBudgetOptions' => OrderPartsAccess::applies($order) ? app(OrderPartsInvoices::class)->options($actor, $order) : null,
|
||||
'budgetDistributionOptions' => OrderPartsAccess::applies($order) ? null : app(RequisitionBudgetDistributions::class)->options($actor, Requisition::query()->findOrFail($order->requisition_id))]),
|
||||
'sgfDispatchAvailable' => config('sgf_invoice.workspace_enabled') === true && $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor),
|
||||
'payablesAvailable' => SupplierPayables::enabled() && app(SupplierPayables::class)->can($actor, 'view'), 'canManage' => $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor)])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
@@ -50,7 +54,9 @@ class InvoiceController extends Controller
|
||||
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Finance]), 403);
|
||||
$decimal = ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'];
|
||||
$data = $request->validate(['number' => 'required|string|max:100', 'issued_on' => 'required|date_format:Y-m-d', 'subtotal' => $decimal, 'tax' => $decimal, 'total' => $decimal, 'items' => 'required|array|min:1|max:50', 'items.*.purchase_order_item_id' => 'required|integer|distinct', 'items.*.quantity' => ['required', 'regex:/^\d{1,9}(\.\d{1,3})?$/'], 'items.*.unit' => 'sometimes|required|string|max:30', 'items.*.unit_price' => ['sometimes', ...$decimal], 'items.*.tax_rate' => ['sometimes', 'required', 'regex:/^\d{1,3}(\.\d{1,2})?$/']]);
|
||||
if (app(RequisitionBudgetDistributions::class)->applies(Requisition::query()->findOrFail($order->requisition_id))) {
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
$data += $request->validate(app(OrderPartsInvoices::class)->rules());
|
||||
} elseif (app(RequisitionBudgetDistributions::class)->applies(Requisition::query()->findOrFail($order->requisition_id))) {
|
||||
$data += $request->validate(app(RequisitionBudgetDistributions::class)->rules(Requisition::query()->findOrFail($order->requisition_id)));
|
||||
}
|
||||
$workflow->register($actor, $order, $data);
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrderItem;
|
||||
use App\Models\Quotation;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\OrderPartsWorkflow;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class OrderPartsController extends Controller
|
||||
{
|
||||
private function actor(Request $request): User
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Procurement])
|
||||
&& ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
abort_unless(app(OrderPartsWorkflow::class)->ready(), 503);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
return $this->page($this->actor($request));
|
||||
}
|
||||
|
||||
public function preview(Request $request, OrderPartsWorkflow $workflow): Response
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
|
||||
return $this->page($actor, $workflow->preview($actor, $request->all()));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed>|null $preview */
|
||||
private function page(User $actor, ?array $preview = null): Response
|
||||
{
|
||||
$candidates = PurchaseAward::query()->where('status', 'approved')
|
||||
->whereIn('requisition_id', Requisition::query()->visibleTo($actor)->select('id'))
|
||||
->whereExists(fn ($lines) => $lines->selectRaw('1')->from('quotation_items as qi')
|
||||
->whereColumn('qi.quotation_id', 'purchase_awards.quotation_id')->whereColumn('qi.tenant_id', 'purchase_awards.tenant_id')
|
||||
->whereRaw('ROUND(qi.quantity * 1000) > (select COALESCE(SUM(ROUND(oi.quantity * 1000)), 0) from purchase_order_items oi where oi.requisition_item_id = qi.requisition_item_id and oi.tenant_id = qi.tenant_id)'))
|
||||
->latest('id')->paginate(20)
|
||||
->through(function (PurchaseAward $award): array {
|
||||
$quote = Quotation::query()->with(['items', 'supplier'])->whereKey($award->quotation_id)->firstOrFail();
|
||||
$request = Requisition::query()->whereKey($award->requisition_id)->firstOrFail();
|
||||
$items = [];
|
||||
foreach ($quote->items as $line) {
|
||||
$before = 0;
|
||||
foreach (PurchaseOrderItem::query()->where('requisition_item_id', $line->requisition_item_id)->get(['quantity']) as $old) {
|
||||
$before += ReceiptWorkflow::milli($old->quantity);
|
||||
}
|
||||
$remaining = max(0, ReceiptWorkflow::milli($line->quantity) - $before);
|
||||
$items[] = ['id' => $line->id, 'description' => $line->description, 'remaining' => (string) BigDecimal::of($remaining)->dividedBy(1000, 3)];
|
||||
}
|
||||
|
||||
return ['id' => $award->id, 'requisition_id' => $request->id, 'number' => $request->number,
|
||||
'supplier' => $quote->supplier?->name, 'currency' => $quote->currency, 'items' => $items];
|
||||
});
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return Inertia::render('purchases/parts', ['candidates' => $candidates, 'preview' => $preview]);
|
||||
}
|
||||
|
||||
public function issue(Request $request, OrderPartsWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$order = $workflow->issue($this->actor($request), $request->all());
|
||||
|
||||
return to_route('orders.show', $order);
|
||||
}
|
||||
|
||||
public function adopt(Request $request, PurchaseAward $award, OrderPartsWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['operation_key' => 'required|uuid']);
|
||||
$workflow->adopt($this->actor($request), $award, $data['operation_key']);
|
||||
|
||||
return to_route('orders.parts');
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ use App\Models\User;
|
||||
use App\Services\AgreementOrderLimits;
|
||||
use App\Services\FormalRecommendation;
|
||||
use App\Services\OrderCancellationWorkflow;
|
||||
use App\Services\OrderPartsAccess;
|
||||
use App\Services\OrderPartsWorkflow;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\ProposalComparison;
|
||||
use App\Services\PurchaseWorkflow;
|
||||
@@ -158,6 +160,7 @@ class PurchaseController extends Controller
|
||||
$actor = $this->access($request);
|
||||
|
||||
return Inertia::render('purchases/index', [
|
||||
'partsAvailable' => $actor->hasFunctions([PurchasingRole::Procurement]) && app(OrderPartsWorkflow::class)->ready(),
|
||||
'orders' => PurchaseOrder::query()->visibleTo($actor)->latest('id')->paginate(15),
|
||||
'awards' => PurchaseAward::query()->whereIn('requisition_id', Requisition::query()->visibleTo($actor)->select('id'))->latest()->paginate(15, ['*'], 'awards_page'),
|
||||
]);
|
||||
@@ -167,14 +170,16 @@ class PurchaseController extends Controller
|
||||
{
|
||||
$actor = $this->access($request);
|
||||
PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id);
|
||||
$origins = app(OrderPartsAccess::class)->origins($order);
|
||||
|
||||
return Inertia::render('purchases/show', [
|
||||
'snapshotComplete' => $order->hasCompleteDocumentSnapshot(),
|
||||
'order' => $order->load('items'),
|
||||
'orderPartsSources' => $order->snapshot['order_parts']['frames'] ?? [],
|
||||
'orderCancellation' => ['enabled' => (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
|
||||
'state' => app(OrderCancellationWorkflow::class)->state($order),
|
||||
'canRequest' => app(OrderCancellationWorkflow::class)->canRequest($actor, $order)],
|
||||
'history' => AuditLog::query()->where('requisition_id', $order->requisition_id)->whereIn('action', ['award.created', 'award.approved', 'award.rejected', 'purchase_order.issued'])->orderBy('id')->get(['id', 'user_id', 'action', 'created_at']),
|
||||
'history' => AuditLog::query()->whereIn('requisition_id', $origins)->whereIn('action', ['award.created', 'award.approved', 'award.rejected', 'purchase_order.issued'])->orderBy('id')->get(['id', 'requisition_id', 'user_id', 'action', 'created_at']),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -182,6 +187,7 @@ class PurchaseController extends Controller
|
||||
{
|
||||
$actor = $this->access($request);
|
||||
PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id);
|
||||
app(OrderPartsAccess::class)->origins($order);
|
||||
|
||||
return view('purchases.print', ['order' => $order->load('items'), 'snapshot' => $order->snapshot,
|
||||
'snapshotComplete' => $order->hasCompleteDocumentSnapshot(),
|
||||
|
||||
@@ -16,6 +16,7 @@ use App\Services\ApprovalRouting;
|
||||
use App\Services\ComparisonPolicy;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\EquipmentWorkflow;
|
||||
use App\Services\ImportTariffCodes;
|
||||
use App\Services\InternalSupplyTrace;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\RequisitionAuditTrail;
|
||||
@@ -121,6 +122,7 @@ class RequisitionController extends Controller
|
||||
'automaticSource' => app(InternalSupplyTrace::class)->purchaseOrigin($this->actor($request), $requisition),
|
||||
'comparisonPolicy' => app(ComparisonPolicy::class)->forRequest($requisition),
|
||||
'canEdit' => app(OrganizationAccess::class)->canRequest($this->actor($request)) && $requisition->requester_id === $this->actor($request)->id && $requisition->status === 'draft',
|
||||
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
|
||||
'canDecide' => $requisition->canDecide($this->actor($request)),
|
||||
'canPrepareDistributions' => app(RequisitionBudgetDistributions::class)->ready() && $requisition->status === 'draft'
|
||||
&& $requisition->requester_id === $this->actor($request)->id && app(OrganizationAccess::class)->canRequest($this->actor($request)),
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\CostCenter;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\PurchaseOrderItem;
|
||||
@@ -14,6 +15,7 @@ use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\AgreementOrderLimits;
|
||||
use App\Services\ImportLandedCosts;
|
||||
use App\Services\InventoryReversals;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
@@ -109,6 +111,7 @@ class SupplyPlanningController extends Controller
|
||||
'contracts' => $ready && $prepare && $kind === 'agreement' && app(AgreementOrderLimits::class)->ready()
|
||||
? $this->approvedOptions($planning, 'contract', $records->pluck('data.contract_key')->push($contractFilters['selected_contract_key'] ?? null), ['agreement_search' => $contractFilters['contract_search'] ?? ''])->map(fn ($r) => $r->only(['record_key', 'version', 'data', 'snapshot'])) : [],
|
||||
'orderLimitsReady' => app(AgreementOrderLimits::class)->ready(),
|
||||
'importCostsReady' => $import && $actor->hasFunctions([PurchasingRole::Finance]) && app(ImportLandedCosts::class)->ready(),
|
||||
'linkedAgreementKey' => $kind === 'policy' ? $request->query('linked_agreement_key') : null,
|
||||
'linkedContractKey' => $kind === 'agreement' ? $request->query('linked_contract_key') : null,
|
||||
'agreementSearch' => $agreementFilters['agreement_search'] ?? '', 'agreementFormKey' => $agreementFilters['agreement_form_key'] ?? null,
|
||||
|
||||
@@ -51,6 +51,22 @@ class PurchaseOrder extends Model
|
||||
public function scopeVisibleTo(Builder $query, User $user): void
|
||||
{
|
||||
$query->whereIn('requisition_id', Requisition::query()->visibleTo($user)->select('id'));
|
||||
if (Schema::hasColumn('purchase_orders', 'order_key')) {
|
||||
if (! Schema::hasTable('purchase_order_sources')) {
|
||||
$query->whereNull('order_key');
|
||||
} else {
|
||||
$query->where(function ($orders) use ($user) {
|
||||
$orders->whereNull('order_key')->orWhere(function ($parts) use ($user) {
|
||||
$parts->whereExists(fn ($sources) => $sources->selectRaw('1')->from('purchase_order_sources as os')
|
||||
->whereColumn('os.purchase_order_id', 'purchase_orders.id')->whereColumn('os.tenant_id', 'purchase_orders.tenant_id'))
|
||||
->whereRaw('(select count(*) from purchase_order_sources os where os.purchase_order_id = purchase_orders.id and os.tenant_id = purchase_orders.tenant_id) = purchase_orders.order_source_count')
|
||||
->whereNotExists(fn ($sources) => $sources->selectRaw('1')->from('purchase_order_sources as os')
|
||||
->whereColumn('os.purchase_order_id', 'purchase_orders.id')->whereColumn('os.tenant_id', 'purchase_orders.tenant_id')
|
||||
->whereNotIn('os.requisition_id', Requisition::query()->visibleTo($user)->select('id')));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param Builder<PurchaseOrder> $query */
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Models\GoodsReceipt;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\OrderPartsAccess;
|
||||
|
||||
class GoodsReceiptPolicy
|
||||
{
|
||||
@@ -17,6 +18,16 @@ class GoodsReceiptPolicy
|
||||
|
||||
public function viewOrder(User $user, PurchaseOrder $order): bool
|
||||
{
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
if (! $this->viewAny($user) || $user->tenant_id !== $order->tenant_id) {
|
||||
return false;
|
||||
}
|
||||
$origins = app(OrderPartsAccess::class)->origins($order);
|
||||
|
||||
return Requisition::query()->whereIn('id', $origins)->count() === count($origins)
|
||||
&& (! $user->departmentScoped() || ! Requisition::query()->whereIn('id', $origins)->where('department_id', '!=', $user->department_id)->exists());
|
||||
}
|
||||
|
||||
return $this->viewAny($user) && $user->tenant_id === $order->tenant_id &&
|
||||
(! $user->departmentScoped() || Requisition::query()->whereKey($order->requisition_id)->where('department_id', $user->department_id)->exists());
|
||||
}
|
||||
@@ -30,6 +41,7 @@ class GoodsReceiptPolicy
|
||||
|
||||
public function create(User $user, PurchaseOrder $order): bool
|
||||
{
|
||||
return $user->tenant_id === $order->tenant_id && $user->hasFunctions([PurchasingRole::Warehouse]) && $user->id !== $order->issued_by;
|
||||
return $user->tenant_id === $order->tenant_id && $user->hasFunctions([PurchasingRole::Warehouse]) && $user->id !== $order->issued_by
|
||||
&& (! OrderPartsAccess::applies($order) || $this->viewOrder($user, $order));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,9 +109,10 @@ final class AgreementOrderLimits
|
||||
|
||||
/** @param list<array<string,mixed>> $lines
|
||||
* @param list<array<string,mixed>> $bindings
|
||||
* @param list<Requisition> $additionalRequests
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function freeze(User $actor, Quotation $quote, Requisition $request, array $lines, array $bindings): array
|
||||
public function freeze(User $actor, Quotation $quote, Requisition $request, array $lines, array $bindings, array $additionalRequests = []): array
|
||||
{
|
||||
if ($bindings === []) {
|
||||
return [];
|
||||
@@ -120,6 +121,11 @@ final class AgreementOrderLimits
|
||||
abort_unless($this->canRead($actor), 403);
|
||||
$bindings = $this->canonical($bindings);
|
||||
$sources = $request->items()->get()->keyBy('id');
|
||||
foreach ($additionalRequests as $additional) {
|
||||
abort_unless($additional->tenant_id === $actor->tenant_id
|
||||
&& Requisition::query()->visibleTo($actor)->whereKey($additional->id)->exists(), 403);
|
||||
$sources = $sources->concat($additional->items()->get())->keyBy('id');
|
||||
}
|
||||
$frozen = [];
|
||||
$groups = [];
|
||||
foreach ($bindings as $binding) {
|
||||
|
||||
@@ -19,10 +19,21 @@ final class CommonBudget
|
||||
|
||||
public const ORDER_PARTS_CONTRACT = 'COMMON-BUDGET-ORDER-PARTS-QA-v1';
|
||||
|
||||
public const LANDED_COSTS_CONTRACT = 'COMMON-BUDGET-LANDED-COST-QA-v2';
|
||||
|
||||
public function for(User $user): BudgetControl
|
||||
{
|
||||
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null, 403);
|
||||
$runtime = new \ReflectionClass(BudgetControl::class);
|
||||
$landedTables = ['budget_landed_commands', 'budget_landed_entries'];
|
||||
$landedPresent = array_values(array_filter($landedTables, fn ($table) => Schema::hasTable($table)));
|
||||
abort_if(count($landedPresent) !== 0 && count($landedPresent) !== count($landedTables), 503, 'Estrutura de aterragem incompleta; saldo não presumido.');
|
||||
if (! $runtime->hasConstant('LANDED_COSTS_VERSION') || $runtime->getConstant('LANDED_COSTS_VERSION') !== self::LANDED_COSTS_CONTRACT
|
||||
|| ! $runtime->hasMethod('reserveLandedCosts') || ! $runtime->hasMethod('transitionLandedCosts')) {
|
||||
foreach ($landedPresent as $table) {
|
||||
abort_if(DB::table($table)->where('tenant_id', $user->tenant_id)->exists(), 503, 'Existem efeitos de aterragem; preserve o motor compatível antes de consultar saldos.');
|
||||
}
|
||||
}
|
||||
$orderTables = ['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions'];
|
||||
$orderPresent = array_values(array_filter($orderTables, fn ($table) => Schema::hasTable($table)));
|
||||
abort_if(count($orderPresent) !== 0 && count($orderPresent) !== count($orderTables), 503,
|
||||
@@ -53,8 +64,8 @@ final class CommonBudget
|
||||
abort_unless(DB::table('tenants')->where('id', $user->tenant_id)->value('currency') === 'MZN', 422, 'Moeda da organização incompatível com esta entrega.');
|
||||
$roles = in_array($action, ['create', 'approve', 'reinforcement.propose', 'reinforcement.review', 'view'], true)
|
||||
? [PurchasingRole::Admin, PurchasingRole::Finance]
|
||||
: (in_array($action, ['consume', 'consume.preview', 'distribution.amend'], true) ? [PurchasingRole::Finance]
|
||||
: (in_array($action, ['orders.commit', 'orders.cancel', 'orders.adopt'], true) ? [PurchasingRole::Procurement] : null));
|
||||
: (in_array($action, ['consume', 'consume.preview', 'distribution.amend', 'orders.cancel', 'landed.reserve', 'landed.commit', 'landed.consume', 'landed.cancel', 'landed.amend'], true) ? [PurchasingRole::Finance]
|
||||
: (in_array($action, ['orders.commit', 'orders.adopt'], true) ? [PurchasingRole::Procurement] : null));
|
||||
app(CurrentActor::class)->lock($user, $roles);
|
||||
},
|
||||
function (string $action, array $data, ?int $origin) use ($user): void {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use LogicException;
|
||||
|
||||
/** Aggregate, bounded technical inspection; never repairs, discloses or removes evidence. */
|
||||
final class ImportCostDocumentHealth
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
public function inspect(int $limit = 1000): array
|
||||
{
|
||||
abort_unless(app()->runningInConsole() && ! auth()->check() && ! request()->hasSession(), 403);
|
||||
if ($limit < 1 || $limit > 10000) {
|
||||
throw new LogicException('Limite fora do intervalo permitido.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($limit): array {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
$result = ['checked_at' => now()->toIso8601String(), 'ok' => false, 'complete' => false,
|
||||
'documents_checked' => 0, 'files_checked' => 0, 'missing' => 0, 'altered' => 0,
|
||||
'invalid_reference' => 0, 'unreferenced' => 0, 'reasons' => []];
|
||||
$disk = Storage::disk('local');
|
||||
$records = DB::table('supply_records')->where('kind', 'import_cost_doc')->orderBy('id')->limit($limit + 1)->get();
|
||||
$limited = $records->count() > $limit;
|
||||
$root = realpath($disk->path(''));
|
||||
foreach ($records->take($limit) as $record) {
|
||||
$result['documents_checked']++;
|
||||
$snapshot = json_decode($record->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$evidence = $snapshot['evidence'] ?? [];
|
||||
$prefix = 'import-costs/'.$record->tenant_id.'/'.$record->purchase_order_id.'/';
|
||||
$path = $evidence['path'] ?? null;
|
||||
if (($evidence['disk'] ?? null) !== 'local' || ! is_string($path)
|
||||
|| ! preg_match('/^[a-f0-9-]{36}$/D', $record->record_key)
|
||||
|| ! preg_match('/^'.preg_quote($prefix.$record->record_key.'-'.$record->version, '/').'\.(pdf|jpg|jpeg|png)$/D', $path)
|
||||
|| ! is_int($evidence['size'] ?? null) || $evidence['size'] < 1 || $evidence['size'] > 2097152
|
||||
|| ! is_string($evidence['sha256'] ?? null) || ! preg_match('/^[a-f0-9]{64}$/D', $evidence['sha256'])
|
||||
|| ! DB::table('purchase_orders')->where('tenant_id', $record->tenant_id)->where('id', $record->purchase_order_id)->exists()) {
|
||||
$result['invalid_reference']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
$resolved = realpath($disk->path($path));
|
||||
if ($resolved === false || ! is_file($resolved)) {
|
||||
$result['missing']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
$absolute = str_replace('\\', '/', $resolved);
|
||||
$boundary = $root === false ? null : str_replace('\\', '/', $root).'/import-costs/';
|
||||
if ($boundary === null || ! (PHP_OS_FAMILY === 'Windows'
|
||||
? str_starts_with(strtolower($absolute), strtolower($boundary)) : str_starts_with($absolute, $boundary))) {
|
||||
$result['invalid_reference']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
if (filesize($resolved) !== $evidence['size']) {
|
||||
$result['altered']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
$checksum = hash_file('sha256', $resolved);
|
||||
if (! is_string($checksum) || ! hash_equals($evidence['sha256'], $checksum)) {
|
||||
$result['altered']++;
|
||||
}
|
||||
}
|
||||
foreach ($disk->getDriver()->listContents('import-costs', true) as $entry) {
|
||||
if (! $entry->isFile()) {
|
||||
continue;
|
||||
}
|
||||
if ($result['files_checked'] >= $limit) {
|
||||
$limited = true;
|
||||
break;
|
||||
}
|
||||
$result['files_checked']++;
|
||||
if (! DB::table('supply_records')->where('kind', 'import_cost_doc')->where('snapshot->evidence->path', $entry->path())->exists()) {
|
||||
$result['unreferenced']++;
|
||||
}
|
||||
}
|
||||
foreach (['missing', 'altered', 'invalid_reference', 'unreferenced'] as $reason) {
|
||||
if ($result[$reason] > 0) {
|
||||
$result['reasons'][] = $reason;
|
||||
}
|
||||
}
|
||||
if ($limited) {
|
||||
$result['reasons'][] = 'limit_reached';
|
||||
}
|
||||
$result['complete'] = ! $limited;
|
||||
$result['ok'] = $result['reasons'] === [];
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Tempo\Finance\Budget\BudgetControl;
|
||||
use Tempo\Finance\Budget\BudgetLandedCostPlan;
|
||||
|
||||
/** Versioned documentary cost preparation. Financial effects remain in the common writer. */
|
||||
final class ImportLandedCosts
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
|
||||
|
||||
return config('import-landed-costs.qa_enabled') === true && app()->environment('testing') && $isolated
|
||||
&& class_exists(BudgetLandedCostPlan::class);
|
||||
}
|
||||
|
||||
public function financialReady(): bool
|
||||
{
|
||||
$runtime = new \ReflectionClass(BudgetControl::class);
|
||||
|
||||
return $this->ready() && Schema::hasTable('budget_landed_commands') && Schema::hasTable('budget_landed_entries')
|
||||
&& Schema::hasColumn('budget_landed_entries', 'source_snapshot')
|
||||
&& $runtime->hasConstant('LANDED_COSTS_VERSION') && $runtime->getConstant('LANDED_COSTS_VERSION') === CommonBudget::LANDED_COSTS_CONTRACT
|
||||
&& $runtime->hasMethod('reserveLandedCosts') && $runtime->hasMethod('transitionLandedCosts') && $runtime->hasMethod('amendLandedCosts');
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, SupplyRecord $import, string $search = ''): array
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
|
||||
return DB::transaction(function () use ($actor, $import, $search): array {
|
||||
[$actor, $current, $order] = $this->context($actor, $import);
|
||||
$invoices = Invoice::query()->where('status', 'validated')->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))
|
||||
->when($search !== '', fn ($query) => $query->where('number', 'like', '%'.addcslashes($search, '%_\\').'%'))
|
||||
->latest('id')->paginate(20, ['id', 'number', 'supplier_id', 'purchase_order_id', 'subtotal_minor', 'tax_minor', 'total_minor'], 'invoices_page')->withQueryString();
|
||||
$invoices->through(fn (Invoice $invoice) => [...$invoice->only(['id', 'number', 'purchase_order_id', 'total_minor']),
|
||||
'currency' => PurchaseOrder::query()->whereKey($invoice->purchase_order_id)->value('currency')]);
|
||||
$documents = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)
|
||||
->whereIn('id', SupplyRecord::query()->selectRaw('MAX(id)')->where('kind', 'import_cost_doc')->groupBy('record_key'))->latest('id')
|
||||
->paginate(20, ['id', 'record_key', 'version', 'data', 'created_at'], 'documents_page')->withQueryString();
|
||||
$budgets = DB::table('budgets')->where('tenant_id', $actor->tenant_id)->whereNotNull('approved_by')->where('year', now()->year)
|
||||
->orderBy('id')->paginate(20, ['id', 'cost_center_id', 'kind', 'includes_tax'], 'budgets_page')->withQueryString();
|
||||
$history = SupplyRecord::query()->where('kind', 'import_cost_plan')->where('purchase_order_id', $order->id)->latest('version')
|
||||
->paginate(10, ['id', 'record_key', 'version', 'state', 'reason', 'created_by', 'created_at', 'data', 'snapshot'], 'history_page')->withQueryString();
|
||||
$latest = SupplyRecord::query()->where('kind', 'import_cost_plan')->where('purchase_order_id', $order->id)->latest('version')->first();
|
||||
$financialEvents = SupplyRecord::query()->where('kind', 'import_cost_event')->where('purchase_order_id', $order->id)->latest('version')
|
||||
->paginate(10, ['id', 'version', 'state', 'reason', 'created_by', 'created_at', 'data', 'snapshot'], 'financial_events_page')->withQueryString();
|
||||
$financial = null;
|
||||
if ($latest !== null && $this->financialReady()) {
|
||||
$engine = app(CommonBudget::class)->for($actor);
|
||||
$state = app(CommonBudget::class)->execute(fn () => (new \ReflectionMethod($engine, 'landedCostState'))->invoke($engine, $latest->record_key));
|
||||
$financial = is_array($state) ? $state['result'] : null;
|
||||
if ($financial !== null) {
|
||||
$financial['native_plan_id'] = SupplyRecord::query()->where('kind', 'import_cost_plan')->where('record_key', $latest->record_key)
|
||||
->where('version', $financial['version'])->where('state', 'approved')->value('id');
|
||||
foreach ($financial['origins'] as &$origin) {
|
||||
$source = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)->whereKey($origin['id'])->firstOrFail();
|
||||
abort_unless($source->version === $origin['source_version'], 503, 'Preserve a versão documental associada ao efeito financeiro.');
|
||||
$origin['reference'] = $source->data['reference'];
|
||||
$origin['evidence_url'] = '/compras/importacoes/'.$current->id.'/custos/documentos/'.$source->id;
|
||||
}
|
||||
unset($origin);
|
||||
}
|
||||
}
|
||||
|
||||
return ['importRecord' => ['id' => $current->id, 'record_key' => $current->record_key, 'version' => $current->version,
|
||||
'order_id' => $order->id, 'order_number' => $order->number, 'context' => array_intersect_key($current->data, array_flip(['purpose', 'jurisdiction', 'origin_country', 'dispatch_country', 'incoterm', 'regime'])),
|
||||
'context_changed' => $latest !== null && $this->preparationImportRevision($latest->snapshot['plan']) !== $this->importRevision($current)],
|
||||
'importTariffs' => $order->snapshot['import_tariffs'] ?? [],
|
||||
'invoices' => $invoices, 'documents' => $documents, 'budgets' => $budgets,
|
||||
'history' => $history, 'latest' => $latest, 'financialReady' => $this->financialReady(), 'financialState' => $financial, 'financialEvents' => $financialEvents,
|
||||
'orderItems' => $order->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity']),
|
||||
'invoiceSearch' => $search, 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
|
||||
public function evidence(User $actor, SupplyRecord $import, int $documentId): SupplyRecord
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
|
||||
return DB::transaction(function () use ($actor, $import, $documentId): SupplyRecord {
|
||||
[, $current, $order] = $this->context($actor, $import);
|
||||
$document = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)->findOrFail($documentId);
|
||||
abort_unless($document->snapshot['import_key'] === $current->record_key, 404);
|
||||
$evidence = $document->snapshot['evidence'];
|
||||
abort_unless(Storage::disk('local')->exists($evidence['path']) && hash_equals($evidence['sha256'], hash('sha256', Storage::disk('local')->get($evidence['path']))), 409, 'A evidência documental está indisponível ou alterada.');
|
||||
|
||||
return $document;
|
||||
});
|
||||
}
|
||||
|
||||
/** Native documentary source, not a supplier invoice or a payable.
|
||||
* @param array<string,mixed> $input
|
||||
*/
|
||||
public function recordDocument(User $actor, SupplyRecord $import, array $input, UploadedFile $file): SupplyRecord
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
$data = Validator::make(['record_key' => null, 'version' => 0, ...$input, 'file' => $file], [
|
||||
'operation_key' => 'required|uuid', 'kind' => 'required|in:customs_assessment,other_charge',
|
||||
'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0',
|
||||
'reference' => 'required|string|min:3|max:180', 'issued_on' => 'required|date_format:Y-m-d|before_or_equal:today',
|
||||
'creditor_reference' => 'required|string|min:3|max:180', 'currency' => 'required|regex:/^[A-Z]{3}$/D',
|
||||
'subtotal_minor' => 'required|integer|min:0|max:100000000000000', 'tax_minor' => 'required|integer|min:0|max:100000000000000',
|
||||
'total_minor' => 'required|integer|min:0|max:100000000000000', 'exchange_basis' => 'present|nullable|array:rate,quoted_on,source',
|
||||
'exchange_basis.rate' => ['required_unless:currency,MZN', 'regex:/^\d{1,8}(?:\.\d{1,10})?$/D'],
|
||||
'exchange_basis.quoted_on' => 'required_unless:currency,MZN|date_format:Y-m-d|before_or_equal:today',
|
||||
'exchange_basis.source' => 'required_unless:currency,MZN|string|min:3|max:1000',
|
||||
'reason' => 'required|string|min:10|max:4000', 'file' => 'required|file|mimes:pdf,jpg,jpeg,png|extensions:pdf,jpg,jpeg,png|max:2048',
|
||||
])->validate();
|
||||
unset($data['file']);
|
||||
// Multipart form fields arrive as strings; normalise only validated exact cent integers.
|
||||
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
|
||||
abort_unless(is_int($data[$field]) || (is_string($data[$field]) && preg_match('/^\d{1,15}$/D', $data[$field])), 422, 'Indique centavos inteiros, sem arredondamentos.');
|
||||
$data[$field] = (int) $data[$field];
|
||||
}
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$sha = hash_file('sha256', $file->getPathname());
|
||||
abort_unless(is_string($sha) && $file->getSize() > 0, 422);
|
||||
$hash = hash('sha256', json_encode([$import->record_key, $data, $sha], JSON_THROW_ON_ERROR));
|
||||
$newPath = null;
|
||||
try {
|
||||
return DB::transaction(function () use ($actor, $import, $data, $file, $sha, $hash, &$newPath): SupplyRecord {
|
||||
[$actor, $current, $order] = $this->context($actor, $import);
|
||||
$old = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($old !== null) {
|
||||
abort_unless($old->kind === 'import_cost_doc' && $old->created_by === $actor->id && hash_equals($old->input_hash, $hash), 409);
|
||||
|
||||
return $old;
|
||||
}
|
||||
$previous = $data['record_key'] === null ? null : SupplyRecord::query()->where('kind', 'import_cost_doc')
|
||||
->where('record_key', $data['record_key'])->latest('version')->lockForUpdate()->firstOrFail();
|
||||
abort_unless((int) $data['version'] === ($previous->version ?? 0), 409, 'O documento mudou. Consulte a versão actual antes de corrigir.');
|
||||
if ($previous !== null) {
|
||||
abort_unless($previous->purchase_order_id === $order->id && $previous->snapshot['import_key'] === $current->record_key && $previous->data['kind'] === $data['kind'], 409, 'A correcção deve conservar a origem e o tipo documental.');
|
||||
abort_unless($previous->data['currency'] === $data['currency'] && $previous->data['exchange_basis'] === $data['exchange_basis'], 409, 'A correcção conserva a moeda e a taxa de Finanças já congeladas nesta origem.');
|
||||
}
|
||||
abort_if(SupplyRecord::query()->where('kind', 'import_cost_doc')
|
||||
->when($previous !== null, fn ($query) => $query->where('record_key', '!=', $previous->record_key))
|
||||
->where('data->kind', $data['kind'])->where('data->creditor_reference', $data['creditor_reference'])
|
||||
->where('data->reference', $data['reference'])->exists(), 409, 'A origem documental já foi registada. Preserve a referência existente.');
|
||||
$reference = $this->reference($data);
|
||||
$recordKey = $previous->record_key ?? (string) Str::uuid();
|
||||
$version = ($previous->version ?? 0) + 1;
|
||||
$newPath = $file->storeAs('import-costs/'.$actor->tenant_id.'/'.$order->id, $recordKey.'-'.$version.'.'.$file->extension(), 'local');
|
||||
abort_unless(is_string($newPath), 503, 'Não foi possível conservar o documento privado.');
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_cost_doc', 'record_key' => $recordKey,
|
||||
'version' => $version, 'state' => 'recorded', 'purchase_order_id' => $order->id, 'created_by' => $actor->id,
|
||||
'data' => array_diff_key($data, array_flip(['operation_key', 'reason', 'record_key', 'version'])),
|
||||
'snapshot' => ['import_key' => $current->record_key, 'import_version' => $current->version, 'reference_amounts' => $reference,
|
||||
'exchange_basis_recorded_by' => $previous->snapshot['exchange_basis_recorded_by'] ?? $actor->id,
|
||||
'supersedes' => $previous->id ?? null, 'contributors' => array_values(array_unique([...($previous?->snapshot['contributors'] ?? []), $actor->id])),
|
||||
'evidence' => ['disk' => 'local', 'path' => $newPath, 'sha256' => $sha, 'size' => $file->getSize(), 'mime_type' => $file->getMimeType()],
|
||||
'financial_effects' => false, 'legal_rate_verified' => false],
|
||||
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'import.cost_document_recorded', Requisition::query()->findOrFail($order->requisition_id), null,
|
||||
['record_id' => $record->id, 'import_key' => $current->record_key, 'sha256' => $sha, 'financial_effects' => false]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
} catch (\Throwable $error) {
|
||||
if (is_string($newPath) && ! SupplyRecord::query()->where('kind', 'import_cost_doc')->where('snapshot->evidence->path', $newPath)->exists()) {
|
||||
Storage::disk('local')->delete($newPath);
|
||||
}
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function preview(User $actor, SupplyRecord $import, array $input): array
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
$data = Validator::make($input, ['documents' => 'required|array|min:1|max:100', 'documents.*' => 'required|array:origin,kind,id',
|
||||
'documents.*.origin' => 'required|string|regex:/^[A-Za-z0-9:_-]{1,120}$/D|distinct',
|
||||
'documents.*.kind' => 'required|in:supplier_invoice,carrier_invoice,insurer_invoice,customs_assessment,other_charge',
|
||||
'documents.*.id' => 'required|integer|min:1', 'components' => 'required|array|min:1|max:500', 'budget_id' => 'required|integer|min:1',
|
||||
'item_references' => 'sometimes|array|list|max:500',
|
||||
'item_references.*' => 'required|array:component_key,purchase_order_item_ids',
|
||||
'item_references.*.component_key' => 'required|string|max:120|distinct',
|
||||
'item_references.*.purchase_order_item_ids' => 'required|array|list|min:1|max:100',
|
||||
'item_references.*.purchase_order_item_ids.*' => 'required|integer|min:1'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $import, $data): array {
|
||||
[$actor, $current, $order] = $this->context($actor, $import);
|
||||
$budget = DB::table('budgets')->where('tenant_id', $actor->tenant_id)->where('id', $data['budget_id'])->lockForUpdate()->first();
|
||||
abort_unless($budget !== null && $budget->approved_by !== null && (int) $budget->year === (int) now()->year, 422, 'Seleccione uma dotação aprovada do exercício.');
|
||||
$documents = $details = [];
|
||||
foreach ($data['documents'] as $selection) {
|
||||
if (in_array($selection['kind'], ['supplier_invoice', 'carrier_invoice', 'insurer_invoice'], true)) {
|
||||
$invoice = Invoice::query()->whereKey($selection['id'])->lockForUpdate()->firstOrFail();
|
||||
abort_unless($invoice->status === 'validated', 409, 'A factura de origem ainda não foi validada.');
|
||||
$sourceOrder = PurchaseOrder::query()->visibleTo($actor)->findOrFail($invoice->purchase_order_id);
|
||||
app(OrderPartsAccess::class)->assertProcess($actor, $sourceOrder);
|
||||
abort_if($selection['kind'] === 'supplier_invoice' && $sourceOrder->id !== $order->id, 422, 'A mercadoria deve pertencer à ordem da importação.');
|
||||
$native = ['currency' => $sourceOrder->currency, 'subtotal_minor' => $invoice->subtotal_minor, 'tax_minor' => $invoice->tax_minor,
|
||||
'total_minor' => $invoice->total_minor, 'exchange_basis' => $invoice->snapshot['exchange_basis'] ?? null];
|
||||
$reference = $this->reference($native);
|
||||
$revision = hash('sha256', json_encode($invoice->getAttributes(), JSON_THROW_ON_ERROR));
|
||||
$creditor = 'supplier:'.$invoice->supplier_id;
|
||||
$sourceKey = 'invoice:'.$invoice->id;
|
||||
$sourceVersion = 1;
|
||||
$details[$selection['origin']] = ['reference' => $invoice->number, 'creditor' => $invoice->snapshot['supplier']['name'],
|
||||
'currency' => $native['currency'], 'exchange_basis' => $native['exchange_basis'], 'financial_authority' => 'native_invoice'];
|
||||
} else {
|
||||
$document = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)->whereKey($selection['id'])->firstOrFail();
|
||||
abort_unless($document->data['kind'] === $selection['kind'] && $document->snapshot['import_key'] === $current->record_key, 409);
|
||||
abort_unless(SupplyRecord::query()->where('kind', 'import_cost_doc')->where('record_key', $document->record_key)->latest('version')->value('id') === $document->id, 409, 'O documento foi corrigido. Seleccione a nova versão, preservando a preparação anterior.');
|
||||
$native = $document->data;
|
||||
$reference = $document->snapshot['reference_amounts'];
|
||||
$evidence = $document->snapshot['evidence'];
|
||||
abort_unless(Storage::disk('local')->exists($evidence['path']) && hash_equals($evidence['sha256'], hash('sha256', Storage::disk('local')->get($evidence['path']))), 409, 'A evidência documental está indisponível ou alterada.');
|
||||
$revision = $document->input_hash;
|
||||
$creditor = 'authority:'.hash('sha256', $native['creditor_reference']);
|
||||
$sourceKey = $document->record_key;
|
||||
$sourceVersion = $document->version;
|
||||
$details[$selection['origin']] = ['reference' => $native['reference'], 'creditor' => $native['creditor_reference'],
|
||||
'currency' => $native['currency'], 'exchange_basis' => $native['exchange_basis'], 'financial_authority' => 'documentary_source_only'];
|
||||
}
|
||||
$documents[$selection['origin']] = ['kind' => $selection['kind'], 'id' => (int) $selection['id'], 'creditor_key' => $creditor,
|
||||
'source_key' => $sourceKey, 'source_version' => $sourceVersion,
|
||||
'currency' => $native['currency'], 'revision' => $revision, 'subtotal_minor' => $native['subtotal_minor'], 'tax_minor' => $native['tax_minor'], 'total_minor' => $native['total_minor'],
|
||||
'reference_subtotal_minor' => $reference['subtotal_minor'], 'reference_tax_minor' => $reference['tax_minor'], 'reference_total_minor' => $reference['total_minor']];
|
||||
}
|
||||
$plan = app(CommonBudget::class)->execute(fn () => BudgetLandedCostPlan::reconcile($data['components'], $documents, (bool) $budget->includes_tax));
|
||||
$items = $order->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity'])->keyBy('id');
|
||||
$references = [];
|
||||
foreach ($data['item_references'] ?? [] as $selection) {
|
||||
abort_unless(in_array($selection['component_key'], array_column($plan['components'], 'component_key'), true), 422, 'A referência exige um componente da preparação.');
|
||||
$ids = array_map(intval(...), $selection['purchase_order_item_ids']);
|
||||
abort_unless(count(array_unique($ids)) === count($ids), 422, 'Não repita o mesmo artigo no componente.');
|
||||
sort($ids, SORT_NUMERIC);
|
||||
foreach ($ids as $id) {
|
||||
abort_unless($items->has($id), 422, 'Seleccione apenas artigos da ordem desta importação.');
|
||||
$references[$selection['component_key']][] = $items->get($id)->only(['id', 'description', 'unit', 'quantity']);
|
||||
}
|
||||
}
|
||||
ksort($references);
|
||||
|
||||
return [...$plan, 'budget_id' => $budget->id, 'import_key' => $current->record_key, 'import_version' => $current->version,
|
||||
'import_revision' => $this->importRevision($current),
|
||||
'item_references' => $references,
|
||||
'purchase_order_id' => $order->id, 'document_details' => $details, 'native_principals_preserved' => true];
|
||||
});
|
||||
}
|
||||
|
||||
/** Persist a recoverable preparation; independent review does not execute budget effects.
|
||||
* @param array<string,mixed> $input
|
||||
*/
|
||||
public function save(User $actor, SupplyRecord $import, array $input): SupplyRecord
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
$envelope = Validator::make($input, ['operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid',
|
||||
'version' => 'required|integer|min:0', 'action' => 'required|in:save,approve,return',
|
||||
'reason' => 'required|string|min:10|max:4000', 'data' => 'present|array'])->validate();
|
||||
$envelope['operation_key'] = strtolower($envelope['operation_key']);
|
||||
$hash = hash('sha256', json_encode([$import->record_key, $import->version, $envelope], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $import, $envelope, $hash): SupplyRecord {
|
||||
[$actor, $current, $order] = $this->context($actor, $import);
|
||||
$replay = SupplyRecord::query()->where('operation_key', $envelope['operation_key'])->first();
|
||||
if ($replay !== null) {
|
||||
abort_unless($replay->kind === 'import_cost_plan' && $replay->created_by === $actor->id && hash_equals($replay->input_hash, $hash), 409);
|
||||
|
||||
return $replay;
|
||||
}
|
||||
$old = $envelope['record_key'] === null ? null : SupplyRecord::query()->where('kind', 'import_cost_plan')
|
||||
->where('record_key', $envelope['record_key'])->latest('version')->lockForUpdate()->firstOrFail();
|
||||
abort_unless((int) $envelope['version'] === ($old->version ?? 0), 409, 'A preparação mudou. Conserve os seus valores e consulte a versão actual.');
|
||||
if ($old !== null) {
|
||||
abort_unless($old->purchase_order_id === $order->id && $old->snapshot['import_key'] === $current->record_key, 409);
|
||||
} else {
|
||||
abort_if(SupplyRecord::query()->where('kind', 'import_cost_plan')->where('purchase_order_id', $order->id)->exists(), 409, 'A importação já tem uma preparação. Continue a versão existente.');
|
||||
}
|
||||
$action = $envelope['action'];
|
||||
if ($action === 'save') {
|
||||
$selection = $envelope['data'];
|
||||
$plan = $this->preview($actor, $current, $selection);
|
||||
$contributors = array_values(array_unique([...($old?->snapshot['contributors'] ?? []), $actor->id]));
|
||||
foreach ($selection['documents'] as $document) {
|
||||
if (in_array($document['kind'], ['customs_assessment', 'other_charge'], true)) {
|
||||
$source = SupplyRecord::query()->where('kind', 'import_cost_doc')->whereKey($document['id'])->sole();
|
||||
$contributors = [...$contributors, ...$source->snapshot['contributors']];
|
||||
}
|
||||
}
|
||||
$contributors = array_values(array_unique($contributors));
|
||||
$state = 'draft';
|
||||
} else {
|
||||
abort_unless($old !== null && $old->state === 'draft' && $envelope['data'] === [], 409, 'A conferência exige uma preparação actual sem alterar o seu conteúdo.');
|
||||
$contributors = $old->snapshot['contributors'];
|
||||
abort_if(in_array($actor->id, $contributors, true), 403, 'A conferência exige Finanças independente da preparação e dos documentos adicionais.');
|
||||
$selection = $old->data;
|
||||
$plan = $action === 'return' ? $old->snapshot['plan'] : $this->preview($actor, $current, $selection);
|
||||
abort_unless($action === 'return' || $this->equivalentPreparation($plan, $old->snapshot['plan']), 409, 'As origens ou a dotação mudaram. Devolva e actualize a preparação.');
|
||||
$state = $action === 'approve' ? 'approved' : 'returned';
|
||||
}
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_cost_plan',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||
'state' => $state, 'purchase_order_id' => $order->id, 'created_by' => $actor->id, 'data' => $selection,
|
||||
'snapshot' => ['import_key' => $current->record_key, 'contributors' => $contributors, 'plan' => $plan, 'financial_effects' => false],
|
||||
'reason' => $envelope['reason'], 'operation_key' => $envelope['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'import.cost_plan_'.$action, Requisition::query()->findOrFail($order->requisition_id), null,
|
||||
['record_id' => $record->id, 'record_key' => $record->record_key, 'version' => $record->version, 'state' => $state, 'fingerprint' => $plan['fingerprint'], 'financial_effects' => false]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
/** One native receipt around one common financial command.
|
||||
* @param array<string,mixed> $input
|
||||
*/
|
||||
public function financial(User $actor, SupplyRecord $import, SupplyRecord $plan, array $input): SupplyRecord
|
||||
{
|
||||
abort_unless($this->financialReady(), 503, 'A estrutura financeira adicional só está preparada em QA.');
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'action' => 'required|in:reserve,commit,consume,amend,cancel',
|
||||
'financial_revision' => 'required|integer|min:0', 'sources' => 'sometimes|array|max:100',
|
||||
'sources.*' => 'required|string|max:120|distinct|regex:/^[A-Za-z0-9:_-]+$/D',
|
||||
'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$data['financial_revision'] = (int) $data['financial_revision'];
|
||||
$data['sources'] ??= [];
|
||||
sort($data['sources'], SORT_STRING);
|
||||
$hash = hash('sha256', json_encode([$import->record_key, $plan->id, $data], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $import, $plan, $data, $hash): SupplyRecord {
|
||||
[$actor, $current, $order] = $this->context($actor, $import);
|
||||
$plan = SupplyRecord::query()->where('kind', 'import_cost_plan')->whereKey($plan->id)->lockForUpdate()->firstOrFail();
|
||||
abort_unless($plan->purchase_order_id === $order->id && $plan->snapshot['import_key'] === $current->record_key, 404);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'import_cost_event' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
abort_unless($plan->state === 'approved', 409, 'A aplicação financeira exige conferência independente da preparação.');
|
||||
if ($data['action'] !== 'cancel') {
|
||||
abort_unless(SupplyRecord::query()->where('kind', 'import_cost_plan')->where('record_key', $plan->record_key)->latest('version')->value('id') === $plan->id, 409, 'Existe uma nova preparação; conclua a sua revisão antes de movimentar.');
|
||||
abort_unless($this->equivalentPreparation($this->preview($actor, $current, $plan->data), $plan->snapshot['plan']), 409, 'As origens documentais mudaram. Prepare e confira uma nova versão.');
|
||||
}
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$state = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'landedCostState'))->invoke($engine, $plan->record_key));
|
||||
abort_unless($data['financial_revision'] === (is_array($state) ? $state['result']['revision'] : 0), 409, 'A posição orçamental mudou; conserve a preparação e actualize antes de continuar.');
|
||||
abort_unless(! in_array($data['action'], ['reserve', 'amend'], true) || $data['sources'] === [], 422, 'A reserva e a reafectação usam a preparação conferida completa.');
|
||||
$args = [$plan->record_key, $plan->version, $plan->snapshot['plan']['budget_id'], $plan->data['components'], $plan->snapshot['plan']['documents'], $data['operation_key']];
|
||||
$method = 'reserveLandedCosts';
|
||||
if ($data['action'] !== 'reserve') {
|
||||
abort_unless(is_array($state), 409, 'Registe primeiro a reserva adicional.');
|
||||
if ($data['action'] === 'amend') {
|
||||
abort_unless($state['result']['budget_id'] === $plan->snapshot['plan']['budget_id'], 409, 'A reafectação desta versão conserva a dotação e a sua base de imposto.');
|
||||
$method = 'amendLandedCosts';
|
||||
$args = [$plan->record_key, $state['result']['version'], $state['result']['plan_hash'], $plan->version,
|
||||
$plan->data['components'], $plan->snapshot['plan']['documents'], $data['operation_key'], $data['financial_revision']];
|
||||
} else {
|
||||
abort_unless($data['action'] === 'cancel' || ($state['result']['version'] === $plan->version && $state['result']['plan_hash'] === $plan->snapshot['plan']['fingerprint']), 409, 'Aplique a alteração documental aprovada antes de continuar.');
|
||||
$method = 'transitionLandedCosts';
|
||||
$args = [$plan->record_key, $state['result']['version'], $state['result']['plan_hash'], $data['action'], $data['operation_key'], $data['sources'], $data['financial_revision']];
|
||||
}
|
||||
}
|
||||
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, $method))->invoke($engine, ...$args));
|
||||
abort_unless(is_array($result), 503, 'Recibo financeiro incompatível; operação não concluída.');
|
||||
$version = (int) SupplyRecord::query()->where('kind', 'import_cost_event')->where('record_key', $plan->record_key)->max('version') + 1;
|
||||
$event = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_cost_event', 'record_key' => $plan->record_key,
|
||||
'version' => $version, 'state' => $result['phase'], 'purchase_order_id' => $order->id, 'created_by' => $actor->id,
|
||||
'data' => ['action' => $data['action'], 'approved_preparation_id' => $plan->id, 'financial_plan_version' => $result['version']],
|
||||
'snapshot' => ['import_key' => $current->record_key, 'common_result' => $result, 'actor' => $actor->only(['id', 'name'])],
|
||||
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||
|
||||
return $event;
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array{User,SupplyRecord,PurchaseOrder} */
|
||||
private function context(User $actor, SupplyRecord $import): array
|
||||
{
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Finance]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$current = SupplyRecord::query()->where('kind', 'import')->where('record_key', $import->record_key)->latest('version')->lockForUpdate()->firstOrFail();
|
||||
abort_unless($current->id === $import->id, 409, 'O processo de importação mudou. Consulte a versão actual.');
|
||||
$order = PurchaseOrder::query()->visibleTo($actor)->lockForUpdate()->findOrFail($current->purchase_order_id);
|
||||
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
||||
|
||||
return [$actor, $current, $order];
|
||||
}
|
||||
|
||||
private function importRevision(SupplyRecord $import): string
|
||||
{
|
||||
$context = ['purchase_order_id' => $import->purchase_order_id];
|
||||
foreach (['purpose', 'jurisdiction', 'origin_country', 'dispatch_country', 'incoterm', 'regime'] as $field) {
|
||||
$context[$field] = $import->data[$field] ?? null;
|
||||
}
|
||||
|
||||
return hash('sha256', json_encode($context, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
/** Logistics events do not revoke accepted financial sources.
|
||||
* @param array<string,mixed> $fresh
|
||||
* @param array<string,mixed> $frozen
|
||||
*/
|
||||
private function equivalentPreparation(array $fresh, array $frozen): bool
|
||||
{
|
||||
$frozen['import_revision'] = $this->preparationImportRevision($frozen);
|
||||
$frozen['item_references'] ??= [];
|
||||
if ($frozen['import_revision'] === null) {
|
||||
return false;
|
||||
}
|
||||
unset($fresh['import_version'], $frozen['import_version']);
|
||||
|
||||
// Key order is presentation, not a financial source change.
|
||||
ksort($fresh);
|
||||
ksort($frozen);
|
||||
|
||||
return $fresh === $frozen;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $plan */
|
||||
private function preparationImportRevision(array $plan): ?string
|
||||
{
|
||||
if (isset($plan['import_revision'])) {
|
||||
return $plan['import_revision'];
|
||||
}
|
||||
$historical = SupplyRecord::query()->where('kind', 'import')->where('record_key', $plan['import_key'])
|
||||
->where('version', $plan['import_version'])->first();
|
||||
|
||||
return $historical === null ? null : $this->importRevision($historical);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $document
|
||||
* @return array{subtotal_minor:int,tax_minor:int,total_minor:int}
|
||||
*/
|
||||
private function reference(array $document): array
|
||||
{
|
||||
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
|
||||
abort_unless(is_int($document[$field]) && $document[$field] >= 0 && $document[$field] <= 100000000000000, 422, 'Indique montantes documentais inteiros em centavos.');
|
||||
}
|
||||
abort_unless($document['subtotal_minor'] <= $document['total_minor'] && $document['tax_minor'] === $document['total_minor'] - $document['subtotal_minor'], 422, 'Os valores documentais não reconciliam.');
|
||||
$basis = $document['exchange_basis'];
|
||||
if ($document['currency'] === 'MZN') {
|
||||
abort_unless($basis === null, 422, 'Documentos MZN conservam os valores nativos.');
|
||||
|
||||
return array_intersect_key($document, array_flip(['subtotal_minor', 'tax_minor', 'total_minor']));
|
||||
}
|
||||
abort_unless(is_array($basis) && is_string($basis['rate'] ?? null) && is_string($basis['quoted_on'] ?? null)
|
||||
&& is_string($basis['source'] ?? null) && trim($basis['source']) !== '', 422, 'Conserve a taxa, data e fonte explícitas de Finanças.');
|
||||
try {
|
||||
$subtotal = app(QuotationExchange::class)->convert($document['subtotal_minor'], $basis['rate']);
|
||||
$tax = app(QuotationExchange::class)->convert($document['tax_minor'], $basis['rate']);
|
||||
} catch (\InvalidArgumentException) {
|
||||
abort(422, 'Montante ou taxa de câmbio não representável.');
|
||||
}
|
||||
abort_if($subtotal > 100000000000000 - $tax, 422, 'Total convertido não representável.');
|
||||
|
||||
return ['subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
<?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];
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,9 @@ class InvoiceBudgetDistributions
|
||||
*/
|
||||
public function prepare(User $actor, Invoice $invoice, PurchaseOrder $order, array $input, array $nativeLines): array
|
||||
{
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
return app(OrderPartsInvoices::class)->prepare($actor, $invoice, $order, $input, $nativeLines);
|
||||
}
|
||||
$host = app(RequisitionBudgetDistributions::class);
|
||||
abort_unless($host->ready() && DB::transactionLevel() > 0, 503);
|
||||
abort_unless(auth()->id() === $actor->id && $actor->hasFunctions([PurchasingRole::Finance])
|
||||
@@ -84,6 +87,9 @@ class InvoiceBudgetDistributions
|
||||
*/
|
||||
public function consume(User $actor, Invoice $invoice, PurchaseOrder $order, array $reference): array
|
||||
{
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
return app(OrderPartsInvoices::class)->consume($actor, $invoice, $order);
|
||||
}
|
||||
abort_unless(app(RequisitionBudgetDistributions::class)->ready() && DB::transactionLevel() > 0, 503);
|
||||
$plan = $invoice->snapshot['budget_distribution'] ?? null;
|
||||
if (! is_array($plan) || $plan['revision'] !== $this->revision($invoice, $order) || $plan['reference'] !== $reference) {
|
||||
|
||||
@@ -33,7 +33,7 @@ class InvoiceWorkflow
|
||||
if ($invoice->status !== 'pending' || ! $this->reviewerBaseEligible($user, $invoice)) {
|
||||
return false;
|
||||
}
|
||||
$order = PurchaseOrder::query()->whereKey($invoice->purchase_order_id)->first();
|
||||
$order = PurchaseOrder::query()->visibleTo($user)->whereKey($invoice->purchase_order_id)->first();
|
||||
if ($order === null) {
|
||||
return false;
|
||||
}
|
||||
@@ -76,10 +76,12 @@ class InvoiceWorkflow
|
||||
$this->invalid('Preço, unidade e IVA devem coincidir exactamente com a ordem. Não há tolerância ou excepção configurada.');
|
||||
}
|
||||
// Cumulative rounding ensures partial invoices sum exactly to the frozen order.
|
||||
$amounts = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, (int) $previous, $quantity);
|
||||
$offset = $source->getAttribute('quantity_offset_milli') ?? 0;
|
||||
$amounts = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, $offset + (int) $previous, $quantity);
|
||||
$lines[] = ['tenant_id' => $order->tenant_id, 'purchase_order_item_id' => $source->id, 'quantity_milli' => $quantity,
|
||||
'subtotal_minor' => $amounts['subtotal_minor'], 'tax_minor' => $amounts['tax_minor'],
|
||||
'snapshot' => $source->only(['description', 'unit', 'unit_price_minor', 'tax_rate'])];
|
||||
'snapshot' => [...$source->only(['description', 'unit', 'unit_price_minor', 'tax_rate']),
|
||||
...($source->getAttribute('quantity_offset_milli') === null ? [] : ['quantity_offset_milli' => $offset])]];
|
||||
}
|
||||
if ($lines === []) {
|
||||
$this->invalid('Indique pelo menos uma linha.');
|
||||
@@ -99,6 +101,9 @@ class InvoiceWorkflow
|
||||
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Finance]);
|
||||
$this->access($user);
|
||||
$order = PurchaseOrder::query()->lockForUpdate()->findOrFail($order->id);
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
app(OrderPartsAccess::class)->assertProcess($user, $order);
|
||||
}
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($order);
|
||||
$request = Requisition::query()->findOrFail($order->requisition_id);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user);
|
||||
@@ -147,6 +152,9 @@ class InvoiceWorkflow
|
||||
return;
|
||||
}
|
||||
$order = PurchaseOrder::query()->lockForUpdate()->findOrFail($invoice->purchase_order_id);
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
app(OrderPartsAccess::class)->assertProcess($user, $order);
|
||||
}
|
||||
$request = Requisition::query()->findOrFail($order->requisition_id);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user);
|
||||
if (substr((string) $invoice->issued_on, 0, 4) !== now()->format('Y')) {
|
||||
|
||||
@@ -18,6 +18,7 @@ class OperationalHealth
|
||||
$checks = [];
|
||||
$startedAt = now()->toIso8601String();
|
||||
foreach (['replenishment' => fn () => app(ReplenishmentQueue::class)->health(),
|
||||
'import_cost_documents' => fn () => app(ImportCostDocumentHealth::class)->inspect($documentLimit),
|
||||
'receipt_documents' => fn () => app(ReceiptDocumentHealth::class)->inspect($documentLimit)] as $key => $read) {
|
||||
try {
|
||||
$result = $read();
|
||||
|
||||
@@ -27,7 +27,8 @@ class OrderCancellationWorkflow
|
||||
}
|
||||
$order = PurchaseOrder::query()->visibleTo($actor)->find($record->purchase_order_id);
|
||||
|
||||
return $order && Requisition::query()->whereKey($order->requisition_id)->where('requester_id', $actor->id)->where('department_id', $actor->department_id)->exists();
|
||||
return $order && ! OrderPartsAccess::applies($order)
|
||||
&& Requisition::query()->whereKey($order->requisition_id)->where('requester_id', $actor->id)->where('department_id', $actor->department_id)->exists();
|
||||
}
|
||||
|
||||
public function canRequest(User $actor, PurchaseOrder $order): bool
|
||||
@@ -38,6 +39,17 @@ class OrderCancellationWorkflow
|
||||
}
|
||||
$request = Requisition::query()->visibleTo($actor)->find($order->requisition_id);
|
||||
$policy = app(OrderCancellationPolicyWorkflow::class)->current();
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
if (! PurchaseOrder::query()->visibleTo($actor)->whereKey($order->id)->exists()) {
|
||||
return false;
|
||||
}
|
||||
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
|
||||
$source = Requisition::query()->whereKey($origin)->first();
|
||||
if (! $source || $source->requester_id === $actor->id || app(ConflictGuard::class)->processBlocked($source, $order->supplier_id, $actor)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $request && $request->requester_id !== $actor->id && $policy && $policy->enabled && $policy->mode === 'issued_order'
|
||||
&& $policy->valid_until >= today()->format('Y-m-d')
|
||||
@@ -53,6 +65,16 @@ class OrderCancellationWorkflow
|
||||
$order = PurchaseOrder::query()->visibleTo($actor)->find($record->purchase_order_id);
|
||||
$request = $order ? Requisition::query()->find($order->requisition_id) : null;
|
||||
$award = $order ? PurchaseAward::query()->find($order->purchase_award_id) : null;
|
||||
if ($order && OrderPartsAccess::applies($order)) {
|
||||
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
|
||||
$source = Requisition::query()->whereKey($origin)->first();
|
||||
$sourceAward = PurchaseAward::query()->where('requisition_id', $origin)->first();
|
||||
if (! $source || ! $sourceAward || in_array($actor->id, [$source->requester_id, $sourceAward->created_by], true)
|
||||
|| app(ConflictGuard::class)->processBlocked($source, $order->supplier_id, $actor)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $order && $request && $award && ! in_array($actor->id, [$record->created_by, $request->requester_id, $award->created_by, $order->issued_by], true);
|
||||
}
|
||||
@@ -92,6 +114,8 @@ class OrderCancellationWorkflow
|
||||
private function basis(PurchaseOrder $order): string
|
||||
{
|
||||
return hash('sha256', json_encode(['order' => $order->getAttributes(), 'items' => $order->items()->orderBy('id')->get()->toArray(),
|
||||
...(OrderPartsAccess::applies($order) ? ['order_parts_financial' => DB::table('budget_order_allocations')->where('tenant_id', $order->tenant_id)
|
||||
->where('order_key', $order->getAttribute('order_key'))->orderBy('id')->get()->toArray()] : []),
|
||||
'budget' => DB::table('budget_entries')->where('tenant_id', $order->tenant_id)->where('requisition_id', $order->requisition_id)->orderBy('id')->get()->toArray()], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
@@ -111,6 +135,10 @@ class OrderCancellationWorkflow
|
||||
$request = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
|
||||
abort_if($actor->id === $request->requester_id, 403);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
||||
abort_if(Requisition::query()->whereIn('id', app(OrderPartsAccess::class)->origins($order))->where('requester_id', $actor->id)->exists(), 403);
|
||||
}
|
||||
$old = OrderCancellation::query()->where('created_by', $actor->id)->where('operation_key', $data['operation_key'])->first();
|
||||
if ($old) {
|
||||
abort_unless($old->input_hash === $hash, 422, 'Chave utilizada com outro conteúdo.');
|
||||
@@ -143,36 +171,72 @@ class OrderCancellationWorkflow
|
||||
$award = PurchaseAward::query()->findOrFail($order->purchase_award_id);
|
||||
abort_if(in_array($actor->id, [$record->created_by, $request->requester_id, $award->created_by, $order->issued_by], true), 403);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
||||
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
|
||||
$source = Requisition::query()->whereKey($origin)->firstOrFail();
|
||||
$sourceAward = PurchaseAward::query()->where('requisition_id', $origin)->firstOrFail();
|
||||
abort_if(in_array($actor->id, [$source->requester_id, $sourceAward->created_by], true), 403);
|
||||
}
|
||||
}
|
||||
if ($record->status !== 'pending') {
|
||||
abort_unless($record->status === $decision && $record->review_reason === $reason && $record->reviewed_by === $actor->id, 409, 'Decisão imutável.');
|
||||
|
||||
return;
|
||||
}
|
||||
$entry = null;
|
||||
$partReversal = null;
|
||||
if ($decision === 'approved') {
|
||||
$this->source($order);
|
||||
abort_unless($record->basis_hash === $this->basis($order), 409, 'A base da ordem ou do compromisso mudou.');
|
||||
$policy = app(OrderCancellationPolicyWorkflow::class)->requireCurrent();
|
||||
abort_unless($policy->id === $record->policy_id, 409, 'Política alterada; rejeite o pedido para retomar o circuito.');
|
||||
abort_unless(DB::table('tenants')->where('id', $actor->tenant_id)->value('currency') === 'MZN', 422);
|
||||
if (! empty($order->snapshot['budget_control']) && ! DB::table('budget_entries')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->exists()) {
|
||||
throw ValidationException::withMessages(['budget' => 'A ordem indica controlo orçamental, mas o compromisso não está disponível.']);
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
$partReversal = $this->reverseParts($actor, $order, $record);
|
||||
} else {
|
||||
if (! empty($order->snapshot['budget_control']) && ! DB::table('budget_entries')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->exists()) {
|
||||
throw ValidationException::withMessages(['budget' => 'A ordem indica controlo orçamental, mas o compromisso não está disponível.']);
|
||||
}
|
||||
$path = base_path('packages/order-cancellation/src/CommitmentReversal.php');
|
||||
abort_unless(is_file($path) && hash_file('sha256', $path) === config('order_cancellation.reversal_sha256'), 503, 'Capacidade de reversão indisponível.');
|
||||
require_once $path;
|
||||
try {
|
||||
$entry = (new CommitmentReversal)->reverse(DB::connection(), new BudgetContext($actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN'), $request->id, $order->id);
|
||||
} catch (\LogicException $error) {
|
||||
throw ValidationException::withMessages(['budget' => 'O compromisso não está integralmente disponível para reversão ou a sua base é inconsistente. Reveja o controlo orçamental.']);
|
||||
}
|
||||
$request->update(['status' => 'cancelled']);
|
||||
}
|
||||
$path = base_path('packages/order-cancellation/src/CommitmentReversal.php');
|
||||
abort_unless(is_file($path) && hash_file('sha256', $path) === config('order_cancellation.reversal_sha256'), 503, 'Capacidade de reversão indisponível.');
|
||||
require_once $path;
|
||||
try {
|
||||
$entry = (new CommitmentReversal)->reverse(DB::connection(), new BudgetContext($actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN'), $request->id, $order->id);
|
||||
} catch (\LogicException $error) {
|
||||
throw ValidationException::withMessages(['budget' => 'O compromisso não está integralmente disponível para reversão ou a sua base é inconsistente. Reveja o controlo orçamental.']);
|
||||
}
|
||||
$request->update(['status' => 'cancelled']);
|
||||
}
|
||||
$record->update(['status' => $decision, 'reviewed_by' => $actor->id, 'review_reason' => $reason, 'reviewed_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'order_cancellation.'.$decision, $request, null, ['cancellation_id' => $record->id, 'order_id' => $order->id, 'budget_reversal_entry_id' => $entry]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'order_cancellation.'.$decision, $request, null, ['cancellation_id' => $record->id, 'order_id' => $order->id, 'budget_reversal_entry_id' => $entry,
|
||||
...($partReversal === null ? [] : ['order_parts_reversal' => $partReversal])]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function reverseParts(User $actor, PurchaseOrder $order, OrderCancellation $record): array
|
||||
{
|
||||
abort_unless(app(OrderPartsWorkflow::class)->ready(), 503);
|
||||
$sources = $order->snapshot['order_parts']['budget_sources'];
|
||||
foreach ($sources as &$source) {
|
||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['origin'])->lockForUpdate()->first();
|
||||
abort_unless($distribution !== null, 503, 'Preserve a origem do compromisso.');
|
||||
$source['version'] = DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count();
|
||||
$source['plan_hash'] = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR)['plan_hash'];
|
||||
}
|
||||
unset($source);
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'cancelOrderParts'))->invoke($engine, $order->getAttribute('order_key'), $sources, $record->operation_key));
|
||||
if (! is_array($result)) {
|
||||
throw new \LogicException('Resposta incompatível da reversão por parcelas.');
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function revise(User $actor, OrderCancellation $record, string $neededBy, string $reason): Requisition
|
||||
{
|
||||
$this->enabled();
|
||||
@@ -184,6 +248,7 @@ class OrderCancellationWorkflow
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$record = OrderCancellation::query()->lockForUpdate()->findOrFail($record->id);
|
||||
$order = PurchaseOrder::query()->findOrFail($record->purchase_order_id);
|
||||
abort_if(OrderPartsAccess::applies($order), 422, 'Cancelar uma parcela não encerra a requisição nem autoriza uma nova requisição por arrasto.');
|
||||
$source = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
|
||||
abort_unless($actor->id === $source->requester_id && $actor->department_id === $source->department_id && $record->status === 'approved', 403);
|
||||
if ($record->revised_requisition_id) {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Finance's explicit native invoice imputations, with one common consumption command. */
|
||||
final class OrderPartsInvoices
|
||||
{
|
||||
/** @return list<array<string,mixed>>|null */
|
||||
public function options(User $actor, PurchaseOrder $order): ?array
|
||||
{
|
||||
if (! app(OrderPartsWorkflow::class)->ready() || ! $actor->hasFunctions([PurchasingRole::Finance])
|
||||
|| app(OrganizationAccess::class)->maintenanceOnly($actor)) {
|
||||
return null;
|
||||
}
|
||||
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
||||
$rows = [];
|
||||
foreach ($order->snapshot['order_parts']['sources'] as $source) {
|
||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->first();
|
||||
abort_unless($distribution !== null, 503);
|
||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$nativeLines = array_column($source['items'], null, 'requisition_item_id');
|
||||
foreach ($snapshot['allocations'] as $allocation) {
|
||||
if (! isset($nativeLines[$allocation['line_id']]) || ! DB::table('budget_order_allocations')->where('tenant_id', $actor->tenant_id)
|
||||
->where('order_key', $order->getAttribute('order_key'))->where('distribution_id', $distribution->id)->where('allocation_key', $allocation['allocation_key'])->where('kind', 'commit')->exists()) {
|
||||
continue;
|
||||
}
|
||||
$rows[] = ['origin' => $source['requisition_id'], 'allocation_key' => $allocation['allocation_key'], 'line_id' => $allocation['line_id'],
|
||||
'centre_id' => $allocation['centre_id'], 'description' => $nativeLines[$allocation['line_id']]['description']];
|
||||
}
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
$money = ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/D'];
|
||||
|
||||
return ['order_part_allocations' => 'required|array|min:1|max:500',
|
||||
'order_part_allocations.*' => 'required|array:origin,allocation_key,subtotal,total',
|
||||
'order_part_allocations.*.origin' => 'required|integer|min:1',
|
||||
'order_part_allocations.*.allocation_key' => 'required|string|max:120',
|
||||
'order_part_allocations.*.subtotal' => $money, 'order_part_allocations.*.total' => $money,
|
||||
'reason' => 'required|string|min:10|max:4000'];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @param list<array<string,mixed>> $nativeLines
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function prepare(User $actor, Invoice $invoice, PurchaseOrder $order, array $input, array $nativeLines): array
|
||||
{
|
||||
abort_unless(app(OrderPartsWorkflow::class)->ready() && DB::transactionLevel() > 0 && OrderPartsAccess::applies($order), 503);
|
||||
abort_unless(auth()->id() === $actor->id && $actor->hasFunctions([PurchasingRole::Finance])
|
||||
&& $invoice->tenant_id === $actor->tenant_id && $order->tenant_id === $actor->tenant_id && $invoice->purchase_order_id === $order->id, 403);
|
||||
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
||||
abort_unless($order->currency === 'MZN', 503, 'A imputação multimoeda por origem ainda está em preparação.');
|
||||
$data = Validator::make($input, $this->rules())->validate();
|
||||
$rows = [];
|
||||
$seen = [];
|
||||
foreach ($data['order_part_allocations'] as $row) {
|
||||
$origin = BigDecimal::of($row['origin'])->toInt();
|
||||
$key = $origin.':'.$row['allocation_key'];
|
||||
if (isset($seen[$key])) {
|
||||
throw ValidationException::withMessages(['order_part_allocations' => 'Cada atribuição é indicada uma única vez por origem.']);
|
||||
}
|
||||
$seen[$key] = true;
|
||||
$rows[] = ['origin' => $origin, 'allocation_key' => $row['allocation_key'],
|
||||
'subtotal_minor' => BigDecimal::of($row['subtotal'])->multipliedBy(100)->toInt(),
|
||||
'total_minor' => BigDecimal::of($row['total'])->multipliedBy(100)->toInt()];
|
||||
}
|
||||
usort($rows, fn ($a, $b) => [$a['origin'], $a['allocation_key']] <=> [$b['origin'], $b['allocation_key']]);
|
||||
$sources = $this->bindings($actor, $order, $rows, $nativeLines);
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'checkOrderPartsConsumption'))->invoke($engine, $sources));
|
||||
|
||||
return ['allocations' => $rows, 'source_versions_at_preparation' => array_column($sources, 'version', 'origin'),
|
||||
'revision' => $this->revision($invoice, $order, $nativeLines), 'operation_key' => (string) Str::uuid(),
|
||||
'prepared_by' => $actor->id, 'reason' => trim($data['reason'])];
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $rows
|
||||
* @param list<array<string,mixed>> $nativeLines
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
private function bindings(User $actor, PurchaseOrder $order, array $rows, array $nativeLines): array
|
||||
{
|
||||
$orderKey = $order->getAttribute('order_key');
|
||||
abort_unless(is_string($orderKey) && $orderKey === ($order->snapshot['order_parts']['order_key'] ?? null), 503,
|
||||
'Preserve o identificador nativo da ordem por parcelas.');
|
||||
$origins = app(OrderPartsAccess::class)->origins($order);
|
||||
$orderLines = $order->items()->get()->keyBy('id');
|
||||
$lineOrigins = [];
|
||||
foreach ($order->snapshot['order_parts']['sources'] as $source) {
|
||||
foreach ($source['items'] as $line) {
|
||||
$lineOrigins[$line['requisition_item_id']] = $source['requisition_id'];
|
||||
}
|
||||
}
|
||||
$expected = [];
|
||||
foreach ($nativeLines as $line) {
|
||||
$native = $orderLines->get($line['purchase_order_item_id']);
|
||||
abort_unless($native !== null && isset($lineOrigins[$native->requisition_item_id]), 409);
|
||||
$expected[$native->requisition_item_id] = ['origin' => $lineOrigins[$native->requisition_item_id],
|
||||
'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['subtotal_minor'] + $line['tax_minor']];
|
||||
}
|
||||
$sources = $sums = [];
|
||||
foreach ($rows as $row) {
|
||||
if (! in_array($row['origin'], $origins, true)) {
|
||||
throw ValidationException::withMessages(['order_part_allocations' => 'Origem fora desta ordem.']);
|
||||
}
|
||||
if (! isset($sources[$row['origin']])) {
|
||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $row['origin'])->lockForUpdate()->first();
|
||||
abort_unless($distribution !== null, 503, 'Preserve a distribuição da origem.');
|
||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$sources[$row['origin']] = ['origin' => $row['origin'], 'version' => DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count(),
|
||||
'plan_hash' => $snapshot['plan_hash'], 'allocations' => [], 'frozen' => array_column($snapshot['allocations'], null, 'allocation_key')];
|
||||
}
|
||||
$binding = $sources[$row['origin']]['frozen'][$row['allocation_key']] ?? null;
|
||||
$id = $binding['line_id'] ?? null;
|
||||
if ($id === null || ! isset($expected[$id]) || $expected[$id]['origin'] !== $row['origin']) {
|
||||
throw ValidationException::withMessages(['order_part_allocations' => 'Distribua apenas as linhas e origens efectivamente facturadas.']);
|
||||
}
|
||||
$sums[$id] ??= ['subtotal_minor' => 0, 'total_minor' => 0];
|
||||
$sums[$id]['subtotal_minor'] += $row['subtotal_minor'];
|
||||
$sums[$id]['total_minor'] += $row['total_minor'];
|
||||
$sources[$row['origin']]['allocations'][] = ['order_key' => $orderKey, 'allocation_key' => $row['allocation_key'],
|
||||
'subtotal_minor' => $row['subtotal_minor'], 'total_minor' => $row['total_minor']];
|
||||
}
|
||||
foreach ($expected as $id => $line) {
|
||||
if (($sums[$id] ?? null) !== ['subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]) {
|
||||
throw ValidationException::withMessages(['order_part_allocations' => 'As imputações devem coincidir exactamente com cada linha nativa da factura.']);
|
||||
}
|
||||
}
|
||||
foreach ($sources as &$source) {
|
||||
unset($source['frozen']);
|
||||
}
|
||||
unset($source);
|
||||
ksort($sources, SORT_NUMERIC);
|
||||
|
||||
return array_values($sources);
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $lines */
|
||||
private function revision(Invoice $invoice, PurchaseOrder $order, array $lines): string
|
||||
{
|
||||
$items = array_map(fn ($line) => array_intersect_key($line, array_flip(['purchase_order_item_id', 'quantity_milli', 'subtotal_minor', 'tax_minor'])), $lines);
|
||||
usort($items, fn ($a, $b) => $a['purchase_order_item_id'] <=> $b['purchase_order_item_id']);
|
||||
foreach ($items as &$item) {
|
||||
ksort($item);
|
||||
}
|
||||
unset($item);
|
||||
|
||||
return hash('sha256', json_encode([$invoice->only(['tenant_id', 'purchase_order_id', 'number', 'subtotal_minor', 'tax_minor', 'total_minor']),
|
||||
$order->only(['id', 'order_key', 'currency', 'snapshot']), $items], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function consume(User $actor, Invoice $invoice, PurchaseOrder $order): array
|
||||
{
|
||||
abort_unless(app(OrderPartsWorkflow::class)->ready() && DB::transactionLevel() > 0, 503);
|
||||
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
||||
$plan = $invoice->snapshot['budget_distribution'] ?? null;
|
||||
$lines = array_values($invoice->items()->orderBy('purchase_order_item_id')->get()->map(fn ($item) => $item->only(['purchase_order_item_id', 'quantity_milli', 'subtotal_minor', 'tax_minor']))->all());
|
||||
if (! is_array($plan) || ($plan['revision'] ?? null) !== $this->revision($invoice, $order, $lines)) {
|
||||
throw ValidationException::withMessages(['order_part_allocations' => 'Preserve a imputação nativa confirmada para esta factura.']);
|
||||
}
|
||||
$sources = $this->bindings($actor, $order, $plan['allocations'], $lines);
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'consumeOrderParts'))->invoke($engine, $invoice->id, $sources, $plan['operation_key']));
|
||||
if (! is_array($result)) {
|
||||
throw new \LogicException('Resposta incompatível do consumo por origem.');
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace App\Services;
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrderItem;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
@@ -32,7 +33,19 @@ final class OrderPartsPreparation
|
||||
public function prepare(User $actor, array $input): array
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
$data = Validator::make($input, [
|
||||
$data = $this->selection($input);
|
||||
|
||||
return DB::transaction(function () use ($actor, $data): array {
|
||||
return $this->prepareSelected($actor, $data);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function selection(array $input): array
|
||||
{
|
||||
return Validator::make($input, [
|
||||
'sources' => 'required|array|min:1|max:100',
|
||||
'sources.*' => 'required|array:award_id,items',
|
||||
'sources.*.award_id' => 'required|integer|min:1|distinct',
|
||||
@@ -41,64 +54,68 @@ final class OrderPartsPreparation
|
||||
'sources.*.items.*.quotation_item_id' => 'required|integer|min:1|distinct',
|
||||
'sources.*.items.*.quantity' => ['required', 'string', 'regex:/^\d{1,10}(?:\.\d{1,3})?$/D'],
|
||||
])->validate();
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($actor, $data): array {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$sources = $data['sources'];
|
||||
usort($sources, fn ($a, $b) => $a['award_id'] <=> $b['award_id']);
|
||||
$result = [];
|
||||
$compatibility = null;
|
||||
foreach ($sources as $selection) {
|
||||
$award = PurchaseAward::query()->where('id', $selection['award_id'])->firstOrFail();
|
||||
$quote = app(PurchaseWorkflow::class)->approvedSource($actor, $award);
|
||||
$key = [$quote->tenant_id, $quote->supplier_id, $quote->currency];
|
||||
if ($compatibility !== null && $key !== $compatibility) {
|
||||
throw ValidationException::withMessages(['sources' => 'Consolide apenas adjudicações da mesma empresa, fornecedor e moeda documental.']);
|
||||
}
|
||||
$compatibility = $key;
|
||||
$lines = $quote->items()->orderBy('id')->lockForUpdate()->get()->keyBy('id');
|
||||
$prepared = [];
|
||||
foreach ($selection['items'] as $item) {
|
||||
$source = $lines->get($item['quotation_item_id']);
|
||||
abort_unless($source !== null, 422, 'Linha fora da proposta aprovada.');
|
||||
$ordered = PurchaseOrderItem::query()->where('requisition_item_id', $source->requisition_item_id)->orderBy('id')->lockForUpdate()->get();
|
||||
$before = 0;
|
||||
foreach ($ordered as $old) {
|
||||
// Cancelled lines remain used; cancellation never authorizes automatic reissue.
|
||||
$before += ReceiptWorkflow::milli($old->quantity);
|
||||
}
|
||||
$quantity = ReceiptWorkflow::milli($item['quantity']);
|
||||
$full = ReceiptWorkflow::milli($source->quantity);
|
||||
if ($quantity < 1 || $before > $full || $quantity > $full - $before) {
|
||||
throw ValidationException::withMessages(['sources' => 'A parcela ultrapassa a quantidade aprovada ainda não emitida.']);
|
||||
}
|
||||
$amounts = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, $before, $quantity);
|
||||
$native = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, 0, $full);
|
||||
if ($native['subtotal_minor'] !== $source->subtotal_minor || $native['tax_minor'] !== $source->tax_minor || $native['total_minor'] !== $source->total_minor) {
|
||||
throw ValidationException::withMessages(['sources' => 'A base nativa da linha aprovada está inconsistente.']);
|
||||
}
|
||||
$prepared[] = ['quotation_item_id' => $source->id, 'requisition_item_id' => $source->requisition_item_id,
|
||||
'description' => $source->description, 'quantity_milli' => $quantity, 'quantity_offset_milli' => $before,
|
||||
'unit_price_minor' => $source->unit_price_minor, 'tax_rate' => (string) $source->tax_rate, ...$amounts];
|
||||
}
|
||||
usort($prepared, fn ($a, $b) => $a['quotation_item_id'] <=> $b['quotation_item_id']);
|
||||
$result[] = ['requisition_id' => $award->requisition_id, 'award_id' => $award->id, 'quotation_id' => $quote->id,
|
||||
'supplier_id' => $quote->supplier_id, 'currency' => $quote->currency, 'items' => $prepared,
|
||||
'exchange_basis' => $quote->exchange_basis, 'approved_reference' => app(QuotationExchange::class)->amounts($quote),
|
||||
'explicit_reference_allocation_required' => $quote->currency !== 'MZN',
|
||||
'quotation_terms' => $quote->only(['reference', 'valid_until', 'payment_terms', 'delivery_days']),
|
||||
'award_terms' => $award->only(['delivery_date', 'delivery_location', 'justification']),
|
||||
'approval_snapshot' => $award->approval_snapshot,
|
||||
'approval_fingerprint' => $award->comparison_hash];
|
||||
/** @param array<string,mixed> $data
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function prepareSelected(User $actor, array $data): array
|
||||
{
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$sources = $data['sources'];
|
||||
usort($sources, fn ($a, $b) => $a['award_id'] <=> $b['award_id']);
|
||||
$result = [];
|
||||
$compatibility = null;
|
||||
foreach ($sources as $selection) {
|
||||
$award = PurchaseAward::query()->where('id', $selection['award_id'])->firstOrFail();
|
||||
$quote = app(PurchaseWorkflow::class)->approvedSource($actor, $award);
|
||||
$key = [$quote->tenant_id, $quote->supplier_id, $quote->currency];
|
||||
if ($compatibility !== null && $key !== $compatibility) {
|
||||
throw ValidationException::withMessages(['sources' => 'Consolide apenas adjudicações da mesma empresa, fornecedor e moeda documental.']);
|
||||
}
|
||||
$subtotal = array_sum(array_map(fn ($source) => array_sum(array_column($source['items'], 'subtotal_minor')), $result));
|
||||
$tax = array_sum(array_map(fn ($source) => array_sum(array_column($source['items'], 'tax_minor')), $result));
|
||||
$compatibility = $key;
|
||||
$lines = $quote->items()->orderBy('id')->lockForUpdate()->get()->keyBy('id');
|
||||
$prepared = [];
|
||||
foreach ($selection['items'] as $item) {
|
||||
$source = $lines->get($item['quotation_item_id']);
|
||||
abort_unless($source !== null, 422, 'Linha fora da proposta aprovada.');
|
||||
$ordered = PurchaseOrderItem::query()->where('requisition_item_id', $source->requisition_item_id)->orderBy('id')->lockForUpdate()->get();
|
||||
$before = 0;
|
||||
foreach ($ordered as $old) {
|
||||
// Cancelled lines remain used; cancellation never authorizes automatic reissue.
|
||||
$before += ReceiptWorkflow::milli($old->quantity);
|
||||
}
|
||||
$quantity = ReceiptWorkflow::milli($item['quantity']);
|
||||
$full = ReceiptWorkflow::milli($source->quantity);
|
||||
if ($quantity < 1 || $before > $full || $quantity > $full - $before) {
|
||||
throw ValidationException::withMessages(['sources' => 'A parcela ultrapassa a quantidade aprovada ainda não emitida.']);
|
||||
}
|
||||
$amounts = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, $before, $quantity);
|
||||
$native = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, 0, $full);
|
||||
if ($native['subtotal_minor'] !== $source->subtotal_minor || $native['tax_minor'] !== $source->tax_minor || $native['total_minor'] !== $source->total_minor) {
|
||||
throw ValidationException::withMessages(['sources' => 'A base nativa da linha aprovada está inconsistente.']);
|
||||
}
|
||||
$prepared[] = ['quotation_item_id' => $source->id, 'requisition_item_id' => $source->requisition_item_id, 'approved_quantity_milli' => $full,
|
||||
'description' => $source->description, 'quantity_milli' => $quantity, 'quantity_offset_milli' => $before,
|
||||
'unit_price_minor' => $source->unit_price_minor, 'tax_rate' => (string) $source->tax_rate, ...$amounts];
|
||||
}
|
||||
usort($prepared, fn ($a, $b) => $a['quotation_item_id'] <=> $b['quotation_item_id']);
|
||||
$result[] = ['requisition_id' => $award->requisition_id, 'requisition_number' => Requisition::query()->whereKey($award->requisition_id)->value('number'), 'award_id' => $award->id, 'quotation_id' => $quote->id,
|
||||
'supplier_id' => $quote->supplier_id, 'currency' => $quote->currency, 'items' => $prepared,
|
||||
'exchange_basis' => $quote->exchange_basis, 'approved_reference' => app(QuotationExchange::class)->amounts($quote),
|
||||
'explicit_reference_allocation_required' => $quote->currency !== 'MZN',
|
||||
'quotation_terms' => array_intersect_key($quote->attributesToArray(), array_flip(['reference', 'valid_until', 'payment_terms', 'delivery_days'])),
|
||||
'award_terms' => array_intersect_key($award->attributesToArray(), array_flip(['delivery_date', 'delivery_location', 'justification'])),
|
||||
'approval_snapshot' => $award->approval_snapshot,
|
||||
'approval_fingerprint' => $award->comparison_hash];
|
||||
}
|
||||
$subtotal = array_sum(array_map(fn ($source) => array_sum(array_column($source['items'], 'subtotal_minor')), $result));
|
||||
$tax = array_sum(array_map(fn ($source) => array_sum(array_column($source['items'], 'tax_minor')), $result));
|
||||
|
||||
return ['sources' => $result, 'currency' => $compatibility[2], 'subtotal_minor' => $subtotal, 'tax_minor' => $tax,
|
||||
'total_minor' => $subtotal + $tax, 'fingerprint' => hash('sha256', json_encode($result, JSON_THROW_ON_ERROR)),
|
||||
'issued' => false, 'budget_effects' => false];
|
||||
});
|
||||
return ['sources' => $result, 'currency' => $compatibility[2], 'subtotal_minor' => $subtotal, 'tax_minor' => $tax,
|
||||
'total_minor' => $subtotal + $tax, 'fingerprint' => hash('sha256', json_encode($result, JSON_THROW_ON_ERROR)),
|
||||
'issued' => false, 'budget_effects' => false];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\PurchaseOrderItem;
|
||||
use App\Models\Quotation;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\Tenant;
|
||||
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\Validation\ValidationException;
|
||||
|
||||
/** Optional native issuance. Every document and common budget effect shares one transaction. */
|
||||
final class OrderPartsWorkflow
|
||||
{
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function preview(User $actor, array $input): array
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
|
||||
return DB::transaction(function () use ($actor, $input): array {
|
||||
$selection = app(OrderPartsPreparation::class)->selection($input);
|
||||
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
|
||||
$financial = [];
|
||||
foreach ($prepared['sources'] as $source) {
|
||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->lockForUpdate()->first();
|
||||
if ($distribution === null) {
|
||||
$financial[] = ['origin' => $source['requisition_id'], 'award_id' => $source['award_id'], 'requires_adoption' => true, 'allocations' => []];
|
||||
|
||||
continue;
|
||||
}
|
||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$selected = array_column($source['items'], null, 'requisition_item_id');
|
||||
$rows = [];
|
||||
foreach ($snapshot['allocations'] as $row) {
|
||||
if (! isset($selected[$row['line_id']])) {
|
||||
continue;
|
||||
}
|
||||
$line = $selected[$row['line_id']];
|
||||
$count = count(array_filter($snapshot['allocations'], fn ($part) => $part['line_id'] === $row['line_id']));
|
||||
$rows[] = ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'],
|
||||
'description' => $line['description'], 'subtotal' => $count === 1 && $source['currency'] === 'MZN' ? (string) BigDecimal::of($line['subtotal_minor'])->dividedBy(100, 2) : '',
|
||||
'total' => $count === 1 && $source['currency'] === 'MZN' ? (string) BigDecimal::of($line['total_minor'])->dividedBy(100, 2) : ''];
|
||||
}
|
||||
$financial[] = ['origin' => $source['requisition_id'], 'award_id' => $source['award_id'], 'requires_adoption' => false,
|
||||
'plan_hash' => $snapshot['plan_hash'], 'version' => DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count(), 'allocations' => $rows];
|
||||
}
|
||||
|
||||
return ['selection' => $selection, 'prepared' => $prepared, 'financial' => $financial,
|
||||
'can_issue' => $prepared['currency'] === 'MZN' && ! in_array(true, array_column($financial, 'requires_adoption'), true)];
|
||||
});
|
||||
}
|
||||
|
||||
public function adopt(User $actor, PurchaseAward $award, string $operation): void
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
Validator::make(['operation_key' => $operation], ['operation_key' => 'required|uuid'])->validate();
|
||||
DB::transaction(function () use ($actor, $award, $operation): void {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
|
||||
$quote = app(PurchaseWorkflow::class)->approvedSource($actor, $award);
|
||||
$request = Requisition::query()->whereKey($quote->requisition_id)->firstOrFail();
|
||||
abort_unless($quote->currency === 'MZN', 503, 'A adopção multimoeda ainda está em preparação.');
|
||||
$adopted = DB::table('budget_order_commands')->where('tenant_id', $actor->tenant_id)->where('kind', 'adopt')
|
||||
->where('document_key', 'origin-'.$request->id)->where('operation_key', strtolower($operation))->exists();
|
||||
abort_if(! $adopted && PurchaseOrderItem::query()->whereIn('requisition_item_id', $request->items()->select('id'))->exists(), 409,
|
||||
'Uma ordem já emitida não pode ser dividida retroactivamente.');
|
||||
$kind = $request->items()->where('purchase_type', 'equipment')->exists() ? 'investment' : 'operating';
|
||||
$lines = $allocations = [];
|
||||
foreach ($quote->items()->orderBy('id')->get() as $line) {
|
||||
$lines[$line->requisition_item_id] = ['subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor, 'required_kind' => $kind];
|
||||
$allocations[] = ['allocation_key' => 'legacy-line-'.$line->requisition_item_id, 'line_id' => $line->requisition_item_id,
|
||||
'centre_id' => $request->cost_center_id, 'subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor];
|
||||
}
|
||||
$revision = hash('sha256', json_encode(['quotation_id' => $quote->id, 'lines' => $lines], JSON_THROW_ON_ERROR));
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'adoptOrderSource'))->invoke($engine, $request->id,
|
||||
$allocations, $lines, $revision, strtolower($operation)));
|
||||
});
|
||||
}
|
||||
|
||||
public function ready(): bool
|
||||
{
|
||||
foreach (['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions', 'purchase_order_sources'] as $table) {
|
||||
if (! Schema::hasTable($table)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return app(OrderPartsPreparation::class)->ready() && app(RequisitionBudgetDistributions::class)->ready()
|
||||
&& Schema::hasTable('budget_order_commands') && Schema::hasTable('purchase_order_sources')
|
||||
&& Schema::hasColumn('purchase_orders', 'order_key') && Schema::hasColumn('purchase_orders', 'order_source_count')
|
||||
&& Schema::hasColumn('purchase_order_items', 'quantity_offset_milli');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function issue(User $actor, array $input): PurchaseOrder
|
||||
{
|
||||
abort_unless($this->ready(), 503, 'Emissão por parcelas indisponível nesta composição.');
|
||||
$selection = app(OrderPartsPreparation::class)->selection($input);
|
||||
$data = Validator::make($input, [
|
||||
'operation_key' => 'required|uuid', 'order_key' => 'required|uuid', 'fingerprint' => 'required|regex:/^[a-f0-9]{64}$/D',
|
||||
'budget_sources' => 'required|array|min:1|max:100',
|
||||
'budget_sources.*' => 'required|array:origin,version,plan_hash,allocations',
|
||||
'budget_sources.*.origin' => 'required|integer|min:1|distinct', 'budget_sources.*.version' => 'required|integer|min:0',
|
||||
'budget_sources.*.plan_hash' => 'required|regex:/^[a-f0-9]{64}$/D',
|
||||
'budget_sources.*.allocations' => 'required|array|min:1|max:500',
|
||||
'budget_sources.*.allocations.*' => 'required|array:allocation_key,subtotal_minor,total_minor',
|
||||
'budget_sources.*.allocations.*.allocation_key' => 'required|string|max:120',
|
||||
'budget_sources.*.allocations.*.subtotal_minor' => 'required|integer|min:0|max:100000000000000',
|
||||
'budget_sources.*.allocations.*.total_minor' => 'required|integer|min:0|max:100000000000000',
|
||||
'agreement_bindings' => 'sometimes|array|max:100',
|
||||
'tenant_id' => 'prohibited', 'snapshot' => 'prohibited', 'status' => 'prohibited', 'issued_by' => 'prohibited',
|
||||
])->validate();
|
||||
foreach ($selection['sources'] as &$source) {
|
||||
$source['award_id'] = BigDecimal::of($source['award_id'])->toInt();
|
||||
foreach ($source['items'] as &$line) {
|
||||
$line['quotation_item_id'] = BigDecimal::of($line['quotation_item_id'])->toInt();
|
||||
$line['quantity'] = (string) BigDecimal::of($line['quantity'])->toScale(3);
|
||||
}
|
||||
unset($line);
|
||||
usort($source['items'], fn ($a, $b) => $a['quotation_item_id'] <=> $b['quotation_item_id']);
|
||||
}
|
||||
unset($source);
|
||||
usort($selection['sources'], fn ($a, $b) => $a['award_id'] <=> $b['award_id']);
|
||||
$budgetSources = $data['budget_sources'];
|
||||
foreach ($budgetSources as &$source) {
|
||||
$source['origin'] = BigDecimal::of($source['origin'])->toInt();
|
||||
$source['version'] = BigDecimal::of($source['version'])->toInt();
|
||||
foreach ($source['allocations'] as &$row) {
|
||||
$row['subtotal_minor'] = BigDecimal::of($row['subtotal_minor'])->toInt();
|
||||
$row['total_minor'] = BigDecimal::of($row['total_minor'])->toInt();
|
||||
ksort($row);
|
||||
}
|
||||
unset($row);
|
||||
usort($source['allocations'], fn ($a, $b) => $a['allocation_key'] <=> $b['allocation_key']);
|
||||
ksort($source);
|
||||
}
|
||||
unset($source);
|
||||
usort($budgetSources, fn ($a, $b) => $a['origin'] <=> $b['origin']);
|
||||
$orderKey = strtolower($data['order_key']);
|
||||
$hash = hash('sha256', json_encode([$selection, $budgetSources, $data['fingerprint'], $data['agreement_bindings'] ?? []], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $selection, $data, $budgetSources, $orderKey, $hash): PurchaseOrder {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$existing = PurchaseOrder::query()->where('order_key', $orderKey)->lockForUpdate()->first();
|
||||
if ($existing !== null) {
|
||||
abort_unless(hash_equals($existing->getAttribute('order_payload_hash'), $hash), 409, 'A ordem já foi emitida com outra preparação.');
|
||||
PurchaseOrder::query()->visibleTo($actor)->whereKey($existing->id)->firstOrFail();
|
||||
app(OrderPartsAccess::class)->assertProcess($actor, $existing, true);
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($existing);
|
||||
|
||||
return $existing;
|
||||
}
|
||||
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
|
||||
abort_unless(hash_equals($prepared['fingerprint'], $data['fingerprint']), 409, 'A preparação mudou; consulte as origens actuais.');
|
||||
// Foreign references require the full per-origin invoice conversion bridge, never an averaged rate.
|
||||
abort_unless($prepared['currency'] === 'MZN', 503, 'O percurso de emissão multimoeda por origem ainda está em preparação.');
|
||||
$this->checkAllocations($actor, $prepared['sources'], $budgetSources);
|
||||
$frames = $requests = $lines = $catalogue = $tariffs = [];
|
||||
$firstQuote = null;
|
||||
foreach ($prepared['sources'] as $source) {
|
||||
$request = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
||||
$award = PurchaseAward::query()->whereKey($source['award_id'])->firstOrFail();
|
||||
$quote = Quotation::query()->whereKey($source['quotation_id'])->firstOrFail();
|
||||
$firstQuote ??= $quote;
|
||||
$requests[] = $request;
|
||||
$request->load(['department', 'costCenter', 'requester']);
|
||||
abort_unless($request->department !== null && $request->costCenter !== null && $quote->supplier !== null, 409,
|
||||
'Preserve os intervenientes e as referências de cada origem.');
|
||||
$requested = $request->items()->get()->keyBy('id');
|
||||
$tariffs += app(ImportTariffCodes::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||
foreach ($source['items'] as $item) {
|
||||
$native = $requested->get($item['requisition_item_id']);
|
||||
abort_unless($native !== null, 409);
|
||||
$lines[] = ['tenant_id' => $actor->tenant_id,
|
||||
...array_intersect_key($item, array_flip(['quotation_item_id', 'requisition_item_id', 'description', 'quantity_offset_milli', 'unit_price_minor', 'tax_rate', 'subtotal_minor', 'tax_minor', 'total_minor'])),
|
||||
'quantity' => (string) BigDecimal::of($item['quantity_milli'])->dividedBy(1000, 3),
|
||||
...$native->only(['unit', 'category', 'purchase_type', 'equipment_id', 'spare_part_id'])];
|
||||
if ($native->catalogue_snapshot !== null) {
|
||||
$catalogue[$native->id] = $native->catalogue_snapshot;
|
||||
}
|
||||
}
|
||||
$frames[] = ['requisition' => $request->only(['id', 'number', 'justification']),
|
||||
'department' => $request->department->only(['id', 'name']), 'cost_center' => $request->costCenter->only(['id', 'code', 'name']),
|
||||
'requester' => $request->requester?->only(['id', 'name']),
|
||||
'quotation' => [...$source['quotation_terms'], 'id' => $quote->id, 'currency' => $quote->currency],
|
||||
'award' => [...$source['award_terms'], 'id' => $award->id], 'approval_rules' => $award->approval_snapshot,
|
||||
'investment_rules' => $award->investment_snapshot, 'admission' => $award->admission_snapshot, 'recommendation' => $award->recommendation_snapshot,
|
||||
'estimate_approvals' => $request->steps()->get()->toArray(), 'final_approvals' => $award->approvals()->get()->toArray(),
|
||||
'decision_matrix' => $award->decision_matrix, 'comparison_policy' => app(ComparisonPolicy::class)->forRequest($request),
|
||||
'native_preparation' => $source];
|
||||
}
|
||||
$first = $prepared['sources'][0];
|
||||
$limits = app(AgreementOrderLimits::class)->freeze($actor, $firstQuote, $requests[0], $lines,
|
||||
$data['agreement_bindings'] ?? [], array_slice($requests, 1));
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$commit = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'commitOrderParts'))->invoke($engine,
|
||||
$orderKey, $budgetSources, strtolower($data['operation_key'])));
|
||||
$snapshot = [...$frames[0], ...$limits, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
|
||||
'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']),
|
||||
'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue,
|
||||
'budget_control' => $commit, 'development_only' => true, 'budget_checked' => true,
|
||||
'order_parts' => ['version' => 1, 'order_key' => $orderKey, 'preparation_fingerprint' => $prepared['fingerprint'],
|
||||
'sources' => $prepared['sources'], 'frames' => $frames, 'budget_sources' => $budgetSources]];
|
||||
$order = new PurchaseOrder(['tenant_id' => $actor->tenant_id, 'requisition_id' => $first['requisition_id'],
|
||||
'purchase_award_id' => $first['award_id'], 'supplier_id' => $first['supplier_id'], 'issued_by' => $actor->id,
|
||||
'currency' => $prepared['currency'],
|
||||
'subtotal_minor' => $prepared['subtotal_minor'], 'tax_minor' => $prepared['tax_minor'], 'total_minor' => $prepared['total_minor'],
|
||||
'snapshot' => $snapshot, 'issued_at' => now()]);
|
||||
// Trusted metadata must survive an ORM column cache warmed before the optional QA schema.
|
||||
$order->setAttribute('order_key', $orderKey);
|
||||
$order->setAttribute('order_payload_hash', $hash);
|
||||
$order->setAttribute('order_source_count', count($prepared['sources']));
|
||||
$order->save();
|
||||
DB::table('purchase_orders')->where('id', $order->id)->update(['number' => sprintf('OC-%s-%06d', now()->format('Y'), $order->id)]);
|
||||
$order->refresh();
|
||||
foreach ($lines as $line) {
|
||||
$record = new PurchaseOrderItem(array_diff_key($line, array_flip(['quotation_item_id', 'quantity_offset_milli'])));
|
||||
$record->setAttribute('quotation_item_id', $line['quotation_item_id']);
|
||||
$record->setAttribute('quantity_offset_milli', $line['quantity_offset_milli']);
|
||||
$order->items()->save($record);
|
||||
}
|
||||
foreach ($prepared['sources'] as $index => $source) {
|
||||
DB::table('purchase_order_sources')->insert(['tenant_id' => $actor->tenant_id, 'purchase_order_id' => $order->id,
|
||||
'requisition_id' => $source['requisition_id'], 'purchase_award_id' => $source['award_id'], 'quotation_id' => $source['quotation_id'],
|
||||
'snapshot' => json_encode($frames[$index], JSON_THROW_ON_ERROR)]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'purchase_order.issued', $requests[$index], null,
|
||||
['order_id' => $order->id, 'number' => $order->number, 'order_key' => $orderKey, 'source' => $source, 'budget_control' => $commit]);
|
||||
}
|
||||
|
||||
return $order;
|
||||
});
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $sources
|
||||
* @param list<array<string,mixed>> $financial
|
||||
*/
|
||||
private function checkAllocations(User $actor, array $sources, array $financial): void
|
||||
{
|
||||
$expected = array_column($sources, 'requisition_id');
|
||||
$actual = array_column($financial, 'origin');
|
||||
sort($expected, SORT_NUMERIC);
|
||||
sort($actual, SORT_NUMERIC);
|
||||
if ($expected !== $actual) {
|
||||
throw ValidationException::withMessages(['budget_sources' => 'Distribua exactamente as origens seleccionadas.']);
|
||||
}
|
||||
$byOrigin = array_column($financial, null, 'origin');
|
||||
foreach ($sources as $source) {
|
||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->lockForUpdate()->first();
|
||||
abort_unless($distribution !== null, 422, 'Prepare a distribuição ou a adopção explícita da reserva antes de emitir parcelas.');
|
||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$frozen = array_column($snapshot['allocations'], null, 'allocation_key');
|
||||
$amounts = [];
|
||||
foreach ($byOrigin[$source['requisition_id']]['allocations'] as $row) {
|
||||
$binding = $frozen[$row['allocation_key']] ?? null;
|
||||
if ($binding === null) {
|
||||
throw ValidationException::withMessages(['budget_sources' => 'Atribuição fora da origem seleccionada.']);
|
||||
}
|
||||
$id = $binding['line_id'];
|
||||
$amounts[$id] ??= ['subtotal_minor' => 0, 'total_minor' => 0];
|
||||
$amounts[$id]['subtotal_minor'] += $row['subtotal_minor'];
|
||||
$amounts[$id]['total_minor'] += $row['total_minor'];
|
||||
}
|
||||
$selected = array_column($source['items'], null, 'requisition_item_id');
|
||||
if (array_diff(array_keys($amounts), array_keys($selected)) !== []) {
|
||||
throw ValidationException::withMessages(['budget_sources' => 'Não inclua artigos que não pertencem a esta parcela.']);
|
||||
}
|
||||
foreach ($selected as $id => $line) {
|
||||
if (($amounts[$id] ?? null) !== array_intersect_key($line, array_flip(['subtotal_minor', 'total_minor']))) {
|
||||
throw ValidationException::withMessages(['budget_sources' => 'As atribuições devem reconciliar exactamente com cada linha nativa emitida.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,6 +129,7 @@ class PurchaseWorkflow
|
||||
// An already committed issue is returned, never re-created or re-snapshotted.
|
||||
$existing = PurchaseOrder::query()->where('requisition_id', $requisition->id)->first();
|
||||
if ($existing) {
|
||||
abort_if(OrderPartsAccess::applies($existing), 409, 'Esta adjudicação utiliza parcelas. Consulte as ordens emitidas ou prepare a parcela restante.');
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($existing);
|
||||
app(AgreementOrderLimits::class)->assertReplay($existing, $agreementBindings);
|
||||
|
||||
@@ -168,7 +169,9 @@ class PurchaseWorkflow
|
||||
$catalogueSources[$sourceLine->id] = $sourceLine->catalogue_snapshot;
|
||||
}
|
||||
}
|
||||
$tariffs = app(ImportTariffCodes::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||
$snapshot = [
|
||||
...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]),
|
||||
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings),
|
||||
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]),
|
||||
...($catalogueSources === [] ? [] : ['catalogue_sources' => $catalogueSources]),
|
||||
|
||||
@@ -79,6 +79,9 @@ class ReceiptWorkflow
|
||||
$order = PurchaseOrder::query()->lockForUpdate()->findOrFail($order->id);
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($order);
|
||||
Gate::forUser($user)->authorize('create', [GoodsReceipt::class, $order]);
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
app(OrderPartsAccess::class)->assertProcess($user, $order, true, true);
|
||||
}
|
||||
$deliveryNote = Str::squish(Str::upper($data['delivery_note']));
|
||||
if ($deliveryNote === '') {
|
||||
throw ValidationException::withMessages(['delivery_note' => 'Indique a guia de remessa do fornecedor.']);
|
||||
@@ -157,9 +160,11 @@ class ReceiptWorkflow
|
||||
if (GoodsReceipt::query()->where('purchase_order_id', $order->id)->where('delivery_note', $deliveryNote)->exists()) {
|
||||
throw ValidationException::withMessages(['delivery_note' => 'Esta guia já foi confirmada nesta ordem. Consulte o histórico em vez de repetir a recepção.']);
|
||||
}
|
||||
$classifiedImport = ! empty($order->snapshot['import_tariffs']);
|
||||
abort_if($classifiedImport && ! Schema::hasTable('supply_records'), 503, 'Preserve o processo de importação antes da recepção.');
|
||||
if (Schema::hasTable('supply_records')) {
|
||||
$import = app(SupplyPlanning::class)->latest('import')->where('purchase_order_id', $order->id)->first();
|
||||
if ($import !== null && $import->state !== 'released') {
|
||||
if (($classifiedImport && $import === null) || ($import !== null && $import->state !== 'released')) {
|
||||
throw ValidationException::withMessages(['items' => 'A importação ainda não tem libertação aduaneira comprovada. A chegada ou o pagamento não autorizam entrada utilizável.']);
|
||||
}
|
||||
}
|
||||
@@ -202,7 +207,8 @@ class ReceiptWorkflow
|
||||
if (! $source->spare_part_id || ! $source->equipment_id) {
|
||||
throw ValidationException::withMessages(['items' => 'Peça sem associação autorizada na ordem. A recepção está bloqueada.']);
|
||||
}
|
||||
$part = app(EquipmentWorkflow::class)->linkedPart((int) $source->spare_part_id, (int) $source->equipment_id, $requisition->department_id);
|
||||
$lineRequest = OrderPartsAccess::applies($order) ? app(OrderPartsAccess::class)->requestForLine($order, $source) : $requisition;
|
||||
$part = app(EquipmentWorkflow::class)->linkedPart((int) $source->spare_part_id, (int) $source->equipment_id, $lineRequest->department_id);
|
||||
if ($accepted > 0 && $stockItem?->id !== $part->stock_item_id) {
|
||||
throw ValidationException::withMessages(['items' => 'A peça recebida deve usar o artigo de stock autorizado na ordem.']);
|
||||
}
|
||||
@@ -225,6 +231,7 @@ class ReceiptWorkflow
|
||||
'rejected_milli' => $received - $accepted, 'quality_status' => $input['quality_status'], 'notes' => $input['notes'],
|
||||
'snapshot' => [
|
||||
'order_item' => $source->only(['id', 'description', 'unit', 'purchase_type', 'quantity']),
|
||||
...(OrderPartsAccess::applies($order) ? ['source_line' => $source->only(['requisition_item_id', 'quotation_item_id', 'quantity_offset_milli'])] : []),
|
||||
'stock_item' => $stockItem?->only(['id', 'code', 'name', 'unit']),
|
||||
'warehouse' => $warehouse?->only(['id', 'code', 'name']),
|
||||
'physical' => $physical,
|
||||
|
||||
@@ -204,6 +204,12 @@ class SupplyPlanning
|
||||
$this->check(! $this->latest('import')->where('purchase_order_id', $order->id)->exists(), 'purchase_order_id', 'A ordem já tem processo de importação. Consulte-o sem duplicar a compra.');
|
||||
$this->check(! GoodsReceipt::query()->where('purchase_order_id', $order->id)->exists(), 'purchase_order_id', 'Registe a importação antes da primeira recepção da ordem.');
|
||||
}
|
||||
if ($kind === 'import' && $old !== null && $old->purchase_order_id !== $order->id) {
|
||||
$this->check(! $this->latest('import')->where('purchase_order_id', $order->id)->where('record_key', '!=', $old->record_key)->exists(),
|
||||
'purchase_order_id', 'A ordem de destino já tem um processo de importação.');
|
||||
$this->check(! SupplyRecord::query()->whereIn('kind', ['import_cost_doc', 'import_cost_plan', 'import_cost_event'])
|
||||
->where('snapshot->import_key', $old->record_key)->exists(), 'purchase_order_id', 'A importação já conserva documentos ou custos financeiros. Preserve a ligação à ordem de origem.');
|
||||
}
|
||||
$snapshot = $action === 'save' ? ['prepared_by' => $actor->id, 'contributors' => array_values(array_unique([...($old?->snapshot['contributors'] ?? []), $actor->id])), 'item' => $item?->only(['id', 'code', 'name', 'unit']), 'warehouse' => $warehouse?->only(['id', 'code', 'name']),
|
||||
'supplier' => $supplier?->only(['id', 'name', 'version']), 'order' => $order?->only(['id', 'number', 'currency', 'supplier_id', 'total_minor'])] : $old->snapshot;
|
||||
if ($action === 'save' && $kind === 'agreement' && ! empty($data['contract_key'])) {
|
||||
|
||||
Reference in New Issue
Block a user