@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrderItem;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\Finance\Budget\BudgetControl;
|
||||
|
||||
/** Native approved-source and quantity preflight. Does not issue an order or move a budget. */
|
||||
final class OrderPartsPreparation
|
||||
{
|
||||
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()));
|
||||
$runtime = new \ReflectionClass(BudgetControl::class);
|
||||
|
||||
return config('order-parts.qa_enabled') === true && app()->environment('testing') && $isolated
|
||||
&& $runtime->hasMethod('commitOrderParts') && $runtime->hasConstant('ORDER_PARTS_VERSION')
|
||||
&& $runtime->getConstant('ORDER_PARTS_VERSION') === CommonBudget::ORDER_PARTS_CONTRACT;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function prepare(User $actor, array $input): array
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
$data = Validator::make($input, [
|
||||
'sources' => 'required|array|min:1|max:100',
|
||||
'sources.*' => 'required|array:award_id,items',
|
||||
'sources.*.award_id' => 'required|integer|min:1|distinct',
|
||||
'sources.*.items' => 'required|array|min:1|max:100',
|
||||
'sources.*.items.*' => 'required|array:quotation_item_id,quantity',
|
||||
'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];
|
||||
}
|
||||
$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];
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user