@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\OperationalHealth;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class OperationsCheck extends Command
|
||||
{
|
||||
protected $signature = 'sgc:operations-check {--json : Resultado agregado para monitorização} {--document-limit=1000 : Máximo de documentos e ficheiros a inspeccionar, de 1 a 10000}';
|
||||
|
||||
protected $description = 'Consultar reposição e integridade documental sem processar compras, corrigir ficheiros ou alterar configurações';
|
||||
|
||||
public function handle(OperationalHealth $health): int
|
||||
{
|
||||
$limit = filter_var($this->option('document-limit'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 10000]]);
|
||||
if ($limit === false) {
|
||||
$this->error('O limite deve ser um inteiro entre 1 e 10000.');
|
||||
|
||||
return self::INVALID;
|
||||
}
|
||||
$result = $health->inspect($limit);
|
||||
if ($this->option('json')) {
|
||||
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
} else {
|
||||
$this->line($result['ok'] ? 'Operação: verificações concluídas sem divergências observadas.' : 'Operação: verificações requerem atenção.');
|
||||
$labels = ['replenishment' => 'Reposição', 'receipt_documents' => 'Documentos da recepção'];
|
||||
$states = ['passed' => 'sem divergências observadas', 'attention' => 'requer atenção', 'incomplete' => 'verificação incompleta', 'unavailable' => 'consulta indisponível'];
|
||||
foreach ($result['checks'] as $key => $check) {
|
||||
$this->line($labels[$key].': '.$states[$check['status']].'.');
|
||||
foreach ($check['result']['reasons'] as $reason) {
|
||||
$this->line(' '.$reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result['ok'] ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\ReceiptDocumentHealth;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
class ReceiptDocumentsCheck extends Command
|
||||
{
|
||||
protected $signature = 'sgc:receipt-documents-check {--json : Resultado agregado para operação} {--limit=1000 : Máximo de registos e ficheiros, de 1 a 10000}';
|
||||
|
||||
protected $description = 'Verificar documentos privados da recepção sem modificar registos ou ficheiros';
|
||||
|
||||
public function handle(ReceiptDocumentHealth $health): int
|
||||
{
|
||||
$limit = filter_var($this->option('limit'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 10000]]);
|
||||
if ($limit === false) {
|
||||
$this->error('O limite deve ser um inteiro entre 1 e 10000.');
|
||||
|
||||
return self::INVALID;
|
||||
}
|
||||
try {
|
||||
$result = $health->inspect($limit);
|
||||
} catch (Throwable $error) {
|
||||
report($error);
|
||||
$result = ['checked_at' => now()->toIso8601String(), 'ok' => false, 'complete' => false, 'reasons' => ['unavailable']];
|
||||
}
|
||||
if ($this->option('json')) {
|
||||
$this->line(json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
|
||||
} else {
|
||||
$this->line($result['ok'] ? 'Documentos da recepção: verificação concluída sem divergências observadas.' : 'Documentos da recepção: verificação requer atenção.');
|
||||
$labels = ['not_installed' => 'Estrutura documental não instalada.', 'storage_unavailable' => 'Armazenamento privado indisponível.',
|
||||
'missing' => 'Existem ficheiros em falta.', 'invalid_reference' => 'Existem referências inválidas.', 'altered' => 'Existem divergências de tamanho ou conteúdo.',
|
||||
'unreferenced_recent' => 'Existem ficheiros recentes sem referência; podem estar em processamento.', 'unreferenced_older' => 'Existem ficheiros sem referência há pelo menos uma hora.',
|
||||
'limit_reached' => 'Verificação incompleta: atingido o limite configurado.', 'unavailable' => 'Consulta indisponível; verificar o registo técnico.'];
|
||||
foreach ($result['reasons'] as $reason) {
|
||||
$this->line($labels[$reason]);
|
||||
}
|
||||
}
|
||||
|
||||
return $result['ok'] ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\AdministrativeGeography;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\OrganizationConfiguration;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class AdministrativeGeographyController extends Controller
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
private function reviewFilters(Request $request, AdministrativeGeography $geography): array
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
app(OrganizationConfiguration::class)->administrator($actor);
|
||||
abort_unless($geography->enabled(), 503);
|
||||
$filters = $request->validate(['search' => 'nullable|string|max:120', 'issue' => ['nullable', Rule::in(array_keys(AdministrativeGeography::ISSUES))], 'page' => 'sometimes|integer|min:1|max:10000']);
|
||||
|
||||
return ['search' => trim($filters['search'] ?? ''), 'issue' => $filters['issue'] ?? '', 'page' => (int) ($filters['page'] ?? 1)];
|
||||
}
|
||||
|
||||
public function review(Request $request, AdministrativeGeography $geography): Response
|
||||
{
|
||||
$filters = $this->reviewFilters($request, $geography);
|
||||
$rows = $geography->inconsistencies($filters);
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('company/geography-review', ['filters' => $filters, 'records' => array_slice($rows, ($filters['page'] - 1) * 50, 50), 'total' => count($rows), 'manifest' => $geography->catalogue()['manifest'], 'issues' => AdministrativeGeography::ISSUES])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function exportReview(Request $request, AdministrativeGeography $geography): StreamedResponse
|
||||
{
|
||||
$filters = $this->reviewFilters($request, $geography);
|
||||
$rows = $geography->inconsistencies($filters);
|
||||
|
||||
return response()->streamDownload(function () use ($rows) {
|
||||
$output = fopen('php://output', 'w');
|
||||
if ($output === false) {
|
||||
throw new \RuntimeException('Não foi possível preparar a exportação.');
|
||||
}
|
||||
$safe = fn ($value) => preg_match('/^[\s]*[=+@-]|^[\t\r\n]/u', $value) ? "'".$value : $value;
|
||||
fputcsv($output, ['Linha', 'ID', 'Provincia', 'Distrito', 'Posto_Administrativo', 'Localidade', 'Bairro_Urbano', 'Aldeia_Quarteirao', 'Designacao', 'Diagnosticos'], ',', '"', '');
|
||||
foreach ($rows as $record) {
|
||||
$raw = $record['raw'];
|
||||
fputcsv($output, array_map($safe, [(string) $record['source_row'], $record['id'], ...array_values(array_diff_key($raw, ['ID' => true])), implode('; ', array_map(fn ($issue) => AdministrativeGeography::ISSUES[$issue], $record['issues']))]), ',', '"', '');
|
||||
}
|
||||
fclose($output);
|
||||
}, 'sgc-cartografia-pendencias.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
|
||||
public function index(Request $request, AdministrativeGeography $geography): JsonResponse
|
||||
{
|
||||
abort_unless($request->user('web') instanceof User && $request->user('web')->tenant_id !== null, 403);
|
||||
abort_unless($geography->enabled(), 503);
|
||||
$data = $request->validate(['parent' => 'nullable|string|regex:/^[0-9]+$/D|max:20', 'page' => 'sometimes|integer|min:1|max:10000']);
|
||||
|
||||
return response()->json($geography->children($data['parent'] ?? null, (int) ($data['page'] ?? 1)));
|
||||
}
|
||||
|
||||
public function company(Request $request, AdministrativeGeography $geography): RedirectResponse
|
||||
{
|
||||
abort_unless($geography->enabled(), 503);
|
||||
$data = $request->validate(['geography_reference' => 'present|nullable|array:country,catalogue,record_id', 'geography_reference.catalogue' => 'required_with:geography_reference|string|size:64', 'geography_reference.record_id' => 'required_with:geography_reference|string|regex:/^[0-9]+$/D|max:20', 'expected_reference' => 'present|nullable|array:country,catalogue,record_id']);
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
DB::transaction(function () use ($actor, $data, $geography) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(OrganizationConfiguration::class)->administrator($actor);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$company = Tenant::query()->lockForUpdate()->findOrFail($actor->tenant_id);
|
||||
if ($company->geography_reference != $data['expected_reference']) {
|
||||
throw ValidationException::withMessages(['geography_reference' => 'A localização foi alterada. Reabra a parametrização.']);
|
||||
}
|
||||
$before = $company->geography_reference;
|
||||
$after = $geography->canonical($data['geography_reference']);
|
||||
if ($before != $after) {
|
||||
$company->update(['geography_reference' => $after]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'company.geography_updated', null, ['geography_reference' => $before], ['geography_reference' => $after]);
|
||||
}
|
||||
});
|
||||
|
||||
return back();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\OrganizationAccess;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class AuditMetadataController extends Controller
|
||||
{
|
||||
private function actor(Request $request): User
|
||||
{
|
||||
$user = $request->user('web');
|
||||
abort_unless($user instanceof User && $user->tenant_id !== null, 403);
|
||||
$user = User::query()->where('tenant_id', $user->tenant_id)->findOrFail($user->id);
|
||||
$access = app(OrganizationAccess::class);
|
||||
abort_unless(! $access->maintenanceOnly($user) && in_array('audit_metadata_read', $access->permissions($user), true), 403);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function filters(Request $request): array
|
||||
{
|
||||
return $request->validate(['action' => 'nullable|string|max:100', 'actor_id' => 'nullable|integer|min:1',
|
||||
'from' => 'nullable|date_format:Y-m-d', 'to' => ['nullable', 'date_format:Y-m-d', Rule::when($request->filled('from'), 'after_or_equal:from')], 'page' => 'nullable|integer|min:1|max:1000000']);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $filters */
|
||||
private function query(User $actor, array $filters): Builder
|
||||
{
|
||||
return DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)
|
||||
->when(! empty($filters['action']), fn ($q) => $q->where('action', $filters['action']))
|
||||
->when(! empty($filters['actor_id']), fn ($q) => $q->where('user_id', $filters['actor_id']))
|
||||
->when(! empty($filters['from']), fn ($q) => $q->whereDate('created_at', '>=', $filters['from']))
|
||||
->when(! empty($filters['to']), fn ($q) => $q->whereDate('created_at', '<=', $filters['to']))
|
||||
->select(['id', 'created_at', 'action', 'user_id']);
|
||||
}
|
||||
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$this->actor($request);
|
||||
$filters = $this->filters($request);
|
||||
|
||||
return DB::transaction(function () use ($request, $filters) {
|
||||
$this->readOnly();
|
||||
$actor = $this->actor($request);
|
||||
Inertia::encryptHistory();
|
||||
|
||||
$response = Inertia::render('audit/metadata', ['filters' => $filters,
|
||||
'events' => $this->query($actor, $filters)->orderBy('id')->paginate(25)->withQueryString()])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
});
|
||||
}
|
||||
|
||||
public function csv(Request $request): Response
|
||||
{
|
||||
$this->actor($request);
|
||||
$filters = $this->filters($request);
|
||||
|
||||
return response()->streamDownload(function () use ($request, $filters) {
|
||||
DB::transaction(function () use ($request, $filters) {
|
||||
$this->readOnly();
|
||||
$actor = $this->actor($request);
|
||||
$out = fopen('php://output', 'w');
|
||||
if ($out === false) {
|
||||
throw new \RuntimeException('Não foi possível preparar a exportação.');
|
||||
}
|
||||
$text = static function (mixed $value): string {
|
||||
$value = (string) ($value ?? '');
|
||||
|
||||
return preg_match('/^[\s\x00-\x1F]*[=+\-@]/u', $value) ? "'".$value : $value;
|
||||
};
|
||||
try {
|
||||
fwrite($out, "\xEF\xBB\xBF");
|
||||
fputcsv($out, ['Metadados de eventos da empresa', 'Consulta', now()->toIso8601String()], ';', '"', '');
|
||||
fputcsv($out, ['Registo', 'Data', 'Acção', 'Utilizador (id)'], ';', '"', '');
|
||||
foreach ($this->query($actor, $filters)->lazyById(100) as $event) {
|
||||
fputcsv($out, array_map($text, [$event->id, $event->created_at, $event->action, $event->user_id]), ';', '"', '');
|
||||
}
|
||||
} finally {
|
||||
fclose($out);
|
||||
}
|
||||
});
|
||||
}, 'eventos-metadados-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||
}
|
||||
|
||||
private function readOnly(): void
|
||||
{
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,12 @@ use App\Models\CandidateAccount;
|
||||
use App\Models\PeopleProcess;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\AdministrativeGeography;
|
||||
use App\Services\CandidateAccess;
|
||||
use App\Services\CandidateDocuments;
|
||||
use App\Services\CandidateProfiles;
|
||||
use App\Services\CandidateSubmissions;
|
||||
use App\Services\CandidateTerritory;
|
||||
use App\Services\CandidateTriage;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\CurrentActor;
|
||||
@@ -17,6 +19,7 @@ use App\Services\OrganizationConfiguration;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SubmissionForms;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -117,12 +120,25 @@ class CandidatePortalController extends Controller
|
||||
$scopedSelection = is_array($selection) && ($selection['company'] ?? null) === $company && ($selection['account'] ?? null) === $account->id && is_int($selection['id'] ?? null) && $selection['id'] > 0;
|
||||
$selected = $this->rememberOpportunity($request, $account, $scopedSelection ? (int) $selection['id'] : null);
|
||||
|
||||
return $this->page($request, 'candidate/profile', ['companyId' => $company, 'email' => $account->email, 'profile' => $profiles->profile($account),
|
||||
$profile = $profiles->profile($account);
|
||||
|
||||
return $this->page($request, 'candidate/profile', ['companyId' => $company, 'email' => $account->email, 'profile' => $profile,
|
||||
'geographyEnabled' => app(AdministrativeGeography::class)->enabled(),
|
||||
'availabilityGeography' => app(AdministrativeGeography::class)->describe($profile['data']['availability_reference'] ?? null),
|
||||
'emailVerified' => $account->email_verified_at !== null, 'accessStatus' => $scopedSelection && $selected === null ? 'opportunity_unavailable' : $request->session()->get('candidate_access_status'), 'emailDeliveryAvailable' => app(CandidateAccess::class)->deliveryAvailable(),
|
||||
'opportunities' => $opportunities->items(), 'opportunityPagination' => ['prev' => $opportunities->previousPageUrl(), 'next' => $opportunities->nextPageUrl()], 'selectedOpportunity' => $selected,
|
||||
'submissions' => $receipts->items(), 'submissionPagination' => ['prev' => $receipts->previousPageUrl(), 'next' => $receipts->nextPageUrl(), 'total' => $receipts->total()]]);
|
||||
}
|
||||
|
||||
public function geography(Request $request, int $company, AdministrativeGeography $geography): JsonResponse
|
||||
{
|
||||
abort_unless($this->account($request, $company) !== null, 401);
|
||||
abort_unless($geography->enabled(), 503);
|
||||
$data = $request->validate(['parent' => 'nullable|string|regex:/^[0-9]+$/D|max:20', 'page' => 'sometimes|integer|min:1|max:10000']);
|
||||
|
||||
return response()->json($geography->children($data['parent'] ?? null, (int) ($data['page'] ?? 1)), 200, ['Cache-Control' => 'private, no-store, max-age=0']);
|
||||
}
|
||||
|
||||
public function save(Request $request, int $company, CandidateProfiles $profiles): Response
|
||||
{
|
||||
$account = $this->account($request, $company);
|
||||
@@ -293,21 +309,42 @@ class CandidatePortalController extends Controller
|
||||
$record = PeopleProcess::query()->where('tenant_id', $actor->tenant_id)->where('id', $process)->firstOrFail();
|
||||
$triage = app(CandidateTriage::class);
|
||||
abort_unless($triage->canRead($actor, $record), 403);
|
||||
$filter = $request->validate(['submission' => 'nullable|integer|min:1']);
|
||||
$rows = DB::table('candidate_submissions')->where('tenant_id', $actor->tenant_id)->where('people_process_id', $process)->orderBy('id')->paginate(20);
|
||||
$filter = $request->validate(['submission' => 'nullable|integer|min:1', 'location' => 'nullable|string|regex:/^[0-9]+$/D|max:20', 'page' => 'sometimes|integer|min:1|max:1000000']);
|
||||
$query = DB::table('candidate_submissions')->where('tenant_id', $actor->tenant_id)->where('people_process_id', $process);
|
||||
if (isset($filter['submission'])) {
|
||||
$rows = DB::table('candidate_submissions')->where('tenant_id', $actor->tenant_id)->where('people_process_id', $process)->where('id', $filter['submission'])->paginate(20)->withQueryString();
|
||||
$query->where('id', $filter['submission']);
|
||||
}
|
||||
if (! empty($filter['location'])) {
|
||||
app(CandidateTerritory::class)->apply($query, $filter['location']);
|
||||
}
|
||||
$rows = $query->orderBy('id')->paginate(20)->withQueryString();
|
||||
$decisions = Schema::hasTable('candidate_triage') ? DB::table('candidate_triage')->where('tenant_id', $actor->tenant_id)->where('people_process_id', $process)->whereIn('candidate_submission_id', $rows->pluck('id'))->get(['candidate_submission_id', 'outcome', 'reason', 'public_message', 'created_at', 'people_application_id'])->keyBy('candidate_submission_id') : collect();
|
||||
$rows->through(fn ($row) => ['id' => $row->id, 'reference' => $row->reference, 'received_at' => $row->created_at, 'snapshot' => json_decode($row->snapshot, true, 32, JSON_THROW_ON_ERROR), 'decision' => $decisions->get($row->id)]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'candidate_submissions.consulted', null, null, ['process_id' => $process]);
|
||||
|
||||
return $this->page($request, 'people/submissions', ['process' => ['id' => $record->id, 'title' => $record->title, 'version' => $record->version], 'publication' => $submissions->publication($record), 'submissions' => $rows,
|
||||
'filters' => $filter, 'geographyEnabled' => app(AdministrativeGeography::class)->enabled() && in_array(DB::getDriverName(), ['sqlite', 'pgsql'], true),
|
||||
'geographyFilter' => empty($filter['location']) ? null : app(AdministrativeGeography::class)->describe(['country' => 'MZ', 'catalogue' => config('geography.source_sha256'), 'record_id' => $filter['location']]),
|
||||
'canPrepare' => $triage->canPrepare($actor, $record), 'canTriage' => Schema::hasTable('candidate_triage') && $triage->canPrepare($actor, $record) && in_array($record->status, ['open', 'assessment'], true),
|
||||
'publicUrl' => '/candidaturas/'.$actor->tenant_id.'/oportunidades/'.$record->id]);
|
||||
});
|
||||
}
|
||||
|
||||
public function processGeography(Request $request, int $process, AdministrativeGeography $geography): JsonResponse
|
||||
{
|
||||
return DB::transaction(function () use ($request, $process, $geography) {
|
||||
$actor = $this->staff($request);
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
$record = PeopleProcess::query()->where('tenant_id', $actor->tenant_id)->where('id', $process)->firstOrFail();
|
||||
abort_unless(app(CandidateTriage::class)->canRead($actor, $record), 403);
|
||||
abort_unless($geography->enabled(), 503);
|
||||
$data = $request->validate(['parent' => 'nullable|string|regex:/^[0-9]+$/D|max:20', 'page' => 'sometimes|integer|min:1|max:10000']);
|
||||
|
||||
return response()->json($geography->children($data['parent'] ?? null, (int) ($data['page'] ?? 1)), 200, ['Cache-Control' => 'private, no-store, max-age=0']);
|
||||
});
|
||||
}
|
||||
|
||||
public function publish(Request $request, int $process, CandidateSubmissions $submissions): Response
|
||||
{
|
||||
$submissions->publish($this->staff($request), $process, $request->all());
|
||||
|
||||
@@ -7,11 +7,17 @@ use App\Models\CriticalityLevel;
|
||||
use App\Models\Department;
|
||||
use App\Models\Equipment;
|
||||
use App\Models\EquipmentSparePart;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\SparePart;
|
||||
use App\Models\StockItem;
|
||||
use App\Models\StockMovement;
|
||||
use App\Models\StockOperation;
|
||||
use App\Models\User;
|
||||
use App\Services\AdministrativeGeography;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\CurrentActor;
|
||||
use App\Services\EquipmentWarehouseRequests;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Brick\Math\BigDecimal;
|
||||
@@ -26,17 +32,66 @@ use Inertia\Response;
|
||||
|
||||
class EquipmentController extends Controller
|
||||
{
|
||||
private function actor(Request $request): User
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
public function show(Request $request, int $equipment): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$actor = User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($actor->id);
|
||||
abort_unless($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||
$request->validate(['purchases_page' => 'nullable|integer|min:1|max:1000000', 'movements_page' => 'nullable|integer|min:1|max:1000000', 'requests_page' => 'nullable|integer|min:1|max:1000000']);
|
||||
|
||||
return DB::transaction(function () use ($request, $actor, $equipment) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
$asset = Equipment::query()->when($actor->departmentScoped(), fn ($q) => $q->where('department_id', $actor->department_id))->findOrFail($equipment);
|
||||
$purchases = Requisition::query()->visibleTo($actor)->whereHas('items', fn ($q) => $q->where('equipment_id', $asset->id))
|
||||
->with(['items' => fn ($q) => $q->where('equipment_id', $asset->id)->select(['id', 'requisition_id', 'description', 'quantity', 'unit'])])
|
||||
->orderBy('id')->paginate(15, ['id', 'number', 'status', 'needed_by'], 'purchases_page')->withQueryString();
|
||||
$movements = StockOperation::query()->where('equipment_id', $asset->id)->orderBy('id')
|
||||
->paginate(15, ['id', 'kind', 'reference', 'quantity_milli', 'recorded_at', 'snapshot'], 'movements_page')->withQueryString()
|
||||
->through(fn (StockOperation $operation) => [
|
||||
'id' => $operation->id, 'kind' => $operation->kind, 'reference' => $operation->reference,
|
||||
'quantity_milli' => $operation->quantity_milli, 'recorded_at' => $operation->recorded_at,
|
||||
'item' => $operation->snapshot['stock_item'] ?? null, 'warehouse' => $operation->snapshot['warehouse'] ?? null,
|
||||
]);
|
||||
Inertia::encryptHistory();
|
||||
|
||||
$response = Inertia::render('equipment/show', ['equipment' => $asset->only(['id', 'code', 'description', 'area', 'status']),
|
||||
'geography' => app(AdministrativeGeography::class)->describe($asset->geography_reference),
|
||||
'warehouseRequests' => app(EquipmentWarehouseRequests::class)->page($actor, $asset),
|
||||
'purchases' => $purchases, 'movements' => $movements])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
});
|
||||
}
|
||||
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||
abort_unless($this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||
$filters = $request->validate(['location' => 'nullable|string|regex:/^[0-9]+$/D|max:20']);
|
||||
$geography = app(AdministrativeGeography::class);
|
||||
$assets = Equipment::query();
|
||||
if ($request->user()->departmentScoped()) {
|
||||
$assets->where('department_id', $request->user()->department_id);
|
||||
if (! empty($filters['location'])) {
|
||||
abort_unless($geography->availableFor('equipment'), 503);
|
||||
$assets->where('geography_reference->catalogue', config('geography.source_sha256'))->whereIn('geography_reference->record_id', $geography->descendants($filters['location']));
|
||||
}
|
||||
if ($this->actor($request)->departmentScoped()) {
|
||||
$assets->where('department_id', $this->actor($request)->department_id);
|
||||
}
|
||||
$equipment = $assets->orderBy('code')->get();
|
||||
$links = EquipmentSparePart::query()->whereIn('equipment_id', $equipment->pluck('id'))->get();
|
||||
$parts = SparePart::query();
|
||||
if ($request->user()->departmentScoped()) {
|
||||
if ($this->actor($request)->departmentScoped() || ! empty($filters['location'])) {
|
||||
$parts->whereIn('id', $links->pluck('spare_part_id'));
|
||||
}
|
||||
$parts = $parts->get()->map(function (SparePart $part) {
|
||||
@@ -47,24 +102,28 @@ class EquipmentController extends Controller
|
||||
});
|
||||
$items = StockItem::query();
|
||||
$departments = Department::query();
|
||||
if ($request->user()->departmentScoped()) {
|
||||
if ($this->actor($request)->departmentScoped() || ! empty($filters['location'])) {
|
||||
$items->whereIn('id', $parts->pluck('stock_item_id')->merge($equipment->pluck('stock_item_id')->filter()));
|
||||
$departments->whereKey($request->user()->department_id);
|
||||
if ($this->actor($request)->departmentScoped()) {
|
||||
$departments->whereKey($this->actor($request)->department_id);
|
||||
}
|
||||
}
|
||||
|
||||
return Inertia::render('equipment/index', [
|
||||
'geographyEnabled' => $geography->availableFor('equipment'), 'equipmentGeography' => $equipment->mapWithKeys(fn (Equipment $asset) => [$asset->id => $geography->describe($asset->geography_reference)])->all(),
|
||||
'filters' => $filters, 'geographyFilter' => empty($filters['location']) ? null : $geography->describe(['catalogue' => config('geography.source_sha256'), 'record_id' => $filters['location'], 'country' => 'MZ']),
|
||||
'equipment' => $equipment, 'parts' => $parts, 'links' => $links, 'levels' => CriticalityLevel::query()->orderBy('code')->get(),
|
||||
'items' => $items->orderBy('code')->get(['id', 'code', 'name', 'unit']),
|
||||
'departments' => $departments->orderBy('name')->get(['id', 'name']),
|
||||
'history' => StockOperation::query()->whereNotNull('equipment_id')->whereIn('equipment_id', $equipment->pluck('id'))->latest('id')->paginate(15),
|
||||
'canManage' => $request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]),
|
||||
'canConfigure' => $request->user()->hasFunctions([PurchasingRole::Admin]),
|
||||
'canManage' => $this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]),
|
||||
'canConfigure' => $this->actor($request)->hasFunctions([PurchasingRole::Admin]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request, string $kind): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$user = $this->actor($request);
|
||||
abort_unless(in_array($kind, ['categorias', 'activos', 'pecas', 'associacoes']), 404);
|
||||
abort_unless($kind === 'categorias' ? $user->hasFunctions([PurchasingRole::Admin]) : $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]), 403);
|
||||
$tenant = $user->tenant_id;
|
||||
@@ -76,9 +135,17 @@ class EquipmentController extends Controller
|
||||
'pecas' => ['id' => ['nullable', 'integer', $exists('spare_parts')], 'version' => 'nullable|required_with:id|integer|min:1', 'stock_item_id' => ['required', 'integer', $exists('stock_items'), Rule::unique('spare_parts')->ignore($request->input('id'))], 'criticality_level_id' => ['required', 'integer', $exists('criticality_levels')], 'minimum_quantity' => ['required', 'regex:/^\d{1,9}(\.\d{1,3})?$/']],
|
||||
'associacoes' => ['equipment_id' => ['required', 'integer', $exists('equipment')], 'spare_part_id' => ['required', 'integer', $exists('spare_parts')]],
|
||||
};
|
||||
if ($kind === 'activos') {
|
||||
$rules += app(AdministrativeGeography::class)->referenceRules('equipment');
|
||||
}
|
||||
$data = $request->validate($rules);
|
||||
DB::transaction(function () use ($data, $kind, $user) {
|
||||
app(ConflictGuard::class)->lockCompany($user);
|
||||
$user = app(CurrentActor::class)->lock($user, $kind === 'categorias' ? [PurchasingRole::Admin] : [PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
if ($kind === 'activos' && array_key_exists('geography_reference', $data)) {
|
||||
$data['geography_reference'] = app(AdministrativeGeography::class)->canonicalFor('equipment', $data['geography_reference']);
|
||||
}
|
||||
$model = match ($kind) {
|
||||
'categorias' => new CriticalityLevel,'activos' => new Equipment,'pecas' => new SparePart,'associacoes' => new EquipmentSparePart
|
||||
};
|
||||
|
||||
@@ -38,7 +38,7 @@ class GoodsReceiptController extends Controller
|
||||
private function visibleOrders(Request $request): Builder
|
||||
{
|
||||
Gate::authorize('viewAny', GoodsReceipt::class);
|
||||
$orders = PurchaseOrder::query();
|
||||
$orders = PurchaseOrder::query()->operational();
|
||||
if ($this->actor($request)->departmentScoped()) {
|
||||
$orders->whereIn('requisition_id', Requisition::query()->visibleTo($this->actor($request))->select('id'));
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ class InvoiceController extends Controller
|
||||
$response = Inertia::render('invoices/index', ['focusInvoiceId' => $focus, 'focusOrderId' => $focusOrder, 'stockReversals' => app(InventoryReversals::class)->financialNotices(), 'stockReturns' => app(InventoryDispositions::class)->financialNotices(),
|
||||
'invoices' => Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))->when($focus !== null, fn ($q) => $q->whereKey($focus))->when($focusOrder !== null, fn ($q) => $q->where('purchase_order_id', $focusOrder))->with('items')->latest('id')->paginate(15)->withQueryString()
|
||||
->through(fn (Invoice $invoice) => [...$invoice->toArray(), 'canValidate' => app(InvoiceWorkflow::class)->reviewerEligible($actor, $invoice)]),
|
||||
'orders' => PurchaseOrder::query()->visibleTo($actor)->with('items')->latest('id')->get()->map(fn ($order) => ['id' => $order->id, 'number' => $order->number, 'supplier' => $order->snapshot['supplier']['name'], 'items' => $order->items]),
|
||||
'orders' => PurchaseOrder::query()->visibleTo($actor)->operational()->with('items')->latest('id')->get()->map(fn ($order) => ['id' => $order->id, 'number' => $order->number, 'supplier' => $order->snapshot['supplier']['name'], 'items' => $order->items]),
|
||||
'payablesAvailable' => SupplierPayables::enabled() && app(SupplierPayables::class)->can($actor, 'view'), 'canManage' => $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor)])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\OrderCancellation;
|
||||
use App\Models\OrderCancellationPolicy;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\OrderCancellationPolicyWorkflow;
|
||||
use App\Services\OrderCancellationWorkflow;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class OrderCancellationController extends Controller
|
||||
{
|
||||
private function actor(Request $request): User
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
abort_unless(config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'), 503, 'Cancelamento de ordens não activado.');
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
public function index(Request $request, OrderCancellationWorkflow $workflow): Response
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
$focus = $request->validate(['cancellation_id' => 'nullable|integer|min:1'])['cancellation_id'] ?? null;
|
||||
abort_unless($actor->hasFunctions(['admin', 'procurement', 'finance', 'requester', 'department_head']), 403);
|
||||
|
||||
return DB::transaction(function () use ($request, $actor, $workflow, $focus) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
Inertia::encryptHistory();
|
||||
$records = OrderCancellation::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))
|
||||
->when($focus !== null, fn ($q) => $q->whereKey($focus))
|
||||
->orderByDesc('id')->paginate(15)->withQueryString()->through(function ($record) use ($actor, $workflow) {
|
||||
$order = PurchaseOrder::query()->findOrFail($record->purchase_order_id);
|
||||
$source = Requisition::query()->findOrFail($order->requisition_id);
|
||||
|
||||
return [...$record->only(['id', 'purchase_order_id', 'created_by', 'reason', 'evidence', 'status', 'review_reason', 'reviewed_at', 'revised_requisition_id']),
|
||||
'order_number' => $order->number, 'canDecide' => $workflow->canDecide($actor, $record),
|
||||
'source_href' => $actor->hasFunctions(['admin', 'procurement', 'finance', 'department_head']) ? '/ordens/'.$order->id : '/requisicoes/'.$source->id.'/processo',
|
||||
'canRevise' => $workflow->canRevise($actor, $record)];
|
||||
});
|
||||
$response = Inertia::render('purchase-controls/orders', ['records' => $records,
|
||||
'policies' => $actor->hasFunctions(['admin']) ? OrderCancellationPolicy::query()->latest('revision')->get()->map(fn ($p) => [...$p->toArray(),
|
||||
'canReview' => app(OrderCancellationPolicyWorkflow::class)->canReview($actor, $p)]) : [],
|
||||
'canAdminister' => $actor->hasFunctions(['admin']), 'canDecide' => $actor->hasFunctions(['finance'])])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
});
|
||||
}
|
||||
|
||||
public function request(Request $request, PurchaseOrder $order, OrderCancellationWorkflow $workflow): Response
|
||||
{
|
||||
$workflow->request($this->actor($request), $order, $request->all());
|
||||
|
||||
return redirect('/ordens/cancelamentos');
|
||||
}
|
||||
|
||||
public function decide(Request $request, int $cancellation, OrderCancellationWorkflow $workflow): Response
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|min:10|max:4000']);
|
||||
$workflow->decide($actor, OrderCancellation::query()->findOrFail($cancellation), $data['decision'], $data['reason']);
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function revise(Request $request, int $cancellation, OrderCancellationWorkflow $workflow): Response
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
$data = $request->validate(['needed_by' => 'required|date_format:Y-m-d|after_or_equal:today', 'reason' => 'required|string|min:10|max:4000']);
|
||||
$record = $workflow->revise($actor, OrderCancellation::query()->findOrFail($cancellation), $data['needed_by'], $data['reason']);
|
||||
|
||||
return redirect('/requisicoes/'.$record->id);
|
||||
}
|
||||
|
||||
public function policy(Request $request, OrderCancellationPolicyWorkflow $workflow): Response
|
||||
{
|
||||
$workflow->propose($this->actor($request), $request->all());
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function policyReview(Request $request, int $policy, OrderCancellationPolicyWorkflow $workflow): Response
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|min:10|max:4000']);
|
||||
$workflow->review($actor, OrderCancellationPolicy::query()->findOrFail($policy), $data['decision'], $data['reason']);
|
||||
|
||||
return back();
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\AdministrativeGeography;
|
||||
use App\Services\AiPreparationPlan;
|
||||
use App\Services\ComparisonPolicy;
|
||||
use App\Services\IntelligencePolicy;
|
||||
@@ -37,6 +38,8 @@ class OrganizationConfigurationController extends Controller
|
||||
$response = Inertia::render('company/parameters', ['ready' => $ready, 'active' => (bool) ($state->active ?? false), 'version' => $state->version ?? 1,
|
||||
'workflowTasks' => app(WorkflowTasks::class)->catalogue(),
|
||||
'activationPreview' => app(OrganizationActivationPreview::class)->build($actor),
|
||||
'geographyEnabled' => app(AdministrativeGeography::class)->enabled(),
|
||||
'geography' => app(AdministrativeGeography::class)->describe(Tenant::query()->findOrFail($actor->tenant_id)->geography_reference),
|
||||
'companyRules' => $this->companyRules((int) $actor->tenant_id),
|
||||
'comparisonPolicy' => app(ComparisonPolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
||||
'intelligencePolicy' => app(IntelligencePolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
||||
|
||||
@@ -15,9 +15,11 @@ use App\Services\PeopleEvidenceBrief;
|
||||
use App\Services\PeopleForms;
|
||||
use App\Services\PeopleHiring;
|
||||
use App\Services\PeopleOperationalInsights;
|
||||
use App\Services\PeopleProcessProjection;
|
||||
use App\Services\PeopleRegistry;
|
||||
use App\Services\PeopleWorkdesk;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -89,21 +91,9 @@ class PeopleHiringController extends Controller
|
||||
$access = app(PeopleAccess::class);
|
||||
abort_unless($access->can($this->actor($request), $record, 'view'), 403);
|
||||
$registrySearch = $request->validate(['cadastro' => 'nullable|string|max:100'])['cadastro'] ?? '';
|
||||
$snapshot = $workflow->snapshot($record);
|
||||
$rows = $workflow->matrix($record);
|
||||
if (! $access->can($this->actor($request), $record, 'financial')) {
|
||||
unset($snapshot['rules']['annex']['fields']['financial']);
|
||||
unset($snapshot['selection']['rules']['annex']['fields']['financial']);
|
||||
}
|
||||
if (! $access->can($this->actor($request), $record, 'interviews')) {
|
||||
$rows = array_map(fn ($row) => [...$row, 'reviews' => []], $rows);
|
||||
if (isset($snapshot['selection']['rows'])) {
|
||||
$snapshot['selection']['rows'] = array_map(fn ($row) => [...$row, 'reviews' => []], $snapshot['selection']['rows']);
|
||||
}
|
||||
}
|
||||
if (! $access->can($this->actor($request), $record, 'contract') && ! $access->can($this->actor($request), $record, 'contract_view')) {
|
||||
$snapshot['contract'] = null;
|
||||
}
|
||||
$projection = app(PeopleProcessProjection::class)->read($this->actor($request), $record);
|
||||
$snapshot = $projection['process'];
|
||||
$rows = $projection['candidates'];
|
||||
$clarifications = app(PeopleClarifications::class)->page($this->actor($request), $record);
|
||||
$company = Tenant::query()->findOrFail($this->actor($request)->tenant_id);
|
||||
$policy = app(IntelligencePolicy::class)->company($company);
|
||||
@@ -127,6 +117,24 @@ class PeopleHiringController extends Controller
|
||||
});
|
||||
}
|
||||
|
||||
public function dossier(Request $request, int $process, PeopleProcessProjection $projection): Response
|
||||
{
|
||||
return DB::transaction(function () use ($request, $process, $projection) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
$record = PeopleProcess::query()->findOrFail($process);
|
||||
$data = $projection->read($this->actor($request), $record);
|
||||
|
||||
return response()->json(['schema' => 'sgc.people.process-dossier.v1', 'exported_at' => now()->toIso8601String(),
|
||||
'effect' => 'preparation_only',
|
||||
'process' => Arr::only($data['process'], ['id', 'kind', 'title', 'purpose', 'closes_on', 'status', 'version', 'selected_application_id', 'rules', 'selection', 'contract']),
|
||||
'candidates' => $data['candidates']])
|
||||
->header('Content-Disposition', 'attachment; filename="PES-'.$record->id.'-dossier-v'.$record->version.'.json"')
|
||||
->header('Cache-Control', 'private, no-store, max-age=0')->header('X-Content-Type-Options', 'nosniff');
|
||||
});
|
||||
}
|
||||
|
||||
public function access(Request $request, int $process, PeopleAccess $access): Response
|
||||
{
|
||||
$record = PeopleProcess::query()->findOrFail($process);
|
||||
|
||||
@@ -11,12 +11,14 @@ use App\Models\RecommendationAttempt;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\FormalRecommendation;
|
||||
use App\Services\OrderCancellationWorkflow;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\ProposalComparison;
|
||||
use App\Services\PurchaseWorkflow;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
@@ -117,6 +119,9 @@ class PurchaseController extends Controller
|
||||
|
||||
return Inertia::render('purchases/show', [
|
||||
'order' => $order->load('items'),
|
||||
'orderCancellation' => ['enabled' => (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
|
||||
'state' => app(OrderCancellationWorkflow::class)->state($order),
|
||||
'canRequest' => app(OrderCancellationWorkflow::class)->canRequest($actor, $order)],
|
||||
'history' => AuditLog::query()->where('requisition_id', $order->requisition_id)->whereIn('action', ['award.created', 'award.approved', 'award.rejected', 'purchase_order.issued'])->orderBy('id')->get(['id', 'user_id', 'action', 'created_at']),
|
||||
]);
|
||||
}
|
||||
@@ -126,6 +131,7 @@ class PurchaseController extends Controller
|
||||
$actor = $this->access($request);
|
||||
PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id);
|
||||
|
||||
return view('purchases.print', ['order' => $order->load('items'), 'snapshot' => $order->snapshot]);
|
||||
return view('purchases.print', ['order' => $order->load('items'), 'snapshot' => $order->snapshot,
|
||||
'operationalState' => app(OrderCancellationWorkflow::class)->state($order)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,24 +5,39 @@ namespace App\Http\Controllers;
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\StockItem;
|
||||
use App\Models\StockMovement;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\AdministrativeGeography;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\CurrentActor;
|
||||
use App\Services\InventoryLots;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class StockController extends Controller
|
||||
{
|
||||
private function actor(Request $request): User
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
private function access(Request $request, bool $manage = false): void
|
||||
{
|
||||
$roles = $manage ? [PurchasingRole::Admin, PurchasingRole::Warehouse] : [PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance];
|
||||
abort_unless($request->user()->hasFunctions($roles), 403);
|
||||
abort_unless($this->actor($request)->hasFunctions($roles), 403);
|
||||
}
|
||||
|
||||
public function index(Request $request): Response
|
||||
@@ -30,15 +45,30 @@ class StockController extends Controller
|
||||
$this->access($request);
|
||||
$filters = $request->validate([
|
||||
'search' => 'nullable|string|max:100',
|
||||
'warehouse_id' => ['nullable', 'integer', Rule::exists('warehouses', 'id')->where('tenant_id', $request->user()->tenant_id)],
|
||||
'location' => 'nullable|string|regex:/^[0-9]+$/D|max:20',
|
||||
'warehouse_id' => ['nullable', 'integer', Rule::exists('warehouses', 'id')->where('tenant_id', $this->actor($request)->tenant_id)],
|
||||
]);
|
||||
$items = StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']);
|
||||
$warehouses = Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']);
|
||||
$geography = app(AdministrativeGeography::class);
|
||||
$warehouseQuery = Warehouse::query();
|
||||
if (! empty($filters['location'])) {
|
||||
abort_unless($geography->availableFor('warehouses'), 503);
|
||||
$warehouseQuery->where('geography_reference->catalogue', config('geography.source_sha256'))->whereIn('geography_reference->record_id', $geography->descendants($filters['location']));
|
||||
}
|
||||
$columns = ['id', 'code', 'name'];
|
||||
if (Schema::hasColumn('warehouses', 'geography_reference')) {
|
||||
$columns[] = 'geography_reference';
|
||||
}
|
||||
$warehouses = $warehouseQuery->orderBy('code')->get($columns);
|
||||
$warehouseGeography = $warehouses->mapWithKeys(fn (Warehouse $warehouse) => [$warehouse->id => $geography->describe($warehouse->geography_reference)])->all();
|
||||
$selected = StockItem::query();
|
||||
if (! empty($filters['search'])) {
|
||||
$selected->where(fn ($q) => $q->where('code', 'like', '%'.$filters['search'].'%')->orWhere('name', 'like', '%'.$filters['search'].'%'));
|
||||
}
|
||||
$movements = StockMovement::query()->whereIn('stock_item_id', $selected->select('id'));
|
||||
if (! empty($filters['location'])) {
|
||||
$movements->whereIn('warehouse_id', $warehouses->pluck('id'));
|
||||
}
|
||||
if (! empty($filters['warehouse_id'])) {
|
||||
$movements->where('warehouse_id', $filters['warehouse_id']);
|
||||
}
|
||||
@@ -50,8 +80,10 @@ class StockController extends Controller
|
||||
|
||||
return Inertia::render('stock/index', [
|
||||
'items' => $items, 'warehouses' => $warehouses, 'balances' => $balances,
|
||||
'geographyEnabled' => $geography->availableFor('warehouses'), 'warehouseGeography' => $warehouseGeography,
|
||||
'geographyFilter' => empty($filters['location']) ? null : $geography->describe(['catalogue' => config('geography.source_sha256'), 'record_id' => $filters['location'], 'country' => 'MZ']),
|
||||
'movements' => $movements->latest('id')->paginate(20)->withQueryString(), 'filters' => $filters,
|
||||
'canManage' => $request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse]),
|
||||
'canManage' => $this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse]),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -60,12 +92,12 @@ class StockController extends Controller
|
||||
$this->access($request, true);
|
||||
$request->merge(['code' => Str::upper(trim($request->string('code')->toString())), 'unit' => Str::lower(trim($request->string('unit')->toString()))]);
|
||||
$data = $request->validate([
|
||||
'code' => ['required', 'regex:/^[A-Z0-9][A-Z0-9._-]{0,29}$/', Rule::unique('stock_items')->where('tenant_id', $request->user()->tenant_id)],
|
||||
'code' => ['required', 'regex:/^[A-Z0-9][A-Z0-9._-]{0,29}$/', Rule::unique('stock_items')->where('tenant_id', $this->actor($request)->tenant_id)],
|
||||
'name' => 'required|string|max:200', 'unit' => 'required|string|max:30',
|
||||
]);
|
||||
DB::transaction(function () use ($request, $audit, $data) {
|
||||
$item = StockItem::query()->create([...$data, 'tenant_id' => $request->user()->tenant_id, 'created_by' => $request->user()->id]);
|
||||
$audit->audit($request->user(), 'stock.item_created', null, null, $item->toArray());
|
||||
$item = StockItem::query()->create([...$data, 'tenant_id' => $this->actor($request)->tenant_id, 'created_by' => $this->actor($request)->id]);
|
||||
$audit->audit($this->actor($request), 'stock.item_created', null, null, $item->toArray());
|
||||
});
|
||||
|
||||
return back();
|
||||
@@ -76,12 +108,44 @@ class StockController extends Controller
|
||||
$this->access($request, true);
|
||||
$request->merge(['code' => Str::upper(trim($request->string('code')->toString()))]);
|
||||
$data = $request->validate([
|
||||
'code' => ['required', 'regex:/^[A-Z0-9][A-Z0-9._-]{0,29}$/', Rule::unique('warehouses')->where('tenant_id', $request->user()->tenant_id)],
|
||||
'code' => ['required', 'regex:/^[A-Z0-9][A-Z0-9._-]{0,29}$/', Rule::unique('warehouses')->where('tenant_id', $this->actor($request)->tenant_id)],
|
||||
'name' => 'required|string|max:200',
|
||||
...app(AdministrativeGeography::class)->referenceRules('warehouses'),
|
||||
]);
|
||||
DB::transaction(function () use ($request, $audit, $data) {
|
||||
$warehouse = Warehouse::query()->create([...$data, 'tenant_id' => $request->user()->tenant_id, 'created_by' => $request->user()->id]);
|
||||
$audit->audit($request->user(), 'stock.warehouse_created', null, null, $warehouse->toArray());
|
||||
app(ConflictGuard::class)->lockCompany($this->actor($request));
|
||||
$actor = app(CurrentActor::class)->lock($this->actor($request), [PurchasingRole::Admin, PurchasingRole::Warehouse]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
if (array_key_exists('geography_reference', $data)) {
|
||||
$data['geography_reference'] = app(AdministrativeGeography::class)->canonicalFor('warehouses', $data['geography_reference']);
|
||||
}
|
||||
$warehouse = Warehouse::query()->create([...$data, 'tenant_id' => $this->actor($request)->tenant_id, 'created_by' => $this->actor($request)->id]);
|
||||
$audit->audit($this->actor($request), 'stock.warehouse_created', null, null, $warehouse->toArray());
|
||||
});
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function warehouseGeography(Request $request, int $warehouse, RequisitionWorkflow $audit): RedirectResponse
|
||||
{
|
||||
$this->access($request, true);
|
||||
$geography = app(AdministrativeGeography::class);
|
||||
abort_unless($geography->availableFor('warehouses'), 503);
|
||||
$data = $request->validate([...$geography->referenceRules('warehouses'), 'geography_reference' => 'present|nullable|array:country,catalogue,record_id', 'expected_reference' => 'present|nullable|array:country,catalogue,record_id']);
|
||||
DB::transaction(function () use ($request, $warehouse, $audit, $data, $geography) {
|
||||
app(ConflictGuard::class)->lockCompany($this->actor($request));
|
||||
$actor = app(CurrentActor::class)->lock($this->actor($request), [PurchasingRole::Admin, PurchasingRole::Warehouse]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$record = Warehouse::query()->lockForUpdate()->findOrFail($warehouse);
|
||||
if ($record->geography_reference != $data['expected_reference']) {
|
||||
throw ValidationException::withMessages(['geography_reference' => 'A localização mudou. Actualize antes de guardar.']);
|
||||
}
|
||||
$before = $record->toArray();
|
||||
$after = $geography->canonicalFor('warehouses', $data['geography_reference']);
|
||||
if ($record->geography_reference != $after) {
|
||||
$record->update(['geography_reference' => $after]);
|
||||
$audit->audit($actor, 'stock.warehouse_geography_updated', null, $before, $record->toArray());
|
||||
}
|
||||
});
|
||||
|
||||
return back();
|
||||
|
||||
@@ -6,9 +6,11 @@ use App\Enums\PurchasingRole;
|
||||
use App\Http\Requests\SaveSupplierRequest;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Services\AdministrativeGeography;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\CurrentActor;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplierGeography;
|
||||
use App\Services\SupplierParticipation;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -41,13 +43,16 @@ class SupplierController extends Controller
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
abort_unless($this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||
$filters = $request->validate(['search' => 'nullable|string|max:100']);
|
||||
$filters = $request->validate(['search' => 'nullable|string|max:100', 'location' => 'nullable|string|regex:/^[0-9]+$/D|max:20']);
|
||||
$query = Supplier::query();
|
||||
if (! empty($filters['location'])) {
|
||||
$query = app(SupplierGeography::class)->matching($filters['location']);
|
||||
}
|
||||
if (! empty($filters['search'])) {
|
||||
$query->where(fn ($q) => $q->where('name', 'like', '%'.$filters['search'].'%')->orWhere('nuit', 'like', '%'.$filters['search'].'%'));
|
||||
}
|
||||
|
||||
return Inertia::render('suppliers/index', ['suppliers' => $query->orderBy('name')->paginate(15)->withQueryString(), 'filters' => $filters, 'canCreate' => app(SupplierParticipation::class)->canPrepare($this->actor($request)), 'canReview' => app(SupplierParticipation::class)->canReviewRole($this->actor($request))]);
|
||||
return Inertia::render('suppliers/index', ['suppliers' => $query->orderBy('name')->paginate(15)->withQueryString(), 'filters' => $filters, 'geographyFilter' => empty($filters['location']) ? null : app(AdministrativeGeography::class)->describe(['catalogue' => config('geography.source_sha256'), 'record_id' => $filters['location'], 'country' => 'MZ']), 'geographyEnabled' => app(AdministrativeGeography::class)->enabled(), 'canCreate' => app(SupplierParticipation::class)->canPrepare($this->actor($request)), 'canReview' => app(SupplierParticipation::class)->canReviewRole($this->actor($request))]);
|
||||
}
|
||||
|
||||
public function store(SaveSupplierRequest $request, RequisitionWorkflow $workflow): RedirectResponse
|
||||
@@ -56,6 +61,9 @@ class SupplierController extends Controller
|
||||
DB::transaction(function () use ($request, $data, $workflow) {
|
||||
$actor = $this->currentActor($request, PurchasingRole::Procurement);
|
||||
abort_unless(app(SupplierParticipation::class)->canPrepare($actor), 403);
|
||||
if (array_key_exists('geography_reference', $data)) {
|
||||
$data['geography_reference'] = app(AdministrativeGeography::class)->canonical($data['geography_reference']);
|
||||
}
|
||||
$supplier = Supplier::query()->create([...$data, 'tenant_id' => $actor->tenant_id, 'created_by' => $actor->id, 'last_changed_by' => $actor->id, 'status' => 'pending']);
|
||||
$workflow->audit($actor, 'supplier.created', null, null, $supplier->toArray());
|
||||
});
|
||||
@@ -71,6 +79,7 @@ class SupplierController extends Controller
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('suppliers/show', [
|
||||
'supplier' => $supplier,
|
||||
'geography' => app(AdministrativeGeography::class)->describe($supplier->geography_reference),
|
||||
'documents' => $canDocuments ? $supplier->documents()->latest('id')->get() : [],
|
||||
'canEdit' => $this->actor($request)->can('update', $supplier),
|
||||
'canDocuments' => $canDocuments,
|
||||
@@ -85,7 +94,7 @@ class SupplierController extends Controller
|
||||
{
|
||||
Gate::authorize('update', $supplier);
|
||||
|
||||
return Inertia::render('suppliers/edit', ['supplier' => $supplier]);
|
||||
return Inertia::render('suppliers/edit', ['supplier' => $supplier, 'geographyEnabled' => app(AdministrativeGeography::class)->enabled(), 'geography' => app(AdministrativeGeography::class)->describe($supplier->geography_reference)]);
|
||||
}
|
||||
|
||||
public function update(SaveSupplierRequest $request, Supplier $supplier, RequisitionWorkflow $workflow): RedirectResponse
|
||||
@@ -95,6 +104,9 @@ class SupplierController extends Controller
|
||||
DB::transaction(function () use ($request, $supplier, $workflow, $data) {
|
||||
$actor = $this->currentActor($request, PurchasingRole::Procurement);
|
||||
abort_unless(app(SupplierParticipation::class)->canPrepare($actor), 403);
|
||||
if (array_key_exists('geography_reference', $data)) {
|
||||
$data['geography_reference'] = app(AdministrativeGeography::class)->canonical($data['geography_reference']);
|
||||
}
|
||||
$supplier = Supplier::query()->lockForUpdate()->findOrFail($supplier->id);
|
||||
if ($supplier->version !== (int) $data['version']) {
|
||||
throw ValidationException::withMessages(['version' => 'A ficha foi alterada por outro utilizador. Reabra a edição para carregar os dados actuais.']);
|
||||
|
||||
@@ -5,7 +5,9 @@ namespace App\Http\Controllers;
|
||||
use App\Models\SupplierEvaluation;
|
||||
use App\Models\SupplierImprovement;
|
||||
use App\Models\User;
|
||||
use App\Services\AdministrativeGeography;
|
||||
use App\Services\SupplierEvaluationWorkflow;
|
||||
use App\Services\SupplierGeography;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -16,6 +18,22 @@ use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class SupplierImprovementReportController extends Controller
|
||||
{
|
||||
private function actor(Request $request): User
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $filters
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
private function territory(array $filters): ?array
|
||||
{
|
||||
return empty($filters['location']) ? null : app(AdministrativeGeography::class)->describe(['country' => 'MZ', 'catalogue' => config('geography.source_sha256'), 'record_id' => $filters['location']]);
|
||||
}
|
||||
|
||||
private function snapshot(\Closure $read): mixed
|
||||
{
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() !== 0) {
|
||||
@@ -34,12 +52,12 @@ class SupplierImprovementReportController extends Controller
|
||||
/** @return array<string,mixed> */
|
||||
private function filters(Request $request): array
|
||||
{
|
||||
$actor = app(SupplierEvaluationWorkflow::class)->reader($request->user());
|
||||
$actor = app(SupplierEvaluationWorkflow::class)->reader($this->actor($request));
|
||||
$request->setUserResolver(fn () => $actor);
|
||||
abort_unless(Schema::hasTable('supplier_improvements'), 503, 'A instalação das medidas de melhoria ainda não está concluída.');
|
||||
$filters = $request->validate(['supplier_id' => 'nullable|integer|min:1', 'responsible_id' => 'nullable|integer|min:1',
|
||||
'status' => 'nullable|in:open,review,returned,closed', 'from' => 'nullable|date_format:Y-m-d', 'to' => 'nullable|date_format:Y-m-d',
|
||||
'overdue' => 'nullable|in:1', 'search' => 'nullable|string|max:200']);
|
||||
'overdue' => 'nullable|in:1', 'search' => 'nullable|string|max:200', 'location' => 'nullable|string|regex:/^[0-9]+$/D|max:20']);
|
||||
if (! empty($filters['from']) && ! empty($filters['to']) && $filters['to'] < $filters['from']) {
|
||||
throw ValidationException::withMessages(['to' => 'O fim do intervalo deve ser igual ou posterior ao início.']);
|
||||
}
|
||||
@@ -52,7 +70,11 @@ class SupplierImprovementReportController extends Controller
|
||||
*/
|
||||
private function query(Request $request, array $filters, string $today): Builder
|
||||
{
|
||||
$query = SupplierImprovement::query()->visibleTo($request->user());
|
||||
$query = SupplierImprovement::query()->visibleTo($this->actor($request));
|
||||
if (! empty($filters['location'])) {
|
||||
$suppliers = app(SupplierGeography::class)->matching($filters['location'])->select('id');
|
||||
$query->whereHas('evaluation', fn ($evaluation) => $evaluation->whereIn('supplier_id', $suppliers));
|
||||
}
|
||||
if (! empty($filters['supplier_id'])) {
|
||||
$query->whereHas('evaluation', fn ($q) => $q->where('supplier_id', $filters['supplier_id']));
|
||||
}
|
||||
@@ -81,7 +103,7 @@ class SupplierImprovementReportController extends Controller
|
||||
*/
|
||||
private function records(Builder $query, Request $request): Builder
|
||||
{
|
||||
return $query->with(['evaluation:id,supplier_id,supplier_snapshot,revision', 'responsible' => fn ($q) => $q->where('tenant_id', $request->user()->tenant_id)->select(['id', 'name'])]);
|
||||
return $query->with(['evaluation:id,supplier_id,supplier_snapshot,revision', 'responsible' => fn ($q) => $q->where('tenant_id', $this->actor($request)->tenant_id)->select(['id', 'name'])]);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
@@ -99,17 +121,17 @@ class SupplierImprovementReportController extends Controller
|
||||
$props = $this->snapshot(function () use ($request): array {
|
||||
$filters = $this->filters($request);
|
||||
$today = today()->toDateString();
|
||||
$all = SupplierImprovement::query()->visibleTo($request->user());
|
||||
$all = SupplierImprovement::query()->visibleTo($this->actor($request));
|
||||
$query = $this->query($request, $filters, $today);
|
||||
$counts = (clone $query)->selectRaw('status, COUNT(*) AS count')->groupBy('status')->pluck('count', 'status')->map(fn ($n) => (int) $n);
|
||||
$overdue = (clone $query)->where('status', '!=', 'closed')->where('due_on', '<', $today)->count();
|
||||
// Choices derive only from visible measures, including prior revisions and former assignees.
|
||||
$evaluations = SupplierEvaluation::query()->visibleTo($request->user())->whereIn('id', (clone $all)->select('supplier_evaluation_id'))->orderByDesc('id')->get(['supplier_id', 'supplier_snapshot']);
|
||||
$evaluations = SupplierEvaluation::query()->visibleTo($this->actor($request))->whereIn('id', (clone $all)->select('supplier_evaluation_id'))->orderByDesc('id')->get(['supplier_id', 'supplier_snapshot']);
|
||||
|
||||
return ['filters' => $filters, 'today' => $today, 'generatedAt' => now()->toIso8601String(), 'counts' => $counts, 'overdue' => $overdue,
|
||||
return ['filters' => $filters, 'geographyEnabled' => app(AdministrativeGeography::class)->enabled(), 'geographyFilter' => $this->territory($filters), 'today' => $today, 'generatedAt' => now()->toIso8601String(), 'counts' => $counts, 'overdue' => $overdue,
|
||||
'records' => $this->records($query, $request)->orderBy('due_on')->orderBy('id')->paginate(25)->withQueryString()->through(fn (SupplierImprovement $m) => $this->row($m, $today)),
|
||||
'suppliers' => $evaluations->map(fn (SupplierEvaluation $e) => ['id' => $e->supplier_id, 'name' => $e->supplier_snapshot['name']])->unique('id')->values(),
|
||||
'responsibles' => User::query()->where('tenant_id', $request->user()->tenant_id)->whereIn('id', (clone $all)->select('responsible_id'))->orderBy('name')->get(['id', 'name'])];
|
||||
'responsibles' => User::query()->where('tenant_id', $this->actor($request)->tenant_id)->whereIn('id', (clone $all)->select('responsible_id'))->orderBy('name')->get(['id', 'name'])];
|
||||
});
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('reports/supplier-improvements', $props)->toResponse($request);
|
||||
@@ -121,6 +143,9 @@ class SupplierImprovementReportController extends Controller
|
||||
public function csv(Request $request): Response
|
||||
{
|
||||
$filters = $this->filters($request);
|
||||
if (! empty($filters['location'])) {
|
||||
app(SupplierGeography::class)->matching($filters['location']);
|
||||
}
|
||||
$text = fn (?string $value) => preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', $value ?? '') ? "'".$value : ($value ?? '');
|
||||
|
||||
return response()->streamDownload(fn () => $this->snapshot(function () use ($request, $filters, $text) {
|
||||
@@ -133,7 +158,12 @@ class SupplierImprovementReportController extends Controller
|
||||
}
|
||||
fwrite($out, "\xEF\xBB\xBF");
|
||||
fputcsv($out, ['Medidas de melhoria de fornecedores', 'Consulta', now()->toIso8601String(), 'Data de referência', $today], ';', '"', '');
|
||||
fputcsv($out, ['Filtros', $text(json_encode($filters, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR))], ';', '"', '');
|
||||
$exportFilters = $filters;
|
||||
if (! empty($filters['location'])) {
|
||||
$territory = $this->territory($filters);
|
||||
$exportFilters['localizacao_actual_da_ficha'] = implode(' / ', array_column($territory['path'] ?? [], 'name'));
|
||||
}
|
||||
fputcsv($out, ['Filtros', $text(json_encode($exportFilters, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR))], ';', '"', '');
|
||||
fputcsv($out, ['Medida', 'Fornecedor preservado', 'Avaliação', 'Revisão', 'Título', 'Objectivo', 'Responsável', 'Prazo', 'Estado', 'Prazo ultrapassado', 'Versão', 'Resultado', 'Evidência', 'Última conferência', 'Conferida em', 'Avaliação e acompanhamento', 'Relatório individual'], ';', '"', '');
|
||||
foreach ($this->records($this->query($request, $filters, $today), $request)->lazyById(200) as $m) {
|
||||
$row = $this->row($m, $today);
|
||||
|
||||
@@ -8,6 +8,7 @@ use App\Models\StockItem;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Models\WarehouseRequest;
|
||||
use App\Models\WarehouseRequestEvent;
|
||||
use App\Services\InternalSupplyTrace;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\WarehouseFulfilment;
|
||||
@@ -22,6 +23,12 @@ use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class WarehouseRequestController extends Controller
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
private function filters(Request $request, User $actor): array
|
||||
{
|
||||
return $request->validate(['view' => 'nullable|in:all,review,reserve,delivery,receipt', 'state' => 'nullable|in:all,draft,submitted,authorized,partial,delivered,closed,rejected,cancelled', 'search' => 'nullable|string|max:100', 'warehouse_id' => ['nullable', 'integer', Rule::exists('warehouses', 'id')->where('tenant_id', $actor->tenant_id)], 'page' => 'nullable|integer|min:1|max:1000000']);
|
||||
}
|
||||
|
||||
public function index(Request $request, WarehouseWorkdesk $desk): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
@@ -31,21 +38,10 @@ class WarehouseRequestController extends Controller
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
$filters = $request->validate(['view' => 'nullable|in:all,review,reserve,delivery,receipt', 'state' => 'nullable|in:all,draft,submitted,authorized,partial,delivered,closed,rejected,cancelled', 'search' => 'nullable|string|max:100', 'warehouse_id' => ['nullable', 'integer', Rule::exists('warehouses', 'id')->where('tenant_id', $actor->tenant_id)], 'page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$filters = $this->filters($request, $actor);
|
||||
$prepare = $actor->hasFunctions(['warehouse_request_prepare']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor);
|
||||
$ready = Schema::hasTable('warehouse_requests');
|
||||
$base = $desk->visible($actor);
|
||||
if (! empty($filters['warehouse_id'])) {
|
||||
$base->where('warehouse_id', $filters['warehouse_id']);
|
||||
}
|
||||
if (! empty($filters['search'])) {
|
||||
$search = trim($filters['search']);
|
||||
if (preg_match('/^(?:RA-)?([1-9][0-9]{0,9})$/iD', $search, $match)) {
|
||||
$base->whereKey($match[1]);
|
||||
} else {
|
||||
$base->where(fn ($q) => $q->whereLike('snapshot->requester->name', '%'.$search.'%')->orWhereLike('snapshot->destination', '%'.$search.'%'));
|
||||
}
|
||||
}
|
||||
$base = $desk->filteredBase($actor, $filters);
|
||||
$views = $ready ? $desk->views(clone $base, $actor) : [];
|
||||
$query = $desk->forView(clone $base, $actor, $filters['view'] ?? 'all');
|
||||
$states = $ready ? DB::query()->fromSub((clone $query)->selectRaw($desk->stateExpression().' as projected_state')->toBase(), 'request_states')->selectRaw('projected_state, COUNT(*) as total')->groupBy('projected_state')->pluck('total', 'projected_state') : [];
|
||||
@@ -70,6 +66,49 @@ class WarehouseRequestController extends Controller
|
||||
});
|
||||
}
|
||||
|
||||
public function csv(Request $request, WarehouseWorkdesk $desk): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User && $actor->hasFunctions(['admin', 'warehouse_request_read', 'warehouse_request_prepare', 'warehouse_request_review', 'warehouse_request_deliver']), 403);
|
||||
$filters = $this->filters($request, $actor);
|
||||
abort_unless(Schema::hasTable('warehouse_requests'), 503);
|
||||
|
||||
return response()->streamDownload(function () use ($actor, $filters, $desk) {
|
||||
DB::transaction(function () use ($actor, $filters, $desk) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
$actor = User::query()->findOrFail($actor->id);
|
||||
abort_unless($actor->hasFunctions(['admin', 'warehouse_request_read', 'warehouse_request_prepare', 'warehouse_request_review', 'warehouse_request_deliver']), 403);
|
||||
$query = $desk->forView($desk->filteredBase($actor, $filters), $actor, $filters['view'] ?? 'all');
|
||||
if (($filters['state'] ?? 'all') !== 'all') {
|
||||
$query->whereRaw($desk->stateExpression().' = ?', [$filters['state']]);
|
||||
}
|
||||
$out = fopen('php://output', 'w');
|
||||
if ($out === false) {
|
||||
throw new \RuntimeException('Não foi possível gerar o ficheiro.');
|
||||
}
|
||||
$safe = fn (string $value): string => preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', $value) ? "'".$value : $value;
|
||||
try {
|
||||
fwrite($out, "\xEF\xBB\xBF");
|
||||
fputcsv($out, ['Requisições internas', now()->toIso8601String(), 'Sem factura; entregas acumuladas não descontam devoluções ou correcções.'], ';', '"', '');
|
||||
fputcsv($out, ['Filtros', json_encode(array_diff_key($filters, ['page' => true]), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)], ';', '"', '');
|
||||
fputcsv($out, ['Requisição', 'Estado', 'Versão', 'Requisitante', 'Armazém', 'Centro de custo', 'Destino', 'Finalidade', 'Linha', 'Artigo', 'Descrição', 'Unidade', 'Utilização', 'Equipamento', 'Pedida', 'Reservada agora', 'Entregue acumulada', 'Por entregar', 'Cancelada', 'Reservas disponíveis', 'Consulta'], ';', '"', '');
|
||||
foreach ($query->lazyById(100) as $record) {
|
||||
$p = app(WarehouseFulfilment::class)->progress($record);
|
||||
$s = $record->snapshot;
|
||||
foreach ($s['lines'] as $index => $line) {
|
||||
$row = ['RA-'.$record->id, $p['state'], (string) $p['version'], $s['requester']['name'], $s['warehouse']['code'], $s['cost_center']['code'], $s['destination'], $s['reason'], (string) ($index + 1), $line['item']['code'], $line['item']['name'], $line['item']['unit'], $line['destination'], $line['equipment']['code'] ?? '', ...array_map(fn ($quantity) => number_format($quantity / 1000, 3, '.', ''), [$line['quantity_milli'], $p['reserved'][$index], $p['delivered'][$index], $p['remaining'][$index], $p['cancelled'][$index]]), $p['reservation_ready'] ? 'Sim' : 'Não', url('/stock/requisicoes/'.$record->id)];
|
||||
fputcsv($out, array_map($safe, $row), ';', '"', '');
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fclose($out);
|
||||
}
|
||||
});
|
||||
}, 'requisicoes-internas-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||
}
|
||||
|
||||
public function store(Request $request, WarehouseRequests $service): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
@@ -94,7 +133,7 @@ class WarehouseRequestController extends Controller
|
||||
$p = $service->progress($r);
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('stock/request', ['record' => $r->only(['id', 'snapshot', 'created_at']), 'progress' => $p, 'ready' => Schema::hasTable('warehouse_request_events'),
|
||||
'canViewReturns' => config('stock_returns.enabled') && $actor->hasFunctions(['warehouse_return_read']) && !app(OrganizationAccess::class)->maintenanceOnly($actor),
|
||||
'canViewReturns' => config('stock_returns.enabled') && $actor->hasFunctions(['warehouse_return_read']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor),
|
||||
'health' => $desk->health($r, $p), 'people' => $desk->people($r, $p),
|
||||
'supplyTrace' => app(InternalSupplyTrace::class)->forRequest($actor, $r, $p), ...$desk->actions($actor, $r, $p)])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
@@ -111,4 +150,44 @@ class WarehouseRequestController extends Controller
|
||||
|
||||
return redirect('/stock/requisicoes/'.$id);
|
||||
}
|
||||
|
||||
public function printRequest(Request $request, int $id, WarehouseFulfilment $service): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $service) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
$record = WarehouseRequest::query()->findOrFail($id);
|
||||
abort_unless(app(WarehouseWorkdesk::class)->canView($actor, $record), 403);
|
||||
|
||||
return response()->view('stock.request-print', ['record' => $record, 'progress' => $service->progress($record), 'generatedAt' => now()])
|
||||
->header('Cache-Control', 'private, no-store, max-age=0')->header('X-Content-Type-Options', 'nosniff');
|
||||
});
|
||||
}
|
||||
|
||||
public function printDelivery(Request $request, int $id, int $delivery): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $delivery) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
$record = WarehouseRequest::query()->findOrFail($id);
|
||||
abort_unless(app(WarehouseWorkdesk::class)->canView($actor, $record), 403);
|
||||
abort_unless(Schema::hasTable('warehouse_request_events'), 503, 'Registo de entregas indisponível.');
|
||||
$event = WarehouseRequestEvent::query()->where('warehouse_request_id', $record->id)->where('action', 'deliver')->findOrFail($delivery);
|
||||
$confirmation = WarehouseRequestEvent::query()->where('warehouse_request_id', $record->id)->where('action', 'receive')
|
||||
->where('data->delivery_event_id', $event->id)->orderBy('version')->first();
|
||||
$authorization = WarehouseRequestEvent::query()->where('warehouse_request_id', $record->id)->where('action', 'authorize')
|
||||
->where('version', '<', $event->version)->orderByDesc('version')->first();
|
||||
|
||||
return response()->view('stock.delivery-print', ['record' => $record, 'delivery' => $event, 'confirmation' => $confirmation, 'authorization' => $authorization])
|
||||
->header('Cache-Control', 'private, no-store, max-age=0')->header('X-Content-Type-Options', 'nosniff');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,12 +8,20 @@ use App\Services\RequisitionWorkflow;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Laravel\Fortify\Features;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class EnterLocalEvaluation
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if (Features::enabled(Features::twoFactorAuthentication())) {
|
||||
if ($request->is('avaliar', 'avaliar/*', 'demo', 'demo/*')) {
|
||||
return redirect('/login')->header('Cache-Control', 'private, no-store, max-age=0');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
$access = app(EvaluationAccess::class);
|
||||
if (app(PublicNavigation::class)->enabled()) {
|
||||
return $next($request);
|
||||
|
||||
@@ -63,6 +63,7 @@ class HandleInertiaRequests extends Middleware
|
||||
'profileLabel' => app(OrganizationAccess::class)->profileLabel($actor),
|
||||
],
|
||||
'payablesAvailable' => $actor !== null && app(SupplierPayables::class)->can($actor, 'view'),
|
||||
'orderCancellationAvailable' => $actor !== null && (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
|
||||
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Services\PublicNavigation;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Laravel\Fortify\Features;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class PublicDevelopmentNavigation
|
||||
@@ -13,7 +14,7 @@ class PublicDevelopmentNavigation
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$navigation = app(PublicNavigation::class);
|
||||
if (! $navigation->enabled() || $request->user('web') !== null || ! in_array($request->method(), ['GET', 'HEAD'], true)) {
|
||||
if (Features::enabled(Features::twoFactorAuthentication()) || ! $navigation->enabled() || $request->user('web') !== null || ! in_array($request->method(), ['GET', 'HEAD'], true)) {
|
||||
return $next($request);
|
||||
}
|
||||
$path = '/'.$request->path();
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Requests;
|
||||
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Services\AdministrativeGeography;
|
||||
use App\Services\SupplierParticipation;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -27,6 +28,9 @@ class SaveSupplierRequest extends FormRequest
|
||||
}
|
||||
|
||||
return [
|
||||
'geography_reference' => app(AdministrativeGeography::class)->enabled() ? 'sometimes|nullable|array:country,catalogue,record_id' : 'prohibited',
|
||||
'geography_reference.catalogue' => 'required_with:geography_reference|string|size:64',
|
||||
'geography_reference.record_id' => 'required_with:geography_reference|string|regex:/^[0-9]+$/D|max:20',
|
||||
'name' => 'required|string|max:200',
|
||||
'nuit' => ['required', 'regex:/^\d{9}$/', $uniqueNuit],
|
||||
'contact' => 'required|string|max:200', 'email' => 'required|email|max:200',
|
||||
|
||||
@@ -5,9 +5,15 @@ namespace App\Models;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/** @property array{country:string,catalogue:string,record_id:string}|null $geography_reference */
|
||||
class Equipment extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
protected $guarded = ['id'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['geography_reference' => 'array'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use LogicException;
|
||||
|
||||
/** @property array<string,mixed> $snapshot */
|
||||
class OrderCancellation extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
protected $guarded = ['id'];
|
||||
|
||||
protected $attributes = ['status' => 'pending'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['snapshot' => 'array'];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::updating(function (self $record) {
|
||||
if ($record->getRawOriginal('status') === 'pending' && (! in_array($record->status, ['approved', 'rejected'], true)
|
||||
|| $record->reviewed_by === null || $record->reviewed_at === null || trim((string) $record->review_reason) === '')) {
|
||||
throw new LogicException('Decisão completa e definitiva obrigatória.');
|
||||
}
|
||||
$allowed = $record->getRawOriginal('status') === 'pending' ? ['status', 'reviewed_by', 'review_reason', 'reviewed_at', 'updated_at']
|
||||
: ($record->getRawOriginal('status') === 'approved' && $record->getRawOriginal('revised_requisition_id') === null ? ['revised_requisition_id', 'updated_at'] : []);
|
||||
if (array_diff(array_keys($record->getDirty()), $allowed) !== []) {
|
||||
throw new LogicException('Preservar pedido e decisão de cancelamento.');
|
||||
}
|
||||
});
|
||||
static::deleting(fn () => throw new LogicException('Preservar cancelamento.'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
class OrderCancellationPolicy extends PurchaseControlPolicy
|
||||
{
|
||||
protected $table = 'order_cancellation_policies';
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
class OrderCancellationPolicyReview extends PurchaseControlReview
|
||||
{
|
||||
protected $table = 'order_cancellation_policy_reviews';
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Models\Concerns\ImmutablePurchaseRecord;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* @property int $id
|
||||
@@ -39,4 +40,15 @@ class PurchaseOrder extends Model
|
||||
{
|
||||
$query->whereIn('requisition_id', Requisition::query()->visibleTo($user)->select('id'));
|
||||
}
|
||||
|
||||
/** @param Builder<PurchaseOrder> $query */
|
||||
public function scopeOperational(Builder $query): void
|
||||
{
|
||||
$query->where('purchase_orders.status', 'issued');
|
||||
if (Schema::hasTable('order_cancellations')) {
|
||||
$query->whereNotExists(fn ($q) => $q->selectRaw('1')->from('order_cancellations as oc')
|
||||
->whereColumn('oc.purchase_order_id', 'purchase_orders.id')->whereColumn('oc.tenant_id', 'purchase_orders.tenant_id')
|
||||
->whereIn('oc.status', ['pending', 'approved']));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* @property array{country:string,catalogue:string,record_id:string}|null $geography_reference
|
||||
* @property int $id
|
||||
* @property int $tenant_id
|
||||
* @property int $created_by
|
||||
@@ -23,7 +24,7 @@ class Supplier extends Model
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['blocked' => 'boolean', 'next_review' => 'date:Y-m-d'];
|
||||
return ['blocked' => 'boolean', 'next_review' => 'date:Y-m-d', 'geography_reference' => 'array'];
|
||||
}
|
||||
|
||||
public function eligible(): bool
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Models;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* @property array{country:string,catalogue:string,record_id:string}|null $geography_reference
|
||||
* @property int $id
|
||||
* @property string $name
|
||||
* @property int $first_limit_minor
|
||||
@@ -22,6 +23,6 @@ class Tenant extends Model
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['work_context_policy' => 'array', 'approval_includes_tax' => 'boolean', 'rules_provisional' => 'boolean', 'default_tax_rate' => 'decimal:2', 'comparison_policy' => 'array', 'intelligence_policy' => 'array'];
|
||||
return ['geography_reference' => 'array', 'work_context_policy' => 'array', 'approval_includes_tax' => 'boolean', 'rules_provisional' => 'boolean', 'default_tax_rate' => 'decimal:2', 'comparison_policy' => 'array', 'intelligence_policy' => 'array'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,15 @@ namespace App\Models;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/** @property array{country:string,catalogue:string,record_id:string}|null $geography_reference */
|
||||
class Warehouse extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
protected $guarded = ['id'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['geography_reference' => 'array'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Services\AdministrativeGeography;
|
||||
use App\Services\FinanceBundle;
|
||||
use App\Services\ReplenishmentRun;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -15,11 +18,12 @@ class AppServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
$this->app->singleton(\App\Services\ReplenishmentRun::class);
|
||||
$this->app->singleton(ReplenishmentRun::class);
|
||||
$this->app->scoped(AdministrativeGeography::class);
|
||||
require_once base_path('packages/purchasing/bootstrap.php');
|
||||
$package = config('common-budget.path');
|
||||
require_once $package.'/bootstrap.php';
|
||||
\App\Services\FinanceBundle::configure();
|
||||
FinanceBundle::configure();
|
||||
$payables = config('common-payables.path');
|
||||
require_once $payables.'/bootstrap.php';
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ class FortifyServiceProvider extends ServiceProvider
|
||||
*/
|
||||
private function configureViews(): void
|
||||
{
|
||||
Fortify::loginView(fn (Request $request) => EvaluationNavigation::local($request) ? redirect('/avaliar') : Inertia::render('auth/login', [
|
||||
Fortify::loginView(fn (Request $request) => EvaluationNavigation::local($request) && ! Features::enabled(Features::twoFactorAuthentication()) ? redirect('/avaliar') : Inertia::render('auth/login', [
|
||||
'canResetPassword' => Features::enabled(Features::resetPasswords()),
|
||||
'status' => $request->session()->get('status'),
|
||||
]));
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AdministrativeGeography
|
||||
{
|
||||
public const ISSUES = [
|
||||
'blank_designation' => 'Designação vazia',
|
||||
'incomplete_code_path' => 'Percurso de códigos incompleto',
|
||||
'duplicate_code_path' => 'Código repetido',
|
||||
'missing_parent' => 'Nível superior ausente',
|
||||
'ambiguous_parent' => 'Nível superior ambíguo',
|
||||
'ancestor_requires_review' => 'Ascendente por rever',
|
||||
];
|
||||
|
||||
/** @var array<string,mixed>|null */
|
||||
private ?array $data = null;
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function catalogue(): array
|
||||
{
|
||||
if ($this->data === null) {
|
||||
$content = file_get_contents(resource_path('data/geography/cartografia-moz.json'));
|
||||
abort_unless(is_string($content) && hash_equals((string) config('geography.catalogue_sha256'), hash('sha256', $content)), 503, 'A integridade do catálogo precisa de verificação.');
|
||||
$data = json_decode($content, true, 32, JSON_THROW_ON_ERROR);
|
||||
abort_unless(is_array($data) && ($data['manifest']['source_sha256'] ?? null) === config('geography.source_sha256'), 503, 'Catálogo geográfico indisponível.');
|
||||
$this->data = $data;
|
||||
}
|
||||
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
public function enabled(): bool
|
||||
{
|
||||
return config('geography.enabled') === true
|
||||
&& Schema::hasColumn('suppliers', 'geography_reference')
|
||||
&& Schema::hasColumn('tenants', 'geography_reference');
|
||||
}
|
||||
|
||||
public function availableFor(string $table): bool
|
||||
{
|
||||
return in_array($table, ['tenants', 'suppliers', 'warehouses', 'equipment'], true)
|
||||
&& (! in_array($table, ['warehouses', 'equipment'], true) || config('geography.operational_enabled') === true)
|
||||
&& $this->enabled() && Schema::hasColumn($table, 'geography_reference');
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
public function referenceRules(string $table): array
|
||||
{
|
||||
return ['geography_reference' => $this->availableFor($table) ? 'sometimes|nullable|array:country,catalogue,record_id' : 'prohibited',
|
||||
'geography_reference.catalogue' => 'required_with:geography_reference|string|size:64',
|
||||
'geography_reference.record_id' => 'required_with:geography_reference|string|regex:/^[0-9]+$/D|max:20'];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed>|null $reference
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
public function canonicalFor(string $table, ?array $reference): ?array
|
||||
{
|
||||
abort_unless($this->availableFor($table), 503, 'A localização deste cadastro ainda não está instalada.');
|
||||
|
||||
return $this->canonical($reference);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function record(string $id): array
|
||||
{
|
||||
foreach ($this->catalogue()['records'] as $record) {
|
||||
if ($record['id'] === $id) {
|
||||
return $record;
|
||||
}
|
||||
}
|
||||
|
||||
throw ValidationException::withMessages(['geography_reference' => 'Localização não encontrada no catálogo.']);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed>|null $reference
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
public function canonical(?array $reference): ?array
|
||||
{
|
||||
abort_unless($this->enabled(), 503, 'A localização administrativa ainda não está disponível.');
|
||||
if ($reference === null) {
|
||||
return null;
|
||||
}
|
||||
if (($reference['catalogue'] ?? null) !== $this->catalogue()['manifest']['source_sha256']) {
|
||||
throw ValidationException::withMessages(['geography_reference' => 'O catálogo foi alterado. Reabra a ficha antes de guardar.']);
|
||||
}
|
||||
$record = $this->record((string) ($reference['record_id'] ?? ''));
|
||||
if (! $record['selectable']) {
|
||||
throw ValidationException::withMessages(['geography_reference' => 'Este registo ou a sua hierarquia precisa de revisão. Escolha um nível superior confirmado.']);
|
||||
}
|
||||
|
||||
return ['country' => 'MZ', 'catalogue' => $reference['catalogue'], 'record_id' => $record['id']];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed>|null $reference
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
public function describe(?array $reference): ?array
|
||||
{
|
||||
if ($reference === null) {
|
||||
return null;
|
||||
}
|
||||
if (($reference['catalogue'] ?? null) !== $this->catalogue()['manifest']['source_sha256']) {
|
||||
return ['reference' => $reference, 'path' => [], 'requires_review' => true];
|
||||
}
|
||||
$record = $this->record((string) $reference['record_id']);
|
||||
$path = [$record];
|
||||
while ($record['parent_id'] !== null) {
|
||||
$record = $this->record($record['parent_id']);
|
||||
array_unshift($path, $record);
|
||||
}
|
||||
|
||||
return ['reference' => $reference, 'path' => array_map(fn ($node) => $this->summary($node), $path), 'requires_review' => ! $path[count($path) - 1]['selectable']];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $record
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function summary(array $record): array
|
||||
{
|
||||
return array_intersect_key($record, array_flip(['id', 'name', 'level', 'parent_id']));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function children(?string $parent, int $page = 1): array
|
||||
{
|
||||
if ($parent !== null && ! $this->record($parent)['selectable']) {
|
||||
throw ValidationException::withMessages(['parent' => 'Hierarquia pendente de revisão.']);
|
||||
}
|
||||
$records = array_values(array_filter($this->catalogue()['records'], fn ($record) => $record['selectable'] && $record['parent_id'] === $parent));
|
||||
usort($records, fn ($a, $b) => strcmp($a['name'], $b['name']) ?: strcmp($a['id'], $b['id']));
|
||||
|
||||
return ['data' => array_map(fn ($record) => $this->summary($record), array_slice($records, ($page - 1) * 50, 50)), 'page' => $page, 'has_more' => count($records) > $page * 50, 'catalogue' => $this->catalogue()['manifest']['source_sha256']];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function descendants(string $id): array
|
||||
{
|
||||
$root = $this->record($id);
|
||||
if (! $root['selectable']) {
|
||||
throw ValidationException::withMessages(['location' => 'Localização pendente de revisão.']);
|
||||
}
|
||||
$prefix = array_slice($root['codes'], 0, $root['level']);
|
||||
|
||||
return array_values(array_map(fn ($record) => $record['id'], array_filter($this->catalogue()['records'], fn ($record) => $record['selectable'] && array_slice($record['codes'], 0, count($prefix)) === $prefix)));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $filters
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function inconsistencies(array $filters): array
|
||||
{
|
||||
$search = trim($filters['search'] ?? '');
|
||||
$issue = $filters['issue'] ?? '';
|
||||
|
||||
return array_values(array_filter($this->catalogue()['records'], fn ($record) => ! $record['selectable']
|
||||
&& ($issue === '' || in_array($issue, $record['issues'], true))
|
||||
&& ($search === '' || $record['id'] === $search || mb_stripos($record['name'], $search) !== false)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class CandidateGeography
|
||||
{
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function resolve(array $input): array
|
||||
{
|
||||
if (($input['availability_reference'] ?? null) !== null) {
|
||||
$data = Validator::make($input, ['availability_reference' => 'required|array:country,catalogue,record_id', 'availability_reference.catalogue' => 'required|string|size:64', 'availability_reference.record_id' => 'required|string|regex:/^[0-9]+$/D|max:20'])->validate();
|
||||
$resolved = $this->locality($data['availability_reference'], 'availability_reference');
|
||||
$input['availability_reference'] = $resolved['reference'];
|
||||
$input['availability'] = $resolved['location'];
|
||||
}
|
||||
if (array_key_exists('additional_availability_references', $input)) {
|
||||
$data = Validator::make($input, ['additional_availability' => 'present|array|list|max:20', 'additional_availability.*' => 'array',
|
||||
'additional_availability_references' => 'present|array|list|max:20', 'additional_availability_references.*' => 'nullable|array:country,catalogue,record_id',
|
||||
'additional_availability_references.*.catalogue' => 'required_with:additional_availability_references.*|string|size:64',
|
||||
'additional_availability_references.*.record_id' => 'required_with:additional_availability_references.*|string|regex:/^[0-9]+$/D|max:20'])->validate();
|
||||
if (count($data['additional_availability']) !== count($data['additional_availability_references'])) {
|
||||
throw ValidationException::withMessages(['additional_availability_references' => 'Cada local adicional deve ter uma referência correspondente ou vazia.']);
|
||||
}
|
||||
foreach ($data['additional_availability_references'] as $index => $reference) {
|
||||
if ($reference !== null) {
|
||||
$resolved = $this->locality($reference, 'additional_availability_references.'.$index);
|
||||
$input['additional_availability'][$index] = $resolved['location'];
|
||||
$input['additional_availability_references'][$index] = $resolved['reference'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $input;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $value
|
||||
* @return array{reference:array<string,mixed>,location:array<string,string>}
|
||||
*/
|
||||
private function locality(array $value, string $field): array
|
||||
{
|
||||
$geography = app(AdministrativeGeography::class);
|
||||
try {
|
||||
$reference = $geography->canonical($value);
|
||||
} catch (ValidationException $error) {
|
||||
throw ValidationException::withMessages([$field => array_merge(...array_values($error->errors()))]);
|
||||
}
|
||||
abort_unless($reference !== null, 422);
|
||||
$record = $geography->record($reference['record_id']);
|
||||
if ($record['level'] !== 4) {
|
||||
throw ValidationException::withMessages([$field => 'Seleccione um percurso completo até à localidade. Não se presume um distrito ou localidade em falta.']);
|
||||
}
|
||||
$description = $geography->describe($reference);
|
||||
abort_unless($description !== null, 422);
|
||||
$names = array_column($description['path'], 'name', 'level');
|
||||
|
||||
return ['reference' => $reference, 'location' => ['province' => $names[1], 'district' => $names[2], 'locality' => $names[4]]];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data
|
||||
* @param array<string,mixed> $previous
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function preserve(array $data, array $previous): array
|
||||
{
|
||||
if (! array_key_exists('availability_reference', $data) && isset($previous['availability_reference']) && array_map(fn ($key) => $data['availability'][$key], ['province', 'district', 'locality']) === array_map(fn ($key) => $previous['availability'][$key], ['province', 'district', 'locality'])) {
|
||||
$data['availability_reference'] = $previous['availability_reference'];
|
||||
}
|
||||
|
||||
if (! array_key_exists('additional_availability_references', $data) && array_key_exists('additional_availability_references', $previous)) {
|
||||
$known = [];
|
||||
foreach ($previous['additional_availability'] ?? [] as $index => $location) {
|
||||
$key = json_encode(array_map(fn ($part) => $location[$part], ['province', 'district', 'locality']), JSON_THROW_ON_ERROR);
|
||||
$known[$key] = $previous['additional_availability_references'][$index] ?? null;
|
||||
}
|
||||
$data['additional_availability_references'] = array_map(function ($location) use ($known) {
|
||||
$key = json_encode(array_map(fn ($part) => $location[$part], ['province', 'district', 'locality']), JSON_THROW_ON_ERROR);
|
||||
|
||||
return $known[$key] ?? null;
|
||||
}, $data['additional_availability']);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -76,9 +76,12 @@ class CandidateProfiles
|
||||
$sessionVersion = $account->session_version;
|
||||
$account = CandidateAccount::query()->where('tenant_id', $account->tenant_id)->where('id', $account->id)->lockForUpdate()->firstOrFail();
|
||||
abort_unless($account->session_version === $sessionVersion, 401);
|
||||
$input = app(CandidateGeography::class)->resolve($input);
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:0', 'name' => 'required|string|min:3|max:200', 'phone' => 'nullable|string|max:50',
|
||||
'availability_reference' => 'sometimes|nullable|array:country,catalogue,record_id',
|
||||
'summary' => 'required|string|min:10|max:5000', 'availability' => 'required|array:province,district,locality',
|
||||
'availability.province' => 'required|string|max:150', 'availability.district' => 'required|string|max:150', 'availability.locality' => 'required|string|max:150',
|
||||
'additional_availability_references' => 'sometimes|array|list|max:20',
|
||||
'additional_availability' => 'sometimes|array|list|max:20',
|
||||
'additional_availability.*' => 'required|array:province,district,locality',
|
||||
'additional_availability.*.province' => 'required|string|max:150',
|
||||
@@ -87,6 +90,7 @@ class CandidateProfiles
|
||||
'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
$previous = $this->profile($account);
|
||||
$data['additional_availability'] ??= $previous['data']['additional_availability'] ?? [];
|
||||
$data = app(CandidateGeography::class)->preserve($data, $previous['data']);
|
||||
$seen = [];
|
||||
foreach ([$data['availability'], ...$data['additional_availability']] as $location) {
|
||||
$key = json_encode(array_map(fn ($part) => mb_strtolower(trim($location[$part])), ['province', 'district', 'locality']), JSON_THROW_ON_ERROR);
|
||||
@@ -99,7 +103,7 @@ class CandidateProfiles
|
||||
throw ValidationException::withMessages(['version' => 'O perfil mudou. Actualize e confira antes de guardar.']);
|
||||
}
|
||||
$id = DB::table('candidate_profile_versions')->insertGetId(['tenant_id' => $account->tenant_id, 'candidate_account_id' => $account->id,
|
||||
'version' => $previous['version'] + 1, 'data' => json_encode(array_intersect_key($data, array_flip(['name', 'phone', 'summary', 'availability', 'additional_availability'])), JSON_THROW_ON_ERROR),
|
||||
'version' => $previous['version'] + 1, 'data' => json_encode(array_intersect_key($data, array_flip(['name', 'phone', 'summary', 'availability', 'additional_availability', 'availability_reference', 'additional_availability_references'])), JSON_THROW_ON_ERROR),
|
||||
'reason' => $data['reason'], 'created_at' => now()]);
|
||||
$this->event($account, 'profile.version_created', ['profile_version_id' => $id, 'version' => $previous['version'] + 1]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\Connection;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
|
||||
class CandidateTerritory
|
||||
{
|
||||
/** Filter only immutable received snapshots; never consult the current candidate profile. */
|
||||
public function apply(Builder $query, string $location): void
|
||||
{
|
||||
$geography = app(AdministrativeGeography::class);
|
||||
abort_unless($geography->enabled(), 503);
|
||||
$ids = $geography->descendants($location);
|
||||
$edition = $geography->catalogue()['manifest']['source_sha256'];
|
||||
$connection = $query->getConnection();
|
||||
abort_unless($connection instanceof Connection, 503);
|
||||
$driver = $connection->getDriverName();
|
||||
abort_unless(in_array($driver, ['sqlite', 'pgsql'], true), 503, 'Filtro territorial ainda não disponível nesta base.');
|
||||
$parameters = implode(',', array_fill(0, count($ids), '?'));
|
||||
if ($driver === 'pgsql') {
|
||||
$source = "candidate_submissions.snapshot::jsonb #> '{profile,data,additional_availability_references}'";
|
||||
$array = "CASE WHEN jsonb_typeof($source) = 'array' THEN $source ELSE '[]'::jsonb END";
|
||||
$additional = "EXISTS (SELECT 1 FROM jsonb_array_elements($array) AS territory(value) WHERE territory.value->>'catalogue' = ? AND territory.value->>'country' = 'MZ' AND territory.value->>'record_id' IN ($parameters))";
|
||||
} else {
|
||||
$source = "json_extract(candidate_submissions.snapshot, '$.profile.data.additional_availability_references')";
|
||||
$array = "CASE WHEN json_type(candidate_submissions.snapshot, '$.profile.data.additional_availability_references') = 'array' THEN $source ELSE '[]' END";
|
||||
$object = "CASE WHEN territory.type = 'object' THEN territory.value ELSE '{}' END";
|
||||
$additional = "EXISTS (SELECT 1 FROM json_each($array) AS territory WHERE json_extract($object, '$.catalogue') = ? AND json_extract($object, '$.country') = 'MZ' AND json_extract($object, '$.record_id') IN ($parameters))";
|
||||
}
|
||||
$query->where(function (Builder $group) use ($ids, $edition, $additional) {
|
||||
$group->where(fn (Builder $main) => $main->where('candidate_submissions.snapshot->profile->data->availability_reference->catalogue', $edition)
|
||||
->where('candidate_submissions.snapshot->profile->data->availability_reference->country', 'MZ')
|
||||
->whereIn('candidate_submissions.snapshot->profile->data->availability_reference->record_id', $ids))
|
||||
->orWhereRaw($additional, [$edition, ...$ids]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Equipment;
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class EquipmentWarehouseRequests
|
||||
{
|
||||
/** Read-only projection; consumers must not insert rows into the paginator.
|
||||
* @return LengthAwarePaginator<int,covariant array<string,mixed>>|null
|
||||
*/
|
||||
public function page(User $actor, Equipment $equipment): ?LengthAwarePaginator
|
||||
{
|
||||
$canRead = $actor->hasFunctions(['admin', 'warehouse_request_read', 'warehouse_request_prepare'])
|
||||
|| ($actor->hasFunctions(['warehouse_request_review']) && $actor->department_id !== null)
|
||||
|| ($actor->hasFunctions(['warehouse_request_deliver']) && $actor->hasFunctions(['warehouse']));
|
||||
if (! $canRead || ! Schema::hasTable('warehouse_requests')) {
|
||||
return null;
|
||||
}
|
||||
$query = app(WarehouseWorkdesk::class)->visible($actor);
|
||||
if (DB::getDriverName() === 'pgsql') {
|
||||
$query->whereRaw("EXISTS (SELECT 1 FROM json_array_elements(warehouse_requests.snapshot->'lines') AS line(value) WHERE line.value->'equipment'->>'id' = ?)", [(string) $equipment->id]);
|
||||
} elseif (DB::getDriverName() === 'sqlite') {
|
||||
$query->whereRaw("EXISTS (SELECT 1 FROM json_each(json_extract(warehouse_requests.snapshot, '$.lines')) AS line WHERE json_extract(line.value, '$.equipment.id') = ?)", [$equipment->id]);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $query->oldest('id')->paginate(15, ['id', 'snapshot'], 'requests_page')->withQueryString()->through(function ($record) use ($equipment) {
|
||||
$p = app(WarehouseFulfilment::class)->progress($record);
|
||||
$lines = [];
|
||||
foreach ($record->snapshot['lines'] as $index => $line) {
|
||||
if (($line['equipment']['id'] ?? null) !== $equipment->id) {
|
||||
continue;
|
||||
}
|
||||
$lines[] = ['line' => $index + 1, 'item' => $line['item'], 'destination' => $line['destination'],
|
||||
'requested_milli' => $line['quantity_milli'], 'reserved_milli' => $p['reserved'][$index],
|
||||
'delivered_milli' => $p['delivered'][$index], 'remaining_milli' => $p['remaining'][$index], 'cancelled_milli' => $p['cancelled'][$index]];
|
||||
}
|
||||
|
||||
return ['id' => $record->id, 'state' => $p['state'], 'version' => $p['version'],
|
||||
'reservation_ready' => $p['reservation_ready'], 'lines' => $lines];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,7 @@ class InvoiceWorkflow
|
||||
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Finance]);
|
||||
$this->access($user);
|
||||
$order = PurchaseOrder::query()->lockForUpdate()->findOrFail($order->id);
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($order);
|
||||
$request = Requisition::query()->findOrFail($order->requisition_id);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user);
|
||||
$number = Str::upper(Str::squish($data['number']));
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use LogicException;
|
||||
use Throwable;
|
||||
|
||||
/** Read-only composition of existing technical inspections; never runs recovery or repairs. */
|
||||
class OperationalHealth
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
public function inspect(int $documentLimit = 1000): array
|
||||
{
|
||||
abort_unless(app()->runningInConsole() && ! auth()->check() && ! request()->hasSession(), 403);
|
||||
if ($documentLimit < 1 || $documentLimit > 10000) {
|
||||
throw new LogicException('Limite fora do intervalo permitido.');
|
||||
}
|
||||
$checks = [];
|
||||
$startedAt = now()->toIso8601String();
|
||||
foreach (['replenishment' => fn () => app(ReplenishmentQueue::class)->health(),
|
||||
'receipt_documents' => fn () => app(ReceiptDocumentHealth::class)->inspect($documentLimit)] as $key => $read) {
|
||||
try {
|
||||
$result = $read();
|
||||
$complete = $result['complete'] ?? true;
|
||||
$checks[$key] = ['status' => ! $complete ? 'incomplete' : ($result['ok'] ? 'passed' : 'attention'), 'result' => $result];
|
||||
} catch (Throwable $error) {
|
||||
report($error);
|
||||
$checks[$key] = ['status' => 'unavailable', 'result' => ['checked_at' => now()->toIso8601String(), 'ok' => false, 'complete' => false, 'reasons' => ['unavailable']]];
|
||||
}
|
||||
}
|
||||
|
||||
return ['schema_version' => 1, 'started_at' => $startedAt, 'checked_at' => now()->toIso8601String(),
|
||||
'ok' => collect($checks)->every(fn ($check) => $check['status'] === 'passed'),
|
||||
'complete' => collect($checks)->every(fn ($check) => in_array($check['status'], ['passed', 'attention'], true)),
|
||||
'checks' => $checks];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PurchaseControlPolicy;
|
||||
use App\Models\PurchaseControlReview;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class OrderCancellationPolicyWorkflow extends PurchaseControlPolicyWorkflow
|
||||
{
|
||||
public function canReview(User $actor, PurchaseControlPolicy $policy): bool
|
||||
{
|
||||
return (bool) config('order_cancellation.enabled') && $actor->tenant_id === $policy->tenant_id && $actor->hasFunctions(['admin'])
|
||||
&& ! app(OrganizationAccess::class)->maintenanceOnly($actor) && $policy->getTable() === 'order_cancellation_policies'
|
||||
&& $policy->status === 'pending' && $policy->created_by !== $actor->id && $policy->revision === $this->policies()->max('revision')
|
||||
&& ! $this->reviews()->where('purchase_control_policy_id', $policy->id)->where('reviewed_by', $actor->id)->exists();
|
||||
}
|
||||
|
||||
/** @return Builder<PurchaseControlPolicy> */
|
||||
protected function policies(): Builder
|
||||
{
|
||||
return (new PurchaseControlPolicy)->setTable('order_cancellation_policies')->newQuery();
|
||||
}
|
||||
|
||||
/** @return Builder<PurchaseControlReview> */
|
||||
protected function reviews(): Builder
|
||||
{
|
||||
return (new PurchaseControlReview)->setTable('order_cancellation_policy_reviews')->newQuery();
|
||||
}
|
||||
|
||||
protected function mode(): string
|
||||
{
|
||||
return 'issued_order';
|
||||
}
|
||||
|
||||
protected function auditPrefix(): string
|
||||
{
|
||||
return 'order_cancellation_policy';
|
||||
}
|
||||
|
||||
private function enabled(): void
|
||||
{
|
||||
abort_unless(config('order_cancellation.enabled') && Schema::hasTable('order_cancellation_policies'), 503, 'Cancelamento de ordens não activado.');
|
||||
}
|
||||
|
||||
public function propose(User $user, array $data): PurchaseControlPolicy
|
||||
{
|
||||
$this->enabled();
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
validator($data, ['previous_id' => 'required|integer|min:0', 'mode' => 'required|in:issued_order', 'enabled' => 'required|boolean',
|
||||
'valid_from' => 'required|date_format:Y-m-d', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:valid_from', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
|
||||
return parent::propose($user, $data);
|
||||
}
|
||||
|
||||
public function review(User $user, PurchaseControlPolicy $policy, string $decision, string $reason): void
|
||||
{
|
||||
$this->enabled();
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
parent::review($user, $policy, $decision, $reason);
|
||||
}
|
||||
|
||||
public function requireCurrent(): PurchaseControlPolicy
|
||||
{
|
||||
$this->enabled();
|
||||
$policy = $this->current();
|
||||
abort_unless($policy && $policy->enabled && $policy->mode === 'issued_order' && $policy->valid_until >= today()->format('Y-m-d'), 422, 'É necessária política vigente de cancelamento de ordens, com duas aprovações administrativas independentes.');
|
||||
|
||||
return $policy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\GoodsReceipt;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\OrderCancellation;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\Finance\Budget\BudgetContext;
|
||||
use Tempo\Finance\OrderCancellation\CommitmentReversal;
|
||||
|
||||
class OrderCancellationWorkflow
|
||||
{
|
||||
public function canRevise(User $actor, OrderCancellation $record): bool
|
||||
{
|
||||
if (! config('order_cancellation.enabled') || $record->tenant_id !== $actor->tenant_id || $record->status !== 'approved' || $record->revised_requisition_id
|
||||
|| app(OrganizationAccess::class)->maintenanceOnly($actor) || ! app(OrganizationAccess::class)->canRequest($actor)) {
|
||||
return false;
|
||||
}
|
||||
$order = PurchaseOrder::query()->visibleTo($actor)->find($record->purchase_order_id);
|
||||
|
||||
return $order && Requisition::query()->whereKey($order->requisition_id)->where('requester_id', $actor->id)->where('department_id', $actor->department_id)->exists();
|
||||
}
|
||||
|
||||
public function canRequest(User $actor, PurchaseOrder $order): bool
|
||||
{
|
||||
if (! config('order_cancellation.enabled') || ! Schema::hasTable('order_cancellations') || ! $actor->hasFunctions([PurchasingRole::Procurement])
|
||||
|| app(OrganizationAccess::class)->maintenanceOnly($actor) || $actor->tenant_id !== $order->tenant_id || $this->state($order) !== 'issued') {
|
||||
return false;
|
||||
}
|
||||
$request = Requisition::query()->visibleTo($actor)->find($order->requisition_id);
|
||||
$policy = app(OrderCancellationPolicyWorkflow::class)->current();
|
||||
|
||||
return $request && $request->requester_id !== $actor->id && $policy && $policy->enabled && $policy->mode === 'issued_order'
|
||||
&& $policy->valid_until >= today()->format('Y-m-d')
|
||||
&& ! GoodsReceipt::query()->where('purchase_order_id', $order->id)->exists() && ! Invoice::query()->where('purchase_order_id', $order->id)->exists()
|
||||
&& ! app(ConflictGuard::class)->processBlocked($request, $order->supplier_id, $actor);
|
||||
}
|
||||
|
||||
public function canDecide(User $actor, OrderCancellation $record): bool
|
||||
{
|
||||
if (! config('order_cancellation.enabled') || $record->tenant_id !== $actor->tenant_id || $record->status !== 'pending' || ! $actor->hasFunctions([PurchasingRole::Finance]) || app(OrganizationAccess::class)->maintenanceOnly($actor)) {
|
||||
return false;
|
||||
}
|
||||
$order = PurchaseOrder::query()->visibleTo($actor)->find($record->purchase_order_id);
|
||||
$request = $order ? Requisition::query()->find($order->requisition_id) : null;
|
||||
$award = $order ? PurchaseAward::query()->find($order->purchase_award_id) : null;
|
||||
|
||||
return $order && $request && $award && ! in_array($actor->id, [$record->created_by, $request->requester_id, $award->created_by, $order->issued_by], true);
|
||||
}
|
||||
|
||||
private function enabled(): void
|
||||
{
|
||||
abort_unless(config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'), 503, 'Cancelamento de ordens não activado.');
|
||||
}
|
||||
|
||||
public function state(PurchaseOrder $order): string
|
||||
{
|
||||
if (! Schema::hasTable('order_cancellations')) {
|
||||
return $order->status;
|
||||
}
|
||||
$states = OrderCancellation::query()->where('purchase_order_id', $order->id)->pluck('status');
|
||||
|
||||
return $states->contains('approved') ? 'cancelled' : ($states->contains('pending') ? 'cancellation_pending' : $order->status);
|
||||
}
|
||||
|
||||
/** Holds survive disabling the feature; hiding a command must not unblock an order. */
|
||||
public function assertOperational(PurchaseOrder $order): void
|
||||
{
|
||||
if (in_array($this->state($order), ['cancelled', 'cancellation_pending'], true)) {
|
||||
throw ValidationException::withMessages(['order' => 'Ordem cancelada ou com pedido de cancelamento pendente. Não é permitida nova execução.']);
|
||||
}
|
||||
}
|
||||
|
||||
private function source(PurchaseOrder $order): void
|
||||
{
|
||||
if ($order->getRawOriginal('status') !== 'issued' || $order->currency !== 'MZN' || GoodsReceipt::query()->where('purchase_order_id', $order->id)->exists()
|
||||
|| Invoice::query()->where('purchase_order_id', $order->id)->exists()) {
|
||||
throw ValidationException::withMessages(['order' => 'Este circuito exige ordem emitida em MZN sem qualquer recepção, factura ou pagamento.']);
|
||||
}
|
||||
}
|
||||
|
||||
private function basis(PurchaseOrder $order): string
|
||||
{
|
||||
return hash('sha256', json_encode(['order' => $order->getAttributes(), 'items' => $order->items()->orderBy('id')->get()->toArray(),
|
||||
'budget' => DB::table('budget_entries')->where('tenant_id', $order->tenant_id)->where('requisition_id', $order->requisition_id)->orderBy('id')->get()->toArray()], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function request(User $actor, PurchaseOrder $order, array $input): OrderCancellation
|
||||
{
|
||||
$this->enabled();
|
||||
$data = validator($input, ['operation_key' => 'required|uuid', 'reason' => 'required|string|min:10|max:4000', 'evidence' => 'required|string|min:10|max:4000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$hash = hash('sha256', json_encode([$order->id, $data], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $order, $data, $hash) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$order = PurchaseOrder::query()->visibleTo($actor)->lockForUpdate()->findOrFail($order->id);
|
||||
$request = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
|
||||
abort_if($actor->id === $request->requester_id, 403);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
|
||||
$old = OrderCancellation::query()->where('created_by', $actor->id)->where('operation_key', $data['operation_key'])->first();
|
||||
if ($old) {
|
||||
abort_unless($old->input_hash === $hash, 422, 'Chave utilizada com outro conteúdo.');
|
||||
|
||||
return $old;
|
||||
}
|
||||
$this->assertOperational($order);
|
||||
$this->source($order);
|
||||
$policy = app(OrderCancellationPolicyWorkflow::class)->requireCurrent();
|
||||
$record = OrderCancellation::query()->create(['tenant_id' => $actor->tenant_id, 'purchase_order_id' => $order->id, 'policy_id' => $policy->id,
|
||||
'created_by' => $actor->id, ...$data, 'input_hash' => $hash, 'basis_hash' => $this->basis($order),
|
||||
'snapshot' => ['order_number' => $order->number, 'policy' => $policy->toArray(), 'original_order_status' => $order->status]]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'order_cancellation.requested', $request, null, ['cancellation_id' => $record->id, 'order_id' => $order->id]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
public function decide(User $actor, OrderCancellation $record, string $decision, string $reason): void
|
||||
{
|
||||
$this->enabled();
|
||||
validator(['decision' => $decision, 'reason' => $reason], ['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
DB::transaction(function () use ($actor, $record, $decision, $reason) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Finance]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$record = OrderCancellation::query()->lockForUpdate()->findOrFail($record->id);
|
||||
$order = PurchaseOrder::query()->visibleTo($actor)->lockForUpdate()->findOrFail($record->purchase_order_id);
|
||||
$request = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
|
||||
$award = PurchaseAward::query()->findOrFail($order->purchase_award_id);
|
||||
abort_if(in_array($actor->id, [$record->created_by, $request->requester_id, $award->created_by, $order->issued_by], true), 403);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
|
||||
if ($record->status !== 'pending') {
|
||||
abort_unless($record->status === $decision && $record->review_reason === $reason && $record->reviewed_by === $actor->id, 409, 'Decisão imutável.');
|
||||
|
||||
return;
|
||||
}
|
||||
$entry = null;
|
||||
if ($decision === 'approved') {
|
||||
$this->source($order);
|
||||
abort_unless($record->basis_hash === $this->basis($order), 409, 'A base da ordem ou do compromisso mudou.');
|
||||
$policy = app(OrderCancellationPolicyWorkflow::class)->requireCurrent();
|
||||
abort_unless($policy->id === $record->policy_id, 409, 'Política alterada; rejeite o pedido para retomar o circuito.');
|
||||
abort_unless(DB::table('tenants')->where('id', $actor->tenant_id)->value('currency') === 'MZN', 422);
|
||||
if (! empty($order->snapshot['budget_control']) && ! DB::table('budget_entries')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->exists()) {
|
||||
throw ValidationException::withMessages(['budget' => 'A ordem indica controlo orçamental, mas o compromisso não está disponível.']);
|
||||
}
|
||||
$path = base_path('packages/order-cancellation/src/CommitmentReversal.php');
|
||||
abort_unless(is_file($path) && hash_file('sha256', $path) === config('order_cancellation.reversal_sha256'), 503, 'Capacidade de reversão indisponível.');
|
||||
require_once $path;
|
||||
try {
|
||||
$entry = (new CommitmentReversal)->reverse(DB::connection(), new BudgetContext($actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN'), $request->id, $order->id);
|
||||
} catch (\LogicException $error) {
|
||||
throw ValidationException::withMessages(['budget' => 'O compromisso não está integralmente disponível para reversão ou a sua base é inconsistente. Reveja o controlo orçamental.']);
|
||||
}
|
||||
$request->update(['status' => 'cancelled']);
|
||||
}
|
||||
$record->update(['status' => $decision, 'reviewed_by' => $actor->id, 'review_reason' => $reason, 'reviewed_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'order_cancellation.'.$decision, $request, null, ['cancellation_id' => $record->id, 'order_id' => $order->id, 'budget_reversal_entry_id' => $entry]);
|
||||
});
|
||||
}
|
||||
|
||||
public function revise(User $actor, OrderCancellation $record, string $neededBy, string $reason): Requisition
|
||||
{
|
||||
$this->enabled();
|
||||
validator(['needed_by' => $neededBy, 'reason' => $reason], ['needed_by' => 'required|date_format:Y-m-d|after_or_equal:today', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $record, $neededBy, $reason) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$record = OrderCancellation::query()->lockForUpdate()->findOrFail($record->id);
|
||||
$order = PurchaseOrder::query()->findOrFail($record->purchase_order_id);
|
||||
$source = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
|
||||
abort_unless($actor->id === $source->requester_id && $actor->department_id === $source->department_id && $record->status === 'approved', 403);
|
||||
if ($record->revised_requisition_id) {
|
||||
return Requisition::query()->findOrFail($record->revised_requisition_id);
|
||||
}
|
||||
$items = $source->items()->get()->map(fn ($item) => [...$item->only(['description', 'category', 'purchase_type', 'quantity', 'unit', 'tax_rate', 'production_area', 'equipment_id', 'spare_part_id']), 'unit_price' => BigDecimal::of($item->unit_price_minor)->dividedBy(100, 2)->__toString()])->all();
|
||||
$revised = app(RequisitionWorkflow::class)->save($actor, ['cost_center_id' => $source->cost_center_id, 'priority' => $source->priority, 'needed_by' => $neededBy, 'justification' => $reason, 'items' => $items]);
|
||||
$record->update(['revised_requisition_id' => $revised->id]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'order_cancellation.revision_created', $revised, null, ['source_requisition_id' => $source->id, 'cancellation_id' => $record->id]);
|
||||
|
||||
return $revised;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use Illuminate\Support\Facades\Schema;
|
||||
class OrganizationAccess
|
||||
{
|
||||
public const PERMISSIONS = [
|
||||
'audit_metadata_read' => 'Consultar e exportar metadados de eventos de todos os módulos da empresa, sem conteúdos privados',
|
||||
'warehouse_return_read' => 'Consultar devoluções de excedentes de entregas internas',
|
||||
'warehouse_return_prepare' => 'Declarar excedente não consumido de entrega interna própria',
|
||||
'warehouse_return_confirm' => 'Conferir ou recusar recepção independente do excedente no armazém (exige função de armazém)',
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PeopleProcess;
|
||||
use App\Models\User;
|
||||
|
||||
/** One permission-aware projection shared by consultation and portable process dossiers. */
|
||||
class PeopleProcessProjection
|
||||
{
|
||||
/** @return array{process:array<string,mixed>,candidates:list<array<string,mixed>>} */
|
||||
public function read(User $actor, PeopleProcess $record): array
|
||||
{
|
||||
$access = app(PeopleAccess::class);
|
||||
abort_unless($access->can($actor, $record, 'view'), 403);
|
||||
$workflow = app(PeopleHiring::class);
|
||||
$snapshot = $workflow->snapshot($record);
|
||||
$rows = $workflow->matrix($record);
|
||||
if (! $access->can($actor, $record, 'financial')) {
|
||||
unset($snapshot['rules']['annex']['fields']['financial']);
|
||||
unset($snapshot['selection']['rules']['annex']['fields']['financial']);
|
||||
}
|
||||
if (! $access->can($actor, $record, 'interviews')) {
|
||||
$rows = array_map(fn ($row) => [...$row, 'reviews' => []], $rows);
|
||||
if (isset($snapshot['selection']['rows'])) {
|
||||
$snapshot['selection']['rows'] = array_map(fn ($row) => [...$row, 'reviews' => []], $snapshot['selection']['rows']);
|
||||
}
|
||||
}
|
||||
if (! $access->can($actor, $record, 'contract') && ! $access->can($actor, $record, 'contract_view')) {
|
||||
$snapshot['contract'] = null;
|
||||
}
|
||||
|
||||
$rows = app(ReceivedCandidateAvailability::class)->attach($actor, $record, $rows);
|
||||
|
||||
return ['process' => $snapshot, 'candidates' => $rows];
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,34 @@ use App\Enums\PurchasingRole;
|
||||
use App\Models\PurchaseControlPolicy;
|
||||
use App\Models\PurchaseControlReview;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class PurchaseControlPolicyWorkflow
|
||||
{
|
||||
/** @return Builder<PurchaseControlPolicy> */
|
||||
protected function policies(): Builder
|
||||
{
|
||||
return PurchaseControlPolicy::query();
|
||||
}
|
||||
|
||||
/** @return Builder<PurchaseControlReview> */
|
||||
protected function reviews(): Builder
|
||||
{
|
||||
return PurchaseControlReview::query();
|
||||
}
|
||||
|
||||
protected function mode(): string
|
||||
{
|
||||
return 'unissued_award';
|
||||
}
|
||||
|
||||
protected function auditPrefix(): string
|
||||
{
|
||||
return 'purchase_control';
|
||||
}
|
||||
|
||||
private function admin(User $user): void
|
||||
{
|
||||
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null && $user->hasFunctions([PurchasingRole::Admin]), 403);
|
||||
@@ -25,12 +48,12 @@ class PurchaseControlPolicyWorkflow
|
||||
app(ConflictGuard::class)->lockCompany($user);
|
||||
$user = User::query()->where('tenant_id', $user->tenant_id)->lockForUpdate()->findOrFail($user->id);
|
||||
$this->admin($user);
|
||||
$latest = PurchaseControlPolicy::query()->latest('revision')->first();
|
||||
if ((int) $data['previous_id'] !== ($latest->id ?? 0) || $data['mode'] !== 'unissued_award') {
|
||||
$latest = $this->policies()->latest('revision')->first();
|
||||
if ((int) $data['previous_id'] !== ($latest->id ?? 0) || $data['mode'] !== $this->mode()) {
|
||||
throw ValidationException::withMessages(['cancellation' => 'Versão desactualizada ou regra não suportada. Não se presume um circuito de excepção.']);
|
||||
}
|
||||
$policy = PurchaseControlPolicy::query()->create(['tenant_id' => $user->tenant_id, 'created_by' => $user->id, 'revision' => ($latest->revision ?? 0) + 1, 'mode' => $data['mode'], 'enabled' => $data['enabled'], 'valid_from' => $data['valid_from'], 'valid_until' => $data['valid_until'], 'reason' => $data['reason']]);
|
||||
app(RequisitionWorkflow::class)->audit($user, 'purchase_control.proposed', null, null, $policy->toArray());
|
||||
$policy = $this->policies()->create(['tenant_id' => $user->tenant_id, 'created_by' => $user->id, 'revision' => ($latest->revision ?? 0) + 1, 'mode' => $data['mode'], 'enabled' => $data['enabled'], 'valid_from' => $data['valid_from'], 'valid_until' => $data['valid_until'], 'reason' => $data['reason']]);
|
||||
app(RequisitionWorkflow::class)->audit($user, $this->auditPrefix().'.proposed', null, null, $policy->toArray());
|
||||
|
||||
return $policy;
|
||||
});
|
||||
@@ -39,6 +62,7 @@ class PurchaseControlPolicyWorkflow
|
||||
public function review(User $user, PurchaseControlPolicy $policy, string $decision, string $reason): void
|
||||
{
|
||||
$this->admin($user);
|
||||
abort_unless($policy->getTable() === $this->policies()->getModel()->getTable(), 403);
|
||||
abort_unless($policy->tenant_id === $user->tenant_id && $policy->created_by !== $user->id, 403);
|
||||
if (! in_array($decision, ['approved', 'rejected']) || trim($reason) === '') {
|
||||
throw ValidationException::withMessages(['cancellation' => 'Decisão e fundamento obrigatórios.']);
|
||||
@@ -47,8 +71,8 @@ class PurchaseControlPolicyWorkflow
|
||||
app(ConflictGuard::class)->lockCompany($user);
|
||||
$user = User::query()->where('tenant_id', $user->tenant_id)->lockForUpdate()->findOrFail($user->id);
|
||||
$this->admin($user);
|
||||
$policy = PurchaseControlPolicy::query()->lockForUpdate()->findOrFail($policy->id);
|
||||
$existing = PurchaseControlReview::query()->where('purchase_control_policy_id', $policy->id)->where('reviewed_by', $user->id)->first();
|
||||
$policy = $this->policies()->lockForUpdate()->findOrFail($policy->id);
|
||||
$existing = $this->reviews()->where('purchase_control_policy_id', $policy->id)->where('reviewed_by', $user->id)->first();
|
||||
if ($existing) {
|
||||
if ($existing->decision !== $decision || $existing->reason !== $reason) {
|
||||
throw ValidationException::withMessages(['cancellation' => 'Decisão anterior imutável.']);
|
||||
@@ -56,35 +80,35 @@ class PurchaseControlPolicyWorkflow
|
||||
|
||||
return;
|
||||
}
|
||||
if ($policy->status !== 'pending' || PurchaseControlPolicy::query()->max('revision') !== $policy->revision) {
|
||||
if ($policy->status !== 'pending' || $this->policies()->max('revision') !== $policy->revision) {
|
||||
throw ValidationException::withMessages(['cancellation' => 'Versão decidida ou substituída por proposta mais recente.']);
|
||||
}
|
||||
if ($decision === 'approved') {
|
||||
$ids = PurchaseControlReview::query()->where('purchase_control_policy_id', $policy->id)->where('decision', 'approved')->pluck('reviewed_by')->push($policy->created_by)->push($user->id)->unique();
|
||||
$ids = $this->reviews()->where('purchase_control_policy_id', $policy->id)->where('decision', 'approved')->pluck('reviewed_by')->push($policy->created_by)->push($user->id)->unique();
|
||||
$actors = User::query()->where('tenant_id', $user->tenant_id)->whereIn('id', $ids)->orderBy('id')->lockForUpdate()->get();
|
||||
if ($actors->count() !== $ids->count() || $actors->contains(fn (User $actor) => ! $actor->hasFunctions([PurchasingRole::Admin]))) {
|
||||
throw ValidationException::withMessages(['cancellation' => 'Proponente e validadores devem continuar elegíveis até à publicação.']);
|
||||
}
|
||||
}
|
||||
PurchaseControlReview::query()->create(['tenant_id' => $user->tenant_id, 'purchase_control_policy_id' => $policy->id, 'reviewed_by' => $user->id, 'decision' => $decision, 'reason' => $reason, 'created_at' => now()]);
|
||||
$this->reviews()->create(['tenant_id' => $user->tenant_id, 'purchase_control_policy_id' => $policy->id, 'reviewed_by' => $user->id, 'decision' => $decision, 'reason' => $reason, 'created_at' => now()]);
|
||||
if ($decision === 'rejected') {
|
||||
$policy->update(['status' => 'rejected', 'decided_at' => now()]);
|
||||
} elseif (PurchaseControlReview::query()->where('purchase_control_policy_id', $policy->id)->where('decision', 'approved')->count() === 2) {
|
||||
} elseif ($this->reviews()->where('purchase_control_policy_id', $policy->id)->where('decision', 'approved')->count() === 2) {
|
||||
$policy->update(['status' => 'approved', 'decided_at' => now()]);
|
||||
}
|
||||
app(RequisitionWorkflow::class)->audit($user, 'purchase_control.'.$decision, null, null, ['policy_id' => $policy->id, 'status' => $policy->status]);
|
||||
app(RequisitionWorkflow::class)->audit($user, $this->auditPrefix().'.'.$decision, null, null, ['policy_id' => $policy->id, 'status' => $policy->status]);
|
||||
});
|
||||
}
|
||||
|
||||
public function current(): ?PurchaseControlPolicy
|
||||
{
|
||||
return PurchaseControlPolicy::query()->where('status', 'approved')->where('valid_from', '<=', today()->format('Y-m-d'))->latest('revision')->first();
|
||||
return $this->policies()->where('status', 'approved')->where('valid_from', '<=', today()->format('Y-m-d'))->latest('revision')->first();
|
||||
}
|
||||
|
||||
public function requireCurrent(): PurchaseControlPolicy
|
||||
{
|
||||
$policy = $this->current();
|
||||
if (! $policy || $policy->valid_until < today()->format('Y-m-d') || $policy->mode !== 'unissued_award' || ! $policy->enabled) {
|
||||
if (! $policy || $policy->valid_until < today()->format('Y-m-d') || $policy->mode !== $this->mode() || ! $policy->enabled) {
|
||||
throw ValidationException::withMessages(['cancellation' => 'A empresa deve activar o cancelamento de adjudicações sem ordem emitida numa política vigente, com duas aprovações administrativas independentes.']);
|
||||
}
|
||||
|
||||
|
||||
@@ -123,6 +123,8 @@ class PurchaseWorkflow
|
||||
// An already committed issue is returned, never re-created or re-snapshotted.
|
||||
$existing = PurchaseOrder::query()->where('requisition_id', $requisition->id)->first();
|
||||
if ($existing) {
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($existing);
|
||||
|
||||
return $existing;
|
||||
}
|
||||
$this->assertNoPendingCancellation($award);
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use LogicException;
|
||||
|
||||
/** Global technical inspection, with aggregate output only. Never repairs or removes files. */
|
||||
class ReceiptDocumentHealth
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
public function inspect(int $limit = 1000): array
|
||||
{
|
||||
abort_unless(app()->runningInConsole() && ! auth()->check(), 403, 'Verificação reservada à operação técnica.');
|
||||
if ($limit < 1 || $limit > 10000) {
|
||||
throw new LogicException('Limite fora do intervalo permitido.');
|
||||
}
|
||||
$result = ['checked_at' => now()->toIso8601String(), 'ok' => false, 'complete' => false, 'reasons' => [],
|
||||
'documents_checked' => 0, 'files_checked' => 0, 'missing' => 0, 'invalid_reference' => 0, 'altered' => 0,
|
||||
'unreferenced_recent' => 0, 'unreferenced_older' => 0];
|
||||
if (! Schema::hasTable('receipt_documents')) {
|
||||
return [...$result, 'reasons' => ['not_installed']];
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($limit, $result) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
$disk = Storage::disk('receipt_documents');
|
||||
$root = realpath($disk->path(''));
|
||||
if ($root === false) {
|
||||
return [...$result, 'reasons' => ['storage_unavailable']];
|
||||
}
|
||||
$records = DB::table('receipt_documents')->orderBy('id')->limit($limit + 1)->get();
|
||||
$limited = $records->count() > $limit;
|
||||
foreach ($records->take($limit) as $document) {
|
||||
$result['documents_checked']++;
|
||||
$prefix = $document->tenant_id.'/'.$document->goods_receipt_id.'/';
|
||||
$name = substr($document->path, strlen($prefix));
|
||||
if (! str_starts_with($document->path, $prefix) || ! preg_match('/\A[A-Za-z0-9_-]+\.[A-Za-z0-9]+\z/D', $name)
|
||||
|| ! DB::table('goods_receipts')->where('id', $document->goods_receipt_id)->where('tenant_id', $document->tenant_id)->exists()) {
|
||||
$result['invalid_reference']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
$path = realpath($disk->path($document->path));
|
||||
if ($path === false || ! is_file($path)) {
|
||||
$result['missing']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
$normalizedPath = str_replace('\\', '/', $path);
|
||||
$normalizedRoot = str_replace('\\', '/', $root).'/';
|
||||
$withinRoot = PHP_OS_FAMILY === 'Windows'
|
||||
? str_starts_with(strtolower($normalizedPath), strtolower($normalizedRoot))
|
||||
: str_starts_with($normalizedPath, $normalizedRoot);
|
||||
if (! $withinRoot) {
|
||||
$result['invalid_reference']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
$size = filesize($path);
|
||||
if ($size !== (int) $document->size || $size < 1 || $size > 2097152 || hash_file('sha256', $path) !== $document->sha256) {
|
||||
$result['altered']++;
|
||||
}
|
||||
}
|
||||
// Lazy listing and an independent ceiling also bound unreferenced-file inspection.
|
||||
foreach ($disk->getDriver()->listContents('', true) as $entry) {
|
||||
if (! $entry->isFile()) {
|
||||
continue;
|
||||
}
|
||||
if ($result['files_checked'] >= $limit) {
|
||||
$limited = true;
|
||||
break;
|
||||
}
|
||||
$result['files_checked']++;
|
||||
if (! DB::table('receipt_documents')->where('path', $entry->path())->exists()) {
|
||||
$age = now()->getTimestamp() - $disk->lastModified($entry->path());
|
||||
$result[$age >= 3600 ? 'unreferenced_older' : 'unreferenced_recent']++;
|
||||
}
|
||||
}
|
||||
$result['complete'] = ! $limited;
|
||||
foreach (['missing', 'invalid_reference', 'altered', 'unreferenced_recent', 'unreferenced_older'] as $reason) {
|
||||
if ($result[$reason] > 0) {
|
||||
$result['reasons'][] = $reason;
|
||||
}
|
||||
}
|
||||
if ($limited) {
|
||||
$result['reasons'][] = 'limit_reached';
|
||||
}
|
||||
$result['ok'] = $result['reasons'] === [];
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,7 @@ class ReceiptWorkflow
|
||||
$this->conflicts->lockCompany($user);
|
||||
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Warehouse]);
|
||||
$order = PurchaseOrder::query()->lockForUpdate()->findOrFail($order->id);
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($order);
|
||||
Gate::forUser($user)->authorize('create', [GoodsReceipt::class, $order]);
|
||||
$deliveryNote = Str::squish(Str::upper($data['delivery_note']));
|
||||
if ($deliveryNote === '') {
|
||||
@@ -219,7 +220,11 @@ class ReceiptWorkflow
|
||||
$writer = app(ReceiptStockMovement::class)->for($user);
|
||||
$basis = $writer->preview($item->id);
|
||||
$result = $writer->write($item->id, $basis['source_hash']);
|
||||
$movement = StockMovement::query()->findOrFail($result['movement_id']);
|
||||
$movementId = $result['movement_id'] ?? null;
|
||||
if (! is_int($movementId)) {
|
||||
throw new \LogicException('Resposta inválida do escritor de stock da recepção.');
|
||||
}
|
||||
$movement = StockMovement::query()->findOrFail($movementId);
|
||||
$sourceInput = collect($inputs)->firstWhere('purchase_order_item_id', $line['purchase_order_item_id']);
|
||||
app(InventoryLots::class)->receive($user, $movement, $sourceInput['lots'] ?? [], $data['received_on']);
|
||||
app(AutomaticPurchases::class)->signal($user, $line['stock_item_id'], $warehouse->id);
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PeopleProcess;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Query\JoinClause;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class ReceivedCandidateAvailability
|
||||
{
|
||||
/** Add received availability only to the authorized read projection, never to decision matrices.
|
||||
* @param list<array<string,mixed>> $rows
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function attach(User $actor, PeopleProcess $record, array $rows): array
|
||||
{
|
||||
if ($rows === [] || ! Schema::hasTable('candidate_triage') || ! Schema::hasTable('candidate_submissions')) {
|
||||
return $rows;
|
||||
}
|
||||
$current = User::query()->where('tenant_id', $record->tenant_id)->whereKey($actor->id)->first();
|
||||
if ($current === null || ! app(CandidateTriage::class)->canRead($current, $record)) {
|
||||
return $rows;
|
||||
}
|
||||
$sources = DB::table('candidate_triage as t')->join('candidate_submissions as s', function (JoinClause $join) {
|
||||
$join->on('s.id', '=', 't.candidate_submission_id')->on('s.tenant_id', '=', 't.tenant_id')->on('s.people_process_id', '=', 't.people_process_id');
|
||||
})->where('t.tenant_id', $record->tenant_id)->where('t.people_process_id', $record->id)->where('t.outcome', 'accepted_for_analysis')
|
||||
->whereIn('t.people_application_id', array_column($rows, 'id'))
|
||||
->get(['t.people_application_id', 't.profile_version', 's.id', 's.reference', 's.snapshot'])->keyBy('people_application_id');
|
||||
|
||||
return array_map(function (array $row) use ($sources) {
|
||||
$source = $sources->get($row['id']);
|
||||
if ($source === null) {
|
||||
return $row;
|
||||
}
|
||||
$snapshot = json_decode($source->snapshot, true, 32, JSON_THROW_ON_ERROR);
|
||||
$data = $snapshot['profile']['data'] ?? [];
|
||||
$main = $this->location($data['availability'] ?? null);
|
||||
if ($main === null || ($snapshot['profile']['version'] ?? null) !== $source->profile_version) {
|
||||
return $row;
|
||||
}
|
||||
$additional = [];
|
||||
$references = [];
|
||||
foreach ($data['additional_availability'] ?? [] as $index => $location) {
|
||||
$value = $this->location($location);
|
||||
if ($value !== null) {
|
||||
$additional[] = $value;
|
||||
$references[] = $this->reference($data['additional_availability_references'][$index] ?? null);
|
||||
}
|
||||
}
|
||||
|
||||
return [...$row, 'received_availability' => ['submission_id' => $source->id, 'reference' => $source->reference, 'profile_version' => $source->profile_version,
|
||||
'availability' => $main, 'additional_availability' => $additional,
|
||||
'availability_reference' => $this->reference($data['availability_reference'] ?? null), 'additional_availability_references' => $references]];
|
||||
}, $rows);
|
||||
}
|
||||
|
||||
/** @return array{province:string,district:string,locality:string}|null */
|
||||
private function location(mixed $value): ?array
|
||||
{
|
||||
if (! is_array($value) || ! is_string($value['province'] ?? null) || ! is_string($value['district'] ?? null) || ! is_string($value['locality'] ?? null)
|
||||
|| trim($value['province']) === '' || trim($value['district']) === '' || trim($value['locality']) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['province' => $value['province'], 'district' => $value['district'], 'locality' => $value['locality']];
|
||||
}
|
||||
|
||||
/** @return array{country:string,catalogue:string,record_id:string}|null */
|
||||
private function reference(mixed $value): ?array
|
||||
{
|
||||
if (! is_array($value) || ($value['country'] ?? null) !== 'MZ' || ! is_string($value['catalogue'] ?? null) || ! preg_match('/^[a-f0-9]{64}$/D', $value['catalogue'])
|
||||
|| ! is_string($value['record_id'] ?? null) || ! preg_match('/^[0-9]{1,20}$/D', $value['record_id'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['country' => 'MZ', 'catalogue' => $value['catalogue'], 'record_id' => $value['record_id']];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Supplier;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class SupplierGeography
|
||||
{
|
||||
/** Current supplier registration only; never infer geography from address text or evaluation snapshots.
|
||||
* @return Builder<Supplier>
|
||||
*/
|
||||
public function matching(string $location): Builder
|
||||
{
|
||||
$geography = app(AdministrativeGeography::class);
|
||||
abort_unless($geography->enabled(), 503);
|
||||
|
||||
return Supplier::query()->where('geography_reference->country', 'MZ')
|
||||
->where('geography_reference->catalogue', $geography->catalogue()['manifest']['source_sha256'])
|
||||
->whereIn('geography_reference->record_id', $geography->descendants($location));
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,7 @@ class SupplyCoordination
|
||||
if ($kind === 'delivery') {
|
||||
$line = PurchaseOrderItem::query()->whereKey($data['purchase_order_item_id'])->firstOrFail();
|
||||
$order = PurchaseOrder::query()->whereKey($line->purchase_order_id)->firstOrFail();
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($order);
|
||||
$snapshot['order'] = $order->only(['id', 'number']);
|
||||
$snapshot['order_line'] = $line->only(['id', 'quantity', 'unit', 'description']);
|
||||
}
|
||||
@@ -204,6 +205,7 @@ class SupplyCoordination
|
||||
if ($kind === 'delivery') {
|
||||
$line = PurchaseOrderItem::query()->whereKey($data['purchase_order_item_id'])->firstOrFail();
|
||||
$order = PurchaseOrder::query()->whereKey($line->purchase_order_id)->firstOrFail();
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($order);
|
||||
$stock = StockItem::query()->whereKey($data['stock_item_id'])->firstOrFail();
|
||||
$linked = $order->snapshot['catalogue_sources'][$line->requisition_item_id]['stock_item_id'] ?? null;
|
||||
$this->require($order->status === 'issued' && $line->unit === $stock->unit && ($linked === null || $linked === $stock->id), 'data.stock_item_id', 'A confirmação deve respeitar o artigo e unidade da ordem emitida.');
|
||||
|
||||
@@ -153,6 +153,9 @@ class SupplyPlanning
|
||||
$warehouse = isset($data['warehouse_id']) ? Warehouse::query()->whereKey($data['warehouse_id'])->firstOrFail() : null;
|
||||
$supplier = isset($data['supplier_id']) ? Supplier::query()->whereKey($data['supplier_id'])->lockForUpdate()->firstOrFail() : null;
|
||||
$order = isset($data['purchase_order_id']) ? PurchaseOrder::query()->whereKey($data['purchase_order_id'])->firstOrFail() : null;
|
||||
if ($order !== null) {
|
||||
app(OrderCancellationWorkflow::class)->assertOperational($order);
|
||||
}
|
||||
if ($kind === 'agreement' && $state === 'approved') {
|
||||
$this->check($supplier !== null && $supplier->eligible(), 'supplier_id', 'O fornecedor deve estar activo e com revisão documental vigente.');
|
||||
$this->check(! app(ConflictGuard::class)->hasConflict($actor->id, $supplier->id, null), 'supplier_id', 'Existe conflito declarado com este fornecedor.');
|
||||
|
||||
@@ -15,6 +15,27 @@ use Illuminate\Support\Facades\Schema;
|
||||
/** Read-only workdesk over the existing request, event and reservation journals. */
|
||||
class WarehouseWorkdesk
|
||||
{
|
||||
/** @param array<string,mixed> $filters
|
||||
* @return Builder<WarehouseRequest>
|
||||
*/
|
||||
public function filteredBase(User $actor, array $filters): Builder
|
||||
{
|
||||
$base = $this->visible($actor);
|
||||
if (! empty($filters['warehouse_id'])) {
|
||||
$base->where('warehouse_id', $filters['warehouse_id']);
|
||||
}
|
||||
if (! empty($filters['search'])) {
|
||||
$search = trim($filters['search']);
|
||||
if (preg_match('/^(?:RA-)?([1-9][0-9]{0,9})$/iD', $search, $match)) {
|
||||
$base->whereKey($match[1]);
|
||||
} else {
|
||||
$base->where(fn ($q) => $q->whereLike('snapshot->requester->name', '%'.$search.'%')->orWhereLike('snapshot->destination', '%'.$search.'%'));
|
||||
}
|
||||
}
|
||||
|
||||
return $base;
|
||||
}
|
||||
|
||||
public function canView(User $actor, WarehouseRequest $request): bool
|
||||
{
|
||||
return $actor->tenant_id === $request->tenant_id && (
|
||||
|
||||
@@ -5,6 +5,8 @@ namespace App\Services;
|
||||
use App\Models\AdmissionDecision;
|
||||
use App\Models\ExternalPayment;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\OrderCancellation;
|
||||
use App\Models\OrderCancellationPolicy;
|
||||
use App\Models\PeopleProcess;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\QualificationAssessment;
|
||||
@@ -35,6 +37,29 @@ class WorkflowTaskInbox
|
||||
$rows = $area === 'people' ? $this->people($actor) : [...$this->purchases($actor), ...$this->suppliers($actor), ...$this->quotations($actor), ...$this->documentary($actor), ...$this->formalReviews($actor), ...$this->supply($actor), ...$this->suggestions($actor), ...$this->awards($actor), ...$this->warehouse($actor), ...$this->inventoryCorrections($actor), ...$this->lotSetups($actor), ...$this->finance($actor)];
|
||||
if ($area === 'procurement') {
|
||||
$rows = [...$rows, ...$this->supplierImprovements($actor), ...$this->supplierQuality($actor), ...$this->supplyFollowUp($actor), ...$this->lotQuality($actor)];
|
||||
if (config('order_cancellation.enabled') && Schema::hasTable('order_cancellations')) {
|
||||
foreach (OrderCancellation::query()->where('status', 'pending')->lazyById(100) as $record) {
|
||||
if (app(OrderCancellationWorkflow::class)->canDecide($actor, $record)) {
|
||||
$rows[] = ['id' => 'order-cancellation:'.$record->id, 'module' => 'finance', 'reference' => $record->snapshot['order_number'],
|
||||
'label' => 'Conferir cancelamento de ordem emitida', 'task' => 'order_cancellation_review', 'status' => 'pending', 'blocked' => false,
|
||||
'created_at' => $this->date($record->created_at), 'due_on' => null, 'href' => '/ordens/cancelamentos?cancellation_id='.$record->id.'#cancellation-'.$record->id];
|
||||
}
|
||||
}
|
||||
foreach (OrderCancellationPolicy::query()->where('status', 'pending')->lazyById(100) as $policy) {
|
||||
if (app(OrderCancellationPolicyWorkflow::class)->canReview($actor, $policy)) {
|
||||
$rows[] = ['id' => 'order-cancellation-policy:'.$policy->id, 'module' => 'finance', 'reference' => 'Política de cancelamento v'.$policy->revision,
|
||||
'label' => 'Conferir política de cancelamento de ordens', 'task' => 'order_cancellation_policy_review', 'status' => 'pending', 'blocked' => false,
|
||||
'created_at' => $this->date($policy->created_at), 'due_on' => null, 'href' => '/ordens/cancelamentos#policy-'.$policy->id];
|
||||
}
|
||||
}
|
||||
foreach (OrderCancellation::query()->where('status', 'approved')->whereNull('revised_requisition_id')->lazyById(100) as $record) {
|
||||
if (app(OrderCancellationWorkflow::class)->canRevise($actor, $record)) {
|
||||
$rows[] = ['id' => 'order-cancellation-revision:'.$record->id, 'module' => 'purchases', 'reference' => $record->snapshot['order_number'],
|
||||
'label' => 'Preparar nova requisição após cancelamento de ordem', 'task' => 'order_cancellation_revision', 'status' => 'approved', 'blocked' => false,
|
||||
'created_at' => $this->date($record->reviewed_at), 'due_on' => null, 'href' => '/ordens/cancelamentos?cancellation_id='.$record->id.'#cancellation-'.$record->id];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
usort($rows, fn ($a, $b) => strcmp($a['created_at'] ?? '', $b['created_at'] ?? '') ?: strnatcmp($a['id'], $b['id']));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user