@@ -45,6 +45,20 @@ final class CapitalRegister
|
||||
->when($actor->departmentScoped(), fn ($q) => $q->where('data->department_id', $actor->department_id));
|
||||
}
|
||||
|
||||
/** Native read scope for cross-module metadata search; never locks or changes the register.
|
||||
* @return Builder<SupplyRecord>|null
|
||||
*/
|
||||
public function searchQuery(User $actor): ?Builder
|
||||
{
|
||||
if (! $this->ready() || auth()->id() !== $actor->id || $actor->tenant_id === null
|
||||
|| app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||
|| ! $actor->hasFunctions(['admin', 'warehouse', 'procurement', 'finance', 'department_head'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->visible($actor)->where('tenant_id', $actor->tenant_id);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, ?string $historyKey = null): array
|
||||
{
|
||||
|
||||
@@ -7,8 +7,27 @@ use App\Models\SupplyRecord;
|
||||
/** Documentary transcription of a specific supplied edition, never a consolidated/current tariff claim. */
|
||||
final class ImportLegalReferenceDrafts
|
||||
{
|
||||
public const VAT_EDITION_SHA256 = '0c13f4b03dadea7f2dfe30694650078fa7b9de00ef84cb47389422d23a5271cd';
|
||||
|
||||
public const EDITION_SHA256 = 'a0110696253715567af39c159a21bacfebc32f944fa43a4efd18070d36959e50';
|
||||
|
||||
public const ICE_EDITION_SHA256 = '9b10862f60ed87ec42d4f42f3cae42e17580eb761e4b7673bd8d8225691c4de4';
|
||||
|
||||
/** Law 7/2025, second supplement, page 2180-(22); only the explicitly tabulated 2026/2027 positions. */
|
||||
private const ICE_ROWS = [
|
||||
['8702.10.10', 'Veículos para dez ou mais pessoas, diesel, tipo Jeep, tracção às quatro rodas, novos ou usados até 7 anos', '20'],
|
||||
['8702.10.20', 'Veículos para dez ou mais pessoas, diesel, tipo Jeep, tracção às quatro rodas, usados há mais de 7 anos', '25'],
|
||||
['8702.20.00', 'Veículos para dez ou mais pessoas, propulsão simultânea diesel e eléctrica', '20'],
|
||||
['8702.30.00', 'Veículos para dez ou mais pessoas, propulsão simultânea por ignição por faísca e eléctrica', '20'],
|
||||
['8702.40.10', 'Autocarros unicamente eléctricos para transporte de 40 ou mais pessoas', '0'],
|
||||
['8702.40.20', 'Outros veículos unicamente eléctricos para transporte de dez ou mais pessoas', '0'],
|
||||
['8702.90.10', 'Outros veículos para dez ou mais pessoas, tracção às quatro rodas, novos ou usados até 7 anos', '20'],
|
||||
['8702.90.20', 'Outros veículos para dez ou mais pessoas, tracção às quatro rodas, usados há mais de 7 anos', '25'],
|
||||
['8702.90.90', 'Outros veículos para transporte de dez ou mais pessoas', '0'],
|
||||
['8703.80.10', 'Automóveis de passageiros unicamente eléctricos, bateria até 62 kWh', '5'],
|
||||
['8703.80.20', 'Outros automóveis de passageiros unicamente eléctricos', '15'],
|
||||
];
|
||||
|
||||
/** Annex to Law 8/2025, pages 2180-(4) to (7): exact codes and general rates, never preferential eligibility. */
|
||||
private const ROWS = [
|
||||
['3506.91.10', 'Adesivos à base de polímeros ou borracha', '20'],
|
||||
@@ -64,6 +83,16 @@ final class ImportLegalReferenceDrafts
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function forSource(SupplyRecord $source): array
|
||||
{
|
||||
if ($source->kind === 'import_legal_source' && ($source->snapshot['evidence']['sha256'] ?? null) === self::VAT_EDITION_SHA256) {
|
||||
app(ImportEvidence::class)->bytes($source);
|
||||
|
||||
return $this->vatDrafts($source);
|
||||
}
|
||||
if ($source->kind === 'import_legal_source' && ($source->snapshot['evidence']['sha256'] ?? null) === self::ICE_EDITION_SHA256) {
|
||||
app(ImportEvidence::class)->bytes($source);
|
||||
|
||||
return $this->iceDrafts($source);
|
||||
}
|
||||
if ($source->kind !== 'import_legal_source' || ($source->snapshot['evidence']['sha256'] ?? null) !== self::EDITION_SHA256) {
|
||||
return [];
|
||||
}
|
||||
@@ -92,4 +121,54 @@ final class ImportLegalReferenceDrafts
|
||||
|
||||
return $drafts;
|
||||
}
|
||||
|
||||
/**
|
||||
* This edition establishes a rate; it supplies neither an item classification nor an import valuation.
|
||||
*
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
private function vatDrafts(SupplyRecord $source): array
|
||||
{
|
||||
$citation = 'Lei 22/2022, de 28 de Dezembro, artigo 1 (artigo 17, n.º 1, do CIVA), BR I Série 250, página 2238; entrada em vigor em 1 de Janeiro de 2023: artigo 6, página 2239.';
|
||||
|
||||
return [['source_id' => $source->id, 'source_sha256' => self::VAT_EDITION_SHA256,
|
||||
'code' => 'IVA_ART17', 'match_code' => '', 'suggested_code' => '',
|
||||
'label' => 'IVA — taxa normal; completar código e base',
|
||||
'description' => 'IVA — taxa normal do artigo 17; completar código e base',
|
||||
'rate_percent' => '16', 'rate_label' => '16% — base por documentar',
|
||||
'documentary_class' => null, 'title' => 'IVA documental — taxa normal; completar âmbito',
|
||||
'official_reference' => $source->data['official_reference'], 'official_url' => $source->data['official_url'] ?? null,
|
||||
'citation' => $citation, 'valid_from' => '2023-01-01', 'valid_until' => null,
|
||||
'obligations' => 'Esta proposta transcreve apenas a taxa normal do artigo 17, n.º 1, na redacção da Lei 22/2022. Complete expressamente os códigos, incidência, regime, período e base da importação antes de gravar. O artigo 16 do CIVA e as condições de isenção exigem conferência nas respectivas fontes; não usar o preço dos bens como base por inferência. Alterações posteriores, incluindo as Leis 3/2025 e 10/2025, devem ser consideradas no contexto aplicável. Não determina dedutibilidade, taxa reduzida ou outras imposições.',
|
||||
'charges' => [['key' => 'vat_normal_documentary', 'kind' => 'vat', 'label' => 'IVA — taxa normal documental',
|
||||
'method' => 'ad_valorem', 'rate_percent' => '16', 'specific_minor' => null, 'quantity_unit' => null,
|
||||
'basis_reference' => ''],
|
||||
...array_map(fn (array $charge) => ['key' => $charge[0], 'kind' => $charge[1], 'label' => $charge[2],
|
||||
'method' => 'unknown', 'rate_percent' => null, 'specific_minor' => null, 'quantity_unit' => null,
|
||||
'basis_reference' => 'Não determinado por esta transcrição da taxa normal de IVA: conferir a fonte, a incidência, o regime e a base.'],
|
||||
[['duty_pending', 'duty', 'Direitos aduaneiros — por determinar'], ['ice_pending', 'ice', 'ICE — por determinar'], ['other_pending', 'other', 'Outras imposições — por conferir']])]]];
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
private function iceDrafts(SupplyRecord $source): array
|
||||
{
|
||||
return array_values(array_map(function (array $row) use ($source) {
|
||||
[$code, $description, $rate] = $row;
|
||||
$citation = 'Lei 7/2025, de 29 de Dezembro, artigos 3 e 6 e anexo, BR I Série 248, 2.º suplemento, página 2180-(22), código '.$code.'; coluna 2026 e 2027.';
|
||||
$rateLabel = $rate === '0' ? 'ICE Livre — conforme anexo' : 'ICE '.$rate.'%';
|
||||
|
||||
return ['source_id' => $source->id, 'source_sha256' => self::ICE_EDITION_SHA256,
|
||||
'code' => $code, 'description' => $description, 'rate_percent' => $rate, 'rate_label' => $rateLabel,
|
||||
'documentary_class' => null, 'title' => 'ICE documental — '.$code,
|
||||
'official_reference' => $source->data['official_reference'], 'official_url' => $source->data['official_url'] ?? null,
|
||||
'citation' => $citation, 'valid_from' => '2026-01-01', 'valid_until' => '2027-12-31',
|
||||
'obligations' => 'Conferir a descrição completa, capacidade, propulsão, tracção e idade na página 2180-(22). '.($rate === '0' ? 'O anexo indica Livre para ICE nesta posição; o zero documental não significa isenção dos demais impostos. ' : '').'Este segundo suplemento declara sem efeito a publicação anterior da Lei 7/2025 no primeiro suplemento; não altera por inferência a Lei 8/2025. A proposta cobre apenas o ICE desta posição em 2026 e 2027, sem determinar direitos, IVA, origem preferencial, base ou outras imposições; não combinar fontes nem classificar mercadorias automaticamente.',
|
||||
'charges' => [['key' => 'ice_documentary', 'kind' => 'ice', 'label' => $rateLabel,
|
||||
'method' => 'ad_valorem', 'rate_percent' => $rate, 'specific_minor' => null, 'quantity_unit' => null, 'basis_reference' => $citation],
|
||||
...array_map(fn (array $charge) => ['key' => $charge[0], 'kind' => $charge[1], 'label' => $charge[2],
|
||||
'method' => 'unknown', 'rate_percent' => null, 'specific_minor' => null, 'quantity_unit' => null,
|
||||
'basis_reference' => 'Não determinado por este anexo de ICE: documentar incidência, regime, base e período na fonte aplicável.'],
|
||||
[['duty_pending', 'duty', 'Direitos aduaneiros — por determinar'], ['vat_pending', 'vat', 'IVA — por determinar'], ['other_pending', 'other', 'Outras imposições — por conferir']])]];
|
||||
}, self::ICE_ROWS));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Models\Requisition;
|
||||
use App\Models\RequisitionItem;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
@@ -16,6 +17,8 @@ use Illuminate\Validation\ValidationException;
|
||||
/** Documentary production/maintenance orders owned by Compras; no production scheduling or SGF writes. */
|
||||
final class OperationalOrders
|
||||
{
|
||||
private const REGISTRY_READERS = ['admin', 'procurement', 'requester', 'production_order_prepare', 'maintenance_order_prepare'];
|
||||
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
@@ -43,6 +46,26 @@ final class OperationalOrders
|
||||
return app(SupplyPlanning::class)->latest('op_order_policy')->first();
|
||||
}
|
||||
|
||||
/** @return Builder<SupplyRecord> */
|
||||
private function registryOrders(User $actor): Builder
|
||||
{
|
||||
return app(SupplyPlanning::class)->latest('op_order')->where('tenant_id', $actor->tenant_id)
|
||||
->when(! $actor->hasFunctions(['admin', 'procurement']), fn ($q) => $q->where('data->department_id', $actor->department_id));
|
||||
}
|
||||
|
||||
/** Current native registry scope for read-only cross-module search.
|
||||
* @return Builder<SupplyRecord>|null
|
||||
*/
|
||||
public function searchQuery(User $actor): ?Builder
|
||||
{
|
||||
if (! $this->ready() || auth()->id() !== $actor->id || $actor->tenant_id === null
|
||||
|| app(OrganizationAccess::class)->maintenanceOnly($actor) || ! $actor->hasFunctions(self::REGISTRY_READERS)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->registryOrders($actor);
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function types(User $actor, ?SupplyRecord $policy): array
|
||||
{
|
||||
@@ -57,15 +80,15 @@ final class OperationalOrders
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, ?Requisition $request = null): array
|
||||
public function workspace(User $actor, ?Requisition $request = null, ?int $selectedOrderId = null): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $request) {
|
||||
return DB::transaction(function () use ($actor, $request, $selectedOrderId) {
|
||||
$actor = $this->actor($actor);
|
||||
$policy = $this->policy();
|
||||
if ($request !== null) {
|
||||
$request = Requisition::query()->visibleTo($actor)->findOrFail($request->id);
|
||||
} else {
|
||||
abort_unless($actor->hasFunctions(['admin', 'procurement', 'requester', 'production_order_prepare', 'maintenance_order_prepare']), 403);
|
||||
abort_unless($actor->hasFunctions(self::REGISTRY_READERS), 403);
|
||||
}
|
||||
$canLink = $request !== null && $request->status === 'draft' && $request->requester_id === $actor->id
|
||||
&& app(OrganizationAccess::class)->canRequest($actor) && ! app(ConflictGuard::class)->participationBlocked($actor, $request);
|
||||
@@ -75,15 +98,19 @@ final class OperationalOrders
|
||||
$linkedIds[] = $link->data['order_id'];
|
||||
}
|
||||
$allDepartments = $actor->hasFunctions(['admin', 'procurement']);
|
||||
$orders = app(SupplyPlanning::class)->latest('op_order')
|
||||
->when($request !== null && ! $canLink, fn ($q) => $q->whereIn('id', $linkedIds))
|
||||
->when($request !== null, fn ($q) => $q->where('data->department_id', $request->department_id))
|
||||
->when($request === null && ! $allDepartments, fn ($q) => $q->where('data->department_id', $actor->department_id));
|
||||
$orders = $request === null ? $this->registryOrders($actor)
|
||||
: app(SupplyPlanning::class)->latest('op_order')->where('data->department_id', $request->department_id)
|
||||
->when(! $canLink, fn ($q) => $q->whereIn('id', $linkedIds));
|
||||
if ($selectedOrderId !== null) {
|
||||
(clone $orders)->findOrFail($selectedOrderId);
|
||||
$orders->whereKey($selectedOrderId);
|
||||
}
|
||||
|
||||
return ['actorId' => $actor->id, 'tenantId' => $actor->tenant_id, 'policy' => $policy,
|
||||
'canConfigure' => $actor->hasFunctions(['admin']), 'allowedTypes' => $this->types($actor, $policy),
|
||||
'departments' => Department::query()->when(! $allDepartments, fn ($q) => $q->whereKey($actor->department_id))->orderBy('name')->get(['id', 'name']),
|
||||
'orders' => $orders->latest('id')->paginate(15)->withQueryString(),
|
||||
'orders' => $orders->latest('id')->paginate(15, ['*'], 'page', $selectedOrderId === null ? null : 1)->withQueryString(),
|
||||
'selectedOrderId' => $selectedOrderId,
|
||||
'requisition' => $request?->only(['id', 'number', 'status']),
|
||||
'items' => $request?->items()->get(['id', 'description']) ?? [],
|
||||
'links' => $links, 'canLink' => $canLink,
|
||||
|
||||
@@ -139,14 +139,23 @@ final class PrivateAuditSourceReader
|
||||
'configuration' => ['organization.', 'company.', 'audit.private_'],
|
||||
'finance' => ['budget.', 'invoice.', 'payment.', 'expense.', 'payables.', 'ledger.', 'sgf_invoice.'],
|
||||
'stock' => ['stock.', 'receipt.', 'warehouse.', 'inventory.', 'warehouse_request.', 'replenishment.', 'supply.policy.', 'supply.reservation.', 'supply.delivery.', 'supply.issue.', 'supply.alternative.', 'supply.history.', 'supply.suggestion.'],
|
||||
'purchasing' => ['requisition.', 'approval.', 'quotation.', 'award.', 'purchase_order.', 'opening.', 'qualification.', 'admission.', 'recommendation.', 'capital.', 'conflict.', 'equipment.', 'investment.', 'urgent.', 'op_order.', 'op_order_policy.', 'op_order_link.', 'import.', 'supply.agreement.', 'supply.contract.', 'supply.import.'],
|
||||
'purchasing' => ['requisition.', 'approval.', 'quotation.', 'award.', 'purchase_order.', 'opening.', 'qualification.', 'admission.', 'recommendation.', 'capital.', 'conflict.', 'equipment.', 'investment.', 'urgent.', 'op_order.', 'op_order_policy.', 'op_order_link.', 'import.', 'supply.agreement.', 'supply.contract.', 'supply.import.', 'supplier_evaluation.', 'supplier_improvement.', 'supplier_response.'],
|
||||
default => throw new LogicException('Família de eventos desconhecida.'),
|
||||
};
|
||||
if ($family === 'purchasing') {
|
||||
$prefixes = [...$prefixes, 'planning.', 'purchase_control.', 'cancellation.', 'order_cancellation.', 'order_cancellation_policy.'];
|
||||
} elseif ($family === 'stock') {
|
||||
$prefixes[] = 'warehouse_return.';
|
||||
}
|
||||
$columns = ['id', 'tenant_id', 'user_id', 'requisition_id', 'action', 'created_at'];
|
||||
$query = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where(function ($events) use ($prefixes) {
|
||||
$query = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where(function ($events) use ($prefixes, $family) {
|
||||
foreach ($prefixes as $prefix) {
|
||||
$events->orWhereRaw('substr(action, 1, ?) = ?', [strlen($prefix), $prefix]);
|
||||
}
|
||||
if ($family === 'purchasing') {
|
||||
// Supplier bank events remain outside this approved purchasing export.
|
||||
$events->orWhereIn('action', ['supplier.created', 'supplier.updated', 'supplier.reviewed', 'supplier.document_uploaded', 'supplier.document_downloaded']);
|
||||
}
|
||||
});
|
||||
$rows = function () use ($query, $columns, $family): Generator {
|
||||
foreach ($query->select([...$columns, ...($family === 'configuration' ? ['before', 'after'] : [])])->orderBy('id')->lazy(100) as $event) {
|
||||
|
||||
@@ -184,7 +184,7 @@ class PurchaseWorkflow
|
||||
...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]),
|
||||
'development_only' => true, 'budget_checked' => false,
|
||||
'development_only' => true,
|
||||
'budget_control' => app(BudgetWorkflow::class)->record($user, $requisition, 'commit', $award->total_minor, $award->subtotal_minor, $quote),
|
||||
'investment_rules' => $award->investment_snapshot,
|
||||
'equipment_requests' => $requisition->items()->where('purchase_type', 'equipment')->get()->map(fn ($line) => $line->only(['id', 'description', 'production_area']))->all(),
|
||||
@@ -206,6 +206,8 @@ class PurchaseWorkflow
|
||||
...($urgentDocument === [] ? [] : ['urgent_quotation_basis' => $urgentDocument]),
|
||||
'equipment_context' => $requisition->items()->whereNotNull('equipment_id')->get()->map(fn ($line) => ['requisition_item_id' => $line->id, 'equipment' => Equipment::query()->findOrFail($line->equipment_id)->toArray(), 'spare_part' => SparePart::query()->findOrFail($line->spare_part_id)->toArray(), 'downtime_started_at' => $line->downtime_started_at])->all(),
|
||||
];
|
||||
// Preserve the result returned by the existing budget authority at issuance.
|
||||
$snapshot['budget_checked'] = $snapshot['budget_control'] !== null;
|
||||
$order = PurchaseOrder::query()->create([
|
||||
'tenant_id' => $user->tenant_id, 'requisition_id' => $requisition->id, 'purchase_award_id' => $award->id,
|
||||
'supplier_id' => $supplier->id, 'issued_by' => $user->id, 'currency' => $quote->currency,
|
||||
|
||||
@@ -32,11 +32,15 @@ class WarehouseAvailability
|
||||
}
|
||||
}
|
||||
|
||||
$reservations = app(WarehouseReservations::class);
|
||||
$committed = $reservations->ready() ? $reservations->committed($item->id, $warehouse->id) : null;
|
||||
$free = $usable === null || $committed === null ? null : $usable - $committed;
|
||||
|
||||
return ['id' => $item->id, 'code' => $item->code, 'name' => $item->name, 'unit' => $item->unit,
|
||||
'physical_milli' => $physical['quantity'], 'usable_milli' => $usable, 'blocked_milli' => $lots === null || ! $lots['reconciled'] ? null : $lots['blocked_milli'],
|
||||
'lot_control' => $lots !== null, 'reconciled' => $lots === null || $lots['reconciled'], 'planned_milli' => $needs,
|
||||
'minimum_milli' => $minimum, 'at_minimum' => $usable !== null && $minimum !== null && $usable - app(WarehouseReservations::class)->committed($item->id, $warehouse->id) <= $minimum,
|
||||
'physical_commitment_milli' => app(WarehouseReservations::class)->ready() ? app(WarehouseReservations::class)->committed($item->id, $warehouse->id) : null,
|
||||
'free_milli' => $usable === null ? null : $usable - app(WarehouseReservations::class)->committed($item->id, $warehouse->id), 'ledger_version' => $physical['version']];
|
||||
'minimum_milli' => $minimum, 'at_minimum' => $free !== null && $minimum !== null && $free <= $minimum,
|
||||
'physical_commitment_milli' => $committed,
|
||||
'free_milli' => $free, 'ledger_version' => $physical['version']];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user