@@ -13,6 +13,7 @@ use App\Services\OrganizationAccess;
|
||||
use App\Services\OrganizationActivationPreview;
|
||||
use App\Services\OrganizationConfiguration;
|
||||
use App\Services\RequisitionApprovalLevels;
|
||||
use App\Services\RequisitionCategories;
|
||||
use App\Services\WorkContext;
|
||||
use App\Services\WorkflowTasks;
|
||||
use Brick\Math\BigDecimal;
|
||||
@@ -44,6 +45,7 @@ class OrganizationConfigurationController extends Controller
|
||||
'geography' => app(AdministrativeGeography::class)->describe(Tenant::query()->findOrFail($actor->tenant_id)->geography_reference),
|
||||
'companyDetailsReady' => Schema::hasColumn('tenants', 'company_details'),
|
||||
'approvalLevelsReady' => app(RequisitionApprovalLevels::class)->ready(),
|
||||
'requisitionCategoryOptions' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
||||
'approvalLevels' => Tenant::query()->findOrFail($actor->tenant_id)->requisition_approval_policy,
|
||||
'companyDetails' => Tenant::query()->findOrFail($actor->tenant_id)->company_details,
|
||||
'companyRules' => $this->companyRules((int) $actor->tenant_id),
|
||||
|
||||
@@ -13,6 +13,7 @@ use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\SavedProcurementSearches;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
@@ -29,7 +30,7 @@ class ProcurementSearchController extends Controller
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
abort_unless(app(OrganizationAccess::class)->permissions($actor) !== [], 403);
|
||||
$request->setUserResolver(fn () => $actor);
|
||||
$data = $request->validate(['q' => 'nullable|string|max:100', 'requests_page' => 'nullable|integer|min:1|max:1000000', 'orders_page' => 'nullable|integer|min:1|max:1000000', 'suppliers_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$data = $request->validate(['q' => 'nullable|string|max:100', 'archived_page' => 'nullable|integer|min:1|max:1000000', 'requests_page' => 'nullable|integer|min:1|max:1000000', 'orders_page' => 'nullable|integer|min:1|max:1000000', 'suppliers_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$term = trim($data['q'] ?? '');
|
||||
$request->validate(['invoices_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$request->validate(['equipment_page' => 'nullable|integer|min:1|max:1000000', 'stock_page' => 'nullable|integer|min:1|max:1000000', 'warehouses_page' => 'nullable|integer|min:1|max:1000000', 'receipts_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
@@ -97,6 +98,7 @@ class ProcurementSearchController extends Controller
|
||||
});
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('search/procurement', ['term' => $term, 'groups' => $groups,
|
||||
'savedSearches' => app(SavedProcurementSearches::class)->read($actor),
|
||||
'invoiceSearchAvailable' => config('procurement_search.finance_metadata_enabled') === true && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]),
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
@@ -21,6 +21,7 @@ use App\Services\OrganizationAccess;
|
||||
use App\Services\RequisitionAuditTrail;
|
||||
use App\Services\RequisitionBudgetDistributions;
|
||||
use App\Services\RequisitionCatalogue;
|
||||
use App\Services\RequisitionCategories;
|
||||
use App\Services\RequisitionDraftInput;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplySuggestions;
|
||||
@@ -77,6 +78,7 @@ class RequisitionController extends Controller
|
||||
return Inertia::render('requisitions/form', [
|
||||
'costCenters' => CostCenter::query()->where('department_id', $this->actor($request)->department_id)->orderBy('code')->get(),
|
||||
'requisition' => null,
|
||||
'requisitionCategories' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
||||
'incompleteDraftsAvailable' => app(RequisitionDraftInput::class)->available(),
|
||||
'defaultTaxRate' => (string) (Tenant::query()->findOrFail($this->actor($request)->tenant_id)->default_tax_rate ?? '16.00'),
|
||||
...$this->equipmentOptions($request),
|
||||
@@ -167,6 +169,7 @@ class RequisitionController extends Controller
|
||||
|
||||
return Inertia::render('requisitions/form', [
|
||||
'requisition' => $requisition->load('items'),
|
||||
'requisitionCategories' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
||||
'incompleteDraftsAvailable' => app(RequisitionDraftInput::class)->available(),
|
||||
'defaultTaxRate' => (string) (Tenant::query()->findOrFail($this->actor($request)->tenant_id)->default_tax_rate ?? '16.00'),
|
||||
'costCenters' => CostCenter::query()->where('department_id', $this->actor($request)->department_id)->orderBy('code')->get(),
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\SavedProcurementSearches;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
final class SavedProcurementSearchController extends Controller
|
||||
{
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
return $this->change($request, 'save');
|
||||
}
|
||||
|
||||
public function update(Request $request, int $search): RedirectResponse
|
||||
{
|
||||
return $this->change($request, 'save', $search);
|
||||
}
|
||||
|
||||
public function archive(Request $request, int $search): RedirectResponse
|
||||
{
|
||||
return $this->change($request, 'archive', $search);
|
||||
}
|
||||
|
||||
public function restore(Request $request, int $search): RedirectResponse
|
||||
{
|
||||
return $this->change($request, 'restore', $search);
|
||||
}
|
||||
|
||||
private function change(Request $request, string $action, ?int $id = null): RedirectResponse
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$query = $request->validate(['q' => 'nullable|string|max:100']);
|
||||
app(SavedProcurementSearches::class)->command($actor, $action, $id, $request->all());
|
||||
|
||||
return to_route('procurement.search', ['q' => $query['q'] ?? '']);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
* @property int|null $spare_part_id
|
||||
* @property int|null $catalogue_entry_id
|
||||
* @property array<string,mixed>|null $catalogue_snapshot
|
||||
* @property array<string,mixed>|null $category_context
|
||||
*/
|
||||
class RequisitionItem extends Model
|
||||
{
|
||||
@@ -25,6 +26,6 @@ class RequisitionItem extends Model
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['quantity' => 'decimal:3', 'tax_rate' => 'decimal:2', 'catalogue_entry_id' => 'integer', 'catalogue_snapshot' => 'array'];
|
||||
return ['quantity' => 'decimal:3', 'tax_rate' => 'decimal:2', 'catalogue_entry_id' => 'integer', 'catalogue_snapshot' => 'array', 'category_context' => 'array'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Services\AdministrativeGeography;
|
||||
use App\Services\BudgetDistributionArtifact;
|
||||
use App\Services\FinanceBundle;
|
||||
use App\Services\ReplenishmentRun;
|
||||
use Carbon\CarbonImmutable;
|
||||
@@ -22,6 +23,10 @@ class AppServiceProvider extends ServiceProvider
|
||||
$this->app->scoped(AdministrativeGeography::class);
|
||||
require_once base_path('packages/purchasing/bootstrap.php');
|
||||
$package = config('common-budget.path');
|
||||
if (config('budget-distributions.enabled') === true) {
|
||||
BudgetDistributionArtifact::verify($package,
|
||||
config('budget-distributions.artifact_manifest'), config('budget-distributions.artifact_manifest_sha256'));
|
||||
}
|
||||
require_once $package.'/bootstrap.php';
|
||||
FinanceBundle::configure();
|
||||
$payables = config('common-payables.path');
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
/** Verify the separately selected release before any of its executable PHP is loaded. */
|
||||
final class BudgetDistributionArtifact
|
||||
{
|
||||
private const FILES = ['bootstrap.php', 'src/BudgetContext.php', 'src/BudgetFailure.php', 'src/BudgetControl.php', 'src/BudgetDistributionPlan.php', 'src/BudgetDistributions.php', 'README.md'];
|
||||
|
||||
public static function verify(mixed $directory, mixed $manifest, mixed $pin): void
|
||||
{
|
||||
if (! is_string($directory) || ! is_string($manifest) || ! is_string($pin)
|
||||
|| ! preg_match('/^[a-f0-9]{64}$/D', $pin) || is_link($directory) || is_link($manifest)) {
|
||||
throw new \LogicException('BUDGET_DISTRIBUTION_ARTIFACT_CONFIGURATION');
|
||||
}
|
||||
$root = realpath($directory);
|
||||
$bytes = is_file($manifest) ? file_get_contents($manifest) : false;
|
||||
if ($root === false || ! is_string($bytes) || ! hash_equals($pin, hash('sha256', $bytes))) {
|
||||
throw new \LogicException('BUDGET_DISTRIBUTION_MANIFEST_MISMATCH');
|
||||
}
|
||||
$data = json_decode($bytes, true, 32, JSON_THROW_ON_ERROR);
|
||||
if (! is_array($data) || ! isset($data['files']) || ! is_array($data['files'])
|
||||
|| array_keys($data['files']) !== self::FILES) {
|
||||
throw new \LogicException('BUDGET_DISTRIBUTION_INVENTORY_MISMATCH');
|
||||
}
|
||||
foreach (self::FILES as $file) {
|
||||
$path = $root.'/'.$file;
|
||||
$expected = $data['files'][$file];
|
||||
$resolved = realpath($path);
|
||||
$actual = is_file($path) ? hash_file('sha256', $path) : false;
|
||||
if (! is_string($expected) || ! preg_match('/^[a-f0-9]{64}$/D', $expected)
|
||||
|| $resolved === false || ! str_starts_with(str_replace('\\', '/', $resolved), str_replace('\\', '/', $root).'/')
|
||||
|| is_link($path) || ! is_string($actual) || ! hash_equals($expected, $actual)) {
|
||||
throw new \LogicException('BUDGET_DISTRIBUTION_FILE_MISMATCH:'.$file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** One schema definition for guarded QA and explicitly authorised pilot installation. */
|
||||
final class BudgetDistributionSchema
|
||||
{
|
||||
public static function install(): void
|
||||
{
|
||||
$db = DB::connection();
|
||||
$db->transaction(function () use ($db): void {
|
||||
$schema = $db->getSchemaBuilder();
|
||||
$schema->table('requisitions', fn (Blueprint $table) => $table->json('budget_distribution_preparation')->nullable());
|
||||
$schema->create('budget_distributions', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('requisition_id')->unique()->constrained()->restrictOnDelete();
|
||||
$table->string('phase');
|
||||
$table->json('snapshot');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamps();
|
||||
});
|
||||
$schema->create('budget_distribution_events', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
|
||||
$table->string('kind', 50);
|
||||
$table->uuid('operation_key');
|
||||
$table->string('payload_hash', 64);
|
||||
$table->json('result');
|
||||
$table->json('snapshot');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['tenant_id', 'operation_key']);
|
||||
$table->unique(['distribution_id', 'kind']);
|
||||
});
|
||||
$schema->create('budget_distribution_entries', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
|
||||
$table->string('allocation_key', 120);
|
||||
$table->foreignId('budget_id')->constrained('budgets')->restrictOnDelete();
|
||||
$table->string('kind', 50);
|
||||
$table->bigInteger('reserved_minor');
|
||||
$table->bigInteger('committed_minor');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['distribution_id', 'allocation_key', 'kind']);
|
||||
});
|
||||
$schema->create('budget_distribution_consumptions', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
|
||||
$table->string('allocation_key', 120);
|
||||
$table->foreignId('budget_id')->constrained('budgets')->restrictOnDelete();
|
||||
$table->foreignId('invoice_id')->constrained('invoices')->restrictOnDelete();
|
||||
$table->bigInteger('amount_minor');
|
||||
$table->bigInteger('subtotal_minor');
|
||||
$table->bigInteger('total_minor');
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['invoice_id', 'allocation_key']);
|
||||
});
|
||||
if ($db->getDriverName() === 'pgsql') {
|
||||
$db->unprepared("CREATE OR REPLACE FUNCTION sgc_distribution_history_guard() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RAISE EXCEPTION ''Distribution history is append only''; END'");
|
||||
foreach (['budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions'] as $table) {
|
||||
$db->statement('CREATE TRIGGER distribution_history_guard BEFORE UPDATE OR DELETE ON '.$table.' FOR EACH ROW EXECUTE FUNCTION sgc_distribution_history_guard()');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,23 @@ final class CommonBudget
|
||||
{
|
||||
public const DISTRIBUTIONS_CONTRACT = 'COMMON-BUDGET-DISTRIBUTION-QA-v1';
|
||||
|
||||
public const ORDER_PARTS_CONTRACT = 'COMMON-BUDGET-ORDER-PARTS-QA-v1';
|
||||
|
||||
public function for(User $user): BudgetControl
|
||||
{
|
||||
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null, 403);
|
||||
$runtime = new \ReflectionClass(BudgetControl::class);
|
||||
$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,
|
||||
'Estrutura de ordens parciais incompleta; saldo não presumido.');
|
||||
if (! $runtime->hasConstant('ORDER_PARTS_VERSION') || $runtime->getConstant('ORDER_PARTS_VERSION') !== self::ORDER_PARTS_CONTRACT
|
||||
|| ! $runtime->hasMethod('commitOrderParts') || ! $runtime->hasMethod('consumeOrderParts')) {
|
||||
foreach ($orderPresent as $table) {
|
||||
abort_if(DB::table($table)->where('tenant_id', $user->tenant_id)->exists(), 503,
|
||||
'Existem efeitos de ordens parciais; preserve a composição compatível antes de consultar saldos.');
|
||||
}
|
||||
}
|
||||
$distributionsCompatible = $runtime->hasMethod('recordDistribution') && $runtime->hasConstant('DISTRIBUTIONS_VERSION')
|
||||
&& $runtime->getConstant('DISTRIBUTIONS_VERSION') === self::DISTRIBUTIONS_CONTRACT;
|
||||
if (! $distributionsCompatible) {
|
||||
@@ -40,7 +53,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] : null);
|
||||
: (in_array($action, ['consume', 'consume.preview', 'distribution.amend'], true) ? [PurchasingRole::Finance]
|
||||
: (in_array($action, ['orders.commit', 'orders.cancel', 'orders.adopt'], true) ? [PurchasingRole::Procurement] : null));
|
||||
app(CurrentActor::class)->lock($user, $roles);
|
||||
},
|
||||
function (string $action, array $data, ?int $origin) use ($user): void {
|
||||
|
||||
@@ -49,7 +49,17 @@ class EquipmentWorkflow
|
||||
|
||||
public function basis(Requisition $requisition): string
|
||||
{
|
||||
return hash('sha256', json_encode([$requisition->only(['id', 'tenant_id', 'department_id', 'requester_id', 'priority', 'needed_by', 'justification', 'total_minor']), $requisition->items()->orderBy('id')->get()->toArray()], JSON_THROW_ON_ERROR));
|
||||
$items = $requisition->items()->orderBy('id')->get()->map(function ($item) {
|
||||
$row = $item->toArray();
|
||||
// Adding an empty optional classification must not invalidate an accepted review.
|
||||
if (($row['category_context'] ?? null) === null) {
|
||||
unset($row['category_context']);
|
||||
}
|
||||
|
||||
return $row;
|
||||
})->all();
|
||||
|
||||
return hash('sha256', json_encode([$requisition->only(['id', 'tenant_id', 'department_id', 'requester_id', 'priority', 'needed_by', 'justification', 'total_minor']), $items], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function canReview(User $user, Requisition $requisition): bool
|
||||
|
||||
@@ -10,7 +10,6 @@ use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Brick\Math\RoundingMode;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -77,11 +76,10 @@ 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.
|
||||
$subtotal = fn (int $milli) => BigDecimal::of($milli)->multipliedBy($source->unit_price_minor)->dividedBy(1000, 0, RoundingMode::HalfUp)->toInt();
|
||||
$tax = fn (int $minor) => BigDecimal::of($minor)->multipliedBy((string) $source->tax_rate)->dividedBy(100, 0, RoundingMode::HalfUp)->toInt();
|
||||
$before = $subtotal((int) $previous);
|
||||
$after = $subtotal((int) $previous + $quantity);
|
||||
$lines[] = ['tenant_id' => $order->tenant_id, 'purchase_order_item_id' => $source->id, 'quantity_milli' => $quantity, 'subtotal_minor' => $after - $before, 'tax_minor' => $tax($after) - $tax($before), 'snapshot' => $source->only(['description', 'unit', 'unit_price_minor', 'tax_rate'])];
|
||||
$amounts = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, (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'])];
|
||||
}
|
||||
if ($lines === []) {
|
||||
$this->invalid('Indique pelo menos uma linha.');
|
||||
|
||||
@@ -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];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Brick\Math\BigDecimal;
|
||||
use Brick\Math\RoundingMode;
|
||||
|
||||
/** Native cumulative price/VAT calculation shared by order preparation and invoice matching. */
|
||||
final class PurchaseLineAmounts
|
||||
{
|
||||
/** @return array{subtotal_minor:int,tax_minor:int,total_minor:int} */
|
||||
public static function portion(int $unitPrice, string $taxRate, int $beforeMilli, int $quantityMilli): array
|
||||
{
|
||||
if ($unitPrice < 0 || $beforeMilli < 0 || $quantityMilli < 1 || $beforeMilli > PHP_INT_MAX - $quantityMilli
|
||||
|| BigDecimal::of($taxRate)->isNegative()) {
|
||||
throw new \InvalidArgumentException('Base cumulativa da linha inválida.');
|
||||
}
|
||||
$subtotal = fn (int $milli) => BigDecimal::of($milli)->multipliedBy($unitPrice)->dividedBy(1000, 0, RoundingMode::HalfUp)->toInt();
|
||||
$tax = fn (int $minor) => BigDecimal::of($minor)->multipliedBy($taxRate)->dividedBy(100, 0, RoundingMode::HalfUp)->toInt();
|
||||
$before = $subtotal($beforeMilli);
|
||||
$after = $subtotal($beforeMilli + $quantityMilli);
|
||||
$net = $after - $before;
|
||||
$vat = $tax($after) - $tax($before);
|
||||
|
||||
return ['subtotal_minor' => $net, 'tax_minor' => $vat, 'total_minor' => $net + $vat];
|
||||
}
|
||||
}
|
||||
@@ -209,6 +209,26 @@ class PurchaseWorkflow
|
||||
});
|
||||
}
|
||||
|
||||
/** Read-only preflight for optional partial-order preparation; no approval or issuance is inferred. */
|
||||
public function approvedSource(User $user, PurchaseAward $award): Quotation
|
||||
{
|
||||
abort_unless(DB::transactionLevel() > 0 && auth()->id() === $user->id, 403);
|
||||
$this->guard->lockCompany($user);
|
||||
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Procurement]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
$requisition = Requisition::query()->visibleTo($user)->lockForUpdate()->findOrFail($award->requisition_id);
|
||||
$award = PurchaseAward::query()->where('requisition_id', $requisition->id)->lockForUpdate()->findOrFail($award->id);
|
||||
abort_unless($award->status === 'approved', 409, 'Conclua as aprovações da adjudicação.');
|
||||
$this->assertNoPendingCancellation($award);
|
||||
$quote = $this->currentBasis($user, $award, $requisition);
|
||||
$this->validateFinalApprovals($award, $requisition);
|
||||
if ($award->delivery_date < today()) {
|
||||
throw ValidationException::withMessages(['delivery_date' => 'A data de entrega aprovada já passou.']);
|
||||
}
|
||||
|
||||
return $quote;
|
||||
}
|
||||
|
||||
private function currentBasis(User $user, PurchaseAward $award, Requisition $requisition): Quotation
|
||||
{
|
||||
$rules = $this->rules($requisition);
|
||||
|
||||
@@ -36,11 +36,13 @@ class RequisitionApprovalLevels
|
||||
/** @return array<string,mixed> */
|
||||
public function rules(User $actor): array
|
||||
{
|
||||
return ['enabled' => 'required|boolean', 'levels' => 'present|array|list|max:5', 'levels.*' => 'array:name,profile_ids,scope,min_amount,categories,cost_center_ids',
|
||||
return ['enabled' => 'required|boolean', 'levels' => 'present|array|list|max:5', 'levels.*' => 'array:name,profile_ids,scope,min_amount,categories,procurement_categories,cost_center_ids',
|
||||
'levels.*.name' => 'required|string|max:120', 'levels.*.profile_ids' => 'required|array|list|min:1|max:50',
|
||||
'levels.*.profile_ids.*' => ['required', 'integer', Rule::exists('organization_profiles', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||
'levels.*.scope' => 'required|in:department,company', 'levels.*.min_amount' => ['present', 'nullable', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'],
|
||||
'levels.*.categories' => 'present|array|list|max:50', 'levels.*.categories.*' => 'required|string|max:100',
|
||||
'levels.*.procurement_categories' => app(RequisitionCategories::class)->available() ? 'nullable|array|list|max:5' : 'prohibited',
|
||||
'levels.*.procurement_categories.*' => ['required', Rule::in(array_keys(RequisitionCategories::LABELS))],
|
||||
'levels.*.cost_center_ids' => 'present|array|list|max:100',
|
||||
'levels.*.cost_center_ids.*' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||
'reason' => 'required|string|min:10|max:4000'];
|
||||
@@ -70,6 +72,7 @@ class RequisitionApprovalLevels
|
||||
'quorum' => 'one_eligible', 'levels' => array_map(fn ($level) => ['name' => $level['name'], 'profile_ids' => array_values(array_unique(array_map('intval', $level['profile_ids']))), 'scope' => $level['scope'],
|
||||
'min_minor' => $level['min_amount'] === null ? null : BigDecimal::of($level['min_amount'])->multipliedBy(100)->toInt(),
|
||||
'categories' => array_values(array_unique(array_map(fn ($name) => mb_strtolower(trim($name)), $level['categories']))),
|
||||
'procurement_categories' => array_values(array_unique($level['procurement_categories'] ?? [])),
|
||||
'cost_center_ids' => array_values(array_unique(array_map('intval', $level['cost_center_ids'])))], $data['levels'])];
|
||||
}
|
||||
|
||||
@@ -81,6 +84,7 @@ class RequisitionApprovalLevels
|
||||
'levels.*.profile_ids.required' => 'Escolha pelo menos um perfil elegível por nível.',
|
||||
'levels.*.profile_ids.*.exists' => 'Escolha perfis da empresa.', 'levels.*.cost_center_ids.*.exists' => 'Escolha centros de custo da empresa.',
|
||||
'levels.*.min_amount.regex' => 'Use um valor MZN não negativo com até duas casas decimais.',
|
||||
'levels.*.procurement_categories.prohibited' => 'A classificação RQ-01 ainda não está instalada. Preserve o plano e conclua a instalação antes de usar esta condição.',
|
||||
'reason.required' => 'Indique o motivo da alteração.', 'reason.min' => 'Descreva o motivo com pelo menos dez caracteres.'];
|
||||
}
|
||||
|
||||
@@ -98,14 +102,21 @@ class RequisitionApprovalLevels
|
||||
throw ValidationException::withMessages(['submission' => 'Complete os montantes antes de determinar os níveis de aprovação.']);
|
||||
}
|
||||
$categories = array_map(fn ($name) => mb_strtolower(trim($name)), $request->items->pluck('category')->all());
|
||||
$groups = $request->items->map(fn ($item) => $item->category_context['category'] ?? null)->filter()->all();
|
||||
$selected = [];
|
||||
foreach ($plan['levels'] as $index => $level) {
|
||||
$groupFilter = $level['procurement_categories'] ?? [];
|
||||
abort_if($groupFilter !== [] && ! app(RequisitionCategories::class)->available(), 503,
|
||||
'O plano exige a classificação RQ-01. Reponha a composição compatível antes de submeter; os níveis não serão ignorados.');
|
||||
if ($level['min_minor'] !== null && $amount < $level['min_minor']) {
|
||||
continue;
|
||||
}
|
||||
if ($level['categories'] !== [] && array_intersect($categories, $level['categories']) === []) {
|
||||
continue;
|
||||
}
|
||||
if ($groupFilter !== [] && array_intersect($groups, $groupFilter) === []) {
|
||||
continue;
|
||||
}
|
||||
if ($level['cost_center_ids'] !== [] && ! in_array($request->cost_center_id, $level['cost_center_ids'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -26,9 +26,15 @@ class RequisitionBudgetDistributions
|
||||
$isolated = DB::getDriverName() === 'sqlite' ? DB::connection()->getDatabaseName() === ':memory:'
|
||||
: DB::getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName());
|
||||
|
||||
if (config('budget-distributions.qa_enabled') !== true || ! app()->environment('testing') || ! $isolated) {
|
||||
$deployment = config('budget-distributions.enabled') === true;
|
||||
$qa = config('budget-distributions.qa_enabled') === true && app()->environment('testing') && $isolated;
|
||||
if (! $deployment && ! $qa) {
|
||||
return false;
|
||||
}
|
||||
if ($deployment) {
|
||||
BudgetDistributionArtifact::verify(config('common-budget.path'),
|
||||
config('budget-distributions.artifact_manifest'), config('budget-distributions.artifact_manifest_sha256'));
|
||||
}
|
||||
foreach (['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions'] as $table) {
|
||||
if (! Schema::hasTable($table)) {
|
||||
return false;
|
||||
@@ -36,6 +42,11 @@ class RequisitionBudgetDistributions
|
||||
}
|
||||
$runtime = new \ReflectionClass(BudgetControl::class);
|
||||
|
||||
$runtimeFile = $runtime->getFileName();
|
||||
if ($deployment && (! is_string($runtimeFile) || realpath($runtimeFile) !== realpath(config('common-budget.path').'/src/BudgetControl.php'))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Schema::hasColumn('requisitions', 'budget_distribution_preparation')
|
||||
&& $runtime->hasMethod('recordDistribution') && $runtime->hasMethod('consumeDistribution') && $runtime->hasMethod('amendDistribution')
|
||||
&& $runtime->hasMethod('checkDistributionConsumption')
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\RequisitionItem;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** RQ-01 classification, distinct from the original catalogue category and financial purchase type. */
|
||||
final class RequisitionCategories
|
||||
{
|
||||
public const LABELS = [
|
||||
'production_input' => 'Insumos de produção',
|
||||
'spare_part' => 'Peças sobressalentes',
|
||||
'capital_equipment' => 'Maquinaria',
|
||||
'office_equipment' => 'Equipamento de escritório',
|
||||
'other' => 'Outra categoria',
|
||||
];
|
||||
|
||||
public function available(): bool
|
||||
{
|
||||
return Schema::hasColumn('requisition_items', 'category_context');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $line */
|
||||
public function incomplete(array $line): bool
|
||||
{
|
||||
$category = $line['procurement_category'] ?? null;
|
||||
$type = $line['purchase_type'] ?? null;
|
||||
|
||||
return (empty($category) && trim($line['category_reason'] ?? '') !== '')
|
||||
|| ($category === 'production_input' && empty($line['catalogue_entry_id']))
|
||||
|| ($category === 'spare_part' && ((empty($line['catalogue_entry_id']) && $type !== 'spare_part') || empty($line['spare_part_id']) || empty($line['equipment_id'])))
|
||||
|| ($category === 'capital_equipment' && $type !== 'equipment')
|
||||
|| (($category === 'capital_equipment' || (in_array($category, ['office_equipment', 'other'], true) && empty($line['catalogue_entry_id'])))
|
||||
&& mb_strlen(trim($line['category_reason'] ?? '')) < 10);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $line
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
public function context(array $line, int $index, ?RequisitionItem $previous = null): ?array
|
||||
{
|
||||
if (! array_key_exists('procurement_category', $line) && ! array_key_exists('category_reason', $line) && $previous?->category_context !== null) {
|
||||
$line['procurement_category'] = $previous->category_context['category'];
|
||||
$line['category_reason'] = $previous->category_context['reason'];
|
||||
}
|
||||
$category = $line['procurement_category'] ?? null;
|
||||
$reason = trim($line['category_reason'] ?? '');
|
||||
if (empty($category) && $reason === '') {
|
||||
// Accepted legacy lines remain unclassified, never inferred from their description.
|
||||
return null;
|
||||
}
|
||||
if (! $this->available()) {
|
||||
abort(503, 'A classificação RQ-01 ainda não está instalada.');
|
||||
}
|
||||
$field = 'items.'.$index.'.procurement_category';
|
||||
if (! is_string($category) || ! array_key_exists($category, self::LABELS)) {
|
||||
throw ValidationException::withMessages([$field => 'Seleccione a categoria da necessidade.']);
|
||||
}
|
||||
$type = $line['purchase_type'];
|
||||
if ($category === 'production_input' && (empty($line['catalogue_snapshot']['stock_item_id'])
|
||||
|| empty($line['catalogue_snapshot']['code']) || ! in_array($type, ['consumable', 'other'], true))) {
|
||||
throw ValidationException::withMessages([$field => 'Insumos de produção: seleccione um material de stock no catálogo publicado.']);
|
||||
}
|
||||
if ($category === 'spare_part' && ($type !== 'spare_part' || empty($line['spare_part_id']) || empty($line['equipment_id']))) {
|
||||
throw ValidationException::withMessages([$field => 'Peças sobressalentes: escolha o tipo Peça e a associação ao equipamento.']);
|
||||
}
|
||||
if ($category === 'capital_equipment' && $type !== 'equipment') {
|
||||
throw ValidationException::withMessages([$field => 'Maquinaria: escolha o tipo Equipamento para conservar a validação técnica e o orçamento de investimento.']);
|
||||
}
|
||||
if (($category === 'capital_equipment' || (in_array($category, ['office_equipment', 'other'], true) && empty($line['catalogue_entry_id'])))
|
||||
&& mb_strlen($reason) < 10) {
|
||||
throw ValidationException::withMessages(['items.'.$index.'.category_reason' => $category === 'capital_equipment'
|
||||
? 'Descreva a justificação do investimento com pelo menos 10 caracteres.'
|
||||
: 'Justifique o uso de texto livre, sem artigo do catálogo, com pelo menos 10 caracteres.']);
|
||||
}
|
||||
|
||||
return ['version' => 1, 'category' => $category, 'reason' => $reason === '' ? null : $reason];
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,9 @@ class RequisitionDraftInput
|
||||
'items.*.catalogue_entry_id' => 'nullable|integer|min:1',
|
||||
'items.*.catalogue_version' => 'nullable|required_with:items.*.catalogue_entry_id|integer|min:1',
|
||||
'items.*.source_line_id' => 'nullable|integer|min:1',
|
||||
'items.*.procurement_category' => $this->categoriesAvailable()
|
||||
? ['nullable', Rule::in(array_keys(RequisitionCategories::LABELS))] : ['prohibited'],
|
||||
'items.*.category_reason' => $this->categoriesAvailable() ? 'nullable|string|max:2000' : 'prohibited',
|
||||
'items.*.description' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:255'],
|
||||
'items.*.category' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:100'],
|
||||
'items.*.purchase_type' => ['required_without:items.*.catalogue_entry_id', Rule::in(['consumable', 'service', 'other', 'equipment', 'spare_part'])],
|
||||
@@ -42,6 +45,11 @@ class RequisitionDraftInput
|
||||
];
|
||||
}
|
||||
|
||||
private function categoriesAvailable(): bool
|
||||
{
|
||||
return app(RequisitionCategories::class)->available();
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function rules(User $user): array
|
||||
{
|
||||
@@ -64,7 +72,16 @@ class RequisitionDraftInput
|
||||
/** @param array<string,mixed> $data */
|
||||
public function complete(User $user, array $data): bool
|
||||
{
|
||||
return Validator::make($data, $this->completeRules($user))->passes();
|
||||
if (! Validator::make($data, $this->completeRules($user))->passes() || ! is_array($data['items'] ?? null)) {
|
||||
return false;
|
||||
}
|
||||
foreach ($data['items'] as $line) {
|
||||
if (! is_array($line) || app(RequisitionCategories::class)->incomplete($line)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data
|
||||
|
||||
@@ -106,7 +106,7 @@ class RequisitionWorkflow
|
||||
/** @var list<array{description: string, category: string, purchase_type: string, quantity: string, unit: string, unit_price: string, tax_rate: string, equipment_id?: int, spare_part_id?: int, production_area?: string, downtime_started_at?: string|null}> $lines */
|
||||
$lines = $data['items'];
|
||||
$oldLines = $existing ? $requisition->items()->get()->keyBy('id')->all() : [];
|
||||
foreach ($lines as $line) {
|
||||
foreach ($lines as $index => $line) {
|
||||
$line = app(RequisitionCatalogue::class)->line($user, $line, $oldLines);
|
||||
app(EquipmentWorkflow::class)->line($line, (int) $user->department_id, $data['priority']);
|
||||
$calculation = InternalRequisitions::line($line['quantity'], $line['unit_price'], $line['tax_rate']);
|
||||
@@ -115,6 +115,7 @@ class RequisitionWorkflow
|
||||
$lineTax = $calculation['tax_minor'];
|
||||
$items[] = [
|
||||
'tenant_id' => $user->tenant_id,
|
||||
...(app(RequisitionCategories::class)->available() ? ['category_context' => app(RequisitionCategories::class)->context($line, $index, $oldLines[$line['source_line_id'] ?? 0] ?? null)] : []),
|
||||
...(! empty($line['catalogue_entry_id']) ? ['catalogue_entry_id' => $line['catalogue_entry_id'], 'catalogue_snapshot' => $line['catalogue_snapshot']] : []),
|
||||
'description' => $line['description'], 'category' => $line['category'],
|
||||
'purchase_type' => $line['purchase_type'], 'quantity' => $line['quantity'], 'unit' => $line['unit'],
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Private criteria only. Opening a saved query always invokes the native live search. */
|
||||
final class SavedProcurementSearches
|
||||
{
|
||||
// Technical UI capacity, independent from company approval policies or financial limits.
|
||||
public const MAX_ACTIVE = 50;
|
||||
|
||||
public function available(): bool
|
||||
{
|
||||
return Schema::hasTable('procurement_saved_searches');
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public function read(User $actor): ?array
|
||||
{
|
||||
if (! $this->available()) {
|
||||
return null;
|
||||
}
|
||||
abort_unless(auth()->id() === $actor->id, 403);
|
||||
$query = DB::table('procurement_saved_searches')->where('tenant_id', $actor->tenant_id)->where('user_id', $actor->id);
|
||||
$fields = ['id', 'name', 'term', 'version'];
|
||||
$project = fn ($row) => ['id' => $row->id, 'name' => $row->name, 'term' => $row->term, 'version' => $row->version,
|
||||
'href' => '/compras/pesquisa?q='.rawurlencode($row->term)];
|
||||
|
||||
return ['max_active' => self::MAX_ACTIVE, 'active' => (clone $query)->whereNull('archived_at')->orderBy('name')->get($fields)->map($project),
|
||||
'archived' => (clone $query)->whereNotNull('archived_at')->latest('archived_at')->paginate(10, $fields, 'archived_page')->withQueryString()->through($project)];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function command(User $actor, string $action, ?int $id, array $input): void
|
||||
{
|
||||
abort_unless($this->available(), 503);
|
||||
DB::transaction(function () use ($actor, $action, $id, $input): void {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
$access = app(OrganizationAccess::class);
|
||||
abort_unless(! $access->maintenanceOnly($actor) && $access->permissions($actor) !== [], 403);
|
||||
abort_unless(in_array($action, ['save', 'archive', 'restore'], true), 422);
|
||||
$data = Validator::make($input, [
|
||||
'version' => $id === null ? 'nullable|integer|min:1' : 'required|integer|min:1',
|
||||
'name' => $action === 'save' ? 'required|string|max:100' : 'prohibited',
|
||||
'term' => $action === 'save' ? 'required|string|min:2|max:100' : 'prohibited',
|
||||
])->validate();
|
||||
$query = DB::table('procurement_saved_searches')->where('tenant_id', $actor->tenant_id)->where('user_id', $actor->id);
|
||||
$record = $id === null ? null : (clone $query)->where('id', $id)->lockForUpdate()->first();
|
||||
abort_if($id !== null && $record === null, 404);
|
||||
abort_if($record !== null && $record->version !== (int) $data['version'], 409, 'A pesquisa mudou. Actualize a página antes de voltar a editar.');
|
||||
$values = [];
|
||||
if ($action === 'save') {
|
||||
$name = trim($data['name']);
|
||||
$term = trim($data['term']);
|
||||
if ($name === '' || mb_strlen($term) < 2) {
|
||||
throw ValidationException::withMessages(['name' => 'Indique um nome e pelo menos dois caracteres de pesquisa.']);
|
||||
}
|
||||
$values = ['name' => $name, 'term' => $term];
|
||||
} else {
|
||||
abort_unless($record !== null, 404);
|
||||
abort_if(($action === 'archive') === ($record->archived_at !== null), 409);
|
||||
}
|
||||
$active = $action !== 'archive';
|
||||
$nameKey = $active ? hash('sha256', mb_strtolower($values['name'] ?? $record->name)) : null;
|
||||
if ($active) {
|
||||
$duplicate = (clone $query)->where('active_name_key', $nameKey)->when($id !== null, fn ($q) => $q->where('id', '!=', $id))->first();
|
||||
if ($duplicate !== null) {
|
||||
if ($id === null && $duplicate->term === $values['term']) {
|
||||
return; // A repeated create has one private preference, never duplicate results.
|
||||
}
|
||||
throw ValidationException::withMessages(['name' => 'Já existe uma pesquisa activa com este nome. Escolha outro nome.']);
|
||||
}
|
||||
if (($record === null || $record->archived_at !== null) && (clone $query)->whereNull('archived_at')->count() >= self::MAX_ACTIVE) {
|
||||
throw ValidationException::withMessages(['name' => 'Pode manter até '.self::MAX_ACTIVE.' pesquisas activas. Arquive uma antes de acrescentar outra.']);
|
||||
}
|
||||
}
|
||||
$values += ['active_name_key' => $nameKey, 'archived_at' => $active ? null : now(), 'updated_at' => now()];
|
||||
if ($record === null) {
|
||||
$query->insert([...$values, 'tenant_id' => $actor->tenant_id, 'user_id' => $actor->id, 'version' => 1, 'created_at' => now()]);
|
||||
} else {
|
||||
$query->where('id', $id)->update([...$values, 'version' => $record->version + 1]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user