@@ -22,10 +22,16 @@ class ConflictDeclarationController extends Controller
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
Inertia::encryptHistory();
|
||||
$declarations = ConflictDeclaration::query()->visibleTo($this->staffIdentity($request))
|
||||
->with(['author:id,name', 'supplier:id,name', 'requisition:id,number', 'successor:id,previous_id'])
|
||||
->latest('id')->paginate(15);
|
||||
$roots = $declarations->getCollection()->map(fn (ConflictDeclaration $row) => $row->root_id ?? $row->id)->unique();
|
||||
$releasedRoots = app(ConflictReleases::class)->ready()
|
||||
? ConflictRelease::query()->whereIn('root_id', $roots)->orderBy('root_id')->pluck('root_id')->map(fn ($id) => (int) $id)->all()
|
||||
: [];
|
||||
$response = Inertia::render('conflicts/index', [
|
||||
'declarations' => ConflictDeclaration::query()->visibleTo($this->staffIdentity($request))
|
||||
->with(['author:id,name', 'supplier:id,name', 'requisition:id,number', 'successor:id,previous_id'])
|
||||
->latest('id')->paginate(15),
|
||||
'declarations' => $declarations,
|
||||
'releasedRoots' => $releasedRoots,
|
||||
// These minimal choices allow personal declarations without granting supplier-management access.
|
||||
'suppliers' => Supplier::query()->orderBy('name')->get(['id', 'name']),
|
||||
'requisitions' => Requisition::query()->visibleTo($this->staffIdentity($request))->latest()->get(['id', 'number']),
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Http\Requests\ConfirmReceiptRequest;
|
||||
use App\Models\GoodsReceipt;
|
||||
use App\Models\PurchaseOrder;
|
||||
@@ -60,17 +61,19 @@ class GoodsReceiptController extends Controller
|
||||
|
||||
public function order(Request $request, PurchaseOrder $order, ReceiptWorkflow $workflow): Response
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
Gate::authorize('viewOrder', [GoodsReceipt::class, $order]);
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return Inertia::render('receipts/order', [
|
||||
'financialDocumentsHref' => $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]) ? '/facturas?purchase_order_id='.$order->id.'#invoice-documents' : null,
|
||||
'order' => $order->only(['id', 'number', 'issued_by']), 'supplier_name' => $order->snapshot['supplier']['name'],
|
||||
'progress' => $workflow->progress($order),
|
||||
'receipts' => GoodsReceipt::query()->where('purchase_order_id', $order->id)->latest('id')->get(),
|
||||
'warehouses' => Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']),
|
||||
'stockItems' => StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']),
|
||||
'conversionQaEnabled' => app()->environment('testing') && config('inventory_conversion.qa_enabled') === true,
|
||||
'canConfirm' => $request->user()->can('create', [GoodsReceipt::class, $order]),
|
||||
'canConfirm' => $actor->can('create', [GoodsReceipt::class, $order]),
|
||||
'lotScopes' => Schema::hasTable('inventory_lot_allocations')
|
||||
? app(InventoryLots::class)->activeSetups()->get()->map(fn ($r) => ['stock_item_id' => $r->stock_item_id, 'warehouse_id' => $r->warehouse_id, 'quarantine_on_receipt' => $r->data['quarantine_on_receipt'] ?? true])->values()->all() : [],
|
||||
]);
|
||||
@@ -97,6 +100,8 @@ class GoodsReceiptController extends Controller
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return Inertia::render('receipts/show', [
|
||||
'financialDocumentsHref' => $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance])
|
||||
? '/facturas?purchase_order_id='.$order->id.'#invoice-documents' : null,
|
||||
'documentsReady' => $ready,
|
||||
'purchaseProcessHref' => $source === null ? null : '/requisicoes/'.$source->id.'/processo',
|
||||
'canAddDocuments' => $ready && $documents->canAdd($actor, $receipt),
|
||||
|
||||
@@ -12,9 +12,10 @@ final class OperationalOrdersController extends Controller
|
||||
{
|
||||
public function index(Request $request, OperationalOrders $orders, ?Requisition $requisition = null): Response
|
||||
{
|
||||
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$data = $request->validate(['page' => 'nullable|integer|min:1|max:1000000', 'order_id' => 'nullable|integer|min:1']);
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('requisitions/operational-orders', $orders->workspace($this->staffIdentity($request), $requisition))->toResponse($request);
|
||||
$selected = $requisition === null && isset($data['order_id']) ? (int) $data['order_id'] : null;
|
||||
$response = Inertia::render('requisitions/operational-orders', $orders->workspace($this->staffIdentity($request), $requisition, $selected))->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
|
||||
@@ -16,6 +16,7 @@ use App\Services\RequisitionApprovalLevels;
|
||||
use App\Services\RequisitionCategories;
|
||||
use App\Services\RequisitionExpiry;
|
||||
use App\Services\UrgentQuotationBasis;
|
||||
use App\Services\UrgentRequisitionReviews;
|
||||
use App\Services\WorkContext;
|
||||
use App\Services\WorkflowTasks;
|
||||
use Brick\Math\BigDecimal;
|
||||
@@ -48,6 +49,7 @@ class OrganizationConfigurationController extends Controller
|
||||
'companyDetailsReady' => Schema::hasColumn('tenants', 'company_details'),
|
||||
'approvalLevelsReady' => app(RequisitionApprovalLevels::class)->ready(),
|
||||
'expiryReady' => app(RequisitionExpiry::class)->ready(),
|
||||
'urgentReviewsReady' => app(UrgentRequisitionReviews::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,
|
||||
|
||||
@@ -13,6 +13,8 @@ use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\AgreementOrderLimits;
|
||||
use App\Services\CapitalRegister;
|
||||
use App\Services\OperationalOrders;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\SavedProcurementSearches;
|
||||
use App\Services\SupplyPlanning;
|
||||
@@ -56,8 +58,12 @@ class ProcurementSearchController extends Controller
|
||||
$warehouseRequestSearchAvailable = config('procurement_search.warehouse_requests_metadata_enabled') === true
|
||||
&& $warehouseSelectors !== null && Schema::hasTable('warehouse_requests')
|
||||
&& $actor->hasFunctions(['admin', 'warehouse_request_read', 'warehouse_request_prepare', 'warehouse_request_review', 'warehouse_request_deliver']);
|
||||
$capitalQuery = app(CapitalRegister::class)->searchQuery($actor);
|
||||
$operationalQuery = app(OperationalOrders::class)->searchQuery($actor);
|
||||
$request->validate(['capital_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$request->validate(['operational_orders_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']);
|
||||
$groups = DB::transaction(function () use ($actor, $term, $planning, $supplySearchAvailable, $supplySelectors, $warehouseRequestSearchAvailable, $warehouseSelectors) {
|
||||
$groups = DB::transaction(function () use ($actor, $term, $planning, $supplySearchAvailable, $supplySelectors, $warehouseRequestSearchAvailable, $warehouseSelectors, $capitalQuery, $operationalQuery) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
@@ -148,6 +154,40 @@ class ProcurementSearchController extends Controller
|
||||
$groups[] = ['key' => 'warehouse_requests', 'title' => 'Requisições internas de armazém', 'records' => $records];
|
||||
}
|
||||
|
||||
if ($capitalQuery !== null) {
|
||||
$capitalQuery->where(function ($query) use ($pattern) {
|
||||
foreach (['code', 'name', 'reference'] as $field) {
|
||||
// Fixed register fields only; literal search text remains bound.
|
||||
$expression = DB::getDriverName() === 'pgsql'
|
||||
? 'LOWER("data"->>\''.$field.'\') LIKE ? ESCAPE \'!\''
|
||||
: "LOWER(json_extract(data, '$.".$field."')) LIKE ? ESCAPE '!'";
|
||||
$query->orWhereRaw($expression, [$pattern]);
|
||||
}
|
||||
});
|
||||
$records = $capitalQuery->latest('id')->paginate(15, ['id', 'record_key', 'version', 'state',
|
||||
'data->code as code', 'data->name as name', 'data->type as register_type'], 'capital_page')->withQueryString()
|
||||
->through(fn ($row) => ['id' => $row->id,
|
||||
'title' => ($row->getAttribute('register_type') === 'asset' ? 'Imobilizado' : 'Projecto').' '.$row->getAttribute('code').' — '.$row->getAttribute('name').' · v'.$row->version,
|
||||
'detail' => $row->state, 'href' => '/projectos-imobilizado?history='.rawurlencode($row->record_key)]);
|
||||
$groups[] = ['key' => 'capital', 'title' => 'Projectos e imobilizado', 'records' => $records];
|
||||
}
|
||||
|
||||
if ($operationalQuery !== null) {
|
||||
$operationalQuery->where(function ($query) use ($pattern) {
|
||||
foreach (['reference', 'utilisation_location', 'description'] as $field) {
|
||||
$expression = DB::getDriverName() === 'pgsql'
|
||||
? 'LOWER("data"->>\''.$field.'\') LIKE ? ESCAPE \'!\''
|
||||
: "LOWER(json_extract(data, '$.".$field."')) LIKE ? ESCAPE '!'";
|
||||
$query->orWhereRaw($expression, [$pattern]);
|
||||
}
|
||||
});
|
||||
$records = $operationalQuery->latest('id')->paginate(15, ['id', 'version', 'state', 'data->reference as reference', 'data->type as order_type'], 'operational_orders_page')->withQueryString()
|
||||
->through(fn ($row) => ['id' => $row->id,
|
||||
'title' => ($row->getAttribute('order_type') === 'production' ? 'Produção' : 'Manutenção').' '.$row->getAttribute('reference').' · v'.$row->version,
|
||||
'detail' => $row->state, 'href' => '/ordens-operacionais?order_id='.$row->id.'#op-order-'.$row->id]);
|
||||
$groups[] = ['key' => 'operational_orders', 'title' => 'Ordens de produção e manutenção', 'records' => $records];
|
||||
}
|
||||
|
||||
return $groups;
|
||||
});
|
||||
Inertia::encryptHistory();
|
||||
@@ -156,6 +196,8 @@ class ProcurementSearchController extends Controller
|
||||
'invoiceSearchAvailable' => config('procurement_search.finance_metadata_enabled') === true && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]),
|
||||
'supplySearchAvailable' => $supplySearchAvailable,
|
||||
'warehouseRequestSearchAvailable' => $warehouseRequestSearchAvailable,
|
||||
'capitalSearchAvailable' => $capitalQuery !== null,
|
||||
'operationalOrderSearchAvailable' => $operationalQuery !== null,
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response as HttpResponse;
|
||||
|
||||
class PurchaseController extends Controller
|
||||
{
|
||||
@@ -190,8 +191,12 @@ class PurchaseController extends Controller
|
||||
$actor = $this->access($request);
|
||||
PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id);
|
||||
$origins = app(OrderPartsAccess::class)->origins($order);
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return Inertia::render('purchases/show', [
|
||||
'financialDocumentsHref' => $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]) ? '/facturas?purchase_order_id='.$order->id.'#invoice-documents' : null,
|
||||
'relatedProcesses' => Requisition::query()->visibleTo($actor)->whereIn('id', $origins)->orderBy('id')->get(['id', 'number'])
|
||||
->map(fn ($source) => ['id' => $source->id, 'number' => $source->number, 'href' => '/requisicoes/'.$source->id.'/processo']),
|
||||
'snapshotComplete' => $order->hasCompleteDocumentSnapshot(),
|
||||
'order' => $order->load('items'),
|
||||
'orderPartsSources' => $order->snapshot['order_parts']['frames'] ?? [],
|
||||
@@ -205,12 +210,16 @@ class PurchaseController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function print(Request $request, PurchaseOrder $order): View
|
||||
public function print(Request $request, PurchaseOrder $order): View|HttpResponse
|
||||
{
|
||||
$actor = $this->access($request);
|
||||
PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id);
|
||||
app(OrderPartsAccess::class)->origins($order);
|
||||
|
||||
if ($request->header('X-Inertia')) {
|
||||
return Inertia::location(route('orders.print', $order, false));
|
||||
}
|
||||
|
||||
return view('purchases.print', ['order' => $order->load('items'), 'snapshot' => $order->snapshot,
|
||||
'snapshotComplete' => $order->hasCompleteDocumentSnapshot(),
|
||||
'operationalState' => app(OrderCancellationWorkflow::class)->state($order)]);
|
||||
|
||||
@@ -90,7 +90,7 @@ class SupplierEvaluationController extends Controller
|
||||
$responses = $responsesReady ? SupplierResponse::query()->where('supplier_evaluation_id', $id)->orderBy('id')->get() : collect();
|
||||
$responseHistory = $responsesReady ? AuditLog::query()->where('action', 'like', 'supplier_response.%')->where('after->supplier_evaluation_id', $id)->latest('id')->paginate(10, ['id', 'action', 'user_id', 'after', 'created_at'], 'responses_history_page')->withQueryString() : null;
|
||||
$history = AuditLog::query()->where('action', 'like', 'supplier_evaluation.%')->where('after->evaluation_id', $id)->latest('id')->paginate(10, ['id', 'action', 'user_id', 'after', 'created_at'], 'history_page')->withQueryString();
|
||||
$peopleIds = collect($evaluation->contributors)->merge($history->pluck('user_id'))->merge($measures->flatMap(fn (SupplierImprovement $m) => $m->contributors))->merge($measures->pluck('reviewed_by'))->merge($measureHistory?->pluck('user_id') ?? []);
|
||||
$peopleIds = collect($evaluation->contributors)->push($evaluation->reviewed_by)->merge($history->pluck('user_id'))->merge($measures->flatMap(fn (SupplierImprovement $m) => $m->contributors))->merge($measures->pluck('reviewed_by'))->merge($measureHistory?->pluck('user_id') ?? []);
|
||||
$peopleIds = $peopleIds->merge($responses->flatMap(fn (SupplierResponse $r) => $r->contributors))->merge($responses->pluck('reviewed_by'))->merge($responseHistory?->pluck('user_id') ?? []);
|
||||
$people = User::query()->where('tenant_id', $actor->tenant_id)->whereIn('id', $peopleIds)->pluck('name', 'id');
|
||||
$writable = $improvementWorkflow->canParticipate($actor, $evaluation);
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Models\StockItem;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\WarehouseAvailability;
|
||||
use App\Services\WarehouseReservations;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -32,7 +33,7 @@ class WarehouseAvailabilityController extends Controller
|
||||
$query->where(fn ($q) => $q->whereLike('code', '%'.$filters['search'].'%')->orWhereLike('name', '%'.$filters['search'].'%'));
|
||||
}
|
||||
$page = $warehouse === null ? null : $query->orderBy('code')->paginate(25)->withQueryString()->through(fn ($item) => $availability->row($item, $warehouse, $planning));
|
||||
$response = Inertia::render('stock/availability', ['filters' => $filters, 'planningVisible' => $planning, 'rows' => $page,
|
||||
$response = Inertia::render('stock/availability', ['filters' => $filters, 'planningVisible' => $planning, 'reservationsAvailable' => app(WarehouseReservations::class)->ready(), 'rows' => $page,
|
||||
'warehouse' => $warehouse?->only(['id', 'code', 'name']), 'checkedAt' => now()->toIso8601String(),
|
||||
'warehouses' => Warehouse::query()->orderBy('code')->get(['id', 'code', 'name'])])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\CapitalRegister;
|
||||
use App\Services\OperationalOrders;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\PrivateAuditAccess;
|
||||
use App\Services\SupplierPayables;
|
||||
use App\Services\WorkContext;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -66,7 +68,8 @@ class HandleInertiaRequests extends Middleware
|
||||
'payablesAvailable' => $actor !== null && app(SupplierPayables::class)->can($actor, 'view'),
|
||||
'orderCancellationAvailable' => $actor !== null && (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
|
||||
'operationalOrdersAvailable' => $actor !== null && app(OperationalOrders::class)->ready(),
|
||||
'privateAuditAvailable' => $actor !== null && app(\App\Services\PrivateAuditAccess::class)->ready(),
|
||||
'privateAuditAvailable' => $actor !== null && app(PrivateAuditAccess::class)->ready(),
|
||||
'capitalRegisterAvailable' => $actor !== null && app(CapitalRegister::class)->searchQuery($actor) !== null,
|
||||
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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