Compare commits
47
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c9d405e39 | ||
|
|
20fed7d21e | ||
|
|
336184b56b | ||
|
|
9283785c21 | ||
|
|
8c4e55f6c3 | ||
|
|
4e3811ace7 | ||
|
|
e062cfeeaa | ||
|
|
313ed3a300 | ||
|
|
c2cc514318 | ||
|
|
f9558d4563 | ||
|
|
2f2f40b47e | ||
|
|
d667f55b67 | ||
|
|
fa732cbdb4 | ||
|
|
ec934455e7 | ||
|
|
9f719695e3 | ||
|
|
8e1e8799a5 | ||
|
|
7615accf07 | ||
|
|
d652b03467 | ||
|
|
725e80059d | ||
|
|
318b62f458 | ||
|
|
47649bd46c | ||
|
|
96b30368bc | ||
|
|
a935499d64 | ||
|
|
30bfb1a773 | ||
|
|
7da8d6c87a | ||
|
|
448948a487 | ||
|
|
1ddabbbdcc | ||
|
|
060c119ba1 | ||
|
|
eb32c74c56 | ||
|
|
d58b75c87a | ||
|
|
7486007fcf | ||
|
|
9cf9764710 | ||
|
|
930064269e | ||
|
|
e709d900d1 | ||
|
|
dc73540558 | ||
|
|
db1615fac1 | ||
|
|
36dcfdf00c | ||
|
|
efd97e265b | ||
|
|
4fac443dda | ||
|
|
12dd6df28a | ||
|
|
976271f948 | ||
|
|
63d20b10fc | ||
|
|
e753f7a0a4 | ||
|
|
badaada043 | ||
|
|
b44378b899 | ||
|
|
504b01b244 | ||
|
|
13a6cb9922 |
@@ -71,3 +71,14 @@ COMMON_PAYABLES_ENABLED=false
|
|||||||
COMMON_PAYABLES_HISTORY_ENABLED=false
|
COMMON_PAYABLES_HISTORY_ENABLED=false
|
||||||
COMMON_PAYABLES_HISTORY_DECISIONS_ENABLED=false
|
COMMON_PAYABLES_HISTORY_DECISIONS_ENABLED=false
|
||||||
PAYABLE_SOURCE_INSTANCE=
|
PAYABLE_SOURCE_INSTANCE=
|
||||||
|
|
||||||
|
# MFA ligado: obrigatório para as funções em SGC_MFA_REQUIRED_FUNCTIONS, voluntário
|
||||||
|
# para os restantes perfis (decisão de 30/11/2026). Exige a migração dos campos MFA.
|
||||||
|
SGC_TWO_FACTOR_ENABLED=true
|
||||||
|
SGC_MFA_REQUIRED_FUNCTIONS=admin,finance
|
||||||
|
|
||||||
|
# Âmbito da v1: só o núcleo de compras. Módulos laterais desligados por omissão;
|
||||||
|
# activar por instalação quando contratados (ver config/modules.php).
|
||||||
|
SGC_MODULE_PESSOAS=false
|
||||||
|
SGC_MODULE_ARMAZEM_AVANCADO=false
|
||||||
|
SGC_MODULE_FORNECIMENTO=false
|
||||||
|
|||||||
@@ -3,6 +3,9 @@
|
|||||||
# Preserve the exact bytes of pinned shared runtime artifacts and their hashes.
|
# Preserve the exact bytes of pinned shared runtime artifacts and their hashes.
|
||||||
/packages/budget-control/** -text
|
/packages/budget-control/** -text
|
||||||
/packages/payables/** -text
|
/packages/payables/** -text
|
||||||
|
/packages/inventory-*/** -text
|
||||||
|
/packages/order-cancellation/** -text
|
||||||
|
/resources/data/geography/cartografia-moz.json -text whitespace=cr-at-eol
|
||||||
|
|
||||||
*.blade.php diff=html
|
*.blade.php diff=html
|
||||||
*.css diff=css
|
*.css diff=css
|
||||||
|
|||||||
+13
-1
@@ -38,9 +38,21 @@ yarn-error.log
|
|||||||
/.kiro
|
/.kiro
|
||||||
/.pi
|
/.pi
|
||||||
/.mcp.json
|
/.mcp.json
|
||||||
/AGENTS.md
|
|
||||||
/CLAUDE.md
|
/CLAUDE.md
|
||||||
/boost.json
|
/boost.json
|
||||||
/opencode.json
|
/opencode.json
|
||||||
/opencode.jsonc
|
/opencode.jsonc
|
||||||
/storage/framework/payables/
|
/storage/framework/payables/
|
||||||
|
/storage/framework/approval-deadlines-evaluation.lock
|
||||||
|
/storage/framework/approval-deadlines-status.json
|
||||||
|
/storage/framework/approval-deadlines-status.json.*.tmp
|
||||||
|
|
||||||
|
# Estado de execução gerado pela aplicação (não versionar)
|
||||||
|
/storage/framework/replenishment-*.json
|
||||||
|
/storage/framework/replenishment-*.lock
|
||||||
|
|
||||||
|
# Artefactos de trabalho locais
|
||||||
|
/tmp/
|
||||||
|
/output/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Instruções para agentes — SGC (Compras)
|
||||||
|
|
||||||
|
**SGC — Sistema de Gestão de Contratações.** Aquisições, serviços e pessoas · Uma solução TEMPO.
|
||||||
|
Laravel 13, Inertia 3, React 19, TypeScript, Tailwind 4. Repositório canónico: Gitea `nala/compras`.
|
||||||
|
|
||||||
|
As decisões completas e datadas do proprietário estão em
|
||||||
|
[`docs/historico/decisoes-do-proprietario.md`](docs/historico/decisoes-do-proprietario.md) e a política
|
||||||
|
anterior de execução em [`docs/historico/politica-codex-e-produto-unico.md`](docs/historico/politica-codex-e-produto-unico.md).
|
||||||
|
Consultá-las antes de mexer em instalação, piloto, SGF, MFA, geografia ou autorizações.
|
||||||
|
Este ficheiro resume o que vale sempre.
|
||||||
|
|
||||||
|
## 1. Antes de cada commit
|
||||||
|
|
||||||
|
- `composer run ci:check` tem de passar (runtime:check, lint/formatação, tipos, vitest, Pint, Pest, PHPStan). Se não passar, não fazer commit.
|
||||||
|
- Commits pequenos e com mensagem descritiva (o quê e porquê). Nunca «commit compras1».
|
||||||
|
- Uma tarefa = uma alteração coerente. Não misturar funcionalidade nova com formatação ou limpeza.
|
||||||
|
- Não versionar resultados de execução: `tmp/`, `output/`, `__pycache__/`, estado em `storage/framework/`, nem novas provas JSON de verificações de rotina. Em `docs/proofs/` só entram autorizações e decisões do proprietário.
|
||||||
|
|
||||||
|
## 2. Código e testes
|
||||||
|
|
||||||
|
- Sem caminhos de uma máquina concreta (`C:/laragon/...`) em código ou testes. Usar `base_path()`, configuração ou `sgfTempoPath()` (variável `SGF_TEMPO_ROOT`).
|
||||||
|
- Testes que exigem a base PostgreSQL de QA isolada começam com `skipUnlessIsolatedPostgres($this)`; a suite normal corre em SQLite.
|
||||||
|
- Pacotes com hash fixado (`packages/**`, `resources/data/geography/cartografia-moz.json`): os bytes são exactos e em LF. Não reformatar nem editar à mão; actualizar só pelo procedimento de `packages/README.md` e recalcular o pin.
|
||||||
|
- Ao mudar comportamento, actualizar os testes no mesmo commit. Não enfraquecer testes para passarem.
|
||||||
|
- Valores monetários em centavos (Brick Math); isolamento por empresa via `BelongsToTenant`; aprovações independentes e auditoria imutável são requisitos do produto, não obstáculos.
|
||||||
|
|
||||||
|
## 3. Decisões permanentes do proprietário (resumo)
|
||||||
|
|
||||||
|
- **Produto único:** o mesmo código local e público (www.compras.tempo.co.mz). Sem aplicações paralelas, demonstrações ou simulações apresentadas como funcionalidade. As antigas páginas `/consulta` e `/proposta` só redireccionam para os módulos reais.
|
||||||
|
- **SGF e Compras são independentes.** Partilham apenas o núcleo comum aprovado em `packages/`, por artefactos versionados; nunca fundir bases, aceder directamente aos dados do outro produto ou depender de uma pasta SGF na máquina do cliente.
|
||||||
|
- **Roteiros separados:** Compras (aquisições e fornecedores) e Pessoas e contratações (serviços individuais e recrutamento).
|
||||||
|
- **Registar uma vez, reutilizar:** seleccionar cadastros existentes; cada processo conserva a versão dos dados que usou.
|
||||||
|
- **Parametrizável pela interface:** quem é quem, quando usar, como associar — com autoria, versão e vigência. Sem regras organizacionais novas fixas no código.
|
||||||
|
- **Núcleo sem IA:** todas as funções base funcionam sem o adicional de IA.
|
||||||
|
- **Entrega:** dois administradores nominativos da empresa; sem contas de exemplo, credenciais universais ou «backdoor». Manutenção TEMPO só por acesso nominativo, com prazo, revogação e auditoria.
|
||||||
|
- **Dados:** nada de dados reais em testes; contas sintéticas na avaliação local (8005). Instalar migrações, activar funcionalidades ou alterar o piloto exige autorização expressa para essa acção concreta, com cópia de segurança e restauro verificados.
|
||||||
|
- **MFA (decisão de 30/11/2026, substitui a de 03/11):** ligado por omissão; obrigatório para administração e Finanças (`config/mfa.php`), voluntário para os restantes. A avaliação local sem palavra-passe (8005) exige `SGC_TWO_FACTOR_ENABLED=false` nessa instalação.
|
||||||
|
- **Ordens emitidas não entregues (decisão de 01/12/2026):** na v1 não há cancelamento no sistema; segue-se o procedimento manual em `docs/procedimento-ordens-nao-entregues.md` (despacho escrito, mapa de Finanças, reforço `ANUL-…` com dupla aprovação). Nunca corrigir na base de dados.
|
||||||
|
- **Pagamentos na mudança de ano (decisão de 01/12/2026):** registo e conferência de pagamentos aceitam o exercício actual ou o anterior (`ExternalPaymentWorkflow::withinFiscalWindow`). A validação de facturas de outro exercício continua bloqueada.
|
||||||
|
- **Produção (fase 5):** `docs/producao.md` — `.env` de produção, `php artisan sgc:production-check`, cópias (`scripts/producao/backup.sh`) e ensaio de restauro (`restore-check.sh`), plano do piloto. Depois do último commit de código, regenerar `compras-release.json` ou o publicador recusa a entrega.
|
||||||
|
- **Estado actual que não se altera por inferência:** geografia operacional (G3) pendente; cancelamento de ordens e envio SGF preparados mas desligados no piloto.
|
||||||
|
|
||||||
|
## 4. Âmbito
|
||||||
|
|
||||||
|
**v1 = só o núcleo de compras** (decisão de 30/11/2026): requisições, aprovações, cotações/adjudicação/ordens, fornecedores, recepções, artigos e stock básico, facturas, pagamentos externos, orçamentos, empresa/equipa, conflitos, auditoria e relatórios. Pessoas e contratações, armazém avançado e fornecimento/importações/equipamentos ficam no código, desligados por omissão em `config/modules.php` (`SGC_MODULE_*`), e activam-se por instalação. Não ligar um módulo nem lhe acrescentar funcionalidades sem pedido expresso. Código novo de um módulo lateral regista o controlador em `config/modules.php`.
|
||||||
|
|
||||||
|
Executar apenas a tarefa pedida. Não começar módulos novos, refactorizações ou actualizações de dependências sem pedido. Antes de acrescentar funcionalidade, confirmar que o circuito principal de compras (requisição → cotação → adjudicação → ordem → recepção → factura → pagamento) continua verde.
|
||||||
|
|
||||||
|
## 5. Relatório final
|
||||||
|
|
||||||
|
Português de Moçambique, curto: resultado, ficheiros alterados, verificações executadas e resultado, pendências, próxima acção recomendada (recomendar não autoriza iniciar).
|
||||||
@@ -8,6 +8,20 @@ Este é o projecto activo em `C:\laragon\www\compras`. Preserve a conta existent
|
|||||||
|
|
||||||
O produto inclui os artefactos dos núcleos comuns em `packages/`, conferidos por SHA-256 com `composer run runtime:check`. A execução da aplicação já não exige a pasta vizinha do SGF. Actualizar esses artefactos a partir da origem comum, conforme `packages/README.md`. Esta distribuição não activa automaticamente capacidades financeiras nem altera dados/configuração de instalações existentes.
|
O produto inclui os artefactos dos núcleos comuns em `packages/`, conferidos por SHA-256 com `composer run runtime:check`. A execução da aplicação já não exige a pasta vizinha do SGF. Actualizar esses artefactos a partir da origem comum, conforme `packages/README.md`. Esta distribuição não activa automaticamente capacidades financeiras nem altera dados/configuração de instalações existentes.
|
||||||
|
|
||||||
|
## Âmbito da v1
|
||||||
|
|
||||||
|
A v1 é o núcleo de compras: requisições, aprovações, cotações, adjudicação e ordens, fornecedores, recepções, artigos e stock básico, facturas, pagamentos externos, orçamentos, empresa e equipa, conflitos, auditoria e relatórios.
|
||||||
|
|
||||||
|
Os restantes módulos continuam no código e vêm desligados por omissão. Activam-se por instalação no `.env`:
|
||||||
|
|
||||||
|
| Variável | Módulo |
|
||||||
|
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `SGC_MODULE_PESSOAS` | Pessoas e contratações: recrutamento, serviços individuais, cadastro de pessoas, portal de candidaturas |
|
||||||
|
| `SGC_MODULE_ARMAZEM_AVANCADO` | Requisições ao armazém, reposição automática, lotes e validade, devoluções, disponibilidade |
|
||||||
|
| `SGC_MODULE_FORNECIMENTO` | Fornecimento planeado e acordos, importações, equipamentos e peças, projectos e imobilizado, ordens operacionais |
|
||||||
|
|
||||||
|
Desligado, o módulo desaparece dos menus e as suas rotas respondem 404. Os interruptores próprios de cada funcionalidade (`COMPRAS_*_ENABLED`, `SGC_*_ENABLED`) continuam a aplicar-se dentro de um módulo ligado. **Instalações que já usam estes módulos (avaliação 8005, público) têm de os ligar no `.env` antes de actualizar.**
|
||||||
|
|
||||||
## Executar localmente
|
## Executar localmente
|
||||||
|
|
||||||
Durante o desenvolvimento, use `composer run dev` e abra **http://127.0.0.1:8005/**. Este é o ambiente persistente com entrada directa no dashboard, os menus organizados e os processos em avaliação. `/avaliar` permite mudar de perfil. O arranque reutiliza a avaliação existente e inicia o Vite quando necessário, sem migrações, seeds ou alterações de contas.
|
Durante o desenvolvimento, use `composer run dev` e abra **http://127.0.0.1:8005/**. Este é o ambiente persistente com entrada directa no dashboard, os menus organizados e os processos em avaliação. `/avaliar` permite mudar de perfil. O arranque reutiliza a avaliação existente e inicia o Vite quando necessário, sem migrações, seeds ou alterações de contas.
|
||||||
@@ -120,7 +134,7 @@ Revisão visual dos módulos entregues; reposição de stock; conciliação de p
|
|||||||
|
|
||||||
O cadastro guarda referências e ficheiros anexos no disco privado `supplier_documents`, em `storage/app/supplier-documents`, fora da pasta pública e sem URLs públicas. As fichas abrem pelo directório **Fornecedores → Ver ficha → Abrir ficha, edição e documentos**. As versões antigas e documentos existentes são preservados na auditoria e no armazenamento; nesta entrega não há eliminação de documentos, antivírus, quotas acumuladas ou política de retenção. A validação do NUIT é de formato e unicidade, sem consulta a uma autoridade fiscal. Além das declarações por operação, existem declarações pessoais por fornecedor e processo; a periodicidade anual e a política de validade/levantamento ainda não foram definidas. As propostas e avaliações registadas não são editáveis nesta etapa. Os pesos 40/20/15/15/10 são provisórios e ficam guardados por proposta. A comparação liga à fase de adjudicação e emissão. A ordem exige novas aprovações do valor final e revalidação no servidor. As propostas usam MZN; a multimoeda fica para a fase correspondente.
|
O cadastro guarda referências e ficheiros anexos no disco privado `supplier_documents`, em `storage/app/supplier-documents`, fora da pasta pública e sem URLs públicas. As fichas abrem pelo directório **Fornecedores → Ver ficha → Abrir ficha, edição e documentos**. As versões antigas e documentos existentes são preservados na auditoria e no armazenamento; nesta entrega não há eliminação de documentos, antivírus, quotas acumuladas ou política de retenção. A validação do NUIT é de formato e unicidade, sem consulta a uma autoridade fiscal. Além das declarações por operação, existem declarações pessoais por fornecedor e processo; a periodicidade anual e a política de validade/levantamento ainda não foram definidas. As propostas e avaliações registadas não são editáveis nesta etapa. Os pesos 40/20/15/15/10 são provisórios e ficam guardados por proposta. A comparação liga à fase de adjudicação e emissão. A ordem exige novas aprovações do valor final e revalidação no servidor. As propostas usam MZN; a multimoeda fica para a fase correspondente.
|
||||||
|
|
||||||
Esta base não implementa ainda os onze controlos anti-fraude nem todos os requisitos não funcionais do documento. MFA obrigatório, gestão completa do ciclo de vida dos acessos, delegações, política de levantamento de conflitos, alteração de regras com dupla aprovação, retenção, cópias de segurança e restauro por empresa serão tratados nas etapas correspondentes. Não usar para compras reais antes da validação destas regras e controlos.
|
Esta base não implementa ainda os onze controlos anti-fraude nem todos os requisitos não funcionais do documento. O MFA é obrigatório para administração e Finanças desde 30/11/2026 (`config/mfa.php`); ficam por tratar gestão completa do ciclo de vida dos acessos, delegações, política de levantamento de conflitos, alteração de regras com dupla aprovação, retenção, cópias de segurança e restauro por empresa serão tratados nas etapas correspondentes. Não usar para compras reais antes da validação destas regras e controlos.
|
||||||
|
|
||||||
As declarações pessoais abrem no menu **Conflitos de interesses**. Só o autor pode corrigir os próprios fundamentos/datas, acrescentando histórico; Administração e Finanças podem consultar as declarações da empresa. Não existe caducidade automática nem retirada de conflitos. A revisão visual continua pendente. Estão documentados quatro cenários reais de concorrência de recepção e sete de stock aprovados em PostgreSQL isolado; isto não valida a concorrência de todos os módulos nem a carga. Consulte [o relatório de desenvolvimento](docs/desenvolvimento.md).
|
As declarações pessoais abrem no menu **Conflitos de interesses**. Só o autor pode corrigir os próprios fundamentos/datas, acrescentando histórico; Administração e Finanças podem consultar as declarações da empresa. Não existe caducidade automática nem retirada de conflitos. A revisão visual continua pendente. Estão documentados quatro cenários reais de concorrência de recepção e sete de stock aprovados em PostgreSQL isolado; isto não valida a concorrência de todos os módulos nem a carga. Consulte [o relatório de desenvolvimento](docs/desenvolvimento.md).
|
||||||
|
|
||||||
|
|||||||
@@ -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', 'import_cost_documents' => 'Documentos dos custos de importaçã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,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Services\StandaloneInstallation;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
final class PrepareStandaloneRuntime extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'compras:runtime:prepare
|
||||||
|
{--expected-database= : Exact own database name}
|
||||||
|
{--expected-role= : Exact non-elevated database role}
|
||||||
|
{--operator= : Named deployment operator}
|
||||||
|
{--reason= : Recorded installation or recovery reason}
|
||||||
|
{--apply : Apply the explicitly selected installation}
|
||||||
|
{--reuse-components : Reuse only complete recognised canonical V1 components; reject partial or changed schemas}
|
||||||
|
{--rebind : Preserve restored schema and register a new installation binding}';
|
||||||
|
|
||||||
|
protected $description = 'Preparar explicitamente a composição independente; pré-visualizar por defeito';
|
||||||
|
|
||||||
|
public function handle(StandaloneInstallation $installation): int
|
||||||
|
{
|
||||||
|
$result = $installation->prepare((string) $this->option('expected-database'), (string) $this->option('expected-role'),
|
||||||
|
(string) $this->option('operator'), (string) $this->option('reason'), $this->option('apply') === true, $this->option('rebind') === true,
|
||||||
|
$this->option('reuse-components') === true);
|
||||||
|
$this->line(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,37 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Services\ReplenishmentQueue;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class ReplenishmentHealth extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'sgc:replenishment-health {--json : Resultado técnico para integração operacional}';
|
||||||
|
|
||||||
|
protected $description = 'Consultar o estado técnico da reposição sem processar trabalhos ou aprovar compras';
|
||||||
|
|
||||||
|
public function handle(ReplenishmentQueue $queue): int
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$result = $queue->health();
|
||||||
|
} catch (Throwable $error) {
|
||||||
|
report($error);
|
||||||
|
$result = ['checked_at' => now()->toIso8601String(), 'ok' => false, 'reasons' => ['unavailable']];
|
||||||
|
}
|
||||||
|
if ($this->option('json')) {
|
||||||
|
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||||
|
} else {
|
||||||
|
$this->line($result['ok'] ? 'Reposição: verificação técnica sem pendências observadas.' : 'Reposição: verificação técnica requer atenção.');
|
||||||
|
$labels = ['not_installed' => 'Reposição durável não instalada nesta composição.', 'not_recent' => 'Sem passagem recente confirmada.',
|
||||||
|
'last_run_not_successful' => 'Última passagem sem sucesso confirmado.', 'pending_signals' => 'Existem sinais duráveis por processar.',
|
||||||
|
'failed_work' => 'Existem trabalhos a recuperar.', 'unbound_observation' => 'Passagem sem associação confirmada a esta instalação/base.', 'unavailable' => 'Não foi possível consultar. Verifique o registo técnico.'];
|
||||||
|
foreach ($result['reasons'] as $reason) {
|
||||||
|
$this->line($labels[$reason]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result['ok'] ? self::SUCCESS : self::FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Services\ReplenishmentHeartbeat;
|
||||||
|
use App\Services\ReplenishmentProcessLock;
|
||||||
|
use App\Services\ReplenishmentQueue;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
class ReplenishmentTick extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'sgc:replenishment-tick {--limit= : Máximo de artigos/armazéns por execução}';
|
||||||
|
|
||||||
|
protected $description = 'Recuperar reposições pendentes e reavaliar mínimos e validade, sem aprovar compras';
|
||||||
|
|
||||||
|
public function handle(ReplenishmentQueue $queue): int
|
||||||
|
{
|
||||||
|
if (! $queue->ready()) {
|
||||||
|
$this->warn('Reposição durável não instalada nesta composição.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
$limit = $this->option('limit') ?? config('replenishment.batch_size');
|
||||||
|
if (! filter_var($limit, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 500]])) {
|
||||||
|
$this->error('Limite entre 1 e 500.');
|
||||||
|
|
||||||
|
return self::INVALID;
|
||||||
|
}
|
||||||
|
$started = now()->toIso8601String();
|
||||||
|
$exitCode = self::FAILURE;
|
||||||
|
$lock = app(ReplenishmentProcessLock::class);
|
||||||
|
if (! $lock->acquire()) {
|
||||||
|
$this->info('Verificação periódica já em execução; aguarde a próxima passagem.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$queue->discover();
|
||||||
|
$result = $queue->drain((int) $limit);
|
||||||
|
$this->info('Reposição: '.$result['processed'].' trabalhos conferidos; '.$result['failed'].' a recuperar.');
|
||||||
|
$exitCode = $result['failed'] === 0 ? self::SUCCESS : self::FAILURE;
|
||||||
|
|
||||||
|
return $exitCode;
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
app(ReplenishmentHeartbeat::class)->record($started, $exitCode);
|
||||||
|
} catch (\Throwable $error) {
|
||||||
|
report($error);
|
||||||
|
$this->warn('Não foi possível actualizar o acompanhamento técnico desta execução.');
|
||||||
|
} finally {
|
||||||
|
$lock->release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Services\RequisitionExpiry;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
final class RequisitionExpiryTick extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'sgc:approval-deadlines-tick';
|
||||||
|
|
||||||
|
protected $description = 'Conferir prazos configurados, avisos e devoluções de requisições';
|
||||||
|
|
||||||
|
public function handle(RequisitionExpiry $service): int
|
||||||
|
{
|
||||||
|
if (! $service->ready()) {
|
||||||
|
$this->warn('Extensão de prazos indisponível nesta composição.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
$checked = $failed = 0;
|
||||||
|
DB::table('requisitions')->where('status', 'pending')->whereNotNull('approval_snapshot->approval_expiry')->orderBy('id')->chunkById(100,
|
||||||
|
function ($requests) use ($service, &$checked, &$failed) {
|
||||||
|
foreach ($requests as $request) {
|
||||||
|
try {
|
||||||
|
$service->scheduled($request->id);
|
||||||
|
$checked++;
|
||||||
|
} catch (\Throwable $error) {
|
||||||
|
report($error);
|
||||||
|
$failed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
$this->info('Prazos: '.$checked.' pedidos conferidos; '.$failed.' pendentes de recuperação.');
|
||||||
|
|
||||||
|
return $failed === 0 ? self::SUCCESS : self::FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
|
use App\Services\WorkContext;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
class SgcDeliveryCheck extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'sgc:delivery-check {tenant : ID da empresa}';
|
||||||
|
|
||||||
|
protected $description = 'Conferir configuração e ausência de dados de desenvolvimento antes da entrega; não altera dados';
|
||||||
|
|
||||||
|
public function handle(WorkContext $contexts): int
|
||||||
|
{
|
||||||
|
$tenant = Tenant::query()->find($this->argument('tenant'));
|
||||||
|
if ($tenant === null || ! Schema::hasColumn('tenants', 'work_context_policy')) {
|
||||||
|
$this->error('Empresa inexistente ou instalação do contexto pendente.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
$users = User::query()->where('tenant_id', $tenant->id)->get();
|
||||||
|
$actor = $users->first();
|
||||||
|
if ($actor === null || $contexts->policy($actor) === null || $contexts->purchased($actor) === [] || ! app(OrganizationAccess::class)->active($tenant->id)) {
|
||||||
|
$this->error('Defina produto contratado, opções e administração da empresa antes da entrega.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
$administrators = 0;
|
||||||
|
foreach ($users as $user) {
|
||||||
|
$profiles = DB::table('organization_memberships as m')->join('organization_profiles as p', 'p.id', '=', 'm.profile_id')
|
||||||
|
->where('m.tenant_id', $tenant->id)->where('p.tenant_id', $tenant->id)->where('m.user_id', $user->id)
|
||||||
|
->where('m.maintenance', false)->whereNull('m.expires_at')->pluck('p.permissions');
|
||||||
|
if ($profiles->contains(fn ($json) => in_array('admin', json_decode($json, true, 32, JSON_THROW_ON_ERROR), true))) {
|
||||||
|
$administrators++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$clean = true;
|
||||||
|
foreach (Schema::getTables() as $table) {
|
||||||
|
$name = $table['name'];
|
||||||
|
if (in_array($name, ['users', 'departments', 'cost_centers', 'organization_profiles', 'organization_memberships', 'organization_access', 'audit_logs'], true)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (Schema::hasColumn($name, 'tenant_id') && DB::table($name)->where('tenant_id', $tenant->id)->exists()) {
|
||||||
|
$this->error('Existem registos a reconciliar antes da entrega: '.$name);
|
||||||
|
$clean = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$enabled = $contexts->policy($actor)['enabled'] ?? [];
|
||||||
|
if ($administrators < 2 || $enabled === [] || array_diff($enabled, $contexts->purchased($actor)) !== []) {
|
||||||
|
$this->error('Confira dois administradores permanentes e opções activadas dentro do produto contratado.');
|
||||||
|
$clean = false;
|
||||||
|
}
|
||||||
|
foreach ($enabled as $key) {
|
||||||
|
if (! WorkContext::operational($key)) {
|
||||||
|
$this->error('Percurso operacional ainda pendente: '.$key);
|
||||||
|
$clean = false;
|
||||||
|
}
|
||||||
|
if (! $users->contains(fn ($user) => in_array($key, $contexts->available($user), true))) {
|
||||||
|
$this->error('Opção sem utilizador com perfil/contexto autorizado: '.$key);
|
||||||
|
$clean = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($clean) {
|
||||||
|
$this->info('Conferência técnica aprovada. Não substitui aceitação funcional, revisão dos cadastros de configuração ou instalação de RH.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $clean ? self::SUCCESS : self::FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Services\ProductModules;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Database\Migrations\Migrator;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Laravel\Fortify\Features;
|
||||||
|
use Symfony\Component\Process\Process;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/** Conferência da instalação de produção (fase 5). Só lê configuração e esquema; não altera dados. */
|
||||||
|
class SgcProductionCheck extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'sgc:production-check';
|
||||||
|
|
||||||
|
protected $description = 'Conferir se a instalação está pronta para produção (ambiente, base de dados, migrações, MFA, ficheiros); não altera dados';
|
||||||
|
|
||||||
|
private int $failures = 0;
|
||||||
|
|
||||||
|
public function handle(Migrator $migrator): int
|
||||||
|
{
|
||||||
|
$this->check(app()->environment('production'), 'APP_ENV=production');
|
||||||
|
$this->check(! config('app.debug'), 'APP_DEBUG=false');
|
||||||
|
$this->check(filled(config('app.key')), 'APP_KEY definida');
|
||||||
|
$https = str_starts_with((string) config('app.url'), 'https://');
|
||||||
|
$this->check($https, 'APP_URL em https');
|
||||||
|
$this->check(! $https || config('session.secure') === true, 'SESSION_SECURE_COOKIE=true');
|
||||||
|
$this->check(! in_array(config('session.driver'), ['array', 'cookie'], true), 'Sessões persistentes (SESSION_DRIVER)');
|
||||||
|
$this->check(config('cache.default') !== 'array', 'Cache persistente (CACHE_STORE)');
|
||||||
|
|
||||||
|
$this->database($migrator);
|
||||||
|
|
||||||
|
$this->check(Features::enabled(Features::twoFactorAuthentication()), 'MFA ligado (SGC_TWO_FACTOR_ENABLED=true)');
|
||||||
|
$this->check(array_filter((array) config('mfa.required_functions')) !== [], 'Funções com MFA obrigatório (SGC_MFA_REQUIRED_FUNCTIONS)');
|
||||||
|
|
||||||
|
foreach ([storage_path('app/private'), storage_path('logs'), storage_path('framework/sessions'), base_path('bootstrap/cache')] as $path) {
|
||||||
|
$this->check(is_dir($path) && is_writable($path), 'Pasta gravável: '.str_replace(base_path().'/', '', $path));
|
||||||
|
}
|
||||||
|
|
||||||
|
$runtime = new Process([PHP_BINARY, base_path('scripts/check-runtime-packages.php')], base_path());
|
||||||
|
$runtime->run();
|
||||||
|
$this->check($runtime->isSuccessful(), 'Pacotes partilhados conferidos (runtime:check)');
|
||||||
|
|
||||||
|
if (in_array(config('mail.default'), ['log', 'array'], true)) {
|
||||||
|
$this->warn('AVISO Email não configurado (MAIL_MAILER='.config('mail.default').'): avisos de prazos não saem da aplicação.');
|
||||||
|
}
|
||||||
|
$modules = collect(app(ProductModules::class)->states())->map(fn (bool $on, string $key) => $key.'='.($on ? 'ligado' : 'desligado'))->implode(', ');
|
||||||
|
$this->line('INFO Módulos: '.$modules.'; cancelamento de ordens='.(config('order_cancellation.enabled') ? 'ligado' : 'desligado'));
|
||||||
|
$this->line('INFO Confirme também: cron com `php artisan schedule:run` a cada minuto e cópias de segurança diárias (docs/producao.md).');
|
||||||
|
|
||||||
|
if ($this->failures > 0) {
|
||||||
|
$this->error($this->failures.' verificação(ões) falharam. A instalação não está pronta para produção.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
$this->info('Instalação pronta para produção. Não substitui o restauro de teste nem a aceitação do piloto.');
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function database(Migrator $migrator): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
DB::connection()->getPdo();
|
||||||
|
} catch (Throwable) {
|
||||||
|
$this->check(false, 'Ligação à base de dados');
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$this->check(DB::connection()->getDriverName() === 'pgsql', 'Base de dados PostgreSQL');
|
||||||
|
if (! $migrator->repositoryExists()) {
|
||||||
|
$this->check(false, 'Tabela de migrações presente');
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$files = $migrator->getMigrationFiles([database_path('migrations'), ...$migrator->paths()]);
|
||||||
|
$pending = array_diff(array_keys($files), $migrator->getRepository()->getRan());
|
||||||
|
$this->check($pending === [], $pending === [] ? 'Migrações aplicadas' : 'Migrações pendentes: '.count($pending).' ('.implode(', ', array_slice($pending, 0, 3)).')');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function check(bool $passed, string $label): void
|
||||||
|
{
|
||||||
|
if ($passed) {
|
||||||
|
$this->line('OK '.$label);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$this->failures++;
|
||||||
|
$this->line('<fg=red>FALHA</> '.$label);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,87 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Services\AgreementFollowup;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class AgreementFollowupController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, AgreementFollowup $read): Response
|
||||||
|
{
|
||||||
|
return $this->respond($request, $read, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function csv(Request $request, AgreementFollowup $read): Response
|
||||||
|
{
|
||||||
|
return $this->respond($request, $read, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function respond(Request $request, AgreementFollowup $read, bool $csv): Response
|
||||||
|
{
|
||||||
|
$actor = $this->staffIdentity($request);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($request, $read, $csv, $actor) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
$actor = $read->authorize($actor);
|
||||||
|
$filters = $read->filters($request);
|
||||||
|
$kind = $request->validate(['kind' => 'nullable|in:agreement,contract'])['kind'] ?? 'agreement';
|
||||||
|
$today = today()->toDateString();
|
||||||
|
$query = $read->query($actor, $filters, $today, $kind)->orderBy('id');
|
||||||
|
if (! $csv) {
|
||||||
|
$page = $query->paginate(25)->withQueryString();
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('supply/agreement-followup', ['kind' => $kind, 'asOf' => $today, 'filters' => $filters, 'records' => [
|
||||||
|
'data' => $read->rows($page->getCollection(), $today), 'total' => $page->total(), 'current_page' => $page->currentPage(),
|
||||||
|
'last_page' => $page->lastPage(), 'prev_page_url' => $page->previousPageUrl(), 'next_page_url' => $page->nextPageUrl(),
|
||||||
|
]])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
$response->headers->set('X-Content-Type-Options', 'nosniff');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
$file = fopen('php://temp', 'w+');
|
||||||
|
if ($file === false) {
|
||||||
|
throw new \RuntimeException('Não foi possível preparar o CSV.');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
fwrite($file, "\xEF\xBB\xBF");
|
||||||
|
$write = static function (array $cells) use ($file): void {
|
||||||
|
fputcsv($file, array_map(static function (mixed $value): string {
|
||||||
|
$text = $value === null ? 'Não disponível' : (string) $value;
|
||||||
|
|
||||||
|
return preg_match('/^[\s\x00-\x1F]*[=+@-]/u', $text) ? "'".$text : $text;
|
||||||
|
}, $cells), ';', '"', '');
|
||||||
|
};
|
||||||
|
$write([$kind === 'contract' ? 'Vigência de contratos globais aprovados' : 'Vigência de acordos aprovados', 'Data de consulta', $today]);
|
||||||
|
$write(['Pesquisa', $filters['search'], 'Situação', $filters['validity'], 'Termina até', $filters['expires_by']]);
|
||||||
|
$write(['Registo', 'Versão', 'Referência', 'Fornecedor preservado', 'Código do artigo', 'Artigo preservado', 'Armazém preservado', 'Início', 'Fim', 'Situação de vigência', 'Políticas aprovadas ligadas', 'Acordo', 'Políticas',
|
||||||
|
...($kind === 'contract' ? ['Moeda', 'Limite global por ordem (centavos)', 'Periodicidade prevista (dias)', 'Artigos aprovados', 'Artigos ligados'] : [])]);
|
||||||
|
$query->chunk(100, function ($batch) use ($read, $today, $write, $kind) {
|
||||||
|
foreach ($read->rows($batch, $today) as $row) {
|
||||||
|
$write([$row['record_key'], $row['version'], $row['reference'], $row['supplier'], $kind === 'contract' ? 'Não aplicável' : $row['item_code'], $kind === 'contract' ? 'Não aplicável' : $row['item'], $kind === 'contract' ? 'Não aplicável' : $row['warehouse'],
|
||||||
|
$row['valid_from'], $row['valid_until'], match ($row['validity']) {
|
||||||
|
'current' => 'Vigente','expired' => 'Expirado','future' => 'Por iniciar',default => 'Datas indeterminadas'
|
||||||
|
}, $kind === 'contract' ? 'Não aplicável' : $row['approved_policies'], $row['href'], $kind === 'contract' ? 'Não aplicável' : $row['policies_href'],
|
||||||
|
...($kind === 'contract' ? [$row['currency'], $row['max_order_value_minor'] ?? 'Não definido', $row['periodicity_days'], $row['approved_articles'], $row['articles_href']] : [])]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
rewind($file);
|
||||||
|
$body = stream_get_contents($file);
|
||||||
|
if ($body === false) {
|
||||||
|
throw new \RuntimeException('Não foi possível ler o CSV preparado.');
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
fclose($file);
|
||||||
|
}
|
||||||
|
|
||||||
|
return response($body, 200, ['Content-Type' => 'text/csv; charset=UTF-8', 'Content-Disposition' => 'attachment; filename="vigencia-'.($kind === 'contract' ? 'contratos' : 'acordos').'-'.$today.'.csv"',
|
||||||
|
'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
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(['request_reference' => 'nullable|string|max:100', '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(isset($filters['request_reference']) && $filters['request_reference'] !== '', fn ($q) => $q->whereExists(fn ($source) => $source
|
||||||
|
->selectRaw('1')->from('requisitions')->whereColumn('requisitions.id', 'audit_logs.requisition_id')
|
||||||
|
->whereColumn('requisitions.tenant_id', 'audit_logs.tenant_id')->where('requisitions.number', $filters['request_reference'])))
|
||||||
|
->when(isset($filters['action']) && $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();
|
||||||
|
$source = isset($filters['request_reference']) && $filters['request_reference'] !== ''
|
||||||
|
? Requisition::query()->visibleTo($actor)->where('number', $filters['request_reference'])->first(['id', 'number']) : null;
|
||||||
|
|
||||||
|
$response = Inertia::render('audit/metadata', ['filters' => $filters,
|
||||||
|
'requestContext' => $source === null ? null : ['number' => $source->number, 'href' => '/requisicoes/'.$source->id.'#requisition-history'],
|
||||||
|
'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(),
|
||||||
|
'Referência exacta da requisição', $text($filters['request_reference'] ?? ''), 'Acção exacta', $text($filters['action'] ?? ''),
|
||||||
|
'Utilizador (id)', $text($filters['actor_id'] ?? ''), 'Desde', $text($filters['from'] ?? ''), 'Até', $text($filters['to'] ?? '')], ';', '"', '');
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\CostCenter;
|
||||||
|
use App\Models\Equipment;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\AutomaticPurchases;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
|
use App\Services\ReplenishmentQueue;
|
||||||
|
use App\Services\SupplyPlanning;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class AutomaticPurchaseController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, AutomaticPurchases $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions(['admin', 'supply_read', 'supply_prepare', 'supply_review']), 403);
|
||||||
|
$prepare = app(SupplyPlanning::class)->allows($actor, 'supply_prepare');
|
||||||
|
$ready = $service->ready();
|
||||||
|
$planning = app(SupplyPlanning::class);
|
||||||
|
$filters = $request->validate(['rule_id' => ['nullable', 'integer', 'min:1', Rule::exists('supply_records', 'id')->where('tenant_id', $actor->tenant_id)->where('kind', 'auto_rule')], 'need_state' => 'nullable|in:all,pending,created,covered,satisfied', 'rules_page' => 'nullable|integer|min:1|max:1000000', 'needs_page' => 'nullable|integer|min:1|max:1000000', 'history_page' => 'nullable|integer|min:1|max:1000000', 'work_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$focus = isset($filters['rule_id']) ? SupplyRecord::query()->where('kind', 'auto_rule')->findOrFail((int) $filters['rule_id']) : null;
|
||||||
|
$rules = $planning->latest('auto_rule')->when($focus !== null, fn ($query) => $query->where('record_key', $focus->record_key));
|
||||||
|
$latestFocus = $focus === null ? null : (clone $rules)->first();
|
||||||
|
$needs = $planning->latest('auto_need');
|
||||||
|
if (($filters['need_state'] ?? 'all') !== 'all') {
|
||||||
|
$needs->where('state', $filters['need_state']);
|
||||||
|
}
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
|
$response = Inertia::render('stock/replenishment', [
|
||||||
|
'ready' => $ready, 'canPrepare' => $prepare, 'canReview' => $planning->allows($actor, 'supply_review'),
|
||||||
|
'filters' => ['need_state' => $filters['need_state'] ?? 'all'],
|
||||||
|
'focusRuleId' => $focus->id ?? null, 'focusChanged' => $focus !== null && $latestFocus?->id !== $focus->id,
|
||||||
|
'rules' => $ready ? $rules->latest('id')->paginate(20, ['*'], 'rules_page')->withQueryString()->through(fn (SupplyRecord $rule) => [...$rule->toArray(), 'canApprove' => $service->canReview($actor, $rule), 'canSuspend' => $service->canReview($actor, $rule, 'suspend')]) : null,
|
||||||
|
'needs' => $ready ? $needs->orderByRaw("CASE WHEN state = 'pending' THEN 0 ELSE 1 END")->oldest('id')->paginate(20, ['*'], 'needs_page')->withQueryString() : null,
|
||||||
|
'history' => $ready ? SupplyRecord::query()->whereIn('kind', ['auto_rule', 'auto_need'])->latest('id')->paginate(30, ['*'], 'history_page')->withQueryString() : null,
|
||||||
|
...app(ReplenishmentQueue::class)->status($actor),
|
||||||
|
'workItems' => app(ReplenishmentQueue::class)->ready() ? DB::table('replenishment_work as w')->join('stock_items as i', 'i.id', '=', 'w.stock_item_id')->join('warehouses as a', 'a.id', '=', 'w.warehouse_id')->where('w.tenant_id', $actor->tenant_id)->where('i.tenant_id', $actor->tenant_id)->where('a.tenant_id', $actor->tenant_id)->where(fn ($q) => $q->whereColumn('w.generation', '>', 'w.processed_generation')->orWhere('w.failures', '>', 0))->orderBy('w.due_at')->orderBy('w.id')->paginate(20, ['w.id', 'i.code', 'i.name', 'a.name as warehouse', 'w.last_error', 'w.due_at', 'w.failures'], 'work_page')->withQueryString() : null,
|
||||||
|
'policies' => Schema::hasTable('supply_records') && $prepare ? $planning->latest('policy')->where('state', 'approved')->where('data->purpose', 'internal')->get() : [],
|
||||||
|
'requesters' => $prepare ? User::query()->where('tenant_id', $actor->tenant_id)->get(['id', 'name', 'department_id', 'purchasing_role', 'tenant_id'])->filter(fn ($u) => $service->eligibleRequester($u))->map(fn ($u) => $u->only(['id', 'name', 'department_id']))->values() : [],
|
||||||
|
'centers' => $prepare ? CostCenter::query()->orderBy('code')->get(['id', 'department_id', 'code', 'name']) : [],
|
||||||
|
'equipment' => $prepare ? Equipment::query()->orderBy('code')->get(['id', 'code', 'description', 'department_id']) : [],
|
||||||
|
'catalogueTypes' => $prepare && Schema::hasTable('requisition_catalogue') ? DB::table('requisition_catalogue')->where('tenant_id', $actor->tenant_id)->where('published', true)->pluck('purchase_type', 'stock_item_id') : [],
|
||||||
|
])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function save(Request $request, AutomaticPurchases $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$service->save($request->user('web'), $request->all());
|
||||||
|
|
||||||
|
return redirect('/stock/reposicao');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function evaluate(Request $request, int $id, AutomaticPurchases $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && ($actor->hasFunctions(['supply_prepare', 'supply_review'])) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||||
|
$need = SupplyRecord::query()->where('kind', 'auto_need')->findOrFail($id);
|
||||||
|
if (app(ReplenishmentQueue::class)->ready()) {
|
||||||
|
$service->signal($actor, $need->stock_item_id, $need->warehouse_id);
|
||||||
|
} else {
|
||||||
|
$service->evaluate($actor, $need->stock_item_id, $need->warehouse_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect('/stock/reposicao');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function recover(Request $request, int $id, AutomaticPurchases $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions(['supply_prepare', 'supply_review']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||||
|
$work = DB::table('replenishment_work')->where('tenant_id', $actor->tenant_id)->where('id', $id)->firstOrFail();
|
||||||
|
$service->signal($actor, $work->stock_item_id, $work->warehouse_id);
|
||||||
|
|
||||||
|
return redirect('/stock/reposicao');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,36 +15,40 @@ use Illuminate\Http\Request;
|
|||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class BudgetController extends Controller
|
class BudgetController extends Controller
|
||||||
{
|
{
|
||||||
private function access(Request $request): void
|
private function access(Request $request): void
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function index(Request $request): Response
|
public function index(Request $request): Response
|
||||||
{
|
{
|
||||||
$this->access($request);
|
$this->access($request);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
return Inertia::render('budgets/index', ['centers' => CostCenter::query()->orderBy('code')->get(), 'budgets' => Budget::query()->latest('id')->get()->map(function (Budget $budget) use ($request) {
|
$response = Inertia::render('budgets/index', ['centers' => CostCenter::query()->orderBy('code')->get(), 'budgets' => Budget::query()->latest('id')->get()->map(function (Budget $budget) use ($request) {
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
|
|
||||||
return [...$budget->toArray(), ...$adapter->execute(fn () => $adapter->for($request->user())->balance($budget->id))];
|
return [...$budget->toArray(), ...$adapter->execute(fn () => $adapter->for($this->staffIdentity($request))->balance($budget->id))];
|
||||||
}), 'reinforcements' => BudgetReinforcement::query()->latest('id')->paginate(20)]);
|
}), 'reinforcements' => BudgetReinforcement::query()->latest('id')->paginate(20)])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function store(Request $request): RedirectResponse
|
public function store(Request $request): RedirectResponse
|
||||||
{
|
{
|
||||||
$this->access($request);
|
$this->access($request);
|
||||||
$data = $request->validate(['cost_center_id' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $request->user()->tenant_id)], 'year' => 'required|integer|min:2026|max:2100', 'includes_tax' => 'required|boolean', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'reason' => 'required|string|max:4000']);
|
$data = $request->validate(['cost_center_id' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $this->staffIdentity($request)->tenant_id)], 'year' => 'required|integer|min:2026|max:2100', 'includes_tax' => 'required|boolean', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'reason' => 'required|string|max:4000']);
|
||||||
$kind = $request->validate(['kind' => ['sometimes', Rule::in(['operating', 'investment'])]])['kind'] ?? 'operating';
|
$kind = $request->validate(['kind' => ['sometimes', Rule::in(['operating', 'investment'])]])['kind'] ?? 'operating';
|
||||||
DB::transaction(function () use ($request, $data, $kind) {
|
DB::transaction(function () use ($request, $data, $kind) {
|
||||||
app(ConflictGuard::class)->lockCompany($request->user());
|
app(ConflictGuard::class)->lockCompany($this->staffIdentity($request));
|
||||||
app(CurrentActor::class)->lock($request->user(), [PurchasingRole::Admin, PurchasingRole::Finance]);
|
app(CurrentActor::class)->lock($this->staffIdentity($request), [PurchasingRole::Admin, PurchasingRole::Finance]);
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
$adapter->execute(fn () => $adapter->for($request->user())->create(['cost_center_id' => (int) $data['cost_center_id'], 'year' => (int) $data['year'], 'kind' => $kind, 'includes_tax' => (bool) $data['includes_tax'], 'amount_minor' => BigDecimal::of($data['amount'])->multipliedBy(100)->toInt(), 'reason' => $data['reason']]));
|
$adapter->execute(fn () => $adapter->for($this->staffIdentity($request))->create(['cost_center_id' => (int) $data['cost_center_id'], 'year' => (int) $data['year'], 'kind' => $kind, 'includes_tax' => (bool) $data['includes_tax'], 'amount_minor' => BigDecimal::of($data['amount'])->multipliedBy(100)->toInt(), 'reason' => $data['reason']]));
|
||||||
});
|
});
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
@@ -54,10 +58,10 @@ class BudgetController extends Controller
|
|||||||
{
|
{
|
||||||
$this->access($request);
|
$this->access($request);
|
||||||
DB::transaction(function () use ($request, $budget) {
|
DB::transaction(function () use ($request, $budget) {
|
||||||
app(ConflictGuard::class)->lockCompany($request->user());
|
app(ConflictGuard::class)->lockCompany($this->staffIdentity($request));
|
||||||
app(CurrentActor::class)->lock($request->user(), [PurchasingRole::Admin, PurchasingRole::Finance]);
|
app(CurrentActor::class)->lock($this->staffIdentity($request), [PurchasingRole::Admin, PurchasingRole::Finance]);
|
||||||
$adapter = app(CommonBudget::class);
|
$adapter = app(CommonBudget::class);
|
||||||
$adapter->execute(fn () => $adapter->for($request->user())->approve($budget->id));
|
$adapter->execute(fn () => $adapter->for($this->staffIdentity($request))->approve($budget->id));
|
||||||
});
|
});
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
|
|||||||
@@ -13,9 +13,9 @@ class BudgetReinforcementController extends Controller
|
|||||||
{
|
{
|
||||||
public function store(Request $request, Budget $budget, BudgetReinforcementWorkflow $workflow): RedirectResponse
|
public function store(Request $request, Budget $budget, BudgetReinforcementWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
||||||
$data = $request->validate(['reference' => 'required|string|max:100', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'reason' => 'required|string|max:4000']);
|
$data = $request->validate(['reference' => 'required|string|max:100', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'reason' => 'required|string|max:4000']);
|
||||||
$workflow->propose($request->user(), $budget, $data);
|
$workflow->propose($this->staffIdentity($request), $budget, $data);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@ class BudgetReinforcementController extends Controller
|
|||||||
public function review(Request $request, BudgetReinforcement $reinforcement, BudgetReinforcementWorkflow $workflow): RedirectResponse
|
public function review(Request $request, BudgetReinforcement $reinforcement, BudgetReinforcementWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|max:4000']);
|
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|max:4000']);
|
||||||
$workflow->review($request->user(), $reinforcement, $data['decision'], $data['reason']);
|
$workflow->review($this->staffIdentity($request), $reinforcement, $data['decision'], $data['reason']);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\BusinessClient;
|
||||||
|
use App\Services\BusinessClients;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class BusinessClientController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, BusinessClients $clients): Response
|
||||||
|
{
|
||||||
|
$actor = $this->staffIdentity($request);
|
||||||
|
abort_unless($clients->ready(), 503);
|
||||||
|
abort_unless($clients->canRead($actor), 403);
|
||||||
|
$filters = $request->validate(['search' => 'nullable|string|max:180', 'page' => 'nullable|integer|min:1']);
|
||||||
|
$query = BusinessClient::query()->where('tenant_id', $actor->tenant_id)
|
||||||
|
->select(['id', 'client_key', 'code', 'name', 'tax_number', 'address', 'email', 'active', 'version']);
|
||||||
|
if (trim($filters['search'] ?? '') !== '') {
|
||||||
|
$query->where(fn ($q) => $q->where('name', 'like', '%'.$filters['search'].'%')->orWhere('code', 'like', '%'.$filters['search'].'%'));
|
||||||
|
}
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('company/clients', ['clients' => $query->orderBy('name')->paginate(20)->withQueryString(),
|
||||||
|
'filters' => $filters, 'canManage' => $clients->canManage($actor)])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, BusinessClients $clients): Response
|
||||||
|
{
|
||||||
|
$clients->save($this->staffIdentity($request), null, $request->all());
|
||||||
|
|
||||||
|
return redirect('/empresa/clientes')->with('success', 'Cliente registado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(Request $request, int $client, BusinessClients $clients): Response
|
||||||
|
{
|
||||||
|
$clients->save($this->staffIdentity($request), $client, $request->all());
|
||||||
|
|
||||||
|
return redirect('/empresa/clientes')->with('success', 'Cliente actualizado; os processos anteriores conservam a sua identificação original.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,10 +6,12 @@ use App\Models\CandidateAccount;
|
|||||||
use App\Models\PeopleProcess;
|
use App\Models\PeopleProcess;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\AdministrativeGeography;
|
||||||
use App\Services\CandidateAccess;
|
use App\Services\CandidateAccess;
|
||||||
use App\Services\CandidateDocuments;
|
use App\Services\CandidateDocuments;
|
||||||
use App\Services\CandidateProfiles;
|
use App\Services\CandidateProfiles;
|
||||||
use App\Services\CandidateSubmissions;
|
use App\Services\CandidateSubmissions;
|
||||||
|
use App\Services\CandidateTerritory;
|
||||||
use App\Services\CandidateTriage;
|
use App\Services\CandidateTriage;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
use App\Services\CurrentActor;
|
use App\Services\CurrentActor;
|
||||||
@@ -17,6 +19,7 @@ use App\Services\OrganizationConfiguration;
|
|||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
use App\Services\SubmissionForms;
|
use App\Services\SubmissionForms;
|
||||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
use Illuminate\Support\Facades\DB;
|
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;
|
$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);
|
$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(),
|
'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,
|
'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()]]);
|
'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
|
public function save(Request $request, int $company, CandidateProfiles $profiles): Response
|
||||||
{
|
{
|
||||||
$account = $this->account($request, $company);
|
$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();
|
$record = PeopleProcess::query()->where('tenant_id', $actor->tenant_id)->where('id', $process)->firstOrFail();
|
||||||
$triage = app(CandidateTriage::class);
|
$triage = app(CandidateTriage::class);
|
||||||
abort_unless($triage->canRead($actor, $record), 403);
|
abort_unless($triage->canRead($actor, $record), 403);
|
||||||
$filter = $request->validate(['submission' => 'nullable|integer|min:1']);
|
$filter = $request->validate(['submission' => 'nullable|integer|min:1', 'location' => 'nullable|string|regex:/^[0-9]+$/D|max:20', 'page' => 'sometimes|integer|min:1|max:1000000']);
|
||||||
$rows = DB::table('candidate_submissions')->where('tenant_id', $actor->tenant_id)->where('people_process_id', $process)->orderBy('id')->paginate(20);
|
$query = DB::table('candidate_submissions')->where('tenant_id', $actor->tenant_id)->where('people_process_id', $process);
|
||||||
if (isset($filter['submission'])) {
|
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();
|
$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)]);
|
$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]);
|
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,
|
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),
|
'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]);
|
'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
|
public function publish(Request $request, int $process, CandidateSubmissions $submissions): Response
|
||||||
{
|
{
|
||||||
$submissions->publish($this->staff($request), $process, $request->all());
|
$submissions->publish($this->staff($request), $process, $request->all());
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\CapitalAssignments;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class CapitalRegisterController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, CapitalRegister $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$filters = $request->validate(['page' => 'nullable|integer|min:1|max:1000000', 'history' => 'nullable|uuid', 'history_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'origins_page' => 'nullable|integer|min:1|max:1000000', 'receipts_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$props = $service->workspace($actor, $filters['history'] ?? null);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('equipment/capital-register', $props)->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, CapitalRegister $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Versão do cadastro preservada.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assignments(Request $request, Requisition $requisition, CapitalAssignments $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$request->validate(['choices_page' => 'nullable|integer|min:1|max:1000000', 'history_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('requisitions/capital-assignments', $service->workspace($actor, $requisition))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assign(Request $request, Requisition $requisition, CapitalAssignments $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Ligação documental preservada.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\CommonFinanceAdministration;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class CommonFinanceAdministrationController extends Controller
|
||||||
|
{
|
||||||
|
public function show(Request $request, CommonFinanceAdministration $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$data = $request->validate(['user' => 'nullable|integer|min:1', 'q' => 'nullable|string|max:100',
|
||||||
|
'users_page' => 'nullable|integer|min:1|max:1000000', 'history_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('company/finance', $service->workspace($actor, isset($data['user']) ? (int) $data['user'] : null, $data['q'] ?? ''))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, string $kind, CommonFinanceAdministration $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
try {
|
||||||
|
$service->save($actor, $kind, $request->all());
|
||||||
|
} catch (\DomainException $error) {
|
||||||
|
if ($request->header('X-Inertia')) {
|
||||||
|
throw ValidationException::withMessages(['configuration' => $error->getMessage()]);
|
||||||
|
}
|
||||||
|
abort(409, $error->getMessage());
|
||||||
|
} catch (\InvalidArgumentException $error) {
|
||||||
|
if ($request->header('X-Inertia')) {
|
||||||
|
throw ValidationException::withMessages(['configuration' => $error->getMessage()]);
|
||||||
|
}
|
||||||
|
abort(422, $error->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return back()->with('success', 'Configuração financeira registada com histórico.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
|
use Illuminate\Database\QueryException;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Tempo\Inventory\InventoryReadSession;
|
||||||
|
|
||||||
|
final class CommonStockReadController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
// Native authority, reloaded on every request; no SGF grants or identity assumptions.
|
||||||
|
$user = User::query()->findOrFail($this->staffIdentity($request)->id);
|
||||||
|
abort_unless($user->tenant_id !== null && $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance])
|
||||||
|
&& ! app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||||
|
$d = $request->validate(['view' => 'sometimes|in:items,warehouses,balances,movements', 'search' => 'nullable|string|max:100',
|
||||||
|
'warehouse_id' => 'sometimes|integer|min:1', 'page' => 'sometimes|integer|min:1|max:100000', 'per_page' => 'sometimes|integer|min:1|max:100', 'snapshot' => 'sometimes|string|max:8192']);
|
||||||
|
abort_if(array_diff(array_keys($request->query()), array_keys($d)) !== [], 422);
|
||||||
|
$filters = ['view' => $d['view'] ?? 'balances', 'search' => $d['search'] ?? '', 'warehouse_id' => isset($d['warehouse_id']) ? (int) $d['warehouse_id'] : null,
|
||||||
|
'page' => (int) ($d['page'] ?? 1), 'per_page' => (int) ($d['per_page'] ?? 25)];
|
||||||
|
$binding = config('stock_read.synthetic_sources.'.$user->tenant_id.':'.$user->id);
|
||||||
|
if (! $binding) {
|
||||||
|
return response()->json(['status' => 'unavailable', 'message' => 'Fonte autorizada de stock ainda não ligada a este contexto.'], 503)->header('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
abort_unless(app()->environment('testing') && DB::connection()->getDriverName() === 'pgsql', 403);
|
||||||
|
$identity = DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||||
|
abort_unless(preg_match('/^stock_read_compras_([a-f0-9]{12})$/D', $identity->name, $m)
|
||||||
|
&& $identity->role === 'stock_read_qa_'.$m[1] && (int) $identity->port === 55439
|
||||||
|
&& preg_match('/^[a-f0-9]{12}$/D', (string) config('stock_read.qa_run'))
|
||||||
|
&& $identity->cluster === 'sgf_modular_regression_'.config('stock_read.qa_run'), 403);
|
||||||
|
abort_unless(preg_match('/^sgf_stock_read_[a-f0-9]{12}$/D', $binding['schema'] ?? '') && ($binding['append_only'] ?? false) === true
|
||||||
|
&& ($binding['source_tenant_id'] ?? null) === (int) $user->tenant_id, 503, 'Fonte de stock incompatível.');
|
||||||
|
if ($filters['warehouse_id'] !== null) {
|
||||||
|
abort_unless(in_array($filters['warehouse_id'], $binding['warehouse_ids'], true), 403);
|
||||||
|
}
|
||||||
|
$root = base_path('packages/inventory-read/releases/0.1.0');
|
||||||
|
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
|
||||||
|
abort_unless(is_string($bytes) && hash_equals(config('stock_read.package_manifest_sha256'), hash('sha256', $bytes)), 503, 'Pacote de consulta incompatível.');
|
||||||
|
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||||
|
foreach (['bootstrap.php', 'src/InventoryReader.php', 'src/InventoryReadSession.php'] as $file) {
|
||||||
|
$actual = is_file($root.'/'.$file) ? hash_file('sha256', $root.'/'.$file) : false;
|
||||||
|
abort_unless(is_string($actual) && isset($manifest['files'][$file]) && hash_equals($manifest['files'][$file], $actual), 503, 'Pacote de consulta incompatível.');
|
||||||
|
}
|
||||||
|
require_once $root.'/bootstrap.php';
|
||||||
|
$fingerprint = hash('sha256', json_encode(['compras', $user->tenant_id, $user->id, $request->session()->get('work_context'), $binding, array_diff_key($filters, ['page' => true])], JSON_THROW_ON_ERROR));
|
||||||
|
try {
|
||||||
|
$result = (new InventoryReadSession(DB::connection()))->read($binding, $fingerprint, $filters, $d['snapshot'] ?? null);
|
||||||
|
} catch (QueryException $e) {
|
||||||
|
if (! in_array($e->errorInfo[0] ?? null, ['42P01', '42703', '42883', '57014'], true)) {
|
||||||
|
throw $e;
|
||||||
|
}
|
||||||
|
|
||||||
|
return response()->json(['status' => 'unavailable', 'message' => 'A fonte de stock está indisponível ou incompatível. Actualize a consulta mais tarde.'], 503)->header('Cache-Control','no-store');
|
||||||
|
}
|
||||||
|
|
||||||
|
return response()->json($result)->header('Cache-Control','no-store');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,23 +15,30 @@ use Illuminate\Http\Request;
|
|||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class CompanyController extends Controller
|
class CompanyController extends Controller
|
||||||
{
|
{
|
||||||
public function setup(Request $request): Response|RedirectResponse
|
public function setup(Request $request): Response
|
||||||
{
|
{
|
||||||
return $request->user()->tenant_id ? to_route('dashboard') : Inertia::render('company/setup');
|
if ($this->staffIdentity($request)->tenant_id) {
|
||||||
|
return to_route('dashboard');
|
||||||
|
}
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('company/setup')->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function store(Request $request, RequisitionWorkflow $workflow): RedirectResponse
|
public function store(Request $request, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
abort_if($request->user()->tenant_id !== null, 403);
|
abort_if($this->staffIdentity($request)->tenant_id !== null, 403);
|
||||||
$data = $request->validate(['name' => 'required|string|max:150', 'department' => 'required|string|max:100',
|
$data = $request->validate(['name' => 'required|string|max:150', 'department' => 'required|string|max:100',
|
||||||
'second_name' => 'required|string|max:100', 'second_email' => 'required|email|max:255|unique:users,email', 'second_password' => 'required|string|min:12|confirmed',
|
'second_name' => 'required|string|max:100', 'second_email' => 'required|email|max:255|unique:users,email', 'second_password' => 'required|string|min:12|confirmed',
|
||||||
'first_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'second_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'includes_tax' => 'required|boolean']);
|
'first_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'second_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'includes_tax' => 'required|boolean']);
|
||||||
DB::transaction(function () use ($request, $data, $workflow) {
|
DB::transaction(function () use ($request, $data, $workflow) {
|
||||||
$user = User::query()->lockForUpdate()->findOrFail($request->user()->id);
|
$user = User::query()->lockForUpdate()->findOrFail($this->staffIdentity($request)->id);
|
||||||
abort_if($user->tenant_id !== null, 403);
|
abort_if($user->tenant_id !== null, 403);
|
||||||
$tenant = Tenant::query()->create(['name' => $data['name'], ...OrganizationConfiguration::rules($data)]);
|
$tenant = Tenant::query()->create(['name' => $data['name'], ...OrganizationConfiguration::rules($data)]);
|
||||||
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => $data['department']]);
|
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => $data['department']]);
|
||||||
@@ -46,29 +53,33 @@ class CompanyController extends Controller
|
|||||||
return to_route('dashboard');
|
return to_route('dashboard');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function index(Request $request): Response|RedirectResponse
|
public function index(Request $request): Response
|
||||||
{
|
{
|
||||||
$this->admin($request);
|
$this->admin($request);
|
||||||
if (app(OrganizationAccess::class)->active($request->user()->tenant_id)) {
|
if (app(OrganizationAccess::class)->active($this->staffIdentity($request)->tenant_id)) {
|
||||||
return to_route('organization.parameters');
|
return to_route('organization.parameters');
|
||||||
}
|
}
|
||||||
|
|
||||||
return Inertia::render('company/index', [
|
Inertia::encryptHistory();
|
||||||
'company' => Tenant::query()->findOrFail($request->user()->tenant_id),
|
$response = Inertia::render('company/index', [
|
||||||
|
'company' => Tenant::query()->findOrFail($this->staffIdentity($request)->tenant_id),
|
||||||
'departments' => Department::query()->orderBy('name')->get(),
|
'departments' => Department::query()->orderBy('name')->get(),
|
||||||
'costCenters' => CostCenter::query()->orderBy('code')->get(),
|
'costCenters' => CostCenter::query()->orderBy('code')->get(),
|
||||||
'users' => User::query()->where('tenant_id', $request->user()->tenant_id)->orderBy('name')->get(['id', 'name', 'email', 'department_id', 'purchasing_role']),
|
'users' => User::query()->where('tenant_id', $this->staffIdentity($request)->tenant_id)->orderBy('name')->get(['id', 'name', 'email', 'department_id', 'purchasing_role']),
|
||||||
'roles' => collect(PurchasingRole::cases())->reject(fn (PurchasingRole $role) => $role === PurchasingRole::Configured)->values()->map(fn (PurchasingRole $role) => ['value' => $role->value, 'label' => $role->label()]),
|
'roles' => collect(PurchasingRole::cases())->reject(fn (PurchasingRole $role) => $role === PurchasingRole::Configured)->values()->map(fn (PurchasingRole $role) => ['value' => $role->value, 'label' => $role->label()]),
|
||||||
]);
|
])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function department(Request $request, RequisitionWorkflow $workflow): RedirectResponse
|
public function department(Request $request, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$this->admin($request);
|
$this->admin($request);
|
||||||
$data = $request->validate(['name' => ['required', 'string', 'max:100', Rule::unique('departments')->where('tenant_id', $request->user()->tenant_id)]]);
|
$data = $request->validate(['name' => ['required', 'string', 'max:100', Rule::unique('departments')->where('tenant_id', $this->staffIdentity($request)->tenant_id)]]);
|
||||||
DB::transaction(function () use ($request, $data, $workflow) {
|
DB::transaction(function () use ($request, $data, $workflow) {
|
||||||
$department = Department::query()->create(['tenant_id' => $request->user()->tenant_id, ...$data]);
|
$department = Department::query()->create(['tenant_id' => $this->staffIdentity($request)->tenant_id, ...$data]);
|
||||||
$workflow->audit($request->user(), 'department.created', null, null, $department->toArray());
|
$workflow->audit($this->staffIdentity($request), 'department.created', null, null, $department->toArray());
|
||||||
});
|
});
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
@@ -78,13 +89,13 @@ class CompanyController extends Controller
|
|||||||
{
|
{
|
||||||
$this->admin($request);
|
$this->admin($request);
|
||||||
$data = $request->validate([
|
$data = $request->validate([
|
||||||
'department_id' => ['required', Rule::exists('departments', 'id')->where('tenant_id', $request->user()->tenant_id)],
|
'department_id' => ['required', Rule::exists('departments', 'id')->where('tenant_id', $this->staffIdentity($request)->tenant_id)],
|
||||||
'code' => ['required', 'string', 'max:30', Rule::unique('cost_centers')->where('tenant_id', $request->user()->tenant_id)],
|
'code' => ['required', 'string', 'max:30', Rule::unique('cost_centers')->where('tenant_id', $this->staffIdentity($request)->tenant_id)],
|
||||||
'name' => 'required|string|max:100',
|
'name' => 'required|string|max:100',
|
||||||
]);
|
]);
|
||||||
DB::transaction(function () use ($request, $data, $workflow) {
|
DB::transaction(function () use ($request, $data, $workflow) {
|
||||||
$center = CostCenter::query()->create(['tenant_id' => $request->user()->tenant_id, ...$data]);
|
$center = CostCenter::query()->create(['tenant_id' => $this->staffIdentity($request)->tenant_id, ...$data]);
|
||||||
$workflow->audit($request->user(), 'cost_center.created', null, null, $center->toArray());
|
$workflow->audit($this->staffIdentity($request), 'cost_center.created', null, null, $center->toArray());
|
||||||
});
|
});
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
@@ -93,17 +104,17 @@ class CompanyController extends Controller
|
|||||||
public function user(Request $request, RequisitionWorkflow $workflow): RedirectResponse
|
public function user(Request $request, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$this->admin($request);
|
$this->admin($request);
|
||||||
abort_if(app(OrganizationAccess::class)->active($request->user()->tenant_id), 409, 'Crie utilizadores e atribua perfis na parametrização.');
|
abort_if(app(OrganizationAccess::class)->active($this->staffIdentity($request)->tenant_id), 409, 'Crie utilizadores e atribua perfis na parametrização.');
|
||||||
$data = $request->validate([
|
$data = $request->validate([
|
||||||
'name' => 'required|string|max:100', 'email' => 'required|email|max:255|unique:users',
|
'name' => 'required|string|max:100', 'email' => 'required|email|max:255|unique:users',
|
||||||
'password' => 'required|string|min:12|confirmed',
|
'password' => 'required|string|min:12|confirmed',
|
||||||
'department_id' => ['required', Rule::exists('departments', 'id')->where('tenant_id', $request->user()->tenant_id)],
|
'department_id' => ['required', Rule::exists('departments', 'id')->where('tenant_id', $this->staffIdentity($request)->tenant_id)],
|
||||||
'purchasing_role' => ['required', Rule::enum(PurchasingRole::class)],
|
'purchasing_role' => ['required', Rule::enum(PurchasingRole::class)],
|
||||||
]);
|
]);
|
||||||
DB::transaction(function () use ($request, $data, $workflow) {
|
DB::transaction(function () use ($request, $data, $workflow) {
|
||||||
$user = new User;
|
$user = new User;
|
||||||
$user->forceFill($data + ['tenant_id' => $request->user()->tenant_id])->save();
|
$user->forceFill($data + ['tenant_id' => $this->staffIdentity($request)->tenant_id])->save();
|
||||||
$workflow->audit($request->user(), 'user.created', null, null, $user->only(['id', 'name', 'email', 'department_id', 'purchasing_role']));
|
$workflow->audit($this->staffIdentity($request), 'user.created', null, null, $user->only(['id', 'name', 'email', 'department_id', 'purchasing_role']));
|
||||||
});
|
});
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
@@ -111,6 +122,6 @@ class CompanyController extends Controller
|
|||||||
|
|
||||||
private function admin(Request $request): void
|
private function admin(Request $request): void
|
||||||
{
|
{
|
||||||
app(OrganizationConfiguration::class)->administrator($request->user());
|
app(OrganizationConfiguration::class)->administrator($this->staffIdentity($request));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,11 @@
|
|||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\ConflictDeclaration;
|
use App\Models\ConflictDeclaration;
|
||||||
|
use App\Models\ConflictRelease;
|
||||||
use App\Models\Requisition;
|
use App\Models\Requisition;
|
||||||
use App\Models\Supplier;
|
use App\Models\Supplier;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
|
use App\Services\ConflictReleases;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -13,45 +15,55 @@ use Illuminate\Support\Facades\DB;
|
|||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class ConflictDeclarationController extends Controller
|
class ConflictDeclarationController extends Controller
|
||||||
{
|
{
|
||||||
public function index(Request $request): Response
|
public function index(Request $request): Response
|
||||||
{
|
{
|
||||||
return Inertia::render('conflicts/index', [
|
Inertia::encryptHistory();
|
||||||
'declarations' => ConflictDeclaration::query()->visibleTo($request->user())
|
$declarations = ConflictDeclaration::query()->visibleTo($this->staffIdentity($request))
|
||||||
->with(['author:id,name', 'supplier:id,name', 'requisition:id,number', 'successor:id,previous_id'])
|
->with(['author:id,name', 'supplier:id,name', 'requisition:id,number', 'successor:id,previous_id'])
|
||||||
->latest('id')->paginate(15),
|
->latest('id')->paginate(15);
|
||||||
|
$roots = $declarations->getCollection()->map(fn (ConflictDeclaration $row) => $row->root_id ?? $row->id)->unique();
|
||||||
|
$releasedRoots = app(ConflictReleases::class)->ready()
|
||||||
|
? ConflictRelease::query()->whereIn('root_id', $roots)->orderBy('root_id')->pluck('root_id')->map(fn ($id) => (int) $id)->all()
|
||||||
|
: [];
|
||||||
|
$response = Inertia::render('conflicts/index', [
|
||||||
|
'declarations' => $declarations,
|
||||||
|
'releasedRoots' => $releasedRoots,
|
||||||
// These minimal choices allow personal declarations without granting supplier-management access.
|
// These minimal choices allow personal declarations without granting supplier-management access.
|
||||||
'suppliers' => Supplier::query()->orderBy('name')->get(['id', 'name']),
|
'suppliers' => Supplier::query()->orderBy('name')->get(['id', 'name']),
|
||||||
'requisitions' => Requisition::query()->visibleTo($request->user())->latest()->get(['id', 'number']),
|
'requisitions' => Requisition::query()->visibleTo($this->staffIdentity($request))->latest()->get(['id', 'number']),
|
||||||
]);
|
])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function store(Request $request, ConflictGuard $guard, RequisitionWorkflow $workflow): RedirectResponse
|
public function store(Request $request, ConflictGuard $guard, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate([
|
$data = $request->validate([
|
||||||
'scope' => ['required', Rule::in(['supplier', 'process', 'process_supplier'])],
|
'scope' => ['required', Rule::in(['supplier', 'process', 'process_supplier'])],
|
||||||
'supplier_id' => ['nullable', 'required_if:scope,supplier,process_supplier', 'prohibited_if:scope,process', 'integer', Rule::exists('suppliers', 'id')->where('tenant_id', $request->user()->tenant_id)],
|
'supplier_id' => ['nullable', 'required_if:scope,supplier,process_supplier', 'prohibited_if:scope,process', 'integer', Rule::exists('suppliers', 'id')->where('tenant_id', $this->staffIdentity($request)->tenant_id)],
|
||||||
'requisition_id' => ['nullable', 'required_if:scope,process,process_supplier', 'prohibited_if:scope,supplier', 'integer', Rule::exists('requisitions', 'id')->where('tenant_id', $request->user()->tenant_id)],
|
'requisition_id' => ['nullable', 'required_if:scope,process,process_supplier', 'prohibited_if:scope,supplier', 'integer', Rule::exists('requisitions', 'id')->where('tenant_id', $this->staffIdentity($request)->tenant_id)],
|
||||||
'has_conflict' => 'required|boolean', 'known_since' => 'required|date_format:Y-m-d|before_or_equal:today',
|
'has_conflict' => 'required|boolean', 'known_since' => 'required|date_format:Y-m-d|before_or_equal:today',
|
||||||
'reason' => 'required|string|min:10|max:5000',
|
'reason' => 'required|string|min:10|max:5000',
|
||||||
'user_id' => 'prohibited', 'tenant_id' => 'prohibited', 'declared_at' => 'prohibited',
|
'user_id' => 'prohibited', 'tenant_id' => 'prohibited', 'declared_at' => 'prohibited',
|
||||||
'root_id' => 'prohibited', 'previous_id' => 'prohibited',
|
'root_id' => 'prohibited', 'previous_id' => 'prohibited',
|
||||||
]);
|
]);
|
||||||
DB::transaction(function () use ($request, $guard, $workflow, $data) {
|
DB::transaction(function () use ($request, $guard, $workflow, $data) {
|
||||||
$guard->lockCompany($request->user());
|
$guard->lockCompany($this->staffIdentity($request));
|
||||||
if (! empty($data['requisition_id'])) {
|
if (! empty($data['requisition_id'])) {
|
||||||
Requisition::query()->visibleTo($request->user())->findOrFail($data['requisition_id']);
|
Requisition::query()->visibleTo($this->staffIdentity($request))->findOrFail($data['requisition_id']);
|
||||||
}
|
}
|
||||||
$declaration = ConflictDeclaration::query()->create([
|
$declaration = ConflictDeclaration::query()->create([
|
||||||
'tenant_id' => $request->user()->tenant_id, 'user_id' => $request->user()->id,
|
'tenant_id' => $this->staffIdentity($request)->tenant_id, 'user_id' => $this->staffIdentity($request)->id,
|
||||||
'supplier_id' => $data['supplier_id'] ?? null, 'requisition_id' => $data['requisition_id'] ?? null,
|
'supplier_id' => $data['supplier_id'] ?? null, 'requisition_id' => $data['requisition_id'] ?? null,
|
||||||
'has_conflict' => $data['has_conflict'], 'known_since' => $data['known_since'],
|
'has_conflict' => $data['has_conflict'], 'known_since' => $data['known_since'],
|
||||||
'reason' => $data['reason'], 'declared_at' => now(),
|
'reason' => $data['reason'], 'declared_at' => now(),
|
||||||
]);
|
]);
|
||||||
$workflow->audit($request->user(), 'conflict.declared', null, null, $declaration->toArray());
|
$workflow->audit($this->staffIdentity($request), 'conflict.declared', null, null, $declaration->toArray());
|
||||||
});
|
});
|
||||||
|
|
||||||
return to_route('conflicts.index');
|
return to_route('conflicts.index');
|
||||||
@@ -59,18 +71,33 @@ class ConflictDeclarationController extends Controller
|
|||||||
|
|
||||||
public function show(Request $request, ConflictDeclaration $declaration): Response
|
public function show(Request $request, ConflictDeclaration $declaration): Response
|
||||||
{
|
{
|
||||||
ConflictDeclaration::query()->visibleTo($request->user())->findOrFail($declaration->id);
|
ConflictDeclaration::query()->visibleTo($this->staffIdentity($request))->findOrFail($declaration->id);
|
||||||
$rootId = $declaration->root_id ?? $declaration->id;
|
$rootId = $declaration->root_id ?? $declaration->id;
|
||||||
$history = ConflictDeclaration::query()->where(fn ($query) => $query->whereKey($rootId)->orWhere('root_id', $rootId))
|
$history = ConflictDeclaration::query()->where(fn ($query) => $query->whereKey($rootId)->orWhere('root_id', $rootId))
|
||||||
->with(['author:id,name', 'supplier:id,name', 'requisition:id,number'])->orderBy('id')->get();
|
->with(['author:id,name', 'supplier:id,name', 'requisition:id,number'])->orderBy('id')->get();
|
||||||
$latest = $history->last();
|
$latest = $history->last();
|
||||||
|
|
||||||
return Inertia::render('conflicts/show', ['history' => $history, 'canCorrect' => $latest?->user_id === $request->user()->id]);
|
Inertia::encryptHistory();
|
||||||
|
$releases = app(ConflictReleases::class);
|
||||||
|
$release = $releases->ready() ? ConflictRelease::query()->where('root_id', $rootId)->first() : null;
|
||||||
|
$response = Inertia::render('conflicts/show', ['history' => $history, 'canCorrect' => $latest?->user_id === $this->staffIdentity($request)->id,
|
||||||
|
'release' => $release, 'canAuthoriseRelease' => $release === null && $latest?->has_conflict === true && $releases->canAuthorise($this->staffIdentity($request)),
|
||||||
|
])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function authoriseRelease(Request $request, ConflictDeclaration $declaration, ConflictReleases $releases): RedirectResponse
|
||||||
|
{
|
||||||
|
$releases->authorise($this->staffIdentity($request), $declaration, $request->only(['operation_key', 'reason']));
|
||||||
|
|
||||||
|
return to_route('conflicts.show', $declaration);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function update(Request $request, ConflictDeclaration $declaration, ConflictGuard $guard, RequisitionWorkflow $workflow): RedirectResponse
|
public function update(Request $request, ConflictDeclaration $declaration, ConflictGuard $guard, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless($declaration->user_id === $request->user()->id, 403);
|
abort_unless($declaration->user_id === $this->staffIdentity($request)->id, 403);
|
||||||
$data = $request->validate([
|
$data = $request->validate([
|
||||||
'known_since' => 'required|date_format:Y-m-d|before_or_equal:today', 'reason' => 'required|string|min:10|max:5000',
|
'known_since' => 'required|date_format:Y-m-d|before_or_equal:today', 'reason' => 'required|string|min:10|max:5000',
|
||||||
'has_conflict' => 'prohibited', 'supplier_id' => 'prohibited', 'requisition_id' => 'prohibited',
|
'has_conflict' => 'prohibited', 'supplier_id' => 'prohibited', 'requisition_id' => 'prohibited',
|
||||||
@@ -78,7 +105,7 @@ class ConflictDeclarationController extends Controller
|
|||||||
'root_id' => 'prohibited', 'previous_id' => 'prohibited',
|
'root_id' => 'prohibited', 'previous_id' => 'prohibited',
|
||||||
]);
|
]);
|
||||||
DB::transaction(function () use ($request, $guard, $workflow, $declaration, $data) {
|
DB::transaction(function () use ($request, $guard, $workflow, $declaration, $data) {
|
||||||
$guard->lockCompany($request->user());
|
$guard->lockCompany($this->staffIdentity($request));
|
||||||
$declaration = ConflictDeclaration::query()->lockForUpdate()->findOrFail($declaration->id);
|
$declaration = ConflictDeclaration::query()->lockForUpdate()->findOrFail($declaration->id);
|
||||||
if ($declaration->successor()->exists()) {
|
if ($declaration->successor()->exists()) {
|
||||||
throw ValidationException::withMessages(['history' => 'Já existe uma correcção mais recente. Reabra o histórico antes de corrigir.']);
|
throw ValidationException::withMessages(['history' => 'Já existe uma correcção mais recente. Reabra o histórico antes de corrigir.']);
|
||||||
@@ -87,7 +114,7 @@ class ConflictDeclarationController extends Controller
|
|||||||
...$declaration->only(['tenant_id', 'user_id', 'supplier_id', 'requisition_id', 'has_conflict']),
|
...$declaration->only(['tenant_id', 'user_id', 'supplier_id', 'requisition_id', 'has_conflict']),
|
||||||
...$data, 'declared_at' => now(), 'root_id' => $declaration->root_id ?? $declaration->id, 'previous_id' => $declaration->id,
|
...$data, 'declared_at' => now(), 'root_id' => $declaration->root_id ?? $declaration->id, 'previous_id' => $declaration->id,
|
||||||
]);
|
]);
|
||||||
$workflow->audit($request->user(), 'conflict.corrected', null, $declaration->toArray(), $revision->toArray());
|
$workflow->audit($this->staffIdentity($request), 'conflict.corrected', null, $declaration->toArray(), $revision->toArray());
|
||||||
});
|
});
|
||||||
|
|
||||||
return to_route('conflicts.show', $declaration);
|
return to_route('conflicts.show', $declaration);
|
||||||
|
|||||||
@@ -2,7 +2,17 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
abstract class Controller
|
abstract class Controller
|
||||||
{
|
{
|
||||||
//
|
/** Staff endpoints use the web identity; candidate accounts have their own realm. */
|
||||||
|
protected function staffIdentity(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,22 +7,30 @@ use App\Models\PurchaseAward;
|
|||||||
use App\Models\QualificationAssessment;
|
use App\Models\QualificationAssessment;
|
||||||
use App\Models\QualificationSet;
|
use App\Models\QualificationSet;
|
||||||
use App\Models\Requisition;
|
use App\Models\Requisition;
|
||||||
use App\Services\ConflictGuard;
|
use App\Models\User;
|
||||||
use App\Services\DocumentaryQualificationWorkflow;
|
use App\Services\DocumentaryQualificationWorkflow;
|
||||||
use App\Services\ProposalComparison;
|
|
||||||
use App\Services\ProposalOpeningWorkflow;
|
use App\Services\ProposalOpeningWorkflow;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class DocumentaryQualificationController extends Controller
|
class DocumentaryQualificationController extends Controller
|
||||||
{
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
private function access(Request $request, int $id): Requisition
|
private function access(Request $request, int $id): Requisition
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
abort_unless($this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||||
|
|
||||||
return Requisition::query()->visibleTo($request->user())->findOrFail($id);
|
return Requisition::query()->visibleTo($this->actor($request))->findOrFail($id);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Request $request, Requisition $requisition, ProposalOpeningWorkflow $opening): Response
|
public function show(Request $request, Requisition $requisition, ProposalOpeningWorkflow $opening): Response
|
||||||
@@ -32,11 +40,13 @@ class DocumentaryQualificationController extends Controller
|
|||||||
$sets = QualificationSet::query()->where('requisition_id', $requisition->id)->latest('revision')->get(['id', 'revision', 'reason', 'created_at']);
|
$sets = QualificationSet::query()->where('requisition_id', $requisition->id)->latest('revision')->get(['id', 'revision', 'reason', 'created_at']);
|
||||||
$latest = $sets->first() ? QualificationSet::query()->findOrFail($sets->first()->id) : null;
|
$latest = $sets->first() ? QualificationSet::query()->findOrFail($sets->first()->id) : null;
|
||||||
$selected = isset($filters['version']) ? QualificationSet::query()->where('requisition_id', $requisition->id)->findOrFail((int) $filters['version']) : $latest;
|
$selected = isset($filters['version']) ? QualificationSet::query()->where('requisition_id', $requisition->id)->findOrFail((int) $filters['version']) : $latest;
|
||||||
|
$focusInput = $request->validate(['quotation_id' => ['nullable', 'integer', 'min:1', Rule::exists('quotations', 'id')->where('tenant_id', $requisition->tenant_id)->where('requisition_id', $requisition->id), Rule::in(array_column($selected->snapshot['proposals'] ?? [], 'id'))]]);
|
||||||
|
$focus = isset($focusInput['quotation_id']) ? (int) $focusInput['quotation_id'] : null;
|
||||||
$proposals = $opening->proposals($requisition);
|
$proposals = $opening->proposals($requisition);
|
||||||
$basis = $opening->basis($proposals);
|
$basis = $opening->basis($proposals);
|
||||||
$current = $selected && $selected->id === $latest?->id && $selected->basis_hash === $basis;
|
$workflow = app(DocumentaryQualificationWorkflow::class);
|
||||||
|
$current = $selected !== null && $workflow->currentSet($requisition, $selected);
|
||||||
$closed = $requisition->status !== 'approved' || PurchaseAward::query()->where('requisition_id', $requisition->id)->exists();
|
$closed = $requisition->status !== 'approved' || PurchaseAward::query()->where('requisition_id', $requisition->id)->exists();
|
||||||
$open = ! $closed && ! app(ConflictGuard::class)->participationBlocked($request->user(), $requisition);
|
|
||||||
$query = QualificationAssessment::query()->where('qualification_set_id', $selected->id ?? 0);
|
$query = QualificationAssessment::query()->where('qualification_set_id', $selected->id ?? 0);
|
||||||
$recordIds = (clone $query)->selectRaw('MAX(id)')->groupBy('quotation_id', 'analyst_id');
|
$recordIds = (clone $query)->selectRaw('MAX(id)')->groupBy('quotation_id', 'analyst_id');
|
||||||
$records = QualificationAssessment::query()->whereIn('id', $recordIds)->orderBy('quotation_id')->orderBy('analyst_id')->get();
|
$records = QualificationAssessment::query()->whereIn('id', $recordIds)->orderBy('quotation_id')->orderBy('analyst_id')->get();
|
||||||
@@ -46,9 +56,10 @@ class DocumentaryQualificationController extends Controller
|
|||||||
'latestId' => $latest->id ?? 0, 'latestCriteria' => $latest->criteria ?? [], 'basisHash' => $basis, 'isCurrent' => (bool) $current,
|
'latestId' => $latest->id ?? 0, 'latestCriteria' => $latest->criteria ?? [], 'basisHash' => $basis, 'isCurrent' => (bool) $current,
|
||||||
'proposals' => $proposals,
|
'proposals' => $proposals,
|
||||||
'closedForChanges' => $closed,
|
'closedForChanges' => $closed,
|
||||||
'records' => $records, 'history' => $query->latest('id')->paginate(20)->withQueryString(), 'actorId' => $request->user()->id,
|
'records' => $records, 'history' => $query->latest('id')->paginate(20)->withQueryString(), 'actorId' => $this->actor($request)->id,
|
||||||
'canDefine' => $open && $proposals !== [] && $request->user()->hasFunctions([PurchasingRole::Procurement]),
|
'focusQuotationId' => $focus,
|
||||||
'canAssess' => $open && $current && $request->user()->id !== $requisition->requester_id && app(ProposalComparison::class)->eligibleRole($request->user(), $requisition),
|
'canDefine' => $workflow->canDefine($this->actor($request), $requisition),
|
||||||
|
'canAssess' => $selected !== null && $workflow->canAssess($this->actor($request), $requisition, $selected),
|
||||||
])->toResponse($request);
|
])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
@@ -64,7 +75,7 @@ class DocumentaryQualificationController extends Controller
|
|||||||
'criteria.*.label' => 'required|string|min:3|max:500', 'criteria.*.category' => 'required|in:legal,financial,fiscal,technical,administrative', 'criteria.*.required' => 'required|boolean',
|
'criteria.*.label' => 'required|string|min:3|max:500', 'criteria.*.category' => 'required|in:legal,financial,fiscal,technical,administrative', 'criteria.*.required' => 'required|boolean',
|
||||||
'snapshot' => 'prohibited', 'tenant_id' => 'prohibited', 'created_by' => 'prohibited',
|
'snapshot' => 'prohibited', 'tenant_id' => 'prohibited', 'created_by' => 'prohibited',
|
||||||
]);
|
]);
|
||||||
$workflow->define($request->user(), $requisition, $data);
|
$workflow->define($this->actor($request), $requisition, $data);
|
||||||
|
|
||||||
return to_route('qualifications.show', $requisition);
|
return to_route('qualifications.show', $requisition);
|
||||||
}
|
}
|
||||||
@@ -80,7 +91,7 @@ class DocumentaryQualificationController extends Controller
|
|||||||
'snapshot' => 'prohibited', 'analyst_id' => 'prohibited', 'tenant_id' => 'prohibited', 'revision' => 'prohibited',
|
'snapshot' => 'prohibited', 'analyst_id' => 'prohibited', 'tenant_id' => 'prohibited', 'revision' => 'prohibited',
|
||||||
]);
|
]);
|
||||||
$data['answers'] = array_map(fn ($answer) => [...$answer, 'criterion_id' => (int) $answer['criterion_id']], $data['answers']);
|
$data['answers'] = array_map(fn ($answer) => [...$answer, 'criterion_id' => (int) $answer['criterion_id']], $data['answers']);
|
||||||
$workflow->assess($request->user(), $set, $data);
|
$workflow->assess($this->actor($request), $set, $data);
|
||||||
|
|
||||||
return to_route('qualifications.show', $set->requisition_id);
|
return to_route('qualifications.show', $set->requisition_id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,11 +7,18 @@ use App\Models\CriticalityLevel;
|
|||||||
use App\Models\Department;
|
use App\Models\Department;
|
||||||
use App\Models\Equipment;
|
use App\Models\Equipment;
|
||||||
use App\Models\EquipmentSparePart;
|
use App\Models\EquipmentSparePart;
|
||||||
|
use App\Models\Requisition;
|
||||||
use App\Models\SparePart;
|
use App\Models\SparePart;
|
||||||
use App\Models\StockItem;
|
use App\Models\StockItem;
|
||||||
use App\Models\StockMovement;
|
use App\Models\StockMovement;
|
||||||
use App\Models\StockOperation;
|
use App\Models\StockOperation;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\AdministrativeGeography;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
|
use App\Services\CurrentActor;
|
||||||
|
use App\Services\EquipmentWarehouseRequests;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
use App\Services\ReceiptWorkflow;
|
use App\Services\ReceiptWorkflow;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
@@ -22,21 +29,71 @@ use Illuminate\Support\Str;
|
|||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class EquipmentController extends Controller
|
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): 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']),
|
||||||
|
'capitalReference' => app(CapitalRegister::class)->referenceForEquipment($actor, $asset),
|
||||||
|
'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
|
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();
|
$assets = Equipment::query();
|
||||||
if ($request->user()->departmentScoped()) {
|
if (! empty($filters['location'])) {
|
||||||
$assets->where('department_id', $request->user()->department_id);
|
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();
|
$equipment = $assets->orderBy('code')->get();
|
||||||
$links = EquipmentSparePart::query()->whereIn('equipment_id', $equipment->pluck('id'))->get();
|
$links = EquipmentSparePart::query()->whereIn('equipment_id', $equipment->pluck('id'))->get();
|
||||||
$parts = SparePart::query();
|
$parts = SparePart::query();
|
||||||
if ($request->user()->departmentScoped()) {
|
if ($this->actor($request)->departmentScoped() || ! empty($filters['location'])) {
|
||||||
$parts->whereIn('id', $links->pluck('spare_part_id'));
|
$parts->whereIn('id', $links->pluck('spare_part_id'));
|
||||||
}
|
}
|
||||||
$parts = $parts->get()->map(function (SparePart $part) {
|
$parts = $parts->get()->map(function (SparePart $part) {
|
||||||
@@ -47,24 +104,33 @@ class EquipmentController extends Controller
|
|||||||
});
|
});
|
||||||
$items = StockItem::query();
|
$items = StockItem::query();
|
||||||
$departments = Department::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()));
|
$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', [
|
Inertia::encryptHistory();
|
||||||
|
$response = 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(),
|
'equipment' => $equipment, 'parts' => $parts, 'links' => $links, 'levels' => CriticalityLevel::query()->orderBy('code')->get(),
|
||||||
'items' => $items->orderBy('code')->get(['id', 'code', 'name', 'unit']),
|
'items' => $items->orderBy('code')->get(['id', 'code', 'name', 'unit']),
|
||||||
'departments' => $departments->orderBy('name')->get(['id', 'name']),
|
'departments' => $departments->orderBy('name')->get(['id', 'name']),
|
||||||
'history' => StockOperation::query()->whereNotNull('equipment_id')->whereIn('equipment_id', $equipment->pluck('id'))->latest('id')->paginate(15),
|
'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]),
|
'canManage' => $this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]),
|
||||||
'canConfigure' => $request->user()->hasFunctions([PurchasingRole::Admin]),
|
'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
|
||||||
]);
|
'canConfigure' => $this->actor($request)->hasFunctions([PurchasingRole::Admin]),
|
||||||
|
])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function store(Request $request, string $kind): RedirectResponse
|
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(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);
|
abort_unless($kind === 'categorias' ? $user->hasFunctions([PurchasingRole::Admin]) : $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]), 403);
|
||||||
$tenant = $user->tenant_id;
|
$tenant = $user->tenant_id;
|
||||||
@@ -76,9 +142,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})?$/']],
|
'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')]],
|
'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);
|
$data = $request->validate($rules);
|
||||||
DB::transaction(function () use ($data, $kind, $user) {
|
DB::transaction(function () use ($data, $kind, $user) {
|
||||||
app(ConflictGuard::class)->lockCompany($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) {
|
$model = match ($kind) {
|
||||||
'categorias' => new CriticalityLevel,'activos' => new Equipment,'pecas' => new SparePart,'associacoes' => new EquipmentSparePart
|
'categorias' => new CriticalityLevel,'activos' => new Equipment,'pecas' => new SparePart,'associacoes' => new EquipmentSparePart
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\ExternalPayment;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ExpenseAllocations;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class ExpenseAllocationController extends Controller
|
||||||
|
{
|
||||||
|
public function commonShow(Request $request, int $allocation, ExpenseAllocations $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('payments/expense-allocation', $service->workspace($actor, $allocation, 'common_allocation'))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function commonStore(Request $request, int $allocation, ExpenseAllocations $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $allocation, $request->all(), 'common_allocation');
|
||||||
|
|
||||||
|
return back()->with('success', 'Imputação da despesa por categoria preservada.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(Request $request, ExternalPayment $payment, ExpenseAllocations $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('payments/expense-allocation', $service->workspace($actor, $payment->id))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, ExternalPayment $payment, ExpenseAllocations $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $payment->id, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Imputação da despesa por categoria preservada.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,13 +5,19 @@ namespace App\Http\Controllers;
|
|||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\ExternalPayment;
|
use App\Models\ExternalPayment;
|
||||||
use App\Models\Invoice;
|
use App\Models\Invoice;
|
||||||
|
use App\Models\PurchaseOrder;
|
||||||
use App\Models\Supplier;
|
use App\Models\Supplier;
|
||||||
use App\Models\SupplierBankDetail;
|
use App\Models\SupplierBankDetail;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ExpenseAllocations;
|
||||||
use App\Services\ExternalPaymentWorkflow;
|
use App\Services\ExternalPaymentWorkflow;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
use App\Services\SupplierBankWorkflow;
|
use App\Services\SupplierBankWorkflow;
|
||||||
|
use App\Services\SupplierPayables;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
@@ -19,20 +25,36 @@ class ExternalPaymentController extends Controller
|
|||||||
{
|
{
|
||||||
public function index(Request $request, ExternalPaymentWorkflow $workflow): Response
|
public function index(Request $request, ExternalPaymentWorkflow $workflow): Response
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
$actor = $request->user('web');
|
||||||
$canManage = $request->user()->hasFunctions([PurchasingRole::Finance]);
|
abort_unless($actor instanceof User, 403);
|
||||||
$payments = ExternalPayment::query()->latest('id')->paginate(15)->through(fn ($payment) => [...$payment->toArray(), 'external_reference' => $canManage ? $payment->external_reference : null, 'evidence_reference' => $canManage ? $payment->evidence_reference : null]);
|
abort_unless($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
||||||
|
$filter = $request->validate(['payment_id' => ['nullable', 'integer', 'min:1', Rule::exists('external_payments', 'id')->where('tenant_id', $actor->tenant_id)], 'invoice_id' => ['nullable', 'integer', 'min:1', Rule::exists('invoices', 'id')->where('tenant_id', $actor->tenant_id)]]);
|
||||||
|
$focus = isset($filter['payment_id']) ? (int) $filter['payment_id'] : null;
|
||||||
|
$focusInvoice = isset($filter['invoice_id']) ? (int) $filter['invoice_id'] : null;
|
||||||
|
$canManage = $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor);
|
||||||
|
$visibleInvoices = Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'));
|
||||||
|
$payments = ExternalPayment::query()->whereIn('invoice_id', (clone $visibleInvoices)->select('id'))->when($focus !== null, fn ($q) => $q->whereKey($focus))->when($focusInvoice !== null, fn ($q) => $q->where('invoice_id', $focusInvoice))->latest('id')->paginate(15)->withQueryString()
|
||||||
|
->through(fn (ExternalPayment $payment) => [...$payment->toArray(), 'canReview' => $workflow->reviewerEligible($actor, $payment), 'external_reference' => $canManage ? $payment->external_reference : null, 'evidence_reference' => $canManage ? $payment->evidence_reference : null]);
|
||||||
if ($canManage && $payments->count() > 0) {
|
if ($canManage && $payments->count() > 0) {
|
||||||
app(RequisitionWorkflow::class)->audit($request->user(), 'payment.viewed', null, null, ['payment_ids' => $payments->pluck('id')->all()]);
|
app(RequisitionWorkflow::class)->audit($actor, 'payment.viewed', null, null, ['payment_ids' => $payments->pluck('id')->all()]);
|
||||||
}
|
}
|
||||||
$invoices = Invoice::query()->where('status', 'validated')->latest('id')->get()->map(function (Invoice $invoice) use ($workflow) {
|
$invoices = $visibleInvoices->where('status', 'validated')->when($focus !== null, fn ($q) => $q->whereIn('id', $payments->pluck('invoice_id')))->when($focusInvoice !== null, fn ($q) => $q->whereKey($focusInvoice))->latest('id')->get()->map(function (Invoice $invoice) use ($workflow, $canManage) {
|
||||||
$supplier = Supplier::query()->findOrFail($invoice->supplier_id);
|
$supplier = Supplier::query()->findOrFail($invoice->supplier_id);
|
||||||
$bank = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->first();
|
$bankWorkflow = app(SupplierBankWorkflow::class);
|
||||||
|
$currency = $invoice->snapshot['currency'] ?? 'MZN';
|
||||||
|
$banks = $bankWorkflow->currentAccounts($supplier)->where('currency', $currency)->map(fn (SupplierBankDetail $bank) => [
|
||||||
|
'id' => $bank->id, 'revision' => $bank->revision, 'currency' => $bank->currency, 'label' => $bank->bank_name.' · '.$bank->currency.' · v'.$bank->revision,
|
||||||
|
'state' => $bankWorkflow->state($supplier, $bank->account_key),
|
||||||
|
])->values();
|
||||||
|
$approved = $banks->where('state', 'approved');
|
||||||
|
$bank = $approved->count() === 1 ? $approved->first() : null;
|
||||||
|
|
||||||
return ['id' => $invoice->id, 'number' => $invoice->number, 'supplier_id' => $supplier->id, 'supplier_name' => $supplier->name, 'total_minor' => $invoice->total_minor, 'outstanding_minor' => $workflow->outstanding($invoice), 'bank_id' => $bank->id ?? 0, 'bank_revision' => $bank->revision ?? 0, 'bank_state' => app(SupplierBankWorkflow::class)->state($supplier)];
|
return ['id' => $invoice->id, 'number' => $invoice->number, 'currency' => $currency, 'supplier_id' => $supplier->id, 'supplier_name' => $supplier->name, 'total_minor' => $invoice->total_minor, 'outstanding_minor' => $workflow->outstanding($invoice),
|
||||||
|
'bank_id' => $bank['id'] ?? 0, 'bank_revision' => $bank['revision'] ?? 0, 'bank_state' => $approved->isNotEmpty() ? 'approved' : ($banks->first()['state'] ?? 'missing'), 'banks' => $canManage ? $banks->all() : []];
|
||||||
});
|
});
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('payments/index', ['invoices' => $invoices, 'payments' => $payments, 'canManage' => $canManage])->toResponse($request);
|
$response = Inertia::render('payments/index', ['focusPaymentId' => $focus, 'focusInvoiceId' => $focusInvoice, 'invoices' => $invoices, 'payments' => $payments, 'canManage' => $canManage,
|
||||||
|
'expenseAllocationsReady' => app(ExpenseAllocations::class)->ready() && app(SupplierPayables::class)->can($actor, 'view')])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
return $response;
|
return $response;
|
||||||
@@ -40,17 +62,20 @@ class ExternalPaymentController extends Controller
|
|||||||
|
|
||||||
public function store(Request $request, Invoice $invoice, ExternalPaymentWorkflow $workflow): RedirectResponse
|
public function store(Request $request, Invoice $invoice, ExternalPaymentWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Finance]), 403);
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Finance]), 403);
|
||||||
$data = $request->validate(['supplier_bank_detail_id' => 'required|integer|min:1', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'paid_on' => 'required|date_format:Y-m-d', 'external_reference' => 'required|string|max:150', 'evidence_reference' => 'required|string|max:1000']);
|
$data = $request->validate(['supplier_bank_detail_id' => 'required|integer|min:1', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'paid_on' => 'required|date_format:Y-m-d', 'external_reference' => 'required|string|max:150', 'evidence_reference' => 'required|string|max:1000']);
|
||||||
$workflow->register($request->user(), $invoice, $data);
|
$workflow->register($actor, $invoice, $data);
|
||||||
|
|
||||||
return to_route('payments.index');
|
return to_route('payments.index');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function review(Request $request, ExternalPayment $payment, ExternalPaymentWorkflow $workflow): RedirectResponse
|
public function review(Request $request, ExternalPayment $payment, ExternalPaymentWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
$data = $request->validate(['decision' => 'required|in:confirmed,rejected', 'reason' => 'required|string|max:2000', 'independently_verified' => 'accepted']);
|
$data = $request->validate(['decision' => 'required|in:confirmed,rejected', 'reason' => 'required|string|max:2000', 'independently_verified' => 'accepted']);
|
||||||
$workflow->review($request->user(), $payment, $data['decision'], $data['reason']);
|
$workflow->review($actor, $payment, $data['decision'], $data['reason']);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,26 +9,35 @@ use App\Models\AdmissionPolicy;
|
|||||||
use App\Models\AdmissionReview;
|
use App\Models\AdmissionReview;
|
||||||
use App\Models\PurchaseAward;
|
use App\Models\PurchaseAward;
|
||||||
use App\Models\Requisition;
|
use App\Models\Requisition;
|
||||||
use App\Services\ConflictGuard;
|
use App\Models\User;
|
||||||
use App\Services\FormalAdmission;
|
use App\Services\FormalAdmission;
|
||||||
use App\Services\ProposalOpeningWorkflow;
|
use App\Services\ProposalOpeningWorkflow;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class FormalAdmissionController extends Controller
|
class FormalAdmissionController extends Controller
|
||||||
{
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
private function access(Request $request, int $id): Requisition
|
private function access(Request $request, int $id): Requisition
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
abort_unless($this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||||
|
|
||||||
return Requisition::query()->visibleTo($request->user())->findOrFail($id);
|
return Requisition::query()->visibleTo($this->actor($request))->findOrFail($id);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function policy(Request $request): Response
|
public function policy(Request $request): Response
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin]), 403);
|
abort_unless($this->actor($request)->hasFunctions([PurchasingRole::Admin]), 403);
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('purchases/admission-policy', ['policies' => AdmissionPolicy::query()->latest('revision')->paginate(20)->withQueryString(), 'latest' => AdmissionPolicy::query()->latest('revision')->first()])->toResponse($request);
|
$response = Inertia::render('purchases/admission-policy', ['policies' => AdmissionPolicy::query()->latest('revision')->paginate(20)->withQueryString(), 'latest' => AdmissionPolicy::query()->latest('revision')->first()])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
@@ -40,7 +49,7 @@ class FormalAdmissionController extends Controller
|
|||||||
{
|
{
|
||||||
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'enabled' => 'required|boolean', 'roles' => 'required|array|min:1|max:2', 'roles.*' => 'required|distinct|in:finance,department_head', 'required_count' => 'required|integer|min:1|max:50', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'created_by' => 'prohibited', 'snapshot' => 'prohibited']);
|
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'enabled' => 'required|boolean', 'roles' => 'required|array|min:1|max:2', 'roles.*' => 'required|distinct|in:finance,department_head', 'required_count' => 'required|integer|min:1|max:50', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'created_by' => 'prohibited', 'snapshot' => 'prohibited']);
|
||||||
$data['enabled'] = (bool) $data['enabled'];
|
$data['enabled'] = (bool) $data['enabled'];
|
||||||
$workflow->policy($request->user(), $data);
|
$workflow->policy($this->actor($request), $data);
|
||||||
|
|
||||||
return to_route('admissions.policy');
|
return to_route('admissions.policy');
|
||||||
}
|
}
|
||||||
@@ -51,27 +60,27 @@ class FormalAdmissionController extends Controller
|
|||||||
$filter = $request->validate(['version' => 'nullable|integer|min:1']);
|
$filter = $request->validate(['version' => 'nullable|integer|min:1']);
|
||||||
$adoption = $workflow->adoption($requisition);
|
$adoption = $workflow->adoption($requisition);
|
||||||
$selected = isset($filter['version']) ? AdmissionAdoption::query()->where('requisition_id', $requisition->id)->findOrFail((int) $filter['version']) : $adoption;
|
$selected = isset($filter['version']) ? AdmissionAdoption::query()->where('requisition_id', $requisition->id)->findOrFail((int) $filter['version']) : $adoption;
|
||||||
|
$focusInput = $request->validate(['decision_id' => ['nullable', 'integer', 'min:1', Rule::exists('admission_decisions', 'id')->where('tenant_id', $requisition->tenant_id)->where('admission_adoption_id', $selected->id ?? 0)]]);
|
||||||
|
$focus = isset($focusInput['decision_id']) ? (int) $focusInput['decision_id'] : null;
|
||||||
$current = $selected && $selected->id === $adoption?->id;
|
$current = $selected && $selected->id === $adoption?->id;
|
||||||
$closed = $requisition->status !== 'approved' || PurchaseAward::query()->where('requisition_id', $requisition->id)->exists();
|
$closed = $requisition->status !== 'approved' || PurchaseAward::query()->where('requisition_id', $requisition->id)->exists();
|
||||||
$open = ! $closed && ! app(ConflictGuard::class)->participationBlocked($request->user(), $requisition);
|
$open = $workflow->canParticipate($this->actor($request), $requisition);
|
||||||
$decisions = AdmissionDecision::query()->where('admission_adoption_id', $selected->id ?? 0)->latest('id')->get();
|
$decisions = AdmissionDecision::query()->where('admission_adoption_id', $selected->id ?? 0)->latest('id')->get();
|
||||||
$latestIds = $decisions->unique('quotation_id')->pluck('id');
|
|
||||||
$proposals = collect($opening->proposals($requisition))->map(function ($quote) use ($workflow, $requisition, $decisions) {
|
$proposals = collect($opening->proposals($requisition))->map(function ($quote) use ($workflow, $requisition, $decisions) {
|
||||||
$basis = $workflow->basis($requisition, $quote['id']);
|
$basis = $workflow->basis($requisition, $quote['id']);
|
||||||
|
|
||||||
return [...$quote, 'basisHash' => $basis['hash'] ?? null, 'clear' => $basis['clear'] ?? false, 'previousId' => $decisions->firstWhere('quotation_id', $quote['id'])->id ?? 0];
|
return [...$quote, 'basisHash' => $basis['hash'] ?? null, 'clear' => $basis['clear'] ?? false, 'previousId' => $decisions->firstWhere('quotation_id', $quote['id'])->id ?? 0];
|
||||||
});
|
});
|
||||||
$history = AdmissionDecision::query()->where('admission_adoption_id', $selected->id ?? 0)->latest('id')->paginate(15)->withQueryString();
|
$history = AdmissionDecision::query()->where('admission_adoption_id', $selected->id ?? 0)->when($focus !== null, fn ($query) => $query->whereKey($focus))->latest('id')->paginate(15)->withQueryString();
|
||||||
$history->through(function ($decision) use ($workflow, $selected, $current, $latestIds, $requisition, $open, $request) {
|
$history->through(function ($decision) use ($workflow, $selected, $current, $requisition, $request) {
|
||||||
$basis = $workflow->basis($requisition, $decision->quotation_id);
|
$fresh = $current && $workflow->currentReviewBasis($requisition, $selected, $decision);
|
||||||
$fresh = $current && $latestIds->contains($decision->id) && $basis && $basis['hash'] === $decision->basis_hash;
|
|
||||||
|
|
||||||
return [...$decision->toArray(), 'status' => $workflow->status($decision, $selected), 'current' => (bool) $fresh,
|
return [...$decision->toArray(), 'status' => $workflow->status($decision, $selected), 'current' => (bool) $fresh,
|
||||||
'reviews' => AdmissionReview::query()->where('admission_decision_id', $decision->id)->orderBy('id')->get(),
|
'reviews' => AdmissionReview::query()->where('admission_decision_id', $decision->id)->orderBy('id')->get(),
|
||||||
'canReview' => $open && $fresh && $workflow->status($decision, $selected) === 'pending' && $workflow->eligible($request->user(), $requisition, $selected, $decision) && ! AdmissionReview::query()->where('admission_decision_id', $decision->id)->where('reviewed_by', $request->user()->id)->exists()];
|
'canReview' => $fresh && $workflow->canReview($this->actor($request), $requisition, $decision)];
|
||||||
});
|
});
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('purchases/admission', ['requisition' => $requisition->only(['id', 'number']), 'policy' => AdmissionPolicy::query()->latest('revision')->first(), 'adoptions' => AdmissionAdoption::query()->where('requisition_id', $requisition->id)->latest('revision')->get(), 'adoption' => $adoption, 'selected' => $selected, 'proposals' => $proposals, 'history' => $history, 'canAdopt' => $open && $request->user()->hasFunctions([PurchasingRole::Procurement]), 'canPropose' => $open && $current && $request->user()->hasFunctions([PurchasingRole::Procurement]) && $request->user()->id !== $requisition->requester_id, 'closed' => $closed])->toResponse($request);
|
$response = Inertia::render('purchases/admission', ['focusDecisionId' => $focus, 'requisition' => $requisition->only(['id', 'number']), 'policy' => AdmissionPolicy::query()->latest('revision')->first(), 'adoptions' => AdmissionAdoption::query()->where('requisition_id', $requisition->id)->latest('revision')->get(), 'adoption' => $adoption, 'selected' => $selected, 'proposals' => $proposals, 'history' => $history, 'canAdopt' => $open && $this->actor($request)->hasFunctions([PurchasingRole::Procurement]), 'canPropose' => $open && $current && $this->actor($request)->hasFunctions([PurchasingRole::Procurement]) && $this->actor($request)->id !== $requisition->requester_id, 'closed' => $closed])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
return $response;
|
return $response;
|
||||||
@@ -81,7 +90,7 @@ class FormalAdmissionController extends Controller
|
|||||||
{
|
{
|
||||||
$this->access($request, $requisition->id);
|
$this->access($request, $requisition->id);
|
||||||
$data = $request->validate(['policy_id' => 'required|integer', 'previous_id' => 'required|integer|min:0', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'snapshot' => 'prohibited', 'created_by' => 'prohibited']);
|
$data = $request->validate(['policy_id' => 'required|integer', 'previous_id' => 'required|integer|min:0', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'snapshot' => 'prohibited', 'created_by' => 'prohibited']);
|
||||||
$workflow->adopt($request->user(), $requisition, (int) $data['policy_id'], (int) $data['previous_id'], $data['reason']);
|
$workflow->adopt($this->actor($request), $requisition, (int) $data['policy_id'], (int) $data['previous_id'], $data['reason']);
|
||||||
|
|
||||||
return to_route('admissions.show', $requisition);
|
return to_route('admissions.show', $requisition);
|
||||||
}
|
}
|
||||||
@@ -90,7 +99,7 @@ class FormalAdmissionController extends Controller
|
|||||||
{
|
{
|
||||||
$this->access($request, $requisition->id);
|
$this->access($request, $requisition->id);
|
||||||
$data = $request->validate(['quotation_id' => 'required|integer', 'previous_id' => 'required|integer|min:0', 'basis_hash' => 'required|string|size:64', 'outcome' => 'required|in:admit,exclude,clarify', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'created_by' => 'prohibited', 'snapshot' => 'prohibited', 'status' => 'prohibited']);
|
$data = $request->validate(['quotation_id' => 'required|integer', 'previous_id' => 'required|integer|min:0', 'basis_hash' => 'required|string|size:64', 'outcome' => 'required|in:admit,exclude,clarify', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'created_by' => 'prohibited', 'snapshot' => 'prohibited', 'status' => 'prohibited']);
|
||||||
$workflow->propose($request->user(), $requisition, $data);
|
$workflow->propose($this->actor($request), $requisition, $data);
|
||||||
|
|
||||||
return to_route('admissions.show', $requisition);
|
return to_route('admissions.show', $requisition);
|
||||||
}
|
}
|
||||||
@@ -100,7 +109,7 @@ class FormalAdmissionController extends Controller
|
|||||||
$adoption = AdmissionAdoption::query()->findOrFail($decision->admission_adoption_id);
|
$adoption = AdmissionAdoption::query()->findOrFail($decision->admission_adoption_id);
|
||||||
$this->access($request, $adoption->requisition_id);
|
$this->access($request, $adoption->requisition_id);
|
||||||
$data = $request->validate(['verdict' => 'required|in:approved,returned', 'reason' => 'required|string|min:10|max:4000', 'reviewed_by' => 'prohibited', 'snapshot' => 'prohibited', 'tenant_id' => 'prohibited']);
|
$data = $request->validate(['verdict' => 'required|in:approved,returned', 'reason' => 'required|string|min:10|max:4000', 'reviewed_by' => 'prohibited', 'snapshot' => 'prohibited', 'tenant_id' => 'prohibited']);
|
||||||
$workflow->review($request->user(), $decision, $data['verdict'], $data['reason']);
|
$workflow->review($this->actor($request), $decision, $data['verdict'], $data['reason']);
|
||||||
|
|
||||||
return to_route('admissions.show', $adoption->requisition_id);
|
return to_route('admissions.show', $adoption->requisition_id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,27 +10,35 @@ use App\Models\RecommendationPolicy;
|
|||||||
use App\Models\RecommendationReview;
|
use App\Models\RecommendationReview;
|
||||||
use App\Models\Requisition;
|
use App\Models\Requisition;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\ConflictGuard;
|
|
||||||
use App\Services\FormalAdmission;
|
use App\Services\FormalAdmission;
|
||||||
use App\Services\FormalRecommendation;
|
use App\Services\FormalRecommendation;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class FormalRecommendationController extends Controller
|
class FormalRecommendationController extends Controller
|
||||||
{
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
private function access(Request $request, int $id): Requisition
|
private function access(Request $request, int $id): Requisition
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
abort_unless($this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||||
|
|
||||||
return Requisition::query()->visibleTo($request->user())->findOrFail($id);
|
return Requisition::query()->visibleTo($this->actor($request))->findOrFail($id);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function policy(Request $request): Response
|
public function policy(Request $request): Response
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin]), 403);
|
abort_unless($this->actor($request)->hasFunctions([PurchasingRole::Admin]), 403);
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('purchases/recommendation-policy', ['policies' => RecommendationPolicy::query()->latest('revision')->paginate(20)->withQueryString(), 'latest' => RecommendationPolicy::query()->latest('revision')->first()])->toResponse($request);
|
$response = Inertia::render('purchases/recommendation-policy', ['policies' => RecommendationPolicy::query()->latest('revision')->paginate(20)->withQueryString(), 'latest' => RecommendationPolicy::query()->latest('revision')->first()])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
@@ -42,7 +50,7 @@ class FormalRecommendationController extends Controller
|
|||||||
{
|
{
|
||||||
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'enabled' => 'required|boolean', 'roles' => 'required|array|min:1|max:2', 'roles.*' => 'required|distinct|in:finance,department_head', 'required_count' => 'required|integer|min:1|max:50', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'created_by' => 'prohibited', 'snapshot' => 'prohibited']);
|
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'enabled' => 'required|boolean', 'roles' => 'required|array|min:1|max:2', 'roles.*' => 'required|distinct|in:finance,department_head', 'required_count' => 'required|integer|min:1|max:50', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'created_by' => 'prohibited', 'snapshot' => 'prohibited']);
|
||||||
$data['enabled'] = (bool) $data['enabled'];
|
$data['enabled'] = (bool) $data['enabled'];
|
||||||
$workflow->policy($request->user(), $data);
|
$workflow->policy($this->actor($request), $data);
|
||||||
|
|
||||||
return to_route('recommendations.policy');
|
return to_route('recommendations.policy');
|
||||||
}
|
}
|
||||||
@@ -53,22 +61,24 @@ class FormalRecommendationController extends Controller
|
|||||||
$filter = $request->validate(['version' => 'nullable|integer|min:1']);
|
$filter = $request->validate(['version' => 'nullable|integer|min:1']);
|
||||||
$adoption = $workflow->adoption($requisition);
|
$adoption = $workflow->adoption($requisition);
|
||||||
$selected = isset($filter['version']) ? RecommendationAdoption::query()->where('requisition_id', $requisition->id)->findOrFail((int) $filter['version']) : $adoption;
|
$selected = isset($filter['version']) ? RecommendationAdoption::query()->where('requisition_id', $requisition->id)->findOrFail((int) $filter['version']) : $adoption;
|
||||||
|
$focusInput = $request->validate(['attempt_id' => ['nullable', 'integer', 'min:1', Rule::exists('recommendation_attempts', 'id')->where('tenant_id', $requisition->tenant_id)->where('recommendation_adoption_id', $selected->id ?? 0)]]);
|
||||||
|
$focus = isset($focusInput['attempt_id']) ? (int) $focusInput['attempt_id'] : null;
|
||||||
$current = $selected && $selected->id === $adoption?->id;
|
$current = $selected && $selected->id === $adoption?->id;
|
||||||
$basis = $workflow->basis($requisition);
|
$basis = $workflow->basis($requisition);
|
||||||
$latest = RecommendationAttempt::query()->where('recommendation_adoption_id', $selected->id ?? 0)->latest('revision')->first();
|
$latest = RecommendationAttempt::query()->where('recommendation_adoption_id', $selected->id ?? 0)->latest('revision')->first();
|
||||||
$closed = $requisition->status !== 'approved' || PurchaseAward::query()->where('requisition_id', $requisition->id)->exists();
|
$closed = $requisition->status !== 'approved' || PurchaseAward::query()->where('requisition_id', $requisition->id)->exists();
|
||||||
$open = ! $closed && ! app(ConflictGuard::class)->participationBlocked($request->user(), $requisition);
|
$open = $workflow->canParticipate($this->actor($request), $requisition);
|
||||||
$history = RecommendationAttempt::query()->where('recommendation_adoption_id', $selected->id ?? 0)->latest('revision')->paginate(10)->withQueryString();
|
$history = RecommendationAttempt::query()->where('recommendation_adoption_id', $selected->id ?? 0)->when($focus !== null, fn ($query) => $query->whereKey($focus))->latest('revision')->paginate(10)->withQueryString();
|
||||||
$history->through(function ($attempt) use ($workflow, $selected, $current, $latest, $basis, $requisition, $open, $request) {
|
$history->through(function ($attempt) use ($workflow, $selected, $current, $requisition, $request) {
|
||||||
$fresh = $current && $latest?->id === $attempt->id && $basis['ready'] && $basis['hash'] === $attempt->basis_hash;
|
$fresh = $current && $workflow->currentReviewBasis($requisition, $selected, $attempt);
|
||||||
|
|
||||||
return [...$attempt->toArray(), 'status' => $workflow->status($attempt, $selected), 'current' => (bool) $fresh, 'reviews' => RecommendationReview::query()->where('recommendation_attempt_id', $attempt->id)->orderBy('id')->get(),
|
return [...$attempt->toArray(), 'status' => $workflow->status($attempt, $selected), 'current' => (bool) $fresh, 'reviews' => RecommendationReview::query()->where('recommendation_attempt_id', $attempt->id)->orderBy('id')->get(),
|
||||||
'canReview' => $open && $fresh && $workflow->status($attempt, $selected) === 'pending' && $workflow->eligible($request->user(), $requisition, $selected, $attempt) && ! RecommendationReview::query()->where('recommendation_attempt_id', $attempt->id)->where('reviewed_by', $request->user()->id)->exists()];
|
'canReview' => $fresh && $workflow->canReview($this->actor($request), $requisition, $attempt)];
|
||||||
});
|
});
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('purchases/recommendation', ['requisition' => $requisition->only(['id', 'number']), 'policy' => RecommendationPolicy::query()->latest('revision')->first(), 'adoption' => $adoption, 'selected' => $selected, 'adoptions' => RecommendationAdoption::query()->where('requisition_id', $requisition->id)->latest('revision')->get(), 'hasAdmission' => app(FormalAdmission::class)->adoption($requisition) !== null,
|
$response = Inertia::render('purchases/recommendation', ['focusAttemptId' => $focus, 'requisition' => $requisition->only(['id', 'number']), 'policy' => RecommendationPolicy::query()->latest('revision')->first(), 'adoption' => $adoption, 'selected' => $selected, 'adoptions' => RecommendationAdoption::query()->where('requisition_id', $requisition->id)->latest('revision')->get(), 'hasAdmission' => app(FormalAdmission::class)->adoption($requisition) !== null,
|
||||||
'basis' => ['hash' => $basis['hash'], 'ready' => $basis['ready'], 'top_ids' => $basis['top_ids'], 'rows' => collect($basis['payload']['rows'])->map(fn ($row) => array_intersect_key($row, array_flip(['id', 'reference', 'supplier_name', 'currency', 'total_minor', 'eligible', 'ineligibility_reasons', 'evaluation_count', 'score_minor'])))->all()], 'previousId' => $latest->id ?? 0,
|
'basis' => ['hash' => $basis['hash'], 'ready' => $basis['ready'], 'top_ids' => $basis['top_ids'], 'rows' => collect($basis['payload']['rows'])->map(fn ($row) => array_intersect_key($row, array_flip(['id', 'reference', 'supplier_name', 'currency', 'total_minor', 'eligible', 'ineligibility_reasons', 'evaluation_count', 'score_minor'])))->all()], 'previousId' => $latest->id ?? 0,
|
||||||
'history' => $history, 'closed' => $closed, 'canAdopt' => $open && $request->user()->hasFunctions([PurchasingRole::Procurement]), 'canPropose' => $open && $current && $basis['ready'] && $request->user()->hasFunctions([PurchasingRole::Procurement]) && $request->user()->id !== $requisition->requester_id])->toResponse($request);
|
'history' => $history, 'closed' => $closed, 'canAdopt' => $open && $this->actor($request)->hasFunctions([PurchasingRole::Procurement]), 'canPropose' => $open && $current && $basis['ready'] && $this->actor($request)->hasFunctions([PurchasingRole::Procurement]) && $this->actor($request)->id !== $requisition->requester_id])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
return $response;
|
return $response;
|
||||||
@@ -78,7 +88,7 @@ class FormalRecommendationController extends Controller
|
|||||||
{
|
{
|
||||||
$this->access($request, $requisition->id);
|
$this->access($request, $requisition->id);
|
||||||
$data = $request->validate(['policy_id' => 'required|integer', 'previous_id' => 'required|integer|min:0', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'snapshot' => 'prohibited', 'created_by' => 'prohibited']);
|
$data = $request->validate(['policy_id' => 'required|integer', 'previous_id' => 'required|integer|min:0', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'snapshot' => 'prohibited', 'created_by' => 'prohibited']);
|
||||||
$workflow->adopt($request->user(), $requisition, (int) $data['policy_id'], (int) $data['previous_id'], $data['reason']);
|
$workflow->adopt($this->actor($request), $requisition, (int) $data['policy_id'], (int) $data['previous_id'], $data['reason']);
|
||||||
|
|
||||||
return to_route('recommendations.show', $requisition);
|
return to_route('recommendations.show', $requisition);
|
||||||
}
|
}
|
||||||
@@ -87,7 +97,7 @@ class FormalRecommendationController extends Controller
|
|||||||
{
|
{
|
||||||
$this->access($request, $requisition->id);
|
$this->access($request, $requisition->id);
|
||||||
$data = $request->validate(['quotation_id' => 'required|integer', 'previous_id' => 'required|integer|min:0', 'basis_hash' => 'required|string|size:64', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'created_by' => 'prohibited', 'snapshot' => 'prohibited', 'status' => 'prohibited']);
|
$data = $request->validate(['quotation_id' => 'required|integer', 'previous_id' => 'required|integer|min:0', 'basis_hash' => 'required|string|size:64', 'reason' => 'required|string|min:10|max:4000', 'tenant_id' => 'prohibited', 'created_by' => 'prohibited', 'snapshot' => 'prohibited', 'status' => 'prohibited']);
|
||||||
$workflow->propose($request->user(), $requisition, $data);
|
$workflow->propose($this->actor($request), $requisition, $data);
|
||||||
|
|
||||||
return to_route('recommendations.show', $requisition);
|
return to_route('recommendations.show', $requisition);
|
||||||
}
|
}
|
||||||
@@ -97,7 +107,7 @@ class FormalRecommendationController extends Controller
|
|||||||
$adoption = RecommendationAdoption::query()->findOrFail($attempt->recommendation_adoption_id);
|
$adoption = RecommendationAdoption::query()->findOrFail($attempt->recommendation_adoption_id);
|
||||||
$this->access($request, $adoption->requisition_id);
|
$this->access($request, $adoption->requisition_id);
|
||||||
$data = $request->validate(['verdict' => 'required|in:approved,returned', 'reason' => 'required|string|min:10|max:4000', 'reviewed_by' => 'prohibited', 'snapshot' => 'prohibited', 'tenant_id' => 'prohibited']);
|
$data = $request->validate(['verdict' => 'required|in:approved,returned', 'reason' => 'required|string|min:10|max:4000', 'reviewed_by' => 'prohibited', 'snapshot' => 'prohibited', 'tenant_id' => 'prohibited']);
|
||||||
$workflow->review($request->user(), $attempt, $data['verdict'], $data['reason']);
|
$workflow->review($this->actor($request), $attempt, $data['verdict'], $data['reason']);
|
||||||
|
|
||||||
return to_route('recommendations.show', $adoption->requisition_id);
|
return to_route('recommendations.show', $adoption->requisition_id);
|
||||||
}
|
}
|
||||||
@@ -108,7 +118,7 @@ class FormalRecommendationController extends Controller
|
|||||||
if (DB::connection()->getDriverName() === 'pgsql') {
|
if (DB::connection()->getDriverName() === 'pgsql') {
|
||||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
|
||||||
}
|
}
|
||||||
$actor = User::query()->where('tenant_id', $request->user()->tenant_id)->findOrFail($request->user()->id);
|
$actor = User::query()->where('tenant_id', $this->actor($request)->tenant_id)->findOrFail($this->actor($request)->id);
|
||||||
$request->setUserResolver(fn () => $actor);
|
$request->setUserResolver(fn () => $actor);
|
||||||
$adoption = RecommendationAdoption::query()->findOrFail($attempt->recommendation_adoption_id);
|
$adoption = RecommendationAdoption::query()->findOrFail($attempt->recommendation_adoption_id);
|
||||||
$requisition = $this->access($request, $adoption->requisition_id);
|
$requisition = $this->access($request, $adoption->requisition_id);
|
||||||
@@ -118,7 +128,7 @@ class FormalRecommendationController extends Controller
|
|||||||
|
|
||||||
$history = RecommendationAttempt::query()->where('recommendation_adoption_id', $adoption->id)->where('id', '<', $attempt->id)->orderBy('revision')->get()->map(fn ($previous) => ['attempt' => $previous, 'state' => $workflow->status($previous, $adoption), 'reviews' => RecommendationReview::query()->where('recommendation_attempt_id', $previous->id)->orderBy('id')->get()]);
|
$history = RecommendationAttempt::query()->where('recommendation_adoption_id', $adoption->id)->where('id', '<', $attempt->id)->orderBy('revision')->get()->map(fn ($previous) => ['attempt' => $previous, 'state' => $workflow->status($previous, $adoption), 'reviews' => RecommendationReview::query()->where('recommendation_attempt_id', $previous->id)->orderBy('id')->get()]);
|
||||||
|
|
||||||
return response()->view('purchases.recommendation-print', ['requisition' => $requisition, 'attempt' => $attempt, 'adoption' => $adoption, 'history' => $history, 'reviews' => RecommendationReview::query()->where('recommendation_attempt_id', $attempt->id)->orderBy('id')->get(), 'state' => $workflow->status($attempt, $adoption), 'current' => $currentAdoption?->id === $adoption->id && $latest->id === $attempt->id && $basis['ready'] && $basis['hash'] === $attempt->basis_hash, 'generatedAt' => now()->timezone('Africa/Johannesburg'), 'generatedBy' => $request->user()->name], 200, ['Cache-Control' => 'private, no-store, max-age=0']);
|
return response()->view('purchases.recommendation-print', ['requisition' => $requisition, 'attempt' => $attempt, 'adoption' => $adoption, 'history' => $history, 'reviews' => RecommendationReview::query()->where('recommendation_attempt_id', $attempt->id)->orderBy('id')->get(), 'state' => $workflow->status($attempt, $adoption), 'current' => $currentAdoption?->id === $adoption->id && $latest->id === $attempt->id && $basis['ready'] && $basis['hash'] === $attempt->basis_hash, 'generatedAt' => now()->timezone('Africa/Johannesburg'), 'generatedBy' => $this->actor($request)->name], 200, ['Cache-Control' => 'private, no-store, max-age=0']);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\GeneralLedger;
|
||||||
|
use App\Services\StandaloneRuntime;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Response;
|
||||||
|
use Tempo\Finance\GeneralLedger\CycleWorkspace;
|
||||||
|
use Tempo\Finance\GeneralLedger\ReportsWorkspace;
|
||||||
|
|
||||||
|
final class GeneralLedgerController extends Controller
|
||||||
|
{
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
private function presentation(): array
|
||||||
|
{
|
||||||
|
return app(StandaloneRuntime::class)->enabled() ? ['host_journal_policy' => true,
|
||||||
|
'synthetic_only' => app(StandaloneRuntime::class)->syntheticOnly(),
|
||||||
|
'reports_from' => today()->startOfYear()->toDateString(), 'reports_to' => today()->toDateString()] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function report(Request $r, string $kind, GeneralLedger $ledger): Response|JsonResponse
|
||||||
|
{
|
||||||
|
$d = $r->validate(['from_on' => 'required|date_format:Y-m-d', 'to_on' => 'required|date_format:Y-m-d|after_or_equal:from_on', 'account_id' => 'sometimes|required|integer|min:1', 'page' => 'sometimes|integer|min:1|max:100000', 'per_page' => 'sometimes|integer|in:25,100']);
|
||||||
|
abort_if(array_diff(array_keys($r->query()), array_keys($d)) !== [], 422);
|
||||||
|
try {
|
||||||
|
$data = $ledger->report($this->actor($r), $kind, $d);
|
||||||
|
} catch (\InvalidArgumentException $e) {
|
||||||
|
abort(422, $e->getMessage());
|
||||||
|
} catch (\DomainException $e) {
|
||||||
|
abort(403, $e->getMessage());
|
||||||
|
}
|
||||||
|
if ($r->is('api/*')) {
|
||||||
|
return response()->json($data)->header('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
|
||||||
|
return response(ReportsWorkspace::render($data, ['host' => 'SGC autónomo', 'return_url' => '/general-ledger/cycle'] + $this->presentation()))->header('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function actor(Request $r): User
|
||||||
|
{
|
||||||
|
$user = $r->user();
|
||||||
|
abort_unless($user instanceof User, 403);
|
||||||
|
|
||||||
|
return $user;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function page(Request $r, GeneralLedger $ledger): Response
|
||||||
|
{
|
||||||
|
$d = $r->validate(['page' => 'sometimes|integer|min:1|max:100000']);
|
||||||
|
abort_if(array_diff(array_keys($r->query()), ['page']) !== [], 422);
|
||||||
|
$data = $ledger->workspace($this->actor($r), (int) ($d['page'] ?? 1));
|
||||||
|
|
||||||
|
return response(CycleWorkspace::render($data, ['host' => 'SGC autónomo', 'csrf' => csrf_token(), 'financial_url' => '/supplier-payments', 'return_url' => '/obrigacoes-fornecedores', 'page_url' => '/general-ledger/cycle'] + $this->presentation()))->header('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function command(Request $r, string $action, GeneralLedger $ledger): JsonResponse
|
||||||
|
{
|
||||||
|
abort_unless($ledger->cycleEnabled(), 403);
|
||||||
|
try {
|
||||||
|
return response()->json($ledger->engine($this->actor($r))->command($action, $r->all(), (string) $r->header('Idempotency-Key')))->header('Cache-Control', 'no-store');
|
||||||
|
} catch (\InvalidArgumentException $e) {
|
||||||
|
abort(422, $e->getMessage());
|
||||||
|
} catch (\DomainException $e) {
|
||||||
|
abort(409, $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function index(Request $r, GeneralLedger $ledger): JsonResponse
|
||||||
|
{
|
||||||
|
$d = $r->validate(['page' => 'sometimes|integer|min:1|max:100000']);
|
||||||
|
abort_if(array_diff(array_keys($r->query()), ['page']) !== [], 422);
|
||||||
|
|
||||||
|
return response()->json($ledger->workspace($this->actor($r), (int) ($d['page'] ?? 1)))->header('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,31 +2,47 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
use App\Http\Requests\ConfirmReceiptRequest;
|
use App\Http\Requests\ConfirmReceiptRequest;
|
||||||
use App\Models\GoodsReceipt;
|
use App\Models\GoodsReceipt;
|
||||||
use App\Models\PurchaseOrder;
|
use App\Models\PurchaseOrder;
|
||||||
|
use App\Models\ReceiptDocument;
|
||||||
use App\Models\Requisition;
|
use App\Models\Requisition;
|
||||||
use App\Models\StockItem;
|
use App\Models\StockItem;
|
||||||
use App\Models\StockMovement;
|
use App\Models\StockMovement;
|
||||||
|
use App\Models\User;
|
||||||
use App\Models\Warehouse;
|
use App\Models\Warehouse;
|
||||||
|
use App\Services\InventoryConversionRuntime;
|
||||||
|
use App\Services\InventoryLots;
|
||||||
|
use App\Services\InventoryReversals;
|
||||||
|
use App\Services\ReceiptDocuments;
|
||||||
use App\Services\ReceiptWorkflow;
|
use App\Services\ReceiptWorkflow;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Gate;
|
use Illuminate\Support\Facades\Gate;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Inertia\Response;
|
||||||
|
|
||||||
class GoodsReceiptController extends Controller
|
class GoodsReceiptController extends Controller
|
||||||
{
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
/** @return Builder<PurchaseOrder> */
|
/** @return Builder<PurchaseOrder> */
|
||||||
private function visibleOrders(Request $request): Builder
|
private function visibleOrders(Request $request): Builder
|
||||||
{
|
{
|
||||||
Gate::authorize('viewAny', GoodsReceipt::class);
|
Gate::authorize('viewAny', GoodsReceipt::class);
|
||||||
$orders = PurchaseOrder::query();
|
$orders = PurchaseOrder::query()->operational();
|
||||||
if ($request->user()->departmentScoped()) {
|
if ($this->actor($request)->departmentScoped()) {
|
||||||
$orders->whereIn('requisition_id', Requisition::query()->visibleTo($request->user())->select('id'));
|
$orders->whereIn('requisition_id', Requisition::query()->visibleTo($this->actor($request))->select('id'));
|
||||||
}
|
}
|
||||||
|
|
||||||
return $orders;
|
return $orders;
|
||||||
@@ -46,21 +62,27 @@ class GoodsReceiptController extends Controller
|
|||||||
|
|
||||||
public function order(Request $request, PurchaseOrder $order, ReceiptWorkflow $workflow): Response
|
public function order(Request $request, PurchaseOrder $order, ReceiptWorkflow $workflow): Response
|
||||||
{
|
{
|
||||||
|
$actor = $this->actor($request);
|
||||||
Gate::authorize('viewOrder', [GoodsReceipt::class, $order]);
|
Gate::authorize('viewOrder', [GoodsReceipt::class, $order]);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
return Inertia::render('receipts/order', [
|
return Inertia::render('receipts/order', [
|
||||||
|
'financialDocumentsHref' => $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]) ? '/facturas?purchase_order_id='.$order->id.'#invoice-documents' : null,
|
||||||
'order' => $order->only(['id', 'number', 'issued_by']), 'supplier_name' => $order->snapshot['supplier']['name'],
|
'order' => $order->only(['id', 'number', 'issued_by']), 'supplier_name' => $order->snapshot['supplier']['name'],
|
||||||
'progress' => $workflow->progress($order),
|
'progress' => $workflow->progress($order),
|
||||||
'receipts' => GoodsReceipt::query()->where('purchase_order_id', $order->id)->latest('id')->get(),
|
'receipts' => GoodsReceipt::query()->where('purchase_order_id', $order->id)->latest('id')->get(),
|
||||||
'warehouses' => Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']),
|
'warehouses' => Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']),
|
||||||
'stockItems' => StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']),
|
'stockItems' => StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']),
|
||||||
'canConfirm' => $request->user()->can('create', [GoodsReceipt::class, $order]),
|
'conversionQaEnabled' => app(InventoryConversionRuntime::class)->available(),
|
||||||
|
'canConfirm' => $actor->can('create', [GoodsReceipt::class, $order]),
|
||||||
|
'lotScopes' => Schema::hasTable('inventory_lot_allocations')
|
||||||
|
? app(InventoryLots::class)->activeSetups()->get()->map(fn ($r) => ['stock_item_id' => $r->stock_item_id, 'warehouse_id' => $r->warehouse_id, 'quarantine_on_receipt' => $r->data['quarantine_on_receipt'] ?? true])->values()->all() : [],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function store(ConfirmReceiptRequest $request, PurchaseOrder $order, ReceiptWorkflow $workflow): JsonResponse|RedirectResponse
|
public function store(ConfirmReceiptRequest $request, PurchaseOrder $order, ReceiptWorkflow $workflow): JsonResponse|RedirectResponse
|
||||||
{
|
{
|
||||||
$receipt = $workflow->confirm($request->user(), $order, $request->validated());
|
$receipt = $workflow->confirm($this->actor($request), $order, $request->validated());
|
||||||
if ($request->expectsJson()) {
|
if ($request->expectsJson()) {
|
||||||
return response()->json(['id' => $receipt->id, 'number' => $receipt->number, 'created' => $receipt->wasRecentlyCreated, 'status' => $receipt->status], $receipt->wasRecentlyCreated ? 201 : 200);
|
return response()->json(['id' => $receipt->id, 'number' => $receipt->number, 'created' => $receipt->wasRecentlyCreated, 'status' => $receipt->status], $receipt->wasRecentlyCreated ? 201 : 200);
|
||||||
}
|
}
|
||||||
@@ -68,13 +90,39 @@ class GoodsReceiptController extends Controller
|
|||||||
return to_route('receipts.show', $receipt);
|
return to_route('receipts.show', $receipt);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(GoodsReceipt $receipt): Response
|
public function show(Request $request, GoodsReceipt $receipt, ReceiptDocuments $documents): Response
|
||||||
{
|
{
|
||||||
Gate::authorize('view', $receipt);
|
Gate::authorize('view', $receipt);
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$ready = $documents->ready();
|
||||||
|
$order = PurchaseOrder::query()->findOrFail($receipt->purchase_order_id);
|
||||||
|
$source = Requisition::query()->visibleTo($actor)->whereKey($order->requisition_id)->first(['id']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
return Inertia::render('receipts/show', [
|
return Inertia::render('receipts/show', [
|
||||||
|
'financialDocumentsHref' => $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance])
|
||||||
|
? '/facturas?purchase_order_id='.$order->id.'#invoice-documents' : null,
|
||||||
|
'documentsReady' => $ready,
|
||||||
|
'purchaseProcessHref' => $source === null ? null : '/requisicoes/'.$source->id.'/processo',
|
||||||
|
'canAddDocuments' => $ready && $documents->canAdd($actor, $receipt),
|
||||||
|
'documents' => $ready && $documents->canRead($actor, $receipt) ? ReceiptDocument::query()->where('goods_receipt_id', $receipt->id)->orderBy('id')->get(['id', 'document_type', 'original_name', 'size', 'sha256', 'uploaded_by', 'created_at']) : [],
|
||||||
|
'correctedReceiptItems' => collect(app(InventoryReversals::class)->corrections('receipt'))->only($receipt->items()->pluck('id')->all())->map(fn ($r) => $r->data['reference']),
|
||||||
'receipt' => $receipt->load('items'),
|
'receipt' => $receipt->load('items'),
|
||||||
'movements' => StockMovement::query()->whereIn('goods_receipt_item_id', $receipt->items()->select('id'))->orderBy('id')->get(),
|
'movements' => StockMovement::query()->whereIn('goods_receipt_item_id', $receipt->items()->select('id'))->orderBy('id')->get(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function print(Request $request, GoodsReceipt $receipt, ReceiptDocuments $documents): \Illuminate\Http\Response
|
||||||
|
{
|
||||||
|
Gate::authorize('view', $receipt);
|
||||||
|
$actor = $this->actor($request);
|
||||||
|
|
||||||
|
return response()->view('receipts.print', [
|
||||||
|
'receipt' => $receipt->load('items'),
|
||||||
|
'corrections' => collect(app(InventoryReversals::class)->corrections('receipt'))->only($receipt->items()->pluck('id')->all()),
|
||||||
|
'documents' => $documents->ready() && $documents->canRead($actor, $receipt)
|
||||||
|
? ReceiptDocument::query()->where('goods_receipt_id', $receipt->id)->orderBy('id')->get(['document_type', 'original_name', 'sha256', 'created_at']) : collect(),
|
||||||
|
])->header('Cache-Control', 'no-store, private')->header('X-Content-Type-Options', 'nosniff');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportBankSupport;
|
||||||
|
use App\Services\ImportDossier;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class ImportBankSupportController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, SupplyRecord $import, ImportBankSupport $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$request->validate(['bank_current_page' => 'nullable|integer|min:1|max:1000000', 'bank_history_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'bank_documents_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('supply/import-bank-support', $service->workspace($actor, $import))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, SupplyRecord $import, ImportBankSupport $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $import, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Acompanhamento documental bancário versionado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function export(Request $request, SupplyRecord $import, ImportBankSupport $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->assertReadable($actor, $import);
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($actor, $import, $service) {
|
||||||
|
$output = fopen('php://output', 'w');
|
||||||
|
if ($output === false) {
|
||||||
|
throw new \RuntimeException('Não foi possível exportar o acompanhamento bancário.');
|
||||||
|
}
|
||||||
|
$text = fn ($value) => preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', (string) $value) ? "'".$value : $value;
|
||||||
|
fwrite($output, "\xEF\xBB\xBF");
|
||||||
|
fputcsv($output, ['Acompanhamento documental bancário', 'Gerado em', now()->toIso8601String(), 'Não certifica cumprimento nem executa transferências ou submissões JUE'], ';', '"', '');
|
||||||
|
fputcsv($output, ['Termo', 'Versão', 'Situação registada', 'Documento único / declaração', 'Requisitos conhecidos', 'Tipos e quantidades pedidos', 'Fonte dos requisitos',
|
||||||
|
'Suportes seleccionados', 'Comprovativo de entrega', 'Data efectiva da entrega documentada', 'Fundamento da entrega', 'Prazo documental', 'Fonte do prazo', 'Alertas actuais', 'Motivo'], ';', '"', '');
|
||||||
|
$service->report($actor, $import, function (SupplyRecord $record, array $issues) use ($output, $text) {
|
||||||
|
$documents = [];
|
||||||
|
foreach ($record->snapshot['documents'] as $document) {
|
||||||
|
$documents[$document['id']] = $document;
|
||||||
|
}
|
||||||
|
$reference = fn ($id) => $id === null ? 'Por associar' : ($documents[$id]['reference'] ?? 'Indeterminado');
|
||||||
|
$requirements = [];
|
||||||
|
foreach ($record->data['required_support_counts'] as $type => $count) {
|
||||||
|
$requirements[] = ImportDossier::TYPES[$type].': '.$count;
|
||||||
|
}
|
||||||
|
$state = match ($record->state) {
|
||||||
|
'ready' => 'Documentos reunidos; entrega por documentar', 'documented' => 'Comprovativo de entrega associado', default => 'Documentação incompleta'
|
||||||
|
};
|
||||||
|
fputcsv($output, array_map($text, [$reference($record->data['commitment_document_id']), $record->version, $state,
|
||||||
|
$reference($record->data['declaration_document_id']), $record->data['requirements_known'] ? 'Sim' : 'Desconhecidos',
|
||||||
|
$record->data['requirements_known'] ? (implode(' | ', $requirements) ?: 'Nenhum tipo exigido segundo a fonte registada') : 'Desconhecidos', $record->data['requirements_basis'],
|
||||||
|
implode(' | ', array_map($reference, $record->data['support_document_ids'])), $reference($record->data['submission_document_id']), $record->data['submitted_on'] ?? 'Desconhecida', $record->data['submission_basis'] ?? 'Por indicar',
|
||||||
|
$record->data['due_on'] ?? 'Desconhecido', $record->data['deadline_basis'] ?? 'Não indicado', implode(' | ', $issues), $record->reason]), ';', '"', '');
|
||||||
|
});
|
||||||
|
fclose($output);
|
||||||
|
}, 'suporte-bancario-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportBankSupport;
|
||||||
|
use App\Services\ImportDossier;
|
||||||
|
use App\Services\ImportEvidence;
|
||||||
|
use App\Services\ImportParties;
|
||||||
|
use App\Services\ImportReadiness;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class ImportDossierController extends Controller
|
||||||
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function index(Request $request, SupplyRecord $import, ImportDossier $service): Response
|
||||||
|
{
|
||||||
|
$search = $request->validate(['party_search' => 'nullable|string|max:100'])['party_search'] ?? '';
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$actor = $this->actor($request);
|
||||||
|
$response = Inertia::render('supply/import-dossier', [...$service->workspace($actor, $import),
|
||||||
|
'parties' => app(ImportParties::class)->workspace($actor, $import, $search),
|
||||||
|
'bankSupportReady' => app(ImportBankSupport::class)->ready(), 'readinessReady' => app(ImportReadiness::class)->ready()])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, SupplyRecord $import, ImportDossier $service): Response
|
||||||
|
{
|
||||||
|
$request->validate(['file' => 'required|file']);
|
||||||
|
$file = $request->file('file');
|
||||||
|
abort_unless($file instanceof UploadedFile, 422);
|
||||||
|
$service->record($this->actor($request), $import, $request->except('file'), $file);
|
||||||
|
|
||||||
|
return to_route('imports.dossier', $import);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function evidence(Request $request, SupplyRecord $import, int $document, ImportDossier $service): Response
|
||||||
|
{
|
||||||
|
$source = $service->evidence($this->actor($request), $import, $document);
|
||||||
|
$extension = pathinfo($source->snapshot['evidence']['path'], PATHINFO_EXTENSION);
|
||||||
|
|
||||||
|
return response(app(ImportEvidence::class)->bytes($source), 200, ['Content-Type' => 'application/octet-stream',
|
||||||
|
'Content-Disposition' => 'attachment; filename="documento-importacao-'.$source->id.'.'.$extension.'"',
|
||||||
|
'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function selectParty(Request $request, SupplyRecord $import, ImportParties $service): Response
|
||||||
|
{
|
||||||
|
$service->select($this->actor($request), $import, $request->all());
|
||||||
|
|
||||||
|
return to_route('imports.dossier', $import);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportEstimates;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class ImportEstimateController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, Requisition $requisition, ImportEstimates $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$request->validate(['estimate_page' => 'nullable|integer|min:1|max:1000000', 'budgets_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('supply/import-estimate', $service->workspace($actor, $requisition))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, Requisition $requisition, ImportEstimates $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Estimativa versionada. A reserva ocorre apenas na submissão da requisição completa.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportEvidence;
|
||||||
|
use App\Services\ImportLandedCosts;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class ImportLandedCostController extends Controller
|
||||||
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function index(Request $request, SupplyRecord $import, ImportLandedCosts $service): Response
|
||||||
|
{
|
||||||
|
return $this->page($request, $import, $service);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function preview(Request $request, SupplyRecord $import, ImportLandedCosts $service): Response
|
||||||
|
{
|
||||||
|
return $this->page($request, $import, $service, $service->preview($this->actor($request), $import, $request->all()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed>|null $preview */
|
||||||
|
private function page(Request $request, SupplyRecord $import, ImportLandedCosts $service, ?array $preview = null): Response
|
||||||
|
{
|
||||||
|
$search = $request->validate(['invoice_search' => 'nullable|string|max:100', 'estimates_page' => 'nullable|integer|min:1|max:1000000'])['invoice_search'] ?? '';
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('supply/import-costs', [...$service->workspace($this->actor($request), $import, $search), 'preview' => $preview])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function document(Request $request, SupplyRecord $import, ImportLandedCosts $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$request->validate(['file' => 'required|file']);
|
||||||
|
$file = $request->file('file');
|
||||||
|
abort_unless($file instanceof UploadedFile, 422);
|
||||||
|
$service->recordDocument($this->actor($request), $import, $request->except('file'), $file);
|
||||||
|
|
||||||
|
return to_route('imports.costs', $import);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function save(Request $request, SupplyRecord $import, ImportLandedCosts $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$service->save($this->actor($request), $import, $request->all());
|
||||||
|
|
||||||
|
return to_route('imports.costs', $import);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function financial(Request $request, SupplyRecord $import, SupplyRecord $plan, ImportLandedCosts $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$service->financial($this->actor($request), $import, $plan, $request->all());
|
||||||
|
|
||||||
|
return to_route('imports.costs', $import);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function evidence(Request $request, SupplyRecord $import, int $document, ImportLandedCosts $service): Response
|
||||||
|
{
|
||||||
|
$source = $service->evidence($this->actor($request), $import, $document);
|
||||||
|
$evidence = $source->snapshot['evidence'];
|
||||||
|
|
||||||
|
return response(app(ImportEvidence::class)->bytes($source), 200, [
|
||||||
|
'Content-Type' => 'application/octet-stream', 'Content-Disposition' => 'attachment; filename="documento-importacao-'.$source->id.'.'.pathinfo($evidence['path'], PATHINFO_EXTENSION).'"',
|
||||||
|
'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportEvidence;
|
||||||
|
use App\Services\ImportLegalEstimates;
|
||||||
|
use App\Services\ImportLegalRules;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class ImportLegalController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, Requisition $requisition, ImportLegalRules $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$filters = $request->validate(['rules_page' => 'nullable|integer|min:1|max:1000000', 'legal_history_page' => 'nullable|integer|min:1|max:1000000', 'legal_sources_page' => 'nullable|integer|min:1|max:1000000', 'legal_estimates_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'code' => 'nullable|string|max:40', 'origin' => 'nullable|string|max:120', 'sector' => 'nullable|string|max:160', 'date' => 'nullable|date_format:Y-m-d']);
|
||||||
|
$workspace = $service->workspace($actor, $requisition);
|
||||||
|
$date = $filters['date'] ?? today()->toDateString();
|
||||||
|
$suggestions = empty($filters['code']) ? [] : $service->suggestions($actor, $requisition, $filters['code'], $filters['origin'] ?? '', $filters['sector'] ?? '', $date);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
|
$response = Inertia::render('supply/import-legal', [...$workspace, 'filters' => [...$filters, 'date' => $date], 'suggestions' => $suggestions])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, Requisition $requisition, ImportLegalRules $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->workspace($actor, $requisition);
|
||||||
|
$service->save($actor, $request->except('file'), $request->file('file'));
|
||||||
|
|
||||||
|
return back()->with('success', 'Versão da base legal registada.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function source(Request $request, Requisition $requisition, int $source, ImportLegalRules $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$record = $service->source($actor, $requisition, $source);
|
||||||
|
$bytes = app(ImportEvidence::class)->bytes($record);
|
||||||
|
|
||||||
|
return response($bytes, 200, ['Content-Type' => 'application/octet-stream', 'Content-Disposition' => 'attachment; filename="fonte-legal-'.$record->id.'.'.pathinfo($record->snapshot['evidence']['path'], PATHINFO_EXTENSION).'"',
|
||||||
|
'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function estimate(Request $request, Requisition $requisition, ImportLegalEstimates $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Estimativa documentada; sem efeitos financeiros ou pagamentos.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportReadiness;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class ImportReadinessController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, SupplyRecord $import, ImportReadiness $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('supply/import-readiness', $service->workspace($actor, $import))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportTariffCodes;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class ImportTariffController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, Requisition $requisition, ImportTariffCodes $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$data = $request->validate(['search' => 'nullable|string|max:100', 'tariff_history_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'stock_page' => 'nullable|integer|min:1|max:1000000', 'masters_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('supply/import-tariffs', $service->workspace($actor, $requisition, $data['search'] ?? ''))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, Requisition $requisition, ImportTariffCodes $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Classificação documental registada.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\GoodsReceipt;
|
||||||
|
use App\Models\StockItem;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Models\Warehouse;
|
||||||
|
use App\Services\InventoryCorrectionPage;
|
||||||
|
use App\Services\InventoryDispositions;
|
||||||
|
use App\Services\InventoryLots;
|
||||||
|
use App\Services\InventoryReversals;
|
||||||
|
use App\Services\ReceiptQuantityConversion;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class InventoryDispositionController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, InventoryDispositions $workflow): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$capabilities = [];
|
||||||
|
foreach (['read', 'prepare', 'review', 'execute'] as $capability) {
|
||||||
|
$capabilities[$capability] = $workflow->allows($actor, $capability);
|
||||||
|
}
|
||||||
|
$canViewReversals = collect(['read', 'prepare', 'review', 'execute'])->contains(fn ($a) => app(InventoryReversals::class)->allows($actor, $a));
|
||||||
|
if (! collect($capabilities)->contains(fn (bool $allow) => $allow) && $canViewReversals) {
|
||||||
|
return redirect('/stock/estornos');
|
||||||
|
}
|
||||||
|
abort_unless(collect($capabilities)->contains(fn (bool $allow) => $allow), 403);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($request, $workflow, $actor, $capabilities, $canViewReversals) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->page($request, $workflow, $actor, $capabilities, $canViewReversals);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,bool> $capabilities */
|
||||||
|
private function page(Request $request, InventoryDispositions $workflow, User $actor, array $capabilities, bool $canViewReversals): Response
|
||||||
|
{
|
||||||
|
$page = app(InventoryCorrectionPage::class)->read($request, $actor, 'stock_event');
|
||||||
|
['ready' => $ready, 'focus' => $focus, 'records' => $records] = $page;
|
||||||
|
$receipts = [];
|
||||||
|
$lots = [];
|
||||||
|
if ($ready && $capabilities['prepare']) {
|
||||||
|
foreach (app(InventoryCorrectionPage::class)->receipts($records->pluck('data.receipt_item_id')->push($page['lookup']['receipt']), $page['lookup']['search']) as $line) {
|
||||||
|
$receipt = GoodsReceipt::query()->whereKey($line->goods_receipt_id)->firstOrFail();
|
||||||
|
$receipts[] = ['id' => $line->id, 'stock_item_id' => $line->stock_item_id, 'warehouse_id' => $receipt->warehouse_id, 'accepted_milli' => $line->accepted_milli,
|
||||||
|
'returned_milli' => $workflow->returnedForReceipt($line->id), 'physical_accepted_milli' => app(ReceiptQuantityConversion::class)->physicalAccepted($line), 'label' => $receipt->number.' · '.$receipt->snapshot['supplier']['name'].' · '.$line->snapshot['stock_item']['name']];
|
||||||
|
}
|
||||||
|
foreach (app(InventoryLots::class)->activeSetups()->get() as $setup) {
|
||||||
|
$context = app(InventoryLots::class)->context($setup->stock_item_id, $setup->warehouse_id);
|
||||||
|
foreach ($context['lots'] ?? [] as $lot) {
|
||||||
|
if ($lot['quantity_milli'] > 0) {
|
||||||
|
$lots[] = ['id' => $lot['id'], 'stock_item_id' => $setup->stock_item_id, 'warehouse_id' => $setup->warehouse_id, 'code' => $lot['data']['code'], 'quantity_milli' => $lot['quantity_milli'],
|
||||||
|
'receipt_item_id' => $lot['origin']['receipt_item_id'] ?? null, 'reconciled' => $context['reconciled']];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('stock/dispositions', ['ready' => $ready, 'actorId' => $actor->id, 'today' => today()->toDateString(), 'capabilities' => $capabilities,
|
||||||
|
'recordPagination' => $page['pagination'], 'filters' => $page['filters'],
|
||||||
|
'sourceSearch' => $page['lookup']['search'], 'sourceFormKey' => $page['lookup']['form'],
|
||||||
|
'focusRecordId' => $focus->id ?? null, 'focusChanged' => $focus !== null && $records->first()?->id !== $focus->id,
|
||||||
|
'records' => $records->map(fn (SupplyRecord $record) => [...$record->toArray(), 'canApprove' => $workflow->canAct($actor, $record, 'approve'),
|
||||||
|
'canReturn' => $workflow->canAct($actor, $record, 'return'), 'canExecute' => $workflow->canAct($actor, $record, 'execute'),
|
||||||
|
'executionSourceCurrent' => $record->state === 'approved' ? $workflow->executionSourceCurrent($record) : null]),
|
||||||
|
'canViewOperations' => $actor->hasFunctions(['admin', 'warehouse', 'procurement', 'finance', 'inventory_adjust_review']),
|
||||||
|
'canViewReversals' => $canViewReversals,
|
||||||
|
'correctedOperations' => collect(app(InventoryReversals::class)->corrections('operation'))->only($records->pluck('data.stock_operation_id')->filter()->all())->map(fn ($r) => $r->data['reference']),
|
||||||
|
'items' => $capabilities['prepare'] ? StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']) : [],
|
||||||
|
'warehouses' => $capabilities['prepare'] ? Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']) : [], 'receipts' => $receipts, 'lots' => $lots,
|
||||||
|
'history' => $ready ? SupplyRecord::query()->where('kind', 'stock_event')->whereIn('record_key', $records->pluck('record_key'))->latest('id')->get()->groupBy('record_key') : []])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function save(Request $request, InventoryDispositions $workflow): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
abort_unless(Schema::hasTable('supply_records'), 503, 'Instalação do diário de stock pendente.');
|
||||||
|
$workflow->save($actor, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Processo de stock registado.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\StockItem;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Models\Warehouse;
|
||||||
|
use App\Services\InventoryLots;
|
||||||
|
use App\Services\SupplyPlanning;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class InventoryLotController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, InventoryLots $lots): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$capabilities = [];
|
||||||
|
foreach (['read', 'prepare', 'review', 'hold', 'release'] as $capability) {
|
||||||
|
$capabilities[$capability] = $lots->allows($actor, 'inventory_lot_'.$capability);
|
||||||
|
}
|
||||||
|
abort_unless(collect($capabilities)->contains(fn (bool $allowed) => $allowed), 403);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($request, $lots, $actor, $capabilities) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->page($request, $lots, $actor, $capabilities);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,bool> $capabilities */
|
||||||
|
private function page(Request $request, InventoryLots $lots, User $actor, array $capabilities): Response
|
||||||
|
{
|
||||||
|
$ready = Schema::hasTable('inventory_lot_allocations');
|
||||||
|
$filter = $request->validate([
|
||||||
|
'record_id' => ['nullable', Rule::prohibitedIf($request->filled('lot_id')), 'integer', 'min:1', Rule::exists('supply_records', 'id')->where('tenant_id', $actor->tenant_id)->where('kind', 'lot_setup')],
|
||||||
|
'lot_id' => ['nullable', 'required_with:warehouse_id', 'integer', 'min:1', Rule::exists('supply_records', 'id')->where('tenant_id', $actor->tenant_id)->where('kind', 'lot')->where('version', 1)],
|
||||||
|
'warehouse_id' => ['nullable', 'required_with:lot_id', 'integer', 'min:1', Rule::exists('warehouses', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||||
|
'controls_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'history_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
]);
|
||||||
|
$focus = isset($filter['record_id']) ? SupplyRecord::query()->where('tenant_id', $actor->tenant_id)->where('kind', 'lot_setup')->findOrFail((int) $filter['record_id']) : null;
|
||||||
|
if (isset($filter['lot_id'])) {
|
||||||
|
$identity = SupplyRecord::query()->findOrFail((int) $filter['lot_id']);
|
||||||
|
$focus = $lots->setup($identity->stock_item_id, (int) $filter['warehouse_id']);
|
||||||
|
abort_if($focus === null, 404);
|
||||||
|
}
|
||||||
|
$controls = $ready && $focus === null ? app(SupplyPlanning::class)->latest('lot_setup')->latest('id')->paginate(25, ['record_key'], 'controls_page')->withQueryString() : null;
|
||||||
|
$keys = $focus !== null ? collect([$focus->record_key]) : ($controls?->getCollection()->pluck('record_key') ?? collect());
|
||||||
|
$records = $ready ? app(SupplyPlanning::class)->latest('lot_setup')->whereIn('record_key', $keys)->latest('id')->get() : collect();
|
||||||
|
if ($ready) {
|
||||||
|
$records = $records->concat($lots->activeSetups()->whereIn('record_key', $keys)->latest('id')->get())->unique('id')->sortByDesc('id')->values();
|
||||||
|
}
|
||||||
|
$contexts = [];
|
||||||
|
foreach ($records->where('state', 'active') as $record) {
|
||||||
|
$contexts[$record->record_key] = $lots->context($record->stock_item_id, $record->warehouse_id);
|
||||||
|
foreach ($contexts[$record->record_key]['lots'] as &$entry) {
|
||||||
|
$metadata = SupplyRecord::query()->whereKey($entry['metadata_id'])->firstOrFail();
|
||||||
|
$entry['canIdentify'] = $lots->canIdentify($actor, $metadata);
|
||||||
|
$entry['canRelease'] = $lots->canDecideLot($actor, $metadata, $contexts[$record->record_key], $entry, 'release');
|
||||||
|
$entry['canHold'] = $lots->canDecideLot($actor, $metadata, $contexts[$record->record_key], $entry, 'hold');
|
||||||
|
}
|
||||||
|
unset($entry);
|
||||||
|
}
|
||||||
|
if (isset($filter['lot_id'])) {
|
||||||
|
abort_unless(collect($contexts[$focus->record_key]['lots'] ?? [])->contains('id', (int) $filter['lot_id']), 404);
|
||||||
|
}
|
||||||
|
$history = $ready ? SupplyRecord::query()->whereIn('kind', ['lot_setup', 'lot', 'lot_state'])->latest('id')->paginate(50, ['*'], 'history_page')->withQueryString() : null;
|
||||||
|
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('stock/lots', ['ready' => $ready, 'actorId' => $actor->id, 'capabilities' => $capabilities,
|
||||||
|
'focusRecordId' => $focus->id ?? null, 'focusLotId' => isset($filter['lot_id']) ? (int) $filter['lot_id'] : null,
|
||||||
|
'focusChanged' => ! isset($filter['lot_id']) && $focus !== null && $records->first()?->id !== $focus->id,
|
||||||
|
'controlPagination' => $this->pagination($controls), 'historyPagination' => $this->pagination($history),
|
||||||
|
'records' => $records->map(fn (SupplyRecord $record) => [...$record->toArray(), 'canActivate' => $lots->canActivate($actor, $record)]), 'contexts' => $contexts,
|
||||||
|
'items' => $capabilities['prepare'] ? StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']) : [],
|
||||||
|
'warehouses' => $capabilities['prepare'] ? Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']) : [],
|
||||||
|
'history' => $history?->getCollection() ?? []])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param LengthAwarePaginator<int,SupplyRecord>|null $page
|
||||||
|
* @return array<string,mixed>|null
|
||||||
|
*/
|
||||||
|
private function pagination(?LengthAwarePaginator $page): ?array
|
||||||
|
{
|
||||||
|
return $page === null ? null : ['current_page' => $page->currentPage(), 'last_page' => $page->lastPage(), 'total' => $page->total(),
|
||||||
|
'prev_page_url' => $page->previousPageUrl(), 'next_page_url' => $page->nextPageUrl()];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function save(Request $request, InventoryLots $lots): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
abort_unless(Schema::hasTable('inventory_lot_allocations'), 503, 'Instalação do controlo por lotes pendente.');
|
||||||
|
$lots->save($actor, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Conferência de lotes registada.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\GoodsReceipt;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\InventoryCorrectionPage;
|
||||||
|
use App\Services\InventoryDispositions;
|
||||||
|
use App\Services\InventoryReversals;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class InventoryReversalController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, InventoryReversals $workflow): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$capabilities = [];
|
||||||
|
foreach (['read', 'prepare', 'review', 'execute'] as $capability) {
|
||||||
|
$capabilities[$capability] = $workflow->allows($actor, $capability);
|
||||||
|
}
|
||||||
|
abort_unless(collect($capabilities)->contains(fn (bool $allow) => $allow), 403);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($request, $workflow, $actor, $capabilities) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->page($request, $workflow, $actor, $capabilities);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,bool> $capabilities */
|
||||||
|
private function page(Request $request, InventoryReversals $workflow, User $actor, array $capabilities): Response
|
||||||
|
{
|
||||||
|
$page = app(InventoryCorrectionPage::class)->read($request, $actor, 'stock_reversal');
|
||||||
|
['ready' => $ready, 'focus' => $focus, 'records' => $records] = $page;
|
||||||
|
$operations = [];
|
||||||
|
$receipts = [];
|
||||||
|
if ($ready && $capabilities['prepare']) {
|
||||||
|
$operations = app(InventoryCorrectionPage::class)->operations($records->pluck('data.source_operation_id')->push($page['lookup']['operation']), $page['lookup']['search'])
|
||||||
|
->map(fn ($op) => ['id' => $op->id, 'label' => $op->reference.' · '.$op->snapshot['stock_item']['name'].' · '.$op->snapshot['warehouse']['name']])->values()->all();
|
||||||
|
foreach (app(InventoryCorrectionPage::class)->receipts($records->pluck('data.receipt_item_id')->push($page['lookup']['receipt']), $page['lookup']['search']) as $line) {
|
||||||
|
$receipt = GoodsReceipt::query()->whereKey($line->goods_receipt_id)->firstOrFail();
|
||||||
|
$receipts[] = ['id' => $line->id, 'label' => $receipt->number.' · '.$line->snapshot['stock_item']['name'].' · '.$line->snapshot['warehouse']['name']];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$other = app(InventoryDispositions::class);
|
||||||
|
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('stock/reversals', ['ready' => $ready, 'actorId' => $actor->id, 'today' => today()->toDateString(), 'capabilities' => $capabilities,
|
||||||
|
'recordPagination' => $page['pagination'], 'filters' => $page['filters'],
|
||||||
|
'sourceSearch' => $page['lookup']['search'], 'sourceFormKey' => $page['lookup']['form'],
|
||||||
|
'focusRecordId' => $focus->id ?? null, 'focusChanged' => $focus !== null && $records->first()?->id !== $focus->id,
|
||||||
|
'canViewDispositions' => collect(['read', 'prepare', 'review', 'execute'])->contains(fn ($a) => $other->allows($actor, $a)),
|
||||||
|
'records' => $records->map(fn (SupplyRecord $record) => [...$record->toArray(), 'canApprove' => $workflow->canAct($actor, $record, 'approve'),
|
||||||
|
'canReturn' => $workflow->canAct($actor, $record, 'return'), 'canExecute' => $workflow->canAct($actor, $record, 'execute'),
|
||||||
|
'executionSourceCurrent' => $record->state === 'approved' ? $workflow->executionSourceCurrent($record) : null]), 'operations' => $operations, 'receipts' => $receipts,
|
||||||
|
'history' => $ready ? SupplyRecord::query()->where('kind', 'stock_reversal')->whereIn('record_key', $records->pluck('record_key'))->latest('id')->get()->groupBy('record_key') : []])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function save(Request $request, InventoryReversals $workflow): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
abort_unless(Schema::hasTable('supply_records'), 503, 'Instalação do diário pendente.');
|
||||||
|
$workflow->save($actor, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Estorno registado com a origem preservada.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,23 +9,27 @@ use App\Services\InvestmentWorkflow;
|
|||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class InvestmentPolicyController extends Controller
|
class InvestmentPolicyController extends Controller
|
||||||
{
|
{
|
||||||
public function index(Request $request, InvestmentWorkflow $workflow): Response
|
public function index(Request $request, InvestmentWorkflow $workflow): Response
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance, PurchasingRole::Procurement]), 403);
|
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance, PurchasingRole::Procurement]), 403);
|
||||||
$current = $workflow->current();
|
$current = $workflow->current();
|
||||||
|
|
||||||
return Inertia::render('investment/index', ['policies' => InvestmentPolicy::query()->latest('revision')->get(), 'reviews' => InvestmentPolicyReview::query()->orderBy('id')->get(), 'currentPolicyId' => $current && $current->valid_until >= today()->format('Y-m-d') ? $current->id : null, 'canManage' => $request->user()->hasFunctions([PurchasingRole::Admin])]);
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('investment/index', ['policies' => InvestmentPolicy::query()->latest('revision')->get(), 'reviews' => InvestmentPolicyReview::query()->orderBy('id')->get(), 'currentPolicyId' => $current && $current->valid_until >= today()->format('Y-m-d') ? $current->id : null, 'canManage' => $this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin])])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function store(Request $request, InvestmentWorkflow $workflow): RedirectResponse
|
public function store(Request $request, InvestmentWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin]), 403);
|
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin]), 403);
|
||||||
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'mode' => 'required|in:ceiling', 'scope' => 'required|in:process_total', 'currency' => 'required|in:MZN', 'ceiling' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'includes_tax' => '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|max:4000']);
|
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'mode' => 'required|in:ceiling', 'scope' => 'required|in:process_total', 'currency' => 'required|in:MZN', 'ceiling' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'includes_tax' => '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|max:4000']);
|
||||||
$workflow->propose($request->user(), $data);
|
$workflow->propose($this->staffIdentity($request), $data);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -33,7 +37,7 @@ class InvestmentPolicyController extends Controller
|
|||||||
public function review(Request $request, InvestmentPolicy $policy, InvestmentWorkflow $workflow): RedirectResponse
|
public function review(Request $request, InvestmentPolicy $policy, InvestmentWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|max:4000']);
|
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|max:4000']);
|
||||||
$workflow->review($request->user(), $policy, $data['decision'], $data['reason']);
|
$workflow->review($this->staffIdentity($request), $policy, $data['decision'], $data['reason']);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,35 +5,70 @@ namespace App\Http\Controllers;
|
|||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\Invoice;
|
use App\Models\Invoice;
|
||||||
use App\Models\PurchaseOrder;
|
use App\Models\PurchaseOrder;
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\InventoryDispositions;
|
||||||
|
use App\Services\InventoryReversals;
|
||||||
use App\Services\InvoiceWorkflow;
|
use App\Services\InvoiceWorkflow;
|
||||||
|
use App\Services\OrderPartsAccess;
|
||||||
|
use App\Services\OrderPartsInvoices;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
|
use App\Services\RequisitionBudgetDistributions;
|
||||||
use App\Services\SupplierPayables;
|
use App\Services\SupplierPayables;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class InvoiceController extends Controller
|
class InvoiceController extends Controller
|
||||||
{
|
{
|
||||||
public function index(Request $request): Response
|
public function index(Request $request): Response
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
abort_unless($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
||||||
|
$filters = $request->validate(['invoice_id' => ['nullable', 'integer', 'min:1', Rule::exists('invoices', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||||
|
'purchase_order_id' => ['nullable', 'integer', 'min:1', Rule::exists('purchase_orders', 'id')->where('tenant_id', $actor->tenant_id)]]);
|
||||||
|
$focus = isset($filters['invoice_id']) ? (int) $filters['invoice_id'] : null;
|
||||||
|
$focusOrder = isset($filters['purchase_order_id']) ? (int) $filters['purchase_order_id'] : null;
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
return Inertia::render('invoices/index', ['invoices' => Invoice::query()->with('items')->latest('id')->paginate(15), 'orders' => PurchaseOrder::query()->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($request->user(), 'view'), 'canManage' => $request->user()->hasFunctions([PurchasingRole::Finance])]);
|
$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)->operational()->with('items')->latest('id')->get()->map(fn ($order) => ['id' => $order->id, 'number' => $order->number, 'currency' => $order->currency, 'supplier' => $order->snapshot['supplier']['name'], 'items' => $order->items,
|
||||||
|
'orderParts' => OrderPartsAccess::applies($order),
|
||||||
|
'orderPartsBudgetOptions' => OrderPartsAccess::applies($order) ? app(OrderPartsInvoices::class)->options($actor, $order) : null,
|
||||||
|
'budgetDistributionOptions' => OrderPartsAccess::applies($order) ? null : app(RequisitionBudgetDistributions::class)->options($actor, Requisition::query()->findOrFail($order->requisition_id))]),
|
||||||
|
'sgfDispatchAvailable' => config('sgf_invoice.workspace_enabled') === true && $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor),
|
||||||
|
'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');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function store(Request $request, PurchaseOrder $order, InvoiceWorkflow $workflow): RedirectResponse
|
public function store(Request $request, PurchaseOrder $order, InvoiceWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Finance]), 403);
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Finance]), 403);
|
||||||
$decimal = ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'];
|
$decimal = ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'];
|
||||||
$data = $request->validate(['number' => 'required|string|max:100', 'issued_on' => 'required|date_format:Y-m-d', 'subtotal' => $decimal, 'tax' => $decimal, 'total' => $decimal, 'items' => 'required|array|min:1|max:50', 'items.*.purchase_order_item_id' => 'required|integer|distinct', 'items.*.quantity' => ['required', 'regex:/^\d{1,9}(\.\d{1,3})?$/'], 'items.*.unit' => 'required|string|max:30', 'items.*.unit_price' => $decimal, 'items.*.tax_rate' => ['required', 'regex:/^\d{1,3}(\.\d{1,2})?$/']]);
|
$data = $request->validate(['number' => 'required|string|max:100', 'issued_on' => 'required|date_format:Y-m-d', 'subtotal' => $decimal, 'tax' => $decimal, 'total' => $decimal, 'items' => 'required|array|min:1|max:50', 'items.*.purchase_order_item_id' => 'required|integer|distinct', 'items.*.quantity' => ['required', 'regex:/^\d{1,9}(\.\d{1,3})?$/'], 'items.*.unit' => 'sometimes|required|string|max:30', 'items.*.unit_price' => ['sometimes', ...$decimal], 'items.*.tax_rate' => ['sometimes', 'required', 'regex:/^\d{1,3}(\.\d{1,2})?$/']]);
|
||||||
$workflow->register($request->user(), $order, $data);
|
if (OrderPartsAccess::applies($order)) {
|
||||||
|
$data += $request->validate(app(OrderPartsInvoices::class)->rules());
|
||||||
|
} elseif (app(RequisitionBudgetDistributions::class)->applies(Requisition::query()->findOrFail($order->requisition_id))) {
|
||||||
|
$data += $request->validate(app(RequisitionBudgetDistributions::class)->rules(Requisition::query()->findOrFail($order->requisition_id)));
|
||||||
|
}
|
||||||
|
$workflow->register($actor, $order, $data);
|
||||||
|
|
||||||
return to_route('invoices.index');
|
return to_route('invoices.index');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function validateInvoice(Request $request, Invoice $invoice, InvoiceWorkflow $workflow): RedirectResponse
|
public function validateInvoice(Request $request, Invoice $invoice, InvoiceWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$workflow->validate($request->user(), $invoice);
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$workflow->validate($actor, $invoice);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Services\OperationalOrders;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class OperationalOrdersController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, OperationalOrders $orders, ?Requisition $requisition = null): Response
|
||||||
|
{
|
||||||
|
$data = $request->validate(['page' => 'nullable|integer|min:1|max:1000000', 'order_id' => 'nullable|integer|min:1']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$selected = $requisition === null && isset($data['order_id']) ? (int) $data['order_id'] : null;
|
||||||
|
$response = Inertia::render('requisitions/operational-orders', $orders->workspace($this->staffIdentity($request), $requisition, $selected))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function configure(Request $request, OperationalOrders $orders): Response
|
||||||
|
{
|
||||||
|
$orders->configure($this->staffIdentity($request), $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Origem das novas ordens configurada.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, OperationalOrders $orders): Response
|
||||||
|
{
|
||||||
|
$orders->save($this->staffIdentity($request), $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Ordem registada e original preservado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function link(Request $request, Requisition $requisition, OperationalOrders $orders): Response
|
||||||
|
{
|
||||||
|
$orders->link($this->staffIdentity($request), $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Ordem ligada à linha da requisição.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
<?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\OrderCancellationRuntime;
|
||||||
|
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.');
|
||||||
|
app(OrderCancellationRuntime::class)->assertReady();
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\PurchaseAward;
|
||||||
|
use App\Models\PurchaseOrderItem;
|
||||||
|
use App\Models\Quotation;
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\OrderPartsWorkflow;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
|
use App\Services\ReceiptWorkflow;
|
||||||
|
use Brick\Math\BigDecimal;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Inertia\Response;
|
||||||
|
|
||||||
|
class OrderPartsController extends Controller
|
||||||
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Procurement])
|
||||||
|
&& ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||||
|
abort_unless(app(OrderPartsWorkflow::class)->ready(), 503);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function index(Request $request): Response
|
||||||
|
{
|
||||||
|
return $this->page($this->actor($request));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function preview(Request $request, OrderPartsWorkflow $workflow): Response
|
||||||
|
{
|
||||||
|
$actor = $this->actor($request);
|
||||||
|
|
||||||
|
return $this->page($actor, $workflow->preview($actor, $request->all()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed>|null $preview */
|
||||||
|
private function page(User $actor, ?array $preview = null): Response
|
||||||
|
{
|
||||||
|
$candidates = PurchaseAward::query()->where('status', 'approved')
|
||||||
|
->whereIn('requisition_id', Requisition::query()->visibleTo($actor)->select('id'))
|
||||||
|
->whereExists(fn ($lines) => $lines->selectRaw('1')->from('quotation_items as qi')
|
||||||
|
->whereColumn('qi.quotation_id', 'purchase_awards.quotation_id')->whereColumn('qi.tenant_id', 'purchase_awards.tenant_id')
|
||||||
|
->whereRaw('ROUND(qi.quantity * 1000) > (select COALESCE(SUM(ROUND(oi.quantity * 1000)), 0) from purchase_order_items oi where oi.requisition_item_id = qi.requisition_item_id and oi.tenant_id = qi.tenant_id)'))
|
||||||
|
->latest('id')->paginate(20)
|
||||||
|
->through(function (PurchaseAward $award): array {
|
||||||
|
$quote = Quotation::query()->with(['items', 'supplier'])->whereKey($award->quotation_id)->firstOrFail();
|
||||||
|
$request = Requisition::query()->whereKey($award->requisition_id)->firstOrFail();
|
||||||
|
$items = [];
|
||||||
|
foreach ($quote->items as $line) {
|
||||||
|
$before = 0;
|
||||||
|
foreach (PurchaseOrderItem::query()->where('requisition_item_id', $line->requisition_item_id)->get(['quantity']) as $old) {
|
||||||
|
$before += ReceiptWorkflow::milli($old->quantity);
|
||||||
|
}
|
||||||
|
$remaining = max(0, ReceiptWorkflow::milli($line->quantity) - $before);
|
||||||
|
$items[] = ['id' => $line->id, 'description' => $line->description, 'remaining' => (string) BigDecimal::of($remaining)->dividedBy(1000, 3)];
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['id' => $award->id, 'requisition_id' => $request->id, 'number' => $request->number,
|
||||||
|
'supplier' => $quote->supplier?->name, 'currency' => $quote->currency, 'items' => $items];
|
||||||
|
});
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
|
return Inertia::render('purchases/parts', ['candidates' => $candidates, 'preview' => $preview]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function issue(Request $request, OrderPartsWorkflow $workflow): RedirectResponse
|
||||||
|
{
|
||||||
|
$order = $workflow->issue($this->actor($request), $request->all());
|
||||||
|
|
||||||
|
return to_route('orders.show', $order);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function adopt(Request $request, PurchaseAward $award, OrderPartsWorkflow $workflow): RedirectResponse
|
||||||
|
{
|
||||||
|
$data = $request->validate(['operation_key' => 'required|uuid', 'reference_lines' => 'sometimes|array|list|max:500']);
|
||||||
|
$workflow->adopt($this->actor($request), $award, $data['operation_key'], $data['reference_lines'] ?? []);
|
||||||
|
|
||||||
|
return to_route('orders.parts');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,11 +3,23 @@
|
|||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\AdministrativeGeography;
|
||||||
use App\Services\AiPreparationPlan;
|
use App\Services\AiPreparationPlan;
|
||||||
|
use App\Services\CommonFinanceAdministration;
|
||||||
|
use App\Services\CompanyDetails;
|
||||||
use App\Services\ComparisonPolicy;
|
use App\Services\ComparisonPolicy;
|
||||||
use App\Services\IntelligencePolicy;
|
use App\Services\IntelligencePolicy;
|
||||||
use App\Services\OrganizationAccess;
|
use App\Services\OrganizationAccess;
|
||||||
|
use App\Services\OrganizationActivationPreview;
|
||||||
use App\Services\OrganizationConfiguration;
|
use App\Services\OrganizationConfiguration;
|
||||||
|
use App\Services\RequisitionApprovalLevels;
|
||||||
|
use App\Services\RequisitionCategories;
|
||||||
|
use App\Services\RequisitionExpiry;
|
||||||
|
use App\Services\UrgentQuotationBasis;
|
||||||
|
use App\Services\UrgentRequisitionReviews;
|
||||||
|
use App\Services\WorkContext;
|
||||||
|
use App\Services\WorkflowTasks;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -20,37 +32,68 @@ class OrganizationConfigurationController extends Controller
|
|||||||
{
|
{
|
||||||
public function index(Request $request, OrganizationConfiguration $service): Response
|
public function index(Request $request, OrganizationConfiguration $service): Response
|
||||||
{
|
{
|
||||||
$actor = $service->administrator($request->user());
|
return DB::transaction(function () use ($request, $service) {
|
||||||
$ready = Schema::hasTable('organization_access');
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
$state = $ready ? DB::table('organization_access')->where('tenant_id', $actor->tenant_id)->first() : null;
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
Inertia::encryptHistory();
|
}
|
||||||
$response = Inertia::render('company/parameters', ['ready' => $ready, 'active' => (bool) ($state->active ?? false), 'version' => $state->version ?? 1,
|
$user = $request->user('web');
|
||||||
'companyRules' => $this->companyRules((int) $actor->tenant_id),
|
abort_unless($user instanceof User, 403);
|
||||||
'comparisonPolicy' => app(ComparisonPolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
$actor = $service->administrator($user);
|
||||||
'intelligencePolicy' => app(IntelligencePolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
$ready = Schema::hasTable('organization_access');
|
||||||
'intelligenceReady' => Schema::hasColumn('tenants', 'intelligence_policy'),
|
$state = $ready ? DB::table('organization_access')->where('tenant_id', $actor->tenant_id)->first() : null;
|
||||||
'aiPlan' => app(AiPreparationPlan::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
Inertia::encryptHistory();
|
||||||
'aiDomains' => AiPreparationPlan::DOMAINS, 'aiDataScopes' => AiPreparationPlan::SCOPES,
|
$response = Inertia::render('company/parameters', ['ready' => $ready, 'active' => (bool) ($state->active ?? false), 'version' => $state->version ?? 1,
|
||||||
'permissions' => OrganizationAccess::PERMISSIONS,
|
'workflowTasks' => app(WorkflowTasks::class)->catalogue(),
|
||||||
'profiles' => $ready ? DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get()->map(fn ($p) => ['id' => $p->id, 'name' => $p->name, 'permissions' => json_decode($p->permissions, true, 32, JSON_THROW_ON_ERROR)]) : [],
|
'activationPreview' => app(OrganizationActivationPreview::class)->build($actor),
|
||||||
'memberships' => $ready ? DB::table('organization_memberships')->where('tenant_id', $actor->tenant_id)->get(['user_id', 'profile_id', 'maintenance', 'expires_at', 'reason']) : [],
|
'geographyEnabled' => app(AdministrativeGeography::class)->enabled(),
|
||||||
'users' => DB::table('users')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name', 'email', 'department_id']),
|
'geography' => app(AdministrativeGeography::class)->describe(Tenant::query()->findOrFail($actor->tenant_id)->geography_reference),
|
||||||
'departments' => DB::table('departments')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
|
'companyDetailsReady' => Schema::hasColumn('tenants', 'company_details'),
|
||||||
'costCenters' => DB::table('cost_centers')->where('tenant_id', $actor->tenant_id)->orderBy('code')->get(['id', 'code', 'name']),
|
'approvalLevelsReady' => app(RequisitionApprovalLevels::class)->ready(),
|
||||||
'notice' => $request->session()->get('organization_notice')])->toResponse($request);
|
'expiryReady' => app(RequisitionExpiry::class)->ready(),
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
'financeConfigurationReady' => app(CommonFinanceAdministration::class)->ready(),
|
||||||
|
'urgentReviewsReady' => app(UrgentRequisitionReviews::class)->ready(),
|
||||||
|
'requisitionCategoryOptions' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
||||||
|
'approvalLevels' => Tenant::query()->findOrFail($actor->tenant_id)->requisition_approval_policy,
|
||||||
|
'companyDetails' => Tenant::query()->findOrFail($actor->tenant_id)->company_details,
|
||||||
|
'companyRules' => $this->companyRules((int) $actor->tenant_id),
|
||||||
|
'comparisonPolicy' => app(ComparisonPolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
||||||
|
'urgentQuotationReady' => app(UrgentQuotationBasis::class)->ready(),
|
||||||
|
'intelligencePolicy' => app(IntelligencePolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
||||||
|
'intelligenceReady' => Schema::hasColumn('tenants', 'intelligence_policy'),
|
||||||
|
'aiPlan' => app(AiPreparationPlan::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
||||||
|
'aiDomains' => AiPreparationPlan::DOMAINS, 'aiDataScopes' => AiPreparationPlan::SCOPES,
|
||||||
|
'permissions' => OrganizationAccess::PERMISSIONS,
|
||||||
|
'workContextConfiguration' => Schema::hasColumn('tenants', 'work_context_policy') ? app(WorkContext::class)->shared($request) : null,
|
||||||
|
'enabledWorkContexts' => app(WorkContext::class)->policy($actor)['enabled'] ?? [],
|
||||||
|
'profiles' => $ready ? DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get()->map(fn ($p) => ['id' => $p->id, 'name' => $p->name, 'permissions' => json_decode($p->permissions, true, 32, JSON_THROW_ON_ERROR), 'work_contexts' => json_decode($p->work_contexts ?? '[]', true, 32, JSON_THROW_ON_ERROR)]) : [],
|
||||||
|
'memberships' => $ready ? DB::table('organization_memberships')->where('tenant_id', $actor->tenant_id)->get(['user_id', 'profile_id', 'maintenance', 'expires_at', 'reason']) : [],
|
||||||
|
'users' => DB::table('users')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name', 'email', 'department_id']),
|
||||||
|
'departments' => DB::table('departments')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
|
||||||
|
'costCenters' => DB::table('cost_centers')->where('tenant_id', $actor->tenant_id)->orderBy('code')->get(['id', 'code', 'name']),
|
||||||
|
'notice' => $request->session()->get('organization_notice')])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
return $response;
|
return $response;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function command(Request $request, string $command, OrganizationConfiguration $service): Response
|
public function command(Request $request, string $command, OrganizationConfiguration $service): Response
|
||||||
{
|
{
|
||||||
$actor = $service->administrator($request->user());
|
$user = $request->user('web');
|
||||||
|
abort_unless($user instanceof User, 403);
|
||||||
|
$actor = $service->administrator($user);
|
||||||
abort_unless(Schema::hasTable('organization_access'), 503, 'A instalação da parametrização ainda não está concluída.');
|
abort_unless(Schema::hasTable('organization_access'), 503, 'A instalação da parametrização ainda não está concluída.');
|
||||||
$rules = ['version' => 'required|integer|min:1', 'tenant_id' => 'prohibited', 'purchasing_role' => 'prohibited'];
|
$rules = ['version' => 'required|integer|min:1', 'tenant_id' => 'prohibited', 'purchasing_role' => 'prohibited'];
|
||||||
if ($command === 'profile') {
|
if ($command === 'approval_levels') {
|
||||||
|
$rules += app(RequisitionApprovalLevels::class)->rules($actor);
|
||||||
|
} elseif ($command === 'company_details') {
|
||||||
|
$rules += app(CompanyDetails::class)->rules();
|
||||||
|
} elseif ($command === 'profile') {
|
||||||
|
$rules += ['work_contexts' => 'sometimes|array', 'work_contexts.*' => ['string', 'distinct', Rule::in(array_keys(WorkContext::OPTIONS))]];
|
||||||
$rules += ['id' => 'nullable|integer|min:1', 'name' => ['required', 'string', 'max:120', Rule::unique('organization_profiles')->where('tenant_id', $actor->tenant_id)->ignore($request->integer('id'))],
|
$rules += ['id' => 'nullable|integer|min:1', 'name' => ['required', 'string', 'max:120', Rule::unique('organization_profiles')->where('tenant_id', $actor->tenant_id)->ignore($request->integer('id'))],
|
||||||
'permissions' => 'present|array', 'permissions.*' => ['string', 'distinct', Rule::in(array_keys(OrganizationAccess::PERMISSIONS))]];
|
'permissions' => 'present|array', 'permissions.*' => ['string', 'distinct', Rule::in(array_keys(OrganizationAccess::PERMISSIONS))]];
|
||||||
|
} elseif ($command === 'work_contexts') {
|
||||||
|
$rules += ['enabled' => 'present|array', 'enabled.*' => ['string', 'distinct', Rule::in(array_keys(WorkContext::OPTIONS))], 'reason' => 'required|string|min:10|max:4000', 'confirm' => 'accepted'];
|
||||||
} elseif ($command === 'user') {
|
} elseif ($command === 'user') {
|
||||||
$rules += ['name' => 'required|string|max:100', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|string|min:12|confirmed',
|
$rules += ['name' => 'required|string|max:100', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|string|min:12|confirmed',
|
||||||
'department_id' => 'required|integer|min:1', 'profile_ids' => 'present|array', 'profile_ids.*' => 'integer|distinct|min:1', 'reason' => 'required|string|min:10|max:4000'];
|
'department_id' => 'required|integer|min:1', 'profile_ids' => 'present|array', 'profile_ids.*' => 'integer|distinct|min:1', 'reason' => 'required|string|min:10|max:4000'];
|
||||||
@@ -61,6 +104,7 @@ class OrganizationConfigurationController extends Controller
|
|||||||
$rules += ['first_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'second_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'includes_tax' => 'required|boolean', 'reason' => 'required|string|min:10|max:4000'];
|
$rules += ['first_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'second_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'includes_tax' => 'required|boolean', 'reason' => 'required|string|min:10|max:4000'];
|
||||||
} elseif ($command === 'comparison') {
|
} elseif ($command === 'comparison') {
|
||||||
$rules += ['minimum_proposals' => 'required|integer|between:1,100', 'minimum_evaluators' => 'required|integer|between:1,100',
|
$rules += ['minimum_proposals' => 'required|integer|between:1,100', 'minimum_evaluators' => 'required|integer|between:1,100',
|
||||||
|
'urgent_minimum_proposals' => 'sometimes|nullable|integer|between:1,100',
|
||||||
'weights' => 'required|array:price,quality,delivery,history,payment', 'reason' => 'required|string|min:10|max:4000'];
|
'weights' => 'required|array:price,quality,delivery,history,payment', 'reason' => 'required|string|min:10|max:4000'];
|
||||||
foreach (array_keys(ComparisonPolicy::DEFAULTS['weights']) as $criterion) {
|
foreach (array_keys(ComparisonPolicy::DEFAULTS['weights']) as $criterion) {
|
||||||
$rules['weights.'.$criterion] = 'required|integer|between:0,100';
|
$rules['weights.'.$criterion] = 'required|integer|between:0,100';
|
||||||
@@ -76,7 +120,7 @@ class OrganizationConfigurationController extends Controller
|
|||||||
abort_unless($command === 'activate', 404);
|
abort_unless($command === 'activate', 404);
|
||||||
$rules += ['reason' => 'required|string|min:10|max:4000', 'confirm' => 'required|accepted'];
|
$rules += ['reason' => 'required|string|min:10|max:4000', 'confirm' => 'required|accepted'];
|
||||||
}
|
}
|
||||||
$service->execute($actor, $command, $request->validate($rules));
|
$service->execute($actor, $command, $request->validate($rules, $command === 'approval_levels' ? app(RequisitionApprovalLevels::class)->messages() : []));
|
||||||
|
|
||||||
return to_route('organization.parameters')->with('organization_notice', 'Parametrização actualizada e registada na auditoria.');
|
return to_route('organization.parameters')->with('organization_notice', 'Parametrização actualizada e registada na auditoria.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,19 +7,25 @@ use App\Models\PeopleProcess;
|
|||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\AiPreparationPlan;
|
use App\Services\AiPreparationPlan;
|
||||||
|
use App\Services\BusinessClients;
|
||||||
use App\Services\CandidateTriage;
|
use App\Services\CandidateTriage;
|
||||||
use App\Services\IntelligencePolicy;
|
use App\Services\IntelligencePolicy;
|
||||||
use App\Services\PeopleAccess;
|
use App\Services\PeopleAccess;
|
||||||
use App\Services\PeopleClarifications;
|
use App\Services\PeopleClarifications;
|
||||||
|
use App\Services\PeopleContractFormalization;
|
||||||
use App\Services\PeopleEvidenceBrief;
|
use App\Services\PeopleEvidenceBrief;
|
||||||
use App\Services\PeopleForms;
|
use App\Services\PeopleForms;
|
||||||
use App\Services\PeopleHiring;
|
use App\Services\PeopleHiring;
|
||||||
use App\Services\PeopleOperationalInsights;
|
use App\Services\PeopleOperationalInsights;
|
||||||
|
use App\Services\PeopleProcessProjection;
|
||||||
use App\Services\PeopleRegistry;
|
use App\Services\PeopleRegistry;
|
||||||
use App\Services\PeopleWorkdesk;
|
use App\Services\PeopleWorkdesk;
|
||||||
|
use App\Services\WorkContext;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
@@ -35,6 +41,7 @@ class PeopleHiringController extends Controller
|
|||||||
$kinds = $workflow->kinds($this->actor($request));
|
$kinds = $workflow->kinds($this->actor($request));
|
||||||
abort_unless($kinds !== [], 403);
|
abort_unless($kinds !== [], 403);
|
||||||
$availableKinds = $kinds;
|
$availableKinds = $kinds;
|
||||||
|
$clientMode = app(WorkContext::class)->active($request) === 'people.third_party';
|
||||||
$filter = $request->validate(['kind' => 'nullable|in:service,staff', 'search' => 'nullable|string|max:100', 'status' => ['nullable', Rule::in(PeopleWorkdesk::STATES)],
|
$filter = $request->validate(['kind' => 'nullable|in:service,staff', 'search' => 'nullable|string|max:100', 'status' => ['nullable', Rule::in(PeopleWorkdesk::STATES)],
|
||||||
'from' => 'nullable|date_format:Y-m-d', 'to' => ['nullable', 'date_format:Y-m-d', Rule::when($request->filled('from'), 'after_or_equal:from')]]);
|
'from' => 'nullable|date_format:Y-m-d', 'to' => ['nullable', 'date_format:Y-m-d', Rule::when($request->filled('from'), 'after_or_equal:from')]]);
|
||||||
if (isset($filter['kind'])) {
|
if (isset($filter['kind'])) {
|
||||||
@@ -45,8 +52,11 @@ class PeopleHiringController extends Controller
|
|||||||
$query = app(PeopleAccess::class)->visible(PeopleProcess::query()->whereIn('kind', $kinds), $this->actor($request));
|
$query = app(PeopleAccess::class)->visible(PeopleProcess::query()->whereIn('kind', $kinds), $this->actor($request));
|
||||||
if (($filter['search'] ?? '') !== '') {
|
if (($filter['search'] ?? '') !== '') {
|
||||||
$search = $filter['search'];
|
$search = $filter['search'];
|
||||||
$query->where(function ($q) use ($search) {
|
$query->where(function ($q) use ($search, $clientMode) {
|
||||||
$q->whereLike('title', '%'.$search.'%');
|
$q->whereLike('title', '%'.$search.'%');
|
||||||
|
if ($clientMode) {
|
||||||
|
$q->orWhere('rules->client->name', 'like', '%'.$search.'%')->orWhere('rules->client->code', 'like', '%'.$search.'%');
|
||||||
|
}
|
||||||
if (preg_match('/^(?:PES-)?([1-9][0-9]*)$/D', $search, $matches)) {
|
if (preg_match('/^(?:PES-)?([1-9][0-9]*)$/D', $search, $matches)) {
|
||||||
$reference = filter_var($matches[1], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
$reference = filter_var($matches[1], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||||
if ($reference !== false) {
|
if ($reference !== false) {
|
||||||
@@ -65,14 +75,18 @@ class PeopleHiringController extends Controller
|
|||||||
$query->whereDate('created_at', '<=', $filter['to']);
|
$query->whereDate('created_at', '<=', $filter['to']);
|
||||||
}
|
}
|
||||||
$workdesk = $ready ? app(PeopleWorkdesk::class)->build(clone $query, $this->actor($request)) : null;
|
$workdesk = $ready ? app(PeopleWorkdesk::class)->build(clone $query, $this->actor($request)) : null;
|
||||||
|
$processes = $ready ? (clone $query)->select(['id', 'title', 'kind', 'status', 'closes_on', 'created_at', 'rules'])->latest('id')->paginate(15)->withQueryString()
|
||||||
|
->through(fn (PeopleProcess $process) => [...$process->only(['id', 'title', 'kind', 'status', 'closes_on', 'created_at']),
|
||||||
|
...($clientMode ? ['client' => array_intersect_key($process->rules['client'] ?? [], array_flip(['id', 'code', 'name', 'version']))] : [])]) : null;
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('people/index', ['ready' => $ready, 'kinds' => $kinds, 'availableKinds' => $availableKinds,
|
$response = Inertia::render('people/index', ['ready' => $ready, 'kinds' => $kinds, 'availableKinds' => $availableKinds,
|
||||||
'filters' => $filter, 'workdesk' => $workdesk, 'insights' => $workdesk === null ? null : app(PeopleOperationalInsights::class)->build($workdesk),
|
'filters' => $filter, 'workdesk' => $workdesk, 'insights' => $workdesk === null ? null : app(PeopleOperationalInsights::class)->build($workdesk),
|
||||||
|
'clientMode' => $clientMode, 'clients' => $clientMode ? app(BusinessClients::class)->choices($this->actor($request)) : [],
|
||||||
'company' => Tenant::query()->findOrFail($this->actor($request)->tenant_id)->only(['name']),
|
'company' => Tenant::query()->findOrFail($this->actor($request)->tenant_id)->only(['name']),
|
||||||
'canPrepare' => array_values(array_filter($availableKinds, fn ($kind) => $workflow->allowed($this->actor($request), $kind, 'prepare'))),
|
'canPrepare' => array_values(array_filter($availableKinds, fn ($kind) => $workflow->allowed($this->actor($request), $kind, 'prepare'))),
|
||||||
'formFields' => ['staff' => PeopleForms::STAFF, 'service' => PeopleForms::SERVICE],
|
'formFields' => ['staff' => PeopleForms::STAFF, 'service' => PeopleForms::SERVICE],
|
||||||
'administration' => $ready && $this->actor($request)->hasFunctions(['admin']) ? PeopleProcess::query()->whereIn('kind', $kinds)->orderByDesc('id')->get(['id', 'kind', 'status']) : [],
|
'administration' => $ready && $this->actor($request)->hasFunctions(['admin']) ? PeopleProcess::query()->whereIn('kind', $kinds)->orderByDesc('id')->get(['id', 'kind', 'status']) : [],
|
||||||
'processes' => $ready ? (clone $query)->select(['id', 'title', 'kind', 'status', 'closes_on', 'created_at'])->latest('id')->paginate(15)->withQueryString() : null])->toResponse($request);
|
'processes' => $processes])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
return $response;
|
return $response;
|
||||||
@@ -89,21 +103,9 @@ class PeopleHiringController extends Controller
|
|||||||
$access = app(PeopleAccess::class);
|
$access = app(PeopleAccess::class);
|
||||||
abort_unless($access->can($this->actor($request), $record, 'view'), 403);
|
abort_unless($access->can($this->actor($request), $record, 'view'), 403);
|
||||||
$registrySearch = $request->validate(['cadastro' => 'nullable|string|max:100'])['cadastro'] ?? '';
|
$registrySearch = $request->validate(['cadastro' => 'nullable|string|max:100'])['cadastro'] ?? '';
|
||||||
$snapshot = $workflow->snapshot($record);
|
$projection = app(PeopleProcessProjection::class)->read($this->actor($request), $record);
|
||||||
$rows = $workflow->matrix($record);
|
$snapshot = $projection['process'];
|
||||||
if (! $access->can($this->actor($request), $record, 'financial')) {
|
$rows = $projection['candidates'];
|
||||||
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;
|
|
||||||
}
|
|
||||||
$clarifications = app(PeopleClarifications::class)->page($this->actor($request), $record);
|
$clarifications = app(PeopleClarifications::class)->page($this->actor($request), $record);
|
||||||
$company = Tenant::query()->findOrFail($this->actor($request)->tenant_id);
|
$company = Tenant::query()->findOrFail($this->actor($request)->tenant_id);
|
||||||
$policy = app(IntelligencePolicy::class)->company($company);
|
$policy = app(IntelligencePolicy::class)->company($company);
|
||||||
@@ -117,8 +119,9 @@ class PeopleHiringController extends Controller
|
|||||||
'canPrepare' => $workflow->allowed($this->actor($request), $record->kind, 'prepare') && $access->can($this->actor($request), $record, 'prepare'),
|
'canPrepare' => $workflow->allowed($this->actor($request), $record->kind, 'prepare') && $access->can($this->actor($request), $record, 'prepare'),
|
||||||
'canViewElectronicSources' => app(CandidateTriage::class)->canRead($this->actor($request), $record),
|
'canViewElectronicSources' => app(CandidateTriage::class)->canRead($this->actor($request), $record),
|
||||||
'canReview' => $workflow->allowed($this->actor($request), $record->kind, 'review') && $access->can($this->actor($request), $record, 'review') && $this->actor($request)->id !== $record->created_by,
|
'canReview' => $workflow->allowed($this->actor($request), $record->kind, 'review') && $access->can($this->actor($request), $record, 'review') && $this->actor($request)->id !== $record->created_by,
|
||||||
'canApprove' => $workflow->allowed($this->actor($request), $record->kind, 'review') && $access->can($this->actor($request), $record, 'approve') && ! in_array($this->actor($request)->id, $workflow->decisionContributors($record), true),
|
'canApprove' => $workflow->canConfirm($this->actor($request), $record) && ! in_array($this->actor($request)->id, $workflow->decisionContributors($record), true),
|
||||||
'canContract' => $workflow->allowed($this->actor($request), $record->kind, 'prepare') && $access->can($this->actor($request), $record, 'contract'),
|
'canContract' => $workflow->allowed($this->actor($request), $record->kind, 'prepare') && $access->can($this->actor($request), $record, 'contract'),
|
||||||
|
'canFormalize' => app(PeopleContractFormalization::class)->can($this->actor($request), $record),
|
||||||
'canManage' => $access->manages($this->actor($request), $record),
|
'canManage' => $access->manages($this->actor($request), $record),
|
||||||
'history' => AuditLog::query()->where('action', 'like', 'people.%')->where('after->id', $record->id)->orderBy('id')->get(['id', 'action', 'user_id', 'created_at'])])->toResponse($request);
|
'history' => AuditLog::query()->where('action', 'like', 'people.%')->where('after->id', $record->id)->orderBy('id')->get(['id', 'action', 'user_id', 'created_at'])])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
@@ -127,6 +130,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' => $record->status === 'contract_formalized' ? 'sgc.people.process-dossier.v2' : 'sgc.people.process-dossier.v1', 'exported_at' => now()->toIso8601String(),
|
||||||
|
'effect' => $record->status === 'contract_formalized' ? 'signed_contract_record_only' : '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
|
public function access(Request $request, int $process, PeopleAccess $access): Response
|
||||||
{
|
{
|
||||||
$record = PeopleProcess::query()->findOrFail($process);
|
$record = PeopleProcess::query()->findOrFail($process);
|
||||||
@@ -159,6 +180,26 @@ class PeopleHiringController extends Controller
|
|||||||
return redirect('/pessoas/'.$record->id);
|
return redirect('/pessoas/'.$record->id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function formalize(Request $request, int $process, PeopleContractFormalization $service): Response
|
||||||
|
{
|
||||||
|
$record = $service->confirm($this->actor($request), $process, $request->all());
|
||||||
|
|
||||||
|
return redirect('/pessoas/'.$record->id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function signedContract(Request $request, int $process): Response
|
||||||
|
{
|
||||||
|
$record = PeopleProcess::query()->findOrFail($process);
|
||||||
|
$data = app(PeopleProcessProjection::class)->read($this->actor($request), $record);
|
||||||
|
abort_unless(isset($data['process']['contract']['signed_document']) && $record->status === 'contract_formalized', 404);
|
||||||
|
$document = $record->contract['signed_document'];
|
||||||
|
$disk = Storage::disk('people_contracts');
|
||||||
|
abort_unless($disk->exists($document['path']) && hash_equals($document['sha256'], hash('sha256', $disk->get($document['path']))), 409);
|
||||||
|
|
||||||
|
return $disk->download($document['path'], 'contrato-assinado-'.$record->id.'.pdf', [
|
||||||
|
'Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
|
||||||
|
}
|
||||||
|
|
||||||
public function store(Request $request, PeopleHiring $workflow): Response
|
public function store(Request $request, PeopleHiring $workflow): Response
|
||||||
{
|
{
|
||||||
abort_unless(Schema::hasTable('people_processes'), 503);
|
abort_unless(Schema::hasTable('people_processes'), 503);
|
||||||
|
|||||||
@@ -12,22 +12,22 @@ class PeopleRegistryController extends Controller
|
|||||||
{
|
{
|
||||||
public function index(Request $request, PeopleRegistry $registry): Response
|
public function index(Request $request, PeopleRegistry $registry): Response
|
||||||
{
|
{
|
||||||
abort_unless($registry->canRead($request->user()), 403);
|
abort_unless($registry->canRead($this->staffIdentity($request)), 403);
|
||||||
$filter = $request->validate(['search' => 'nullable|string|max:100', 'status' => 'nullable|in:active,archived,all']);
|
$filter = $request->validate(['search' => 'nullable|string|max:100', 'status' => 'nullable|in:active,archived,all']);
|
||||||
$ready = Schema::hasTable('people_registry');
|
$ready = Schema::hasTable('people_registry');
|
||||||
$records = null;
|
$records = null;
|
||||||
if ($ready) {
|
if ($ready) {
|
||||||
$query = $registry->visible($request->user());
|
$query = $registry->visible($this->staffIdentity($request));
|
||||||
if (($filter['search'] ?? '') !== '') {
|
if (($filter['search'] ?? '') !== '') {
|
||||||
$query->where(fn ($q) => $q->whereLike('name', '%'.$filter['search'].'%')->orWhereLike('reference', '%'.$filter['search'].'%'));
|
$query->where(fn ($q) => $q->whereLike('name', '%'.$filter['search'].'%')->orWhereLike('reference', '%'.$filter['search'].'%'));
|
||||||
}
|
}
|
||||||
if (($filter['status'] ?? 'active') !== 'all') {
|
if (($filter['status'] ?? 'active') !== 'all') {
|
||||||
$query->where('active', ($filter['status'] ?? 'active') === 'active');
|
$query->where('active', ($filter['status'] ?? 'active') === 'active');
|
||||||
}
|
}
|
||||||
$records = $query->orderBy('name')->orderBy('id')->paginate(15)->withQueryString()->through(fn ($row) => $registry->item($request->user(), $row));
|
$records = $query->orderBy('name')->orderBy('id')->paginate(15)->withQueryString()->through(fn ($row) => $registry->item($this->staffIdentity($request), $row));
|
||||||
}
|
}
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('people/registry', ['ready' => $ready, 'canCreate' => $registry->canCreate($request->user()), 'records' => $records, 'filters' => $filter])->toResponse($request);
|
$response = Inertia::render('people/registry', ['ready' => $ready, 'canCreate' => $registry->canCreate($this->staffIdentity($request)), 'records' => $records, 'filters' => $filter])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
return $response;
|
return $response;
|
||||||
@@ -36,7 +36,7 @@ class PeopleRegistryController extends Controller
|
|||||||
public function save(Request $request, PeopleRegistry $registry, ?int $person = null): Response
|
public function save(Request $request, PeopleRegistry $registry, ?int $person = null): Response
|
||||||
{
|
{
|
||||||
abort_unless(Schema::hasTable('people_registry'), 503, 'Instalação do cadastro de pessoas pendente.');
|
abort_unless(Schema::hasTable('people_registry'), 503, 'Instalação do cadastro de pessoas pendente.');
|
||||||
$record = $registry->execute($request->user(), $person, $request->all());
|
$record = $registry->execute($this->staffIdentity($request), $person, $request->all());
|
||||||
|
|
||||||
return redirect('/pessoas/cadastro?'.http_build_query(['search' => $record->reference, 'status' => 'all']));
|
return redirect('/pessoas/cadastro?'.http_build_query(['search' => $record->reference, 'status' => 'all']));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\PeopleProcess;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\PeopleAccess;
|
||||||
|
use App\Services\PeopleApplicationReport;
|
||||||
|
use App\Services\PeopleDeadlineReport;
|
||||||
|
use App\Services\PeopleHiring;
|
||||||
|
use App\Services\PeopleSelectionReport;
|
||||||
|
use App\Services\PeopleWorkdesk;
|
||||||
|
use App\Services\WorkContext;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class PeopleReportController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request): Response
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($request) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$kinds = app(PeopleHiring::class)->kinds($actor);
|
||||||
|
abort_unless($kinds !== [], 403);
|
||||||
|
$filters = $request->validate([
|
||||||
|
'view' => 'nullable|in:processes,applications,selections,deadlines',
|
||||||
|
'deadline_window' => 'nullable|in:all,overdue,today,future,undated',
|
||||||
|
'deadline_page' => 'nullable|integer|min:1|max:100000',
|
||||||
|
'kind' => ['nullable', Rule::in($kinds)], 'status' => ['nullable', Rule::in(PeopleWorkdesk::STATES)],
|
||||||
|
'search' => 'nullable|string|max:100', 'from' => 'nullable|date_format:Y-m-d',
|
||||||
|
'to' => ['nullable', 'date_format:Y-m-d', Rule::when($request->filled('from'), 'after_or_equal:from')],
|
||||||
|
]);
|
||||||
|
$query = app(PeopleAccess::class)->visible(PeopleProcess::query()->whereIn('kind', $kinds), $actor);
|
||||||
|
$clientMode = app(WorkContext::class)->active($request) === 'people.third_party';
|
||||||
|
foreach (['kind', 'status'] as $field) {
|
||||||
|
if (! empty($filters[$field])) {
|
||||||
|
$query->where($field, $filters[$field]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (! empty($filters['search'])) {
|
||||||
|
$search = $filters['search'];
|
||||||
|
$query->where(function ($q) use ($search, $clientMode) {
|
||||||
|
$q->whereLike('title', '%'.$search.'%');
|
||||||
|
if ($clientMode) {
|
||||||
|
$q->orWhere('rules->client->name', 'like', '%'.$search.'%')->orWhere('rules->client->code', 'like', '%'.$search.'%');
|
||||||
|
}
|
||||||
|
if (preg_match('/^(?:PES-)?([1-9][0-9]*)$/D', $search, $matches)) {
|
||||||
|
$id = filter_var($matches[1], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||||
|
if ($id !== false) {
|
||||||
|
$q->orWhere('id', $id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (! empty($filters['from'])) {
|
||||||
|
$query->whereDate('created_at', '>=', $filters['from']);
|
||||||
|
}
|
||||||
|
if (! empty($filters['to'])) {
|
||||||
|
$query->whereDate('created_at', '<=', $filters['to']);
|
||||||
|
}
|
||||||
|
$baseColumns = ['id', 'title', 'kind', 'status', 'closes_on', 'created_at'];
|
||||||
|
$columns = [...$baseColumns, ...($clientMode ? ['rules'] : [])];
|
||||||
|
$displayTitle = static fn (PeopleProcess $process): string => $process->title.($clientMode && isset($process->rules['client']['name']) ? ' · Cliente: '.$process->rules['client']['name'] : '');
|
||||||
|
$page = $request->routeIs('people.reports.csv') ? null : (clone $query)->latest('id')->paginate(25, $columns)->withQueryString();
|
||||||
|
$applications = ($filters['view'] ?? 'processes') === 'applications';
|
||||||
|
$selections = ($filters['view'] ?? 'processes') === 'selections';
|
||||||
|
$deadlines = ($filters['view'] ?? 'processes') === 'deadlines';
|
||||||
|
$deadlineReport = $deadlines ? app(PeopleDeadlineReport::class)->build(clone $query, $actor, $filters['deadline_window'] ?? 'all') : null;
|
||||||
|
if ($deadlineReport !== null && ! $request->routeIs('people.reports.csv')) {
|
||||||
|
$number = (int) ($filters['deadline_page'] ?? 1);
|
||||||
|
$pager = (new LengthAwarePaginator(array_slice($deadlineReport['items'], ($number - 1) * 25, 25), $deadlineReport['total_items'], 25, $number,
|
||||||
|
['path' => $request->url(), 'pageName' => 'deadline_page']))->appends($request->except('deadline_page'));
|
||||||
|
$deadlineReport['items'] = $pager->items();
|
||||||
|
$deadlineReport['pagination'] = ['current_page' => $pager->currentPage(), 'last_page' => $pager->lastPage(), 'prev_page_url' => $pager->previousPageUrl(), 'next_page_url' => $pager->nextPageUrl()];
|
||||||
|
}
|
||||||
|
$metrics = [];
|
||||||
|
if ($applications || $selections) {
|
||||||
|
$metricQuery = clone $query;
|
||||||
|
if ($page !== null) {
|
||||||
|
$metricQuery->whereIn('id', $page->getCollection()->modelKeys());
|
||||||
|
}
|
||||||
|
foreach ($metricQuery->orderBy('id')->lazyById(100) as $process) {
|
||||||
|
$metrics[$process->id] = $applications ? app(PeopleApplicationReport::class)->counts($process, $actor) : app(PeopleSelectionReport::class)->facts($process, $actor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($request->routeIs('people.reports.csv') && $deadlineReport !== null) {
|
||||||
|
$response = $this->deadlineCsv($deadlineReport);
|
||||||
|
} elseif ($request->routeIs('people.reports.csv')) {
|
||||||
|
// Materialise within the read-only snapshot; streaming runs after the transaction.
|
||||||
|
$rows = (clone $query)->orderBy('id')->get($columns);
|
||||||
|
$response = response()->streamDownload(function () use ($rows, $applications, $selections, $metrics, $displayTitle) {
|
||||||
|
$file = fopen('php://output', 'w');
|
||||||
|
if ($file === false) {
|
||||||
|
throw new \RuntimeException('Não foi possível abrir a exportação.');
|
||||||
|
}
|
||||||
|
fwrite($file, "\xEF\xBB\xBF");
|
||||||
|
$extra = ['Registadas para avaliação', 'Avaliação completa', 'Por concluir avaliação', 'Sem avaliação', 'Avaliação em curso', 'Base da avaliação', 'Recebidas no portal', 'Admitidas para análise no portal', 'Não admitidas no portal', 'Triagem pendente'];
|
||||||
|
$selectionColumns = ['Situação da selecção', 'Proposta em', 'Decisão em', 'Pendência', 'Acesso à minuta', 'Referência da minuta', 'Minuta preparada em', 'Início previsto na minuta'];
|
||||||
|
fputcsv($file, ['Referência', 'Título', 'Percurso', 'Estado', 'Fecho de candidaturas', 'Criado em', ...($applications ? $extra : ($selections ? $selectionColumns : []))], ';', '"', '');
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$title = $displayTitle($row);
|
||||||
|
$title = preg_match('/^[\s]*[=+@-]/u', $title) ? "'".$title : $title;
|
||||||
|
$counts = $metrics[$row->id] ?? [];
|
||||||
|
$values = $applications ? array_values(array_map(fn ($value) => $value === null ? 'Sem acesso' : ($value === 'selection_snapshot' ? 'Selecção preservada' : ($value === 'current_eligibility' ? 'Elegibilidade actual' : $value)), $counts)) : [];
|
||||||
|
if ($selections) {
|
||||||
|
$values = array_values(array_map(fn ($value) => $value === null ? 'Não registado' : (is_string($value) && preg_match('/^[\s]*[=+@-]/u', $value) ? "'".$value : $value), $counts));
|
||||||
|
}
|
||||||
|
fputcsv($file, ['PES-'.$row->id, $title, $row->kind === 'service' ? 'Serviços individuais' : 'Recrutamento e selecção', self::states()[$row->status] ?? $row->status, $row->closes_on, $row->created_at?->toDateString(), ...$values], ';', '"', '');
|
||||||
|
}
|
||||||
|
fclose($file);
|
||||||
|
}, 'relatorio-pessoas.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||||
|
} else {
|
||||||
|
$summary = (clone $query)->selectRaw('kind, status, count(*) as total')->groupBy('kind', 'status')->get();
|
||||||
|
$page?->through(fn (PeopleProcess $process) => [...$process->only($baseColumns), 'title' => $displayTitle($process)]);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('people/reports', [
|
||||||
|
'filters' => $filters, 'kinds' => $kinds, 'summary' => $summary,
|
||||||
|
'applicationMetrics' => $applications ? $metrics : [],
|
||||||
|
'selectionMetrics' => $selections ? $metrics : [],
|
||||||
|
'deadlineReport' => $deadlineReport,
|
||||||
|
'generatedAt' => now()->toIso8601String(),
|
||||||
|
'processes' => $page,
|
||||||
|
])->toResponse($request);
|
||||||
|
}
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $report */
|
||||||
|
private function deadlineCsv(array $report): Response
|
||||||
|
{
|
||||||
|
return response()->streamDownload(function () use ($report) {
|
||||||
|
$file = fopen('php://output', 'w');
|
||||||
|
if ($file === false) {
|
||||||
|
throw new \RuntimeException('Não foi possível abrir a exportação.');
|
||||||
|
}
|
||||||
|
fwrite($file, "\xEF\xBB\xBF");
|
||||||
|
fputcsv($file, ['Referência', 'Processo', 'Categoria', 'Intervenção', 'Responsabilidade', 'Prazo', 'Dias de atraso', 'Consulta em', 'Filtro de prazo'], ';', '"', '');
|
||||||
|
$windows = ['all' => 'Todos', 'overdue' => 'Vencidos', 'today' => 'Hoje', 'future' => 'Futuros', 'undated' => 'Sem prazo definido'];
|
||||||
|
foreach ($report['items'] as $item) {
|
||||||
|
$values = [$item['reference'], $item['title'], $item['category'], $item['label'], $item['responsibility'], $item['due_on'] ?? 'Sem prazo definido', $item['days_overdue'] ?? 'Não determinável', $report['as_of'], $windows[$report['window']]];
|
||||||
|
$values = array_map(fn ($value) => is_string($value) && preg_match('/^[\s]*[=+@-]/u', $value) ? "'".$value : $value, $values);
|
||||||
|
fputcsv($file, $values, ';', '"', '');
|
||||||
|
}
|
||||||
|
fclose($file);
|
||||||
|
}, 'relatorio-prazos-pessoas.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,string> */
|
||||||
|
private static function states(): array
|
||||||
|
{
|
||||||
|
return ['draft' => 'Abertura por conferir', 'open' => 'Recepção de candidaturas', 'assessment' => 'Avaliação',
|
||||||
|
'selection_review' => 'Selecção por conferir', 'selected' => 'Selecção aprovada', 'contract_draft' => 'Minuta contratual preparada', 'contract_formalized' => 'Contrato formalizado'];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\PrivateAuditExport;
|
||||||
|
use App\Services\PrivateAuditAccess;
|
||||||
|
use App\Services\PrivateAuditExporter;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class PrivateAuditController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, PrivateAuditAccess $access): Response
|
||||||
|
{
|
||||||
|
$scope = $access->current($this->staffIdentity($request));
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$legacyIds = $access->legacyExportIds($scope['actor'], $scope['context']);
|
||||||
|
$exports = PrivateAuditExport::query()->where('created_by', $scope['actor']->id)
|
||||||
|
->where(fn ($query) => $query->where('work_context', $scope['context'])->orWhereIn('id', $legacyIds))->latest('id')->paginate(20)
|
||||||
|
->through(fn (PrivateAuditExport $export) => ['id' => $export->id, 'families' => $export->families,
|
||||||
|
'created_at' => $export->created_at, 'size' => $export->size, 'sha256' => $export->sha256,
|
||||||
|
'download_url' => '/auditoria/privada/'.$export->id.'/download']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('audit/private', ['families' => collect($scope['granted'])->map(fn (string $key) => ['key' => $key, 'label' => PrivateAuditAccess::FAMILIES[$key]['label']])->values(), 'exports' => $exports])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, PrivateAuditExporter $service): Response
|
||||||
|
{
|
||||||
|
$service->generate($this->staffIdentity($request), $request->all());
|
||||||
|
|
||||||
|
return redirect('/auditoria/privada')->with('success', 'Pacote privado preparado e verificado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function download(Request $request, PrivateAuditExport $export, PrivateAuditExporter $service): Response
|
||||||
|
{
|
||||||
|
$actor = $this->staffIdentity($request);
|
||||||
|
$service->verifiedPath($actor, $export);
|
||||||
|
// Snapshot the verified bytes before any response: a later file change cannot alter the download.
|
||||||
|
$copy = tmpfile();
|
||||||
|
abort_unless(is_resource($copy), 503);
|
||||||
|
try {
|
||||||
|
$source = Storage::disk('local')->readStream($export->path);
|
||||||
|
abort_unless(is_resource($source), 409);
|
||||||
|
try {
|
||||||
|
$size = stream_copy_to_stream($source, $copy);
|
||||||
|
} finally {
|
||||||
|
fclose($source);
|
||||||
|
}
|
||||||
|
rewind($copy);
|
||||||
|
$hash = hash_init('sha256');
|
||||||
|
hash_update_stream($hash, $copy);
|
||||||
|
abort_unless($size === $export->size && hash_equals($export->sha256, hash_final($hash)), 409);
|
||||||
|
$service->verifiedPath($actor, $export);
|
||||||
|
rewind($copy);
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($copy): void {
|
||||||
|
try {
|
||||||
|
fpassthru($copy);
|
||||||
|
} finally {
|
||||||
|
fclose($copy);
|
||||||
|
}
|
||||||
|
}, 'auditoria-'.$export->id.'.zip', ['Content-Type' => 'application/zip', 'Content-Length' => (string) $export->size,
|
||||||
|
'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
|
||||||
|
} catch (\Throwable $error) {
|
||||||
|
fclose($copy);
|
||||||
|
throw $error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,17 +8,31 @@ use App\Models\PurchaseOrder;
|
|||||||
use App\Models\Quotation;
|
use App\Models\Quotation;
|
||||||
use App\Models\Requisition;
|
use App\Models\Requisition;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
|
use App\Services\ProcurementContractInsights;
|
||||||
|
use App\Services\ProcurementDeliveryInsights;
|
||||||
use App\Services\ProcurementOperationalInsights;
|
use App\Services\ProcurementOperationalInsights;
|
||||||
|
use App\Services\ProcurementPayableInsights;
|
||||||
|
use App\Services\ProcurementPaymentInsights;
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class ProcurementReportController extends Controller
|
class ProcurementReportController extends Controller
|
||||||
{
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
private function snapshot(\Closure $read): mixed
|
private function snapshot(\Closure $read): mixed
|
||||||
{
|
{
|
||||||
if (DB::connection()->getDriverName() === 'pgsql' && DB::transactionLevel() !== 0) {
|
if (DB::connection()->getDriverName() === 'pgsql' && DB::transactionLevel() !== 0) {
|
||||||
@@ -37,8 +51,10 @@ class ProcurementReportController extends Controller
|
|||||||
/** @return array<string,mixed> */
|
/** @return array<string,mixed> */
|
||||||
private function filters(Request $request): array
|
private function filters(Request $request): array
|
||||||
{
|
{
|
||||||
$actor = User::query()->findOrFail($request->user()->id);
|
$current = $request->user('web');
|
||||||
abort_unless($actor->tenant_id === $request->user()->tenant_id && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
abort_unless($current instanceof User, 403);
|
||||||
|
$actor = User::query()->where('tenant_id', $current->tenant_id)->findOrFail($current->id);
|
||||||
|
abort_unless(! app(OrganizationAccess::class)->maintenanceOnly($actor) && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||||
$request->setUserResolver(fn () => $actor);
|
$request->setUserResolver(fn () => $actor);
|
||||||
|
|
||||||
$filters = $request->validate([
|
$filters = $request->validate([
|
||||||
@@ -47,6 +63,11 @@ class ProcurementReportController extends Controller
|
|||||||
'from' => 'nullable|date_format:Y-m-d',
|
'from' => 'nullable|date_format:Y-m-d',
|
||||||
'to' => 'nullable|date_format:Y-m-d',
|
'to' => 'nullable|date_format:Y-m-d',
|
||||||
'department_id' => 'nullable|integer|min:1',
|
'department_id' => 'nullable|integer|min:1',
|
||||||
|
'attention' => 'nullable|in:unapproved_needed,approved_without_quotes,approved_without_order',
|
||||||
|
'supplier_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'category_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'delivery_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'delivery_state' => 'nullable|in:attention,all,pending_late,pending,partial_late,completed_late,completed_on_time,unknown',
|
||||||
]);
|
]);
|
||||||
if (! empty($filters['from']) && ! empty($filters['to']) && $filters['from'] > $filters['to']) {
|
if (! empty($filters['from']) && ! empty($filters['to']) && $filters['from'] > $filters['to']) {
|
||||||
throw ValidationException::withMessages(['to' => 'A data final deve ser igual ou posterior à data inicial.']);
|
throw ValidationException::withMessages(['to' => 'A data final deve ser igual ou posterior à data inicial.']);
|
||||||
@@ -55,10 +76,31 @@ class ProcurementReportController extends Controller
|
|||||||
return $filters;
|
return $filters;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return Builder<Quotation> */
|
||||||
|
private function registeredQuotes(): Builder
|
||||||
|
{
|
||||||
|
return Quotation::query()->whereColumn('quotations.requisition_id', 'requisitions.id');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return Builder<PurchaseOrder> */
|
||||||
|
private function visibleOrders(User $actor): Builder
|
||||||
|
{
|
||||||
|
return PurchaseOrder::query()->visibleTo($actor)->where(function ($orders) {
|
||||||
|
$orders->whereColumn('purchase_orders.requisition_id', 'requisitions.id');
|
||||||
|
if (Schema::hasTable('purchase_order_sources') && Schema::hasColumn('purchase_orders', 'order_key')) {
|
||||||
|
$orders->orWhere(function ($parts) {
|
||||||
|
$parts->whereNotNull('purchase_orders.order_key')->whereExists(fn ($source) => $source->selectRaw('1')
|
||||||
|
->from('purchase_order_sources as report_origin')->whereColumn('report_origin.purchase_order_id', 'purchase_orders.id')
|
||||||
|
->whereColumn('report_origin.tenant_id', 'purchase_orders.tenant_id')->whereColumn('report_origin.requisition_id', 'requisitions.id'));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** @param array<string,mixed> $filters
|
/** @param array<string,mixed> $filters
|
||||||
* @return Builder<Requisition>
|
* @return Builder<Requisition>
|
||||||
*/
|
*/
|
||||||
private function query(User $actor, array $filters): Builder
|
private function query(User $actor, array $filters, string $today): Builder
|
||||||
{
|
{
|
||||||
$query = Requisition::query()->where('tenant_id', $actor->tenant_id)->visibleTo($actor);
|
$query = Requisition::query()->where('tenant_id', $actor->tenant_id)->visibleTo($actor);
|
||||||
if (isset($filters['search']) && $filters['search'] !== '') {
|
if (isset($filters['search']) && $filters['search'] !== '') {
|
||||||
@@ -69,6 +111,15 @@ class ProcurementReportController extends Controller
|
|||||||
$query->where($field, $filters[$field]);
|
$query->where($field, $filters[$field]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (($filters['attention'] ?? '') === 'unapproved_needed') {
|
||||||
|
$query->whereIn('status', ['draft', 'pending'])->whereDate('needed_by', '<', $today);
|
||||||
|
}
|
||||||
|
if (($filters['attention'] ?? '') === 'approved_without_quotes') {
|
||||||
|
$query->where('status', 'approved')->whereNotExists($this->registeredQuotes()->selectRaw('1'));
|
||||||
|
}
|
||||||
|
if (($filters['attention'] ?? '') === 'approved_without_order') {
|
||||||
|
$query->where('status', 'approved')->whereNotExists($this->visibleOrders($actor)->selectRaw('1'));
|
||||||
|
}
|
||||||
if (! empty($filters['from'])) {
|
if (! empty($filters['from'])) {
|
||||||
$query->where('created_at', '>=', $filters['from'].' 00:00:00');
|
$query->where('created_at', '>=', $filters['from'].' 00:00:00');
|
||||||
}
|
}
|
||||||
@@ -82,11 +133,11 @@ class ProcurementReportController extends Controller
|
|||||||
/** @param Builder<Requisition> $query
|
/** @param Builder<Requisition> $query
|
||||||
* @return Builder<Requisition>
|
* @return Builder<Requisition>
|
||||||
*/
|
*/
|
||||||
private function records(Builder $query): Builder
|
private function records(Builder $query, User $actor): Builder
|
||||||
{
|
{
|
||||||
return $query->select('requisitions.*')->with(['department:id,name', 'requester:id,name'])->addSelect([
|
return $query->select('requisitions.*')->with(['department:id,name', 'requester:id,name'])->addSelect([
|
||||||
'quotations_count' => Quotation::query()->selectRaw('COUNT(*)')->whereColumn('requisition_id', 'requisitions.id'),
|
'quotations_count' => $this->registeredQuotes()->selectRaw('COUNT(*)'),
|
||||||
'order_number' => PurchaseOrder::query()->visibleTo(request()->user())->select('number')->whereColumn('requisition_id', 'requisitions.id')->orderBy('id')->limit(1),
|
'order_number' => $this->visibleOrders($actor)->select('number')->orderBy('id')->limit(1),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,8 +147,9 @@ class ProcurementReportController extends Controller
|
|||||||
return [
|
return [
|
||||||
'id' => $record->id, 'number' => $record->number, 'status' => $record->status,
|
'id' => $record->id, 'number' => $record->number, 'status' => $record->status,
|
||||||
'created_at' => $record->created_at?->toIso8601String(),
|
'created_at' => $record->created_at?->toIso8601String(),
|
||||||
|
'needed_by' => $record->needed_by?->toDateString(),
|
||||||
'department' => $record->department?->name, 'requester' => $record->requester?->name,
|
'department' => $record->department?->name, 'requester' => $record->requester?->name,
|
||||||
'total_minor' => (string) $record->total_minor,
|
'total_minor' => $record->total_minor === null ? null : (string) $record->total_minor,
|
||||||
'quotations_count' => (int) $record->getAttribute('quotations_count'),
|
'quotations_count' => (int) $record->getAttribute('quotations_count'),
|
||||||
'order_number' => $record->getAttribute('order_number'),
|
'order_number' => $record->getAttribute('order_number'),
|
||||||
];
|
];
|
||||||
@@ -106,16 +158,24 @@ class ProcurementReportController extends Controller
|
|||||||
public function index(Request $request): Response
|
public function index(Request $request): Response
|
||||||
{
|
{
|
||||||
$props = $this->snapshot(function () use ($request): array {
|
$props = $this->snapshot(function () use ($request): array {
|
||||||
|
$instant = CarbonImmutable::now(config('app.timezone'));
|
||||||
$filters = $this->filters($request);
|
$filters = $this->filters($request);
|
||||||
$query = $this->query($request->user(), $filters);
|
$actor = $this->actor($request);
|
||||||
|
$query = $this->query($actor, $filters, $instant->toDateString());
|
||||||
$counts = (clone $query)->selectRaw('status, COUNT(*) AS count')->groupBy('status')->pluck('count', 'status')->map(fn ($value) => (int) $value);
|
$counts = (clone $query)->selectRaw('status, COUNT(*) AS count')->groupBy('status')->pluck('count', 'status')->map(fn ($value) => (int) $value);
|
||||||
$records = $this->records(clone $query)->orderByDesc('id')->paginate(25)->withQueryString()->through(fn (Requisition $record) => $this->row($record));
|
$records = $this->records(clone $query, $actor)->orderByDesc('id')->paginate(25)->withQueryString()->through(fn (Requisition $record) => $this->row($record));
|
||||||
$departments = Department::query()->when($request->user()->departmentScoped(), fn ($q) => $q->whereKey($request->user()->department_id))->orderBy('name')->get(['id', 'name']);
|
$departments = Department::query()->when($actor->departmentScoped(), fn ($q) => $q->whereKey($actor->department_id))->orderBy('name')->get(['id', 'name']);
|
||||||
|
|
||||||
$instant = CarbonImmutable::now();
|
$insights = app(ProcurementOperationalInsights::class)->build($this->records(clone $query, $actor), $instant);
|
||||||
$insights = app(ProcurementOperationalInsights::class)->build($this->records(clone $query), $instant);
|
|
||||||
|
|
||||||
return ['records' => $records, 'counts' => $counts, 'filters' => $filters, 'departments' => $departments, 'generatedAt' => $instant->toIso8601String(), 'insights' => $insights];
|
return ['records' => $records, 'counts' => $counts, 'filters' => $filters, 'departments' => $departments, 'generatedAt' => $instant->toIso8601String(), 'insights' => $insights,
|
||||||
|
'contractInsights' => app(ProcurementContractInsights::class)->build($actor, clone $query),
|
||||||
|
'deliveryInsights' => app(ProcurementDeliveryInsights::class)->build($actor, clone $query, $instant,
|
||||||
|
(int) ($filters['delivery_page'] ?? 1), $filters['delivery_state'] ?? 'attention'),
|
||||||
|
'payableInsights' => app(ProcurementPayableInsights::class)->build($actor, clone $query),
|
||||||
|
'paymentInsights' => app(ProcurementPaymentInsights::class)->build($actor,
|
||||||
|
$this->query($actor, array_diff_key($filters, array_flip(['from', 'to'])), $instant->toDateString()),
|
||||||
|
$filters['from'] ?? null, $filters['to'] ?? null, (int) ($filters['supplier_page'] ?? 1), (int) ($filters['category_page'] ?? 1))];
|
||||||
});
|
});
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
@@ -125,25 +185,169 @@ class ProcurementReportController extends Controller
|
|||||||
return $response;
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function exportPositions(Request $request): Response
|
||||||
|
{
|
||||||
|
$data = $this->snapshot(function () use ($request): array {
|
||||||
|
$instant = CarbonImmutable::now(config('app.timezone'));
|
||||||
|
$filters = $this->filters($request);
|
||||||
|
$actor = $this->actor($request);
|
||||||
|
$positions = app(ProcurementPayableInsights::class)->build($actor, $this->query($actor, $filters, $instant->toDateString()));
|
||||||
|
abort_unless($positions !== null, 403);
|
||||||
|
|
||||||
|
return ['positions' => $positions, 'filters' => $filters, 'generated_at' => $instant->toIso8601String()];
|
||||||
|
});
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($data) {
|
||||||
|
$output = fopen('php://output', 'w');
|
||||||
|
if ($output === false) {
|
||||||
|
throw new \RuntimeException('Não foi possível gerar a posição financeira.');
|
||||||
|
}
|
||||||
|
fwrite($output, "\xEF\xBB\xBF");
|
||||||
|
fputcsv($output, ['Posição actual das obrigações', 'Gerado em', $data['generated_at']], ';', '"', '');
|
||||||
|
fputcsv($output, ['Filtros dos pedidos (data de criação)', json_encode($data['filters'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)], ';', '"', '');
|
||||||
|
fputcsv($output, ['Âmbito documental', 'Cada factura conta uma vez se alguma origem corresponder aos filtros; posição integral sem repartição por pedido.'], ';', '"', '');
|
||||||
|
fputcsv($output, ['Facturas autorizadas', 'Reconhecidas e determinadas', 'Por reconhecer', 'Posição indeterminada'], ';', '"', '');
|
||||||
|
$coverage = $data['positions']['coverage'];
|
||||||
|
fputcsv($output, [$coverage['invoices'], $coverage['recognised'], $coverage['unrecognised'], $coverage['indeterminate']], ';', '"', '');
|
||||||
|
fputcsv($output, ['Moeda', 'Obrigações determinadas', 'Principal (centavos)', 'Histórico conferido (centavos)', 'Liquidações imputadas (centavos)', 'Saldo actual (centavos)'], ';', '"', '');
|
||||||
|
foreach ($data['positions']['currencies'] as $row) {
|
||||||
|
fputcsv($output, [$row['currency'], $row['count'], $row['principal_minor'], $row['confirmed_payments_minor'], $row['allocated_payments_minor'], $row['balance_minor']], ';', '"', '');
|
||||||
|
}
|
||||||
|
fclose($output);
|
||||||
|
}, 'posicao-obrigacoes-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function exportPayments(Request $request): Response
|
||||||
|
{
|
||||||
|
$data = $this->snapshot(function () use ($request): array {
|
||||||
|
$instant = CarbonImmutable::now(config('app.timezone'));
|
||||||
|
$filters = $this->filters($request);
|
||||||
|
$actor = $this->actor($request);
|
||||||
|
$payments = app(ProcurementPaymentInsights::class)->build($actor,
|
||||||
|
$this->query($actor, array_diff_key($filters, array_flip(['from', 'to'])), $instant->toDateString()),
|
||||||
|
$filters['from'] ?? null, $filters['to'] ?? null, null, null);
|
||||||
|
abort_unless($payments !== null, 403);
|
||||||
|
|
||||||
|
return ['payments' => $payments, 'generated_at' => $instant->toIso8601String()];
|
||||||
|
});
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($data) {
|
||||||
|
$output = fopen('php://output', 'w');
|
||||||
|
if ($output === false) {
|
||||||
|
throw new \RuntimeException('Não foi possível exportar a despesa.');
|
||||||
|
}
|
||||||
|
fwrite($output, "\xEF\xBB\xBF");
|
||||||
|
$payments = $data['payments'];
|
||||||
|
fputcsv($output, ['Pagamentos externos confirmados pela data de confirmação', 'Gerado em', $data['generated_at']], ';', '"', '');
|
||||||
|
fputcsv($output, ['Confirmação desde', $payments['from'] ?? '', 'Até (inclusive)', $payments['to'] ?? ''], ';', '"', '');
|
||||||
|
fputcsv($output, ['Âmbito documental', 'Cada factura conta uma vez se alguma origem corresponder aos filtros; pagamentos integrais sem repartição por pedido.'], ';', '"', '');
|
||||||
|
fputcsv($output, ['Facturas no âmbito', 'Históricos indeterminados excluídos', 'Pagamentos confirmados determinados'], ';', '"', '');
|
||||||
|
fputcsv($output, array_values($payments['coverage']), ';', '"', '');
|
||||||
|
fputcsv($output, ['Moeda', 'Pagamentos', 'Despesa (centavos)'], ';', '"', '');
|
||||||
|
foreach ($payments['currencies'] as $row) {
|
||||||
|
fputcsv($output, [$row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
|
||||||
|
}
|
||||||
|
fputcsv($output, ['Fornecedor (identificador)', 'Nome conservado na factura', 'Moeda', 'Pagamentos', 'Despesa (centavos)'], ';', '"', '');
|
||||||
|
foreach ($payments['suppliers']['data'] as $row) {
|
||||||
|
$name = preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', $row['supplier_name']) ? "'".$row['supplier_name'] : $row['supplier_name'];
|
||||||
|
fputcsv($output, [$row['supplier_id'], $name, $row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
|
||||||
|
}
|
||||||
|
fputcsv($output, ['Categoria (imputação explícita de Finanças)', 'Moeda', 'Imputações', 'Despesa (centavos)'], ';', '"', '');
|
||||||
|
foreach ($payments['category_attribution']['groups']['data'] as $row) {
|
||||||
|
$category = preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', $row['category']) ? "'".$row['category'] : $row['category'];
|
||||||
|
fputcsv($output, [$category, $row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
|
||||||
|
}
|
||||||
|
fputcsv($output, ['Imputação pendente', 'Moeda', 'Pagamentos', 'Montante (centavos)'], ';', '"', '');
|
||||||
|
foreach ($payments['category_attribution']['unassigned'] as $row) {
|
||||||
|
fputcsv($output, [$row['state'] === 'unallocated' ? 'Não imputada' : 'Imputação indeterminada', $row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
|
||||||
|
}
|
||||||
|
fclose($output);
|
||||||
|
}, 'despesa-confirmada-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function exportContracts(Request $request): Response
|
||||||
|
{
|
||||||
|
$data = $this->snapshot(function () use ($request): array {
|
||||||
|
$instant = CarbonImmutable::now(config('app.timezone'));
|
||||||
|
$filters = $this->filters($request);
|
||||||
|
|
||||||
|
return ['generated_at' => $instant->toIso8601String(), 'filters' => $filters,
|
||||||
|
'contracts' => app(ProcurementContractInsights::class)->build($this->actor($request), $this->query($this->actor($request), $filters, $instant->toDateString()))];
|
||||||
|
});
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($data) {
|
||||||
|
$output = fopen('php://output', 'w');
|
||||||
|
if ($output === false) {
|
||||||
|
throw new \RuntimeException('Não foi possível exportar as associações contratuais.');
|
||||||
|
}
|
||||||
|
fwrite($output, "\xEF\xBB\xBF");
|
||||||
|
fputcsv($output, ['Associação contratual conservada na emissão', 'Gerado em', $data['generated_at']], ';', '"', '');
|
||||||
|
fputcsv($output, ['Base', 'Ordens operacionais visíveis; montantes integrais das ordens, não pagamentos; não certifica conformidade.'], ';', '"', '');
|
||||||
|
fputcsv($output, ['Filtros dos pedidos (data de criação)', json_encode($data['filters'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)], ';', '"', '');
|
||||||
|
fputcsv($output, ['Classificação', 'Moeda', 'Ordens', 'Montante (centavos)'], ';', '"', '');
|
||||||
|
foreach ($data['contracts']['currencies'] as $row) {
|
||||||
|
fputcsv($output, [ProcurementContractInsights::LABELS[$row['classification']], $row['currency'] ?? 'Indeterminada', $row['count'], $row['amount_minor'] ?? 'Indeterminado'], ';', '"', '');
|
||||||
|
}
|
||||||
|
fclose($output);
|
||||||
|
}, 'associacoes-contratuais-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function exportDeliveries(Request $request): Response
|
||||||
|
{
|
||||||
|
$data = $this->snapshot(function () use ($request): array {
|
||||||
|
$instant = CarbonImmutable::now(config('app.timezone'));
|
||||||
|
$filters = $this->filters($request);
|
||||||
|
|
||||||
|
return ['filters' => $filters, 'deliveries' => app(ProcurementDeliveryInsights::class)->build($this->actor($request),
|
||||||
|
$this->query($this->actor($request), $filters, $instant->toDateString()), $instant, null, $filters['delivery_state'] ?? 'attention')];
|
||||||
|
});
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($data) {
|
||||||
|
$output = fopen('php://output', 'w');
|
||||||
|
if ($output === false) {
|
||||||
|
throw new \RuntimeException('Não foi possível exportar o acompanhamento de entregas.');
|
||||||
|
}
|
||||||
|
fwrite($output, "\xEF\xBB\xBF");
|
||||||
|
$write = static function (array $cells) use ($output): void {
|
||||||
|
fputcsv($output, array_map(fn ($cell) => preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', (string) $cell) ? "'".$cell : $cell, $cells), ';', '"', '');
|
||||||
|
};
|
||||||
|
$write(['Entregas documentadas face às datas acordadas na ordem', 'Gerado em', $data['deliveries']['generated_at']]);
|
||||||
|
$write(['Filtros dos pedidos (data de criação)', json_encode($data['filters'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)]);
|
||||||
|
$write(['Base', 'Recepções nativas não estornadas, por origem; datas desconhecidas ficam por determinar; não certifica qualidade ou culpa do fornecedor.']);
|
||||||
|
$write(['Ordem', 'Situação', 'Linhas por receber', 'Linhas indeterminadas', 'Maior atraso documentado (dias)']);
|
||||||
|
foreach ($data['deliveries']['records']['data'] as $row) {
|
||||||
|
$write([$row['number'], ProcurementDeliveryInsights::LABELS[$row['state']], $row['pending_lines'], $row['unknown_lines'], $row['late_days'] ?? 'Indeterminado']);
|
||||||
|
foreach ($row['late_lines'] as $line) {
|
||||||
|
$write(['Linha', $line['description'], 'Data acordada', $line['promised_on'], 'Recepção integral documentada', $line['completed_on'] ?? 'Por completar',
|
||||||
|
'Quantidade por receber', $line['pending_quantity'], $line['unit']]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fclose($output);
|
||||||
|
}, 'entregas-compras-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||||
|
}
|
||||||
|
|
||||||
public function export(Request $request): Response
|
public function export(Request $request): Response
|
||||||
{
|
{
|
||||||
$filters = $this->filters($request);
|
$this->filters($request);
|
||||||
$query = $this->records($this->query($request->user(), $filters));
|
|
||||||
$text = fn (?string $value) => preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', $value ?? '') ? "'".$value : ($value ?? '');
|
$text = fn (?string $value) => preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', $value ?? '') ? "'".$value : ($value ?? '');
|
||||||
|
|
||||||
return response()->streamDownload(fn () => $this->snapshot(function () use ($query, $text, $filters) {
|
return response()->streamDownload(fn () => $this->snapshot(function () use ($request, $text) {
|
||||||
|
$instant = CarbonImmutable::now(config('app.timezone'));
|
||||||
|
$filters = $this->filters($request);
|
||||||
|
$actor = $this->actor($request);
|
||||||
|
$query = $this->records($this->query($actor, $filters, $instant->toDateString()), $actor);
|
||||||
$output = fopen('php://output', 'w');
|
$output = fopen('php://output', 'w');
|
||||||
if ($output === false) {
|
if ($output === false) {
|
||||||
throw new \RuntimeException('Não foi possível gerar o ficheiro.');
|
throw new \RuntimeException('Não foi possível gerar o ficheiro.');
|
||||||
}
|
}
|
||||||
fwrite($output, "\xEF\xBB\xBF");
|
fwrite($output, "\xEF\xBB\xBF");
|
||||||
fputcsv($output, ['Relatório de compras', 'Criado em', now()->toIso8601String()], ';', '"', '');
|
fputcsv($output, ['Relatório de compras', 'Criado em', $instant->toIso8601String()], ';', '"', '');
|
||||||
fputcsv($output, ['Filtros', $text(json_encode($filters, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR))], ';', '"', '');
|
fputcsv($output, ['Filtros', $text(json_encode($filters, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR))], ';', '"', '');
|
||||||
fputcsv($output, ['Requisição', 'Criada em', 'Departamento', 'Solicitante', 'Estado da requisição', 'Estimativa total (centavos MZN)', 'Propostas registadas', 'Ordem de compra', 'Processo', 'Relatório de conferência'], ';', '"', '');
|
fputcsv($output, ['Requisição', 'Criada em', 'Departamento', 'Solicitante', 'Estado da requisição', 'Estimativa total (centavos MZN)', 'Propostas registadas', 'Ordem de compra', 'Processo', 'Relatório de conferência', 'Data de necessidade'], ';', '"', '');
|
||||||
foreach ($query->lazyById(200) as $record) {
|
foreach ($query->lazyById(200) as $record) {
|
||||||
$row = $this->row($record);
|
$row = $this->row($record);
|
||||||
$base = url('/requisicoes/'.$record->id);
|
$base = url('/requisicoes/'.$record->id);
|
||||||
fputcsv($output, [$text($record->number), $row['created_at'], $text($row['department']), $text($row['requester']), $record->status, $row['total_minor'], $row['quotations_count'], $text($row['order_number']), $base.'/processo', $base.'/relatorio'], ';', '"', '');
|
fputcsv($output, [$text($record->number), $row['created_at'], $text($row['department']), $text($row['requester']), $record->status, $row['total_minor'] ?? 'Por completar', $row['quotations_count'], $text($row['order_number']), $base.'/processo', $base.'/relatorio', $row['needed_by']], ';', '"', '');
|
||||||
}
|
}
|
||||||
fclose($output);
|
fclose($output);
|
||||||
}), 'relatorio-compras-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
}), 'relatorio-compras-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Models\Requisition;
|
use App\Models\Requisition;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
use App\Services\AiPreparationPlan;
|
use App\Services\AiPreparationPlan;
|
||||||
use App\Services\IntelligencePolicy;
|
use App\Services\IntelligencePolicy;
|
||||||
use App\Services\ProcurementEvidenceBrief;
|
use App\Services\ProcurementEvidenceBrief;
|
||||||
|
use App\Services\ProcurementReviewCsv;
|
||||||
use App\Services\ProcurementReviewReport;
|
use App\Services\ProcurementReviewReport;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
@@ -14,11 +16,27 @@ use Symfony\Component\HttpFoundation\Response;
|
|||||||
|
|
||||||
class ProcurementReviewReportController extends Controller
|
class ProcurementReviewReportController extends Controller
|
||||||
{
|
{
|
||||||
|
public function csv(Request $request, Requisition $requisition, ProcurementReviewReport $builder, ProcurementReviewCsv $csv): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$report = $builder->build($actor, $requisition->id);
|
||||||
|
|
||||||
|
return response($csv->render($report), 200, [
|
||||||
|
'Content-Type' => 'text/csv; charset=UTF-8',
|
||||||
|
'Content-Disposition' => 'attachment; filename="conferencia-requisicao-'.$requisition->id.'.csv"',
|
||||||
|
'Cache-Control' => 'private, no-store, max-age=0',
|
||||||
|
'X-Content-Type-Options' => 'nosniff',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
public function show(Request $request, Requisition $requisition, ProcurementReviewReport $builder): Response
|
public function show(Request $request, Requisition $requisition, ProcurementReviewReport $builder): Response
|
||||||
{
|
{
|
||||||
$report = $builder->build($request->user(), $requisition->id);
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$report = $builder->build($actor, $requisition->id);
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$company = Tenant::query()->findOrFail($request->user()->tenant_id);
|
$company = Tenant::query()->findOrFail($actor->tenant_id);
|
||||||
$policy = app(IntelligencePolicy::class)->company($company);
|
$policy = app(IntelligencePolicy::class)->company($company);
|
||||||
$brief = app(ProcurementEvidenceBrief::class)->build($report);
|
$brief = app(ProcurementEvidenceBrief::class)->build($report);
|
||||||
$response = Inertia::render('purchases/review-report', ['report' => $report, 'brief' => $policy['procurement_brief'] ? $brief : null,
|
$response = Inertia::render('purchases/review-report', ['report' => $report, 'brief' => $policy['procurement_brief'] ? $brief : null,
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\Equipment;
|
||||||
|
use App\Models\GoodsReceipt;
|
||||||
|
use App\Models\Invoice;
|
||||||
|
use App\Models\PurchaseOrder;
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\StockItem;
|
||||||
|
use App\Models\Supplier;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Models\Warehouse;
|
||||||
|
use App\Services\AgreementOrderLimits;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
|
use App\Services\OperationalOrders;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
|
use App\Services\SavedProcurementSearches;
|
||||||
|
use App\Services\SupplyPlanning;
|
||||||
|
use App\Services\WarehouseWorkdesk;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Gate;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class ProcurementSearchController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request): Response
|
||||||
|
{
|
||||||
|
$identity = $request->user('web');
|
||||||
|
abort_unless($identity instanceof User && $identity->tenant_id !== null, 403);
|
||||||
|
$actor = User::query()->where('tenant_id', $identity->tenant_id)->findOrFail($identity->id);
|
||||||
|
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||||
|
abort_unless(app(OrganizationAccess::class)->permissions($actor) !== [], 403);
|
||||||
|
$request->setUserResolver(fn () => $actor);
|
||||||
|
$data = $request->validate(['q' => 'nullable|string|max:100', 'archived_page' => 'nullable|integer|min:1|max:1000000', 'requests_page' => 'nullable|integer|min:1|max:1000000', 'orders_page' => 'nullable|integer|min:1|max:1000000', 'suppliers_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$term = trim($data['q'] ?? '');
|
||||||
|
$request->validate(['invoices_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$request->validate(['agreements_page' => 'nullable|integer|min:1|max:1000000', 'contracts_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$request->validate(['warehouse_requests_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$planning = app(SupplyPlanning::class);
|
||||||
|
$supplySelectors = match (DB::getDriverName()) {
|
||||||
|
'pgsql' => ['LOWER("data"->>\'reference\') LIKE ? ESCAPE \'!\'', 'LOWER("snapshot"->\'supplier\'->>\'name\') LIKE ? ESCAPE \'!\''],
|
||||||
|
'sqlite' => ["LOWER(json_extract(data, '$.reference')) LIKE ? ESCAPE '!'", "LOWER(json_extract(snapshot, '$.supplier.name')) LIKE ? ESCAPE '!'"],
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
$supplySearchAvailable = config('procurement_search.supply_metadata_enabled') === true && Schema::hasTable('supply_records')
|
||||||
|
&& $supplySelectors !== null
|
||||||
|
&& collect(['supply_read', 'supply_prepare', 'supply_review'])->contains(fn ($permission) => $planning->allows($actor, $permission));
|
||||||
|
$warehouseSelectors = match (DB::getDriverName()) {
|
||||||
|
'pgsql' => ['LOWER("snapshot"->>\'destination\') LIKE ? ESCAPE \'!\'', 'LOWER("snapshot"->\'requester\'->>\'name\') LIKE ? ESCAPE \'!\''],
|
||||||
|
'sqlite' => ["LOWER(json_extract(snapshot, '$.destination')) LIKE ? ESCAPE '!'", "LOWER(json_extract(snapshot, '$.requester.name')) LIKE ? ESCAPE '!'"],
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
$warehouseRequestSearchAvailable = config('procurement_search.warehouse_requests_metadata_enabled') === true
|
||||||
|
&& $warehouseSelectors !== null && Schema::hasTable('warehouse_requests')
|
||||||
|
&& $actor->hasFunctions(['admin', 'warehouse_request_read', 'warehouse_request_prepare', 'warehouse_request_review', 'warehouse_request_deliver']);
|
||||||
|
$capitalQuery = app(CapitalRegister::class)->searchQuery($actor);
|
||||||
|
$operationalQuery = app(OperationalOrders::class)->searchQuery($actor);
|
||||||
|
$request->validate(['capital_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$request->validate(['operational_orders_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$request->validate(['equipment_page' => 'nullable|integer|min:1|max:1000000', 'stock_page' => 'nullable|integer|min:1|max:1000000', 'warehouses_page' => 'nullable|integer|min:1|max:1000000', 'receipts_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$groups = DB::transaction(function () use ($actor, $term, $planning, $supplySearchAvailable, $supplySelectors, $warehouseRequestSearchAvailable, $warehouseSelectors, $capitalQuery, $operationalQuery) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
if (mb_strlen($term) < 2) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
// Treat wildcard characters as text; never expand a term into an unrestricted match.
|
||||||
|
$pattern = '%'.str_replace(['!', '%', '_'], ['!!', '!%', '!_'], mb_strtolower($term)).'%';
|
||||||
|
$requests = Requisition::query()->visibleTo($actor)->where(function ($query) use ($pattern) {
|
||||||
|
$query->whereRaw("LOWER(number) LIKE ? ESCAPE '!'", [$pattern])->orWhereRaw("LOWER(justification) LIKE ? ESCAPE '!'", [$pattern]);
|
||||||
|
})->latest('id')->paginate(15, ['id', 'number', 'status'], 'requests_page')->withQueryString()
|
||||||
|
->through(fn ($row) => ['id' => $row->id, 'title' => $row->number, 'detail' => $row->status, 'href' => '/requisicoes/'.$row->id]);
|
||||||
|
$groups = [['key' => 'requests', 'title' => 'Requisições', 'records' => $requests]];
|
||||||
|
if ($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead])) {
|
||||||
|
$orders = PurchaseOrder::query()->visibleTo($actor)->whereRaw("LOWER(number) LIKE ? ESCAPE '!'", [$pattern])->latest('id')
|
||||||
|
->paginate(15, ['id', 'number', 'status'], 'orders_page')->withQueryString()
|
||||||
|
->through(fn ($row) => ['id' => $row->id, 'title' => $row->number, 'detail' => $row->status, 'href' => '/ordens/'.$row->id]);
|
||||||
|
$groups[] = ['key' => 'orders', 'title' => 'Ordens', 'records' => $orders];
|
||||||
|
}
|
||||||
|
if (Gate::forUser($actor)->allows('viewAny', Supplier::class)) {
|
||||||
|
$suppliers = Supplier::query()->where(function ($query) use ($pattern) {
|
||||||
|
$query->whereRaw("LOWER(name) LIKE ? ESCAPE '!'", [$pattern])->orWhereRaw("LOWER(nuit) LIKE ? ESCAPE '!'", [$pattern]);
|
||||||
|
})->latest('id')->paginate(15, ['id', 'name', 'status'], 'suppliers_page')->withQueryString()
|
||||||
|
->through(fn ($row) => ['id' => $row->id, 'title' => $row->name, 'detail' => $row->status, 'href' => '/fornecedores/'.$row->id]);
|
||||||
|
$groups[] = ['key' => 'suppliers', 'title' => 'Fornecedores', 'records' => $suppliers];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead])) {
|
||||||
|
$equipment = Equipment::query()->when($actor->departmentScoped(), fn ($query) => $query->where('department_id', $actor->department_id))
|
||||||
|
->where(fn ($query) => $query->whereRaw("LOWER(code) LIKE ? ESCAPE '!'", [$pattern])->orWhereRaw("LOWER(description) LIKE ? ESCAPE '!'", [$pattern]))
|
||||||
|
->latest('id')->paginate(15, ['id', 'code', 'description'], 'equipment_page')->withQueryString()
|
||||||
|
->through(fn ($row) => ['id' => $row->id, 'title' => $row->code.' · '.$row->description, 'detail' => 'Equipamento', 'href' => '/equipamentos/'.$row->id]);
|
||||||
|
$groups[] = ['key' => 'equipment', 'title' => 'Equipamentos', 'records' => $equipment];
|
||||||
|
}
|
||||||
|
if ($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance])) {
|
||||||
|
foreach (['stock' => [StockItem::class, 'Artigos de stock'], 'warehouses' => [Warehouse::class, 'Armazéns']] as $key => [$model, $label]) {
|
||||||
|
$records = $model::query()->where(fn ($query) => $query->whereRaw("LOWER(code) LIKE ? ESCAPE '!'", [$pattern])->orWhereRaw("LOWER(name) LIKE ? ESCAPE '!'", [$pattern]))
|
||||||
|
->latest('id')->paginate(15, ['id', 'code', 'name'], $key.'_page')->withQueryString()
|
||||||
|
->through(fn ($row) => ['id' => $row->id, 'title' => $row->code.' · '.$row->name, 'detail' => $label,
|
||||||
|
'href' => $key === 'stock' ? '/stock?search='.rawurlencode($row->code) : '/stock?warehouse_id='.$row->id]);
|
||||||
|
$groups[] = ['key' => $key, 'title' => $label, 'records' => $records];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Gate::forUser($actor)->allows('viewAny', GoodsReceipt::class)) {
|
||||||
|
$orders = PurchaseOrder::query()->when($actor->departmentScoped(), fn ($query) => $query->visibleTo($actor));
|
||||||
|
$receipts = GoodsReceipt::query()->whereIn('purchase_order_id', $orders->select('id'))->whereRaw("LOWER(delivery_note) LIKE ? ESCAPE '!'", [$pattern])
|
||||||
|
->latest('id')->paginate(15, ['id', 'delivery_note'], 'receipts_page')->withQueryString()
|
||||||
|
->through(fn ($row) => ['id' => $row->id, 'title' => 'Recepção #'.$row->id.' · '.$row->delivery_note, 'detail' => 'Recepção', 'href' => '/recepcoes/'.$row->id]);
|
||||||
|
$groups[] = ['key' => 'receipts', 'title' => 'Recepções', 'records' => $receipts];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (config('procurement_search.finance_metadata_enabled') === true && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance])) {
|
||||||
|
$invoices = Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))
|
||||||
|
->whereRaw("LOWER(number) LIKE ? ESCAPE '!'", [$pattern])->latest('id')
|
||||||
|
->paginate(15, ['id', 'number', 'status'], 'invoices_page')->withQueryString()
|
||||||
|
->through(fn ($row) => ['id' => $row->id, 'title' => $row->number, 'detail' => $row->status, 'href' => '/facturas?invoice_id='.$row->id]);
|
||||||
|
$groups[] = ['key' => 'invoices', 'title' => 'Facturas de fornecedor', 'records' => $invoices];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($supplySearchAvailable) {
|
||||||
|
foreach (['agreement' => ['agreements', 'Acordos'], 'contract' => ['contracts', 'Contratos globais']] as $kind => [$key, $title]) {
|
||||||
|
if ($kind === 'contract' && ! app(AgreementOrderLimits::class)->ready()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$query = $planning->latest($kind)->where('tenant_id', $actor->tenant_id);
|
||||||
|
$query->where(function ($query) use ($supplySelectors, $pattern) {
|
||||||
|
// Fixed SQL for the supported engines; the user's term stays bound.
|
||||||
|
$query->whereRaw($supplySelectors[0], [$pattern])->orWhereRaw($supplySelectors[1], [$pattern]);
|
||||||
|
});
|
||||||
|
$records = $query->latest('id')->paginate(15, ['id', 'version', 'state', 'data->reference as reference'], $key.'_page')->withQueryString()
|
||||||
|
->through(fn ($row) => ['id' => $row->id, 'title' => ($row->getAttribute('reference') ?: 'Referência por completar').' · v'.$row->version,
|
||||||
|
'detail' => $row->state, 'href' => '/compras/fornecimento?view='.$key.'&record_id='.$row->id.'#supply-record-'.$row->id]);
|
||||||
|
$groups[] = ['key' => $key, 'title' => $title, 'records' => $records];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($warehouseRequestSearchAvailable) {
|
||||||
|
$desk = app(WarehouseWorkdesk::class);
|
||||||
|
$query = $desk->visible($actor)->where('tenant_id', $actor->tenant_id);
|
||||||
|
if (preg_match('/^(?:RA-)?([1-9][0-9]{0,9})$/iD', $term, $match)) {
|
||||||
|
$query->whereKey($match[1]);
|
||||||
|
} else {
|
||||||
|
$query->where(fn ($query) => $query->whereRaw($warehouseSelectors[0], [$pattern])->orWhereRaw($warehouseSelectors[1], [$pattern]));
|
||||||
|
}
|
||||||
|
$records = $query->select('warehouse_requests.id')->selectRaw($desk->stateExpression().' as projected_state')->latest('id')
|
||||||
|
->paginate(15, ['id'], 'warehouse_requests_page')->withQueryString()->through(fn ($row) => [
|
||||||
|
'id' => $row->id, 'title' => 'RA-'.$row->id, 'detail' => $row->getAttribute('projected_state'), 'href' => '/stock/requisicoes/'.$row->id]);
|
||||||
|
$groups[] = ['key' => 'warehouse_requests', 'title' => 'Requisições internas de armazém', 'records' => $records];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($capitalQuery !== null) {
|
||||||
|
$capitalQuery->where(function ($query) use ($pattern) {
|
||||||
|
foreach (['code', 'name', 'reference'] as $field) {
|
||||||
|
// Fixed register fields only; literal search text remains bound.
|
||||||
|
$expression = DB::getDriverName() === 'pgsql'
|
||||||
|
? 'LOWER("data"->>\''.$field.'\') LIKE ? ESCAPE \'!\''
|
||||||
|
: "LOWER(json_extract(data, '$.".$field."')) LIKE ? ESCAPE '!'";
|
||||||
|
$query->orWhereRaw($expression, [$pattern]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
$records = $capitalQuery->latest('id')->paginate(15, ['id', 'record_key', 'version', 'state',
|
||||||
|
'data->code as code', 'data->name as name', 'data->type as register_type'], 'capital_page')->withQueryString()
|
||||||
|
->through(fn ($row) => ['id' => $row->id,
|
||||||
|
'title' => ($row->getAttribute('register_type') === 'asset' ? 'Imobilizado' : 'Projecto').' '.$row->getAttribute('code').' — '.$row->getAttribute('name').' · v'.$row->version,
|
||||||
|
'detail' => $row->state, 'href' => '/projectos-imobilizado?history='.rawurlencode($row->record_key)]);
|
||||||
|
$groups[] = ['key' => 'capital', 'title' => 'Projectos e imobilizado', 'records' => $records];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($operationalQuery !== null) {
|
||||||
|
$operationalQuery->where(function ($query) use ($pattern) {
|
||||||
|
foreach (['reference', 'utilisation_location', 'description'] as $field) {
|
||||||
|
$expression = DB::getDriverName() === 'pgsql'
|
||||||
|
? 'LOWER("data"->>\''.$field.'\') LIKE ? ESCAPE \'!\''
|
||||||
|
: "LOWER(json_extract(data, '$.".$field."')) LIKE ? ESCAPE '!'";
|
||||||
|
$query->orWhereRaw($expression, [$pattern]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
$records = $operationalQuery->latest('id')->paginate(15, ['id', 'version', 'state', 'data->reference as reference', 'data->type as order_type'], 'operational_orders_page')->withQueryString()
|
||||||
|
->through(fn ($row) => ['id' => $row->id,
|
||||||
|
'title' => ($row->getAttribute('order_type') === 'production' ? 'Produção' : 'Manutenção').' '.$row->getAttribute('reference').' · v'.$row->version,
|
||||||
|
'detail' => $row->state, 'href' => '/ordens-operacionais?order_id='.$row->id.'#op-order-'.$row->id]);
|
||||||
|
$groups[] = ['key' => 'operational_orders', 'title' => 'Ordens de produção e manutenção', 'records' => $records];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $groups;
|
||||||
|
});
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('search/procurement', ['term' => $term, 'groups' => $groups,
|
||||||
|
'savedSearches' => app(SavedProcurementSearches::class)->read($actor),
|
||||||
|
'invoiceSearchAvailable' => config('procurement_search.finance_metadata_enabled') === true && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]),
|
||||||
|
'supplySearchAvailable' => $supplySearchAvailable,
|
||||||
|
'warehouseRequestSearchAvailable' => $warehouseRequestSearchAvailable,
|
||||||
|
'capitalSearchAvailable' => $capitalQuery !== null,
|
||||||
|
'operationalOrderSearchAvailable' => $operationalQuery !== null,
|
||||||
|
])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,9 +19,9 @@ class ProposalOpeningController extends Controller
|
|||||||
{
|
{
|
||||||
private function access(Request $request, int $requisitionId): Requisition
|
private function access(Request $request, int $requisitionId): Requisition
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||||
|
|
||||||
return Requisition::query()->visibleTo($request->user())->findOrFail($requisitionId);
|
return Requisition::query()->visibleTo($this->staffIdentity($request))->findOrFail($requisitionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Request $request, Requisition $requisition, ProposalOpeningWorkflow $workflow): Response
|
public function show(Request $request, Requisition $requisition, ProposalOpeningWorkflow $workflow): Response
|
||||||
@@ -36,7 +36,7 @@ class ProposalOpeningController extends Controller
|
|||||||
'requisition' => $requisition->only(['id', 'number', 'justification']), 'proposals' => $proposals, 'basisHash' => $workflow->basis($proposals), 'openings' => $openings,
|
'requisition' => $requisition->only(['id', 'number', 'justification']), 'proposals' => $proposals, 'basisHash' => $workflow->basis($proposals), 'openings' => $openings,
|
||||||
'sourceChanged' => $latest && $workflow->basis($proposals) !== $latest->basis_hash,
|
'sourceChanged' => $latest && $workflow->basis($proposals) !== $latest->basis_hash,
|
||||||
'latestId' => $latest->id ?? 0,
|
'latestId' => $latest->id ?? 0,
|
||||||
'canRecord' => $request->user()->hasFunctions([PurchasingRole::Procurement]) && $requisition->status === 'approved' && ! PurchaseAward::query()->where('requisition_id', $requisition->id)->exists() && ! app(ConflictGuard::class)->participationBlocked($request->user(), $requisition),
|
'canRecord' => $this->staffIdentity($request)->hasFunctions([PurchasingRole::Procurement]) && $requisition->status === 'approved' && ! PurchaseAward::query()->where('requisition_id', $requisition->id)->exists() && ! app(ConflictGuard::class)->participationBlocked($this->staffIdentity($request), $requisition),
|
||||||
])->toResponse($request);
|
])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
@@ -68,7 +68,7 @@ class ProposalOpeningController extends Controller
|
|||||||
$data['opened_at'] = $opened->utc()->format('Y-m-d H:i:s');
|
$data['opened_at'] = $opened->utc()->format('Y-m-d H:i:s');
|
||||||
$data['submission_deadline'] = empty($data['submission_deadline']) ? null : CarbonImmutable::createFromFormat('!Y-m-d\TH:i', $data['submission_deadline'], $data['timezone'])->utc()->format('Y-m-d H:i:s');
|
$data['submission_deadline'] = empty($data['submission_deadline']) ? null : CarbonImmutable::createFromFormat('!Y-m-d\TH:i', $data['submission_deadline'], $data['timezone'])->utc()->format('Y-m-d H:i:s');
|
||||||
$data['quotation_ids'] = array_map(intval(...), $data['quotation_ids']);
|
$data['quotation_ids'] = array_map(intval(...), $data['quotation_ids']);
|
||||||
$workflow->record($request->user(), $requisition, $data);
|
$workflow->record($this->staffIdentity($request), $requisition, $data);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,19 +16,20 @@ use App\Services\PurchaseRevisionWorkflow;
|
|||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class PurchaseControlController extends Controller
|
class PurchaseControlController extends Controller
|
||||||
{
|
{
|
||||||
public function index(Request $request): Response
|
public function index(Request $request): Response
|
||||||
{
|
{
|
||||||
$user = $request->user();
|
$user = $this->staffIdentity($request);
|
||||||
|
Inertia::encryptHistory();
|
||||||
$operational = $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance]);
|
$operational = $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance]);
|
||||||
$sources = Requisition::query()->where('requester_id', $user->id)->select('id');
|
$sources = Requisition::query()->where('requester_id', $user->id)->select('id');
|
||||||
$ownAwards = PurchaseAward::query()->whereIn('requisition_id', $sources)->select('id');
|
$ownAwards = PurchaseAward::query()->whereIn('requisition_id', $sources)->select('id');
|
||||||
$cancellations = AwardCancellation::query()->whereIn('purchase_award_id', $ownAwards)->where('status', 'approved')->get(['id', 'purchase_award_id']);
|
$cancellations = AwardCancellation::query()->whereIn('purchase_award_id', $ownAwards)->where('status', 'approved')->get(['id', 'purchase_award_id']);
|
||||||
|
|
||||||
return Inertia::render('purchase-controls/index', [
|
$response = Inertia::render('purchase-controls/index', [
|
||||||
'role' => $user->purchasing_role->value ?? '', 'permissions' => app(OrganizationAccess::class)->permissions($user), 'actorId' => $user->id,
|
'role' => $user->purchasing_role->value ?? '', 'permissions' => app(OrganizationAccess::class)->permissions($user), 'actorId' => $user->id,
|
||||||
'policies' => $operational ? PurchaseControlPolicy::query()->latest('revision')->get() : [],
|
'policies' => $operational ? PurchaseControlPolicy::query()->latest('revision')->get() : [],
|
||||||
'reviews' => $operational ? PurchaseControlReview::query()->get() : [],
|
'reviews' => $operational ? PurchaseControlReview::query()->get() : [],
|
||||||
@@ -40,14 +41,17 @@ class PurchaseControlController extends Controller
|
|||||||
|
|
||||||
return ['id' => $cancellation->id, 'number' => $source->number, 'revision_id' => PurchaseRevision::query()->where('award_cancellation_id', $cancellation->id)->value('requisition_id')];
|
return ['id' => $cancellation->id, 'number' => $source->number, 'revision_id' => PurchaseRevision::query()->where('award_cancellation_id', $cancellation->id)->value('requisition_id')];
|
||||||
}),
|
}),
|
||||||
]);
|
])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function propose(Request $request, PurchaseControlPolicyWorkflow $workflow): RedirectResponse
|
public function propose(Request $request, PurchaseControlPolicyWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin]), 403);
|
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin]), 403);
|
||||||
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'mode' => 'required|in:unissued_award', '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']);
|
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'mode' => 'required|in:unissued_award', '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']);
|
||||||
$workflow->propose($request->user(), $data);
|
$workflow->propose($this->staffIdentity($request), $data);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -55,7 +59,7 @@ class PurchaseControlController extends Controller
|
|||||||
public function policyReview(Request $request, PurchaseControlPolicy $policy, PurchaseControlPolicyWorkflow $workflow): RedirectResponse
|
public function policyReview(Request $request, PurchaseControlPolicy $policy, PurchaseControlPolicyWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|min:10|max:4000']);
|
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|min:10|max:4000']);
|
||||||
$workflow->review($request->user(), $policy, $data['decision'], $data['reason']);
|
$workflow->review($this->staffIdentity($request), $policy, $data['decision'], $data['reason']);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -63,7 +67,7 @@ class PurchaseControlController extends Controller
|
|||||||
public function cancel(Request $request, PurchaseAward $award, PurchaseRevisionWorkflow $workflow): RedirectResponse
|
public function cancel(Request $request, PurchaseAward $award, PurchaseRevisionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['reason' => 'required|string|min:10|max:4000']);
|
$data = $request->validate(['reason' => 'required|string|min:10|max:4000']);
|
||||||
$workflow->request($request->user(), $award, $data['reason']);
|
$workflow->request($this->staffIdentity($request), $award, $data['reason']);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -71,7 +75,7 @@ class PurchaseControlController extends Controller
|
|||||||
public function review(Request $request, AwardCancellation $cancellation, PurchaseRevisionWorkflow $workflow): RedirectResponse
|
public function review(Request $request, AwardCancellation $cancellation, PurchaseRevisionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|min:10|max:4000']);
|
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|min:10|max:4000']);
|
||||||
$workflow->review($request->user(), $cancellation, $data['decision'], $data['reason']);
|
$workflow->review($this->staffIdentity($request), $cancellation, $data['decision'], $data['reason']);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -79,7 +83,7 @@ class PurchaseControlController extends Controller
|
|||||||
public function revise(Request $request, AwardCancellation $cancellation, PurchaseRevisionWorkflow $workflow): RedirectResponse
|
public function revise(Request $request, AwardCancellation $cancellation, PurchaseRevisionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['needed_by' => 'required|date_format:Y-m-d|after_or_equal:today', 'justification' => 'required|string|min:10|max:4000']);
|
$data = $request->validate(['needed_by' => 'required|date_format:Y-m-d|after_or_equal:today', 'justification' => 'required|string|min:10|max:4000']);
|
||||||
$revision = $workflow->revise($request->user(), $cancellation, $data['needed_by'], $data['justification']);
|
$revision = $workflow->revise($this->staffIdentity($request), $cancellation, $data['needed_by'], $data['justification']);
|
||||||
|
|
||||||
return to_route('requisitions.edit', $revision);
|
return to_route('requisitions.edit', $revision);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,30 +7,47 @@ use App\Models\AuditLog;
|
|||||||
use App\Models\AwardCancellation;
|
use App\Models\AwardCancellation;
|
||||||
use App\Models\PurchaseAward;
|
use App\Models\PurchaseAward;
|
||||||
use App\Models\PurchaseOrder;
|
use App\Models\PurchaseOrder;
|
||||||
|
use App\Models\Quotation;
|
||||||
use App\Models\RecommendationAttempt;
|
use App\Models\RecommendationAttempt;
|
||||||
use App\Models\Requisition;
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\AgreementOrderLimits;
|
||||||
use App\Services\FormalRecommendation;
|
use App\Services\FormalRecommendation;
|
||||||
|
use App\Services\OrderCancellationWorkflow;
|
||||||
|
use App\Services\OrderPartsAccess;
|
||||||
|
use App\Services\OrderPartsAmendments;
|
||||||
|
use App\Services\OrderPartsWorkflow;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
use App\Services\ProposalComparison;
|
use App\Services\ProposalComparison;
|
||||||
use App\Services\PurchaseWorkflow;
|
use App\Services\PurchaseWorkflow;
|
||||||
|
use App\Services\RequisitionBudgetDistributions;
|
||||||
use Illuminate\Contracts\View\View;
|
use Illuminate\Contracts\View\View;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Inertia\Response;
|
||||||
|
use Symfony\Component\HttpFoundation\Response as HttpResponse;
|
||||||
|
|
||||||
class PurchaseController extends Controller
|
class PurchaseController extends Controller
|
||||||
{
|
{
|
||||||
private function access(Request $request): void
|
private function access(Request $request): User
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
abort_unless($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function award(Request $request, Requisition $requisition, ProposalComparison $comparison, PurchaseWorkflow $workflow): Response
|
public function award(Request $request, Requisition $requisition, ProposalComparison $comparison, PurchaseWorkflow $workflow): Response
|
||||||
{
|
{
|
||||||
$this->access($request);
|
Inertia::encryptHistory();
|
||||||
Requisition::query()->visibleTo($request->user())->findOrFail($requisition->id);
|
$actor = $this->access($request);
|
||||||
|
Requisition::query()->visibleTo($actor)->findOrFail($requisition->id);
|
||||||
$award = PurchaseAward::query()->where('requisition_id', $requisition->id)->with('approvals')->first();
|
$award = PurchaseAward::query()->where('requisition_id', $requisition->id)->with('approvals')->first();
|
||||||
$frozen = $award && AwardCancellation::query()->where('purchase_award_id', $award->id)->where('status', 'pending')->exists();
|
$frozen = $award && AwardCancellation::query()->where('purchase_award_id', $award->id)->where('status', 'pending')->exists();
|
||||||
$recommendation = app(FormalRecommendation::class);
|
$recommendation = app(FormalRecommendation::class);
|
||||||
@@ -48,78 +65,163 @@ class PurchaseController extends Controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$agreementFilters = $request->validate(['agreement_search' => 'nullable|string|max:100', 'selected_agreement_ids' => 'nullable|array|max:100', 'selected_agreement_ids.*' => 'integer|min:1|distinct']);
|
||||||
|
|
||||||
return Inertia::render('purchases/award', [
|
return Inertia::render('purchases/award', [
|
||||||
|
'budgetDistributionOptions' => app(RequisitionBudgetDistributions::class)->options($actor, $requisition),
|
||||||
|
'agreementOrderLimitsReady' => app(AgreementOrderLimits::class)->ready() && app(AgreementOrderLimits::class)->canRead($actor),
|
||||||
|
'agreementSearch' => $agreementFilters['agreement_search'] ?? '',
|
||||||
|
'agreementOptions' => $award === null ? [] : app(AgreementOrderLimits::class)->options($actor, $requisition, Quotation::query()->find($award->quotation_id), trim($agreementFilters['agreement_search'] ?? ''), $agreementFilters['selected_agreement_ids'] ?? []),
|
||||||
|
'agreementLines' => $requisition->items()->get()->map(fn ($line) => ['id' => $line->id, 'description' => $line->description, 'unit' => $line->unit, 'stock_item_id' => $line->catalogue_snapshot['stock_item_id'] ?? null]),
|
||||||
'requisition' => $requisition, 'comparison' => $comparison->inspect($requisition), 'award' => $award,
|
'requisition' => $requisition, 'comparison' => $comparison->inspect($requisition), 'award' => $award,
|
||||||
'canSelect' => $request->user()->hasFunctions([PurchasingRole::Procurement]) && $award === null && $request->user()->id !== $requisition->requester_id && (! $adoption || $candidate !== null),
|
'canSelect' => ! app(OrganizationAccess::class)->maintenanceOnly($actor) && $actor->hasFunctions([PurchasingRole::Procurement]) && $award === null && $actor->id !== $requisition->requester_id && (! $adoption || $candidate !== null),
|
||||||
'recommendation' => ['adopted' => $adoption !== null, 'quotation_id' => $candidate],
|
'recommendation' => ['adopted' => $adoption !== null, 'quotation_id' => $candidate],
|
||||||
'canDecide' => ! $frozen && $award !== null && $workflow->canDecide($request->user(), $award, $requisition),
|
'canDecide' => ! $frozen && $award !== null && $workflow->canDecide($actor, $award, $requisition),
|
||||||
'canIssue' => ! $frozen && $award?->status === 'approved' && $request->user()->hasFunctions([PurchasingRole::Procurement]),
|
'canIssue' => $award !== null && $workflow->canIssue($actor, $award, $requisition),
|
||||||
'order' => PurchaseOrder::query()->where('requisition_id', $requisition->id)->first(['id', 'number']),
|
'order' => PurchaseOrder::query()->where('requisition_id', $requisition->id)->first(['id', 'number']),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function select(Request $request, Requisition $requisition, PurchaseWorkflow $workflow): RedirectResponse
|
public function select(Request $request, Requisition $requisition, PurchaseWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$this->access($request);
|
$actor = $this->access($request);
|
||||||
$data = $request->validate([
|
$data = $request->validate([
|
||||||
|
...(app(RequisitionBudgetDistributions::class)->ready() && $request->has('budget_distribution_preparation') ? app(RequisitionBudgetDistributions::class)->rules($requisition) : []),
|
||||||
'quotation_id' => 'required|integer', 'justification' => 'required|string|min:10|max:5000',
|
'quotation_id' => 'required|integer', 'justification' => 'required|string|min:10|max:5000',
|
||||||
'delivery_date' => 'required|date_format:Y-m-d|after_or_equal:today', 'delivery_location' => 'required|string|min:3|max:500',
|
'delivery_date' => 'required|date_format:Y-m-d|after_or_equal:today', 'delivery_location' => 'required|string|min:3|max:500',
|
||||||
'status' => 'prohibited', 'total_minor' => 'prohibited', 'subtotal_minor' => 'prohibited', 'tax_minor' => 'prohibited',
|
'status' => 'prohibited', 'total_minor' => 'prohibited', 'subtotal_minor' => 'prohibited', 'tax_minor' => 'prohibited',
|
||||||
'approval_snapshot' => 'prohibited', 'decision_matrix' => 'prohibited', 'created_by' => 'prohibited', 'tenant_id' => 'prohibited',
|
'approval_snapshot' => 'prohibited', 'decision_matrix' => 'prohibited', 'created_by' => 'prohibited', 'tenant_id' => 'prohibited',
|
||||||
'override' => 'prohibited', 'exception' => 'prohibited',
|
'override' => 'prohibited', 'exception' => 'prohibited',
|
||||||
]);
|
]);
|
||||||
$workflow->select($request->user(), $requisition, $data);
|
$workflow->select($actor, $requisition, $data);
|
||||||
|
|
||||||
return to_route('purchases.award', $requisition);
|
return to_route('purchases.award', $requisition);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function distributionAmendment(Request $request, PurchaseOrder $order): Response
|
||||||
|
{
|
||||||
|
if (OrderPartsAccess::applies($order)) {
|
||||||
|
$actor = $this->access($request);
|
||||||
|
$sources = app(OrderPartsAmendments::class)->sources($actor, $order);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
|
return Inertia::render('purchases/order-parts-amendment', ['order' => $order->only(['id', 'number', 'currency']), 'sources' => $sources,
|
||||||
|
'history' => DB::table('budget_order_commands')->where('tenant_id', $actor->tenant_id)
|
||||||
|
->where('kind', 'amend')->where('document_key', 'like', $order->getAttribute('order_key').'-%')
|
||||||
|
->orderBy('id')->get(['id', 'created_at', 'created_by', 'snapshot', 'result'])->map(fn ($event) => [
|
||||||
|
'id' => $event->id, 'created_at' => $event->created_at, 'created_by' => $event->created_by,
|
||||||
|
'sources' => json_decode($event->snapshot, true, 64, JSON_THROW_ON_ERROR),
|
||||||
|
'reason' => json_decode($event->result, true, 64, JSON_THROW_ON_ERROR)['reason'] ?? null])]);
|
||||||
|
}
|
||||||
|
$host = app(RequisitionBudgetDistributions::class);
|
||||||
|
abort_unless($host->ready(), 503);
|
||||||
|
$actor = $this->access($request);
|
||||||
|
abort_unless($actor->tenant_id === $order->tenant_id && $actor->hasFunctions([PurchasingRole::Finance])
|
||||||
|
&& ! app(OrganizationAccess::class)->maintenanceOnly($actor) && $order->currency !== 'MZN', 403);
|
||||||
|
$requisition = Requisition::query()->visibleTo($actor)->findOrFail($order->requisition_id);
|
||||||
|
$source = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $requisition->id)->first();
|
||||||
|
abort_unless($source !== null && $source->phase === 'commit', 409);
|
||||||
|
$snapshot = json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
|
return Inertia::render('purchases/distribution-amendment', ['order' => $order->only(['id', 'number', 'currency']),
|
||||||
|
'options' => $host->options($actor, $requisition), 'planHash' => $snapshot['plan_hash'], 'version' => $snapshot['amendment_version'] ?? 0,
|
||||||
|
'history' => DB::table('budget_distribution_events')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $source->id)
|
||||||
|
->orderBy('id')->get(['kind', 'created_at', 'created_by', 'snapshot'])->map(function ($event) {
|
||||||
|
$plan = json_decode($event->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||||
|
|
||||||
|
$label = match ($event->kind) {
|
||||||
|
'reserve' => 'Reserva', 'award' => 'Adjudicação', 'commit' => 'Compromisso',
|
||||||
|
'release' => 'Libertação da reserva', 'cancel' => 'Cancelamento do compromisso',
|
||||||
|
default => str_starts_with($event->kind, 'invoice-') ? 'Consumo de factura' : 'Reafectação',
|
||||||
|
};
|
||||||
|
|
||||||
|
return ['kind' => $label, 'created_at' => $event->created_at, 'created_by' => $event->created_by,
|
||||||
|
'version' => $plan['amendment_version'] ?? null, 'reason' => $plan['reason'] ?? null, 'allocations' => $plan['allocations']];
|
||||||
|
})]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function amendDistribution(Request $request, PurchaseOrder $order): RedirectResponse
|
||||||
|
{
|
||||||
|
if (OrderPartsAccess::applies($order)) {
|
||||||
|
app(OrderPartsAmendments::class)->amend($this->access($request), $order, $request->all());
|
||||||
|
|
||||||
|
return to_route('orders.show', $order);
|
||||||
|
}
|
||||||
|
app(RequisitionBudgetDistributions::class)->amend($this->access($request), $order, $request->all());
|
||||||
|
|
||||||
|
return to_route('orders.show', $order);
|
||||||
|
}
|
||||||
|
|
||||||
public function decide(Request $request, PurchaseAward $award, PurchaseWorkflow $workflow): RedirectResponse
|
public function decide(Request $request, PurchaseAward $award, PurchaseWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$this->access($request);
|
$actor = $this->access($request);
|
||||||
$data = $request->validate(['decision' => ['required', Rule::in(['approved', 'rejected'])], 'comment' => 'nullable|required_if:decision,rejected|string|max:2000']);
|
$data = $request->validate(['decision' => ['required', Rule::in(['approved', 'rejected'])], 'comment' => 'nullable|required_if:decision,rejected|string|max:2000']);
|
||||||
$workflow->decide($request->user(), $award, $data['decision'], $data['comment'] ?? null);
|
$workflow->decide($actor, $award, $data['decision'], $data['comment'] ?? null);
|
||||||
|
|
||||||
return to_route('purchases.award', $award->requisition_id);
|
return to_route('purchases.award', $award->requisition_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function issue(Request $request, PurchaseAward $award, PurchaseWorkflow $workflow): RedirectResponse
|
public function issue(Request $request, PurchaseAward $award, PurchaseWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$this->access($request);
|
$actor = $this->access($request);
|
||||||
$request->validate([
|
$validated = $request->validate([
|
||||||
'status' => 'prohibited', 'snapshot' => 'prohibited', 'total_minor' => 'prohibited', 'subtotal_minor' => 'prohibited', 'tax_minor' => 'prohibited',
|
'status' => 'prohibited', 'snapshot' => 'prohibited', 'total_minor' => 'prohibited', 'subtotal_minor' => 'prohibited', 'tax_minor' => 'prohibited',
|
||||||
'issued_by' => 'prohibited', 'tenant_id' => 'prohibited', 'quotation_id' => 'prohibited', 'override' => 'prohibited', 'exception' => 'prohibited',
|
'issued_by' => 'prohibited', 'tenant_id' => 'prohibited', 'quotation_id' => 'prohibited', 'override' => 'prohibited', 'exception' => 'prohibited',
|
||||||
|
'agreement_bindings' => 'sometimes|array|max:100',
|
||||||
]);
|
]);
|
||||||
$order = $workflow->issue($request->user(), $award);
|
$order = $workflow->issue($actor, $award, $validated['agreement_bindings'] ?? []);
|
||||||
|
|
||||||
return to_route('orders.show', $order);
|
return to_route('orders.show', $order);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function index(Request $request): Response
|
public function index(Request $request): Response
|
||||||
{
|
{
|
||||||
$this->access($request);
|
$actor = $this->access($request);
|
||||||
|
|
||||||
return Inertia::render('purchases/index', [
|
return Inertia::render('purchases/index', [
|
||||||
'orders' => PurchaseOrder::query()->visibleTo($request->user())->latest('id')->paginate(15),
|
'partsAvailable' => $actor->hasFunctions([PurchasingRole::Procurement]) && app(OrderPartsWorkflow::class)->ready(),
|
||||||
'awards' => PurchaseAward::query()->whereIn('requisition_id', Requisition::query()->visibleTo($request->user())->select('id'))->latest()->paginate(15, ['*'], 'awards_page'),
|
'orders' => PurchaseOrder::query()->visibleTo($actor)->latest('id')->paginate(15),
|
||||||
|
'awards' => PurchaseAward::query()->whereIn('requisition_id', Requisition::query()->visibleTo($actor)->select('id'))->latest()->paginate(15, ['*'], 'awards_page'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Request $request, PurchaseOrder $order): Response
|
public function show(Request $request, PurchaseOrder $order): Response
|
||||||
{
|
{
|
||||||
$this->access($request);
|
$actor = $this->access($request);
|
||||||
PurchaseOrder::query()->visibleTo($request->user())->findOrFail($order->id);
|
PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id);
|
||||||
|
$origins = app(OrderPartsAccess::class)->origins($order);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
return Inertia::render('purchases/show', [
|
return Inertia::render('purchases/show', [
|
||||||
|
'financialDocumentsHref' => $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]) ? '/facturas?purchase_order_id='.$order->id.'#invoice-documents' : null,
|
||||||
|
'relatedProcesses' => Requisition::query()->visibleTo($actor)->whereIn('id', $origins)->orderBy('id')->get(['id', 'number'])
|
||||||
|
->map(fn ($source) => ['id' => $source->id, 'number' => $source->number, 'href' => '/requisicoes/'.$source->id.'/processo']),
|
||||||
|
'snapshotComplete' => $order->hasCompleteDocumentSnapshot(),
|
||||||
'order' => $order->load('items'),
|
'order' => $order->load('items'),
|
||||||
'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']),
|
'orderPartsSources' => $order->snapshot['order_parts']['frames'] ?? [],
|
||||||
|
'canAmendOrderParts' => OrderPartsAccess::applies($order) && app(OrderPartsWorkflow::class)->ready()
|
||||||
|
&& $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||||
|
&& app(OrderCancellationWorkflow::class)->state($order) === 'issued',
|
||||||
|
'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()->whereIn('requisition_id', $origins)->whereIn('action', ['award.created', 'award.approved', 'award.rejected', 'purchase_order.issued'])->orderBy('id')->get(['id', 'requisition_id', 'user_id', 'action', 'created_at']),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function print(Request $request, PurchaseOrder $order): View
|
public function print(Request $request, PurchaseOrder $order): View|HttpResponse
|
||||||
{
|
{
|
||||||
$this->access($request);
|
$actor = $this->access($request);
|
||||||
PurchaseOrder::query()->visibleTo($request->user())->findOrFail($order->id);
|
PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id);
|
||||||
|
app(OrderPartsAccess::class)->origins($order);
|
||||||
|
|
||||||
return view('purchases.print', ['order' => $order->load('items'), 'snapshot' => $order->snapshot]);
|
if ($request->header('X-Inertia')) {
|
||||||
|
return Inertia::location(route('orders.print', $order, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
return view('purchases.print', ['order' => $order->load('items'), 'snapshot' => $order->snapshot,
|
||||||
|
'snapshotComplete' => $order->hasCompleteDocumentSnapshot(),
|
||||||
|
'operationalState' => app(OrderCancellationWorkflow::class)->state($order)]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ class PurchasePlanningController extends Controller
|
|||||||
{
|
{
|
||||||
public function index(Request $request): Response
|
public function index(Request $request): Response
|
||||||
{
|
{
|
||||||
$actor = $request->user();
|
$actor = $this->staffIdentity($request);
|
||||||
$canManage = $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement]);
|
$canManage = $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement]);
|
||||||
$filters = $request->validate(['item' => 'nullable|integer|min:1']);
|
$filters = $request->validate(['item' => 'nullable|integer|min:1']);
|
||||||
$items = PurchasePlanItem::query()->visibleTo($actor)->when($filters['item'] ?? null, fn ($query, $id) => $query->whereKey($id))->latest('id')->paginate(15)->withQueryString();
|
$items = PurchasePlanItem::query()->visibleTo($actor)->when($filters['item'] ?? null, fn ($query, $id) => $query->whereKey($id))->latest('id')->paginate(15)->withQueryString();
|
||||||
@@ -62,7 +62,7 @@ class PurchasePlanningController extends Controller
|
|||||||
$data = $request->validate(['title' => 'required|string|min:3|max:200', 'department_id' => 'required|integer', 'responsible_id' => 'required|integer', 'requisition_id' => 'nullable|integer', 'nature' => 'required|in:goods,works,services,consulting']);
|
$data = $request->validate(['title' => 'required|string|min:3|max:200', 'department_id' => 'required|integer', 'responsible_id' => 'required|integer', 'requisition_id' => 'nullable|integer', 'nature' => 'required|in:goods,works,services,consulting']);
|
||||||
$data['department_id'] = (int) $data['department_id'];
|
$data['department_id'] = (int) $data['department_id'];
|
||||||
$data['responsible_id'] = (int) $data['responsible_id'];
|
$data['responsible_id'] = (int) $data['responsible_id'];
|
||||||
$workflow->create($request->user(), $data);
|
$workflow->create($this->staffIdentity($request), $data);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -70,7 +70,7 @@ class PurchasePlanningController extends Controller
|
|||||||
public function assign(Request $request, PurchasePlanItem $item, PurchasePlanningWorkflow $workflow): RedirectResponse
|
public function assign(Request $request, PurchasePlanItem $item, PurchasePlanningWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['responsible_id' => 'required|integer', 'version' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:2000']);
|
$data = $request->validate(['responsible_id' => 'required|integer', 'version' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:2000']);
|
||||||
$workflow->assign($request->user(), $item, (int) $data['responsible_id'], (int) $data['version'], $data['reason']);
|
$workflow->assign($this->staffIdentity($request), $item, (int) $data['responsible_id'], (int) $data['version'], $data['reason']);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -78,7 +78,7 @@ class PurchasePlanningController extends Controller
|
|||||||
public function milestone(Request $request, PurchasePlanItem $item, PurchasePlanningWorkflow $workflow): RedirectResponse
|
public function milestone(Request $request, PurchasePlanItem $item, PurchasePlanningWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['label' => 'required|string|min:3|max:120', 'planned_on' => 'required|date_format:Y-m-d']);
|
$data = $request->validate(['label' => 'required|string|min:3|max:120', 'planned_on' => 'required|date_format:Y-m-d']);
|
||||||
$workflow->milestone($request->user(), $item, $data['label'], $data['planned_on']);
|
$workflow->milestone($this->staffIdentity($request), $item, $data['label'], $data['planned_on']);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -86,7 +86,7 @@ class PurchasePlanningController extends Controller
|
|||||||
public function link(Request $request, PurchasePlanItem $item, PurchasePlanningWorkflow $workflow): RedirectResponse
|
public function link(Request $request, PurchasePlanItem $item, PurchasePlanningWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['requisition_id' => 'required|integer', 'version' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:2000']);
|
$data = $request->validate(['requisition_id' => 'required|integer', 'version' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:2000']);
|
||||||
$workflow->link($request->user(), $item, (int) $data['requisition_id'], (int) $data['version'], $data['reason']);
|
$workflow->link($this->staffIdentity($request), $item, (int) $data['requisition_id'], (int) $data['version'], $data['reason']);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -104,7 +104,7 @@ class PurchasePlanningController extends Controller
|
|||||||
if (array_key_exists('actual_on', $data)) {
|
if (array_key_exists('actual_on', $data)) {
|
||||||
$changes['actual_on'] = $data['actual_on'];
|
$changes['actual_on'] = $data['actual_on'];
|
||||||
}
|
}
|
||||||
$workflow->update($request->user(), $milestone, $changes);
|
$workflow->update($this->staffIdentity($request), $milestone, $changes);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ use App\Models\Requisition;
|
|||||||
use App\Models\TechnicalReview;
|
use App\Models\TechnicalReview;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
@@ -27,7 +29,8 @@ class PurchaseProcessController extends Controller
|
|||||||
{
|
{
|
||||||
public function show(Request $request, Requisition $requisition): Response
|
public function show(Request $request, Requisition $requisition): Response
|
||||||
{
|
{
|
||||||
$actor = $request->user();
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
Requisition::query()->visibleTo($actor)->findOrFail($requisition->id);
|
Requisition::query()->visibleTo($actor)->findOrFail($requisition->id);
|
||||||
$requisition->load(['requester:id,name', 'department:id,name', 'steps']);
|
$requisition->load(['requester:id,name', 'department:id,name', 'steps']);
|
||||||
$purchases = $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]);
|
$purchases = $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]);
|
||||||
@@ -56,7 +59,7 @@ class PurchaseProcessController extends Controller
|
|||||||
$decisions = [];
|
$decisions = [];
|
||||||
$stages[] = ['label' => 'Requisição e aprovação da necessidade', 'state' => $requisition->status, 'owner' => 'Solicitante e aprovadores', 'detail' => 'Estado do pedido; as decisões individuais constam abaixo.', 'href' => $base];
|
$stages[] = ['label' => 'Requisição e aprovação da necessidade', 'state' => $requisition->status, 'owner' => 'Solicitante e aprovadores', 'detail' => 'Estado do pedido; as decisões individuais constam abaixo.', 'href' => $base];
|
||||||
foreach ($requisition->steps as $step) {
|
foreach ($requisition->steps as $step) {
|
||||||
$decisions[] = ['area' => 'Estimativa', 'role' => $step->role, 'decision' => $step->decision, 'actor_id' => $step->approver_id, 'date' => $step->decided_at];
|
$decisions[] = ['area' => 'Estimativa', 'role' => $step->role, 'role_label' => $step->routing['name'] ?? null, 'decision' => $step->decision, 'actor_id' => $step->approver_id, 'date' => $step->decided_at];
|
||||||
}
|
}
|
||||||
$equipment = $requisition->items()->where('purchase_type', 'equipment')->exists();
|
$equipment = $requisition->items()->where('purchase_type', 'equipment')->exists();
|
||||||
$reviews = TechnicalReview::query()->where('requisition_id', $requisition->id)->orderBy('id')->get();
|
$reviews = TechnicalReview::query()->where('requisition_id', $requisition->id)->orderBy('id')->get();
|
||||||
@@ -64,7 +67,9 @@ class PurchaseProcessController extends Controller
|
|||||||
foreach ($reviews as $review) {
|
foreach ($reviews as $review) {
|
||||||
$decisions[] = ['area' => 'Técnica', 'role' => 'department_head', 'decision' => $review->decision, 'actor_id' => $review->reviewed_by, 'date' => $review->reviewed_at];
|
$decisions[] = ['area' => 'Técnica', 'role' => 'department_head', 'decision' => $review->decision, 'actor_id' => $review->reviewed_by, 'date' => $review->reviewed_at];
|
||||||
}
|
}
|
||||||
$stages[] = ['label' => 'Controlo orçamental', 'state' => $finance ? (BudgetEntry::query()->where('requisition_id', $requisition->id)->exists() ? 'recorded' : 'not_started') : 'restricted', 'owner' => 'Finanças', 'detail' => 'Lançamentos associados ao processo. A presença de registos não certifica o orçamento nem a política da empresa.', 'href' => $finance ? '/orcamentos' : null];
|
$budgetRecorded = $finance && (BudgetEntry::query()->where('requisition_id', $requisition->id)->exists()
|
||||||
|
|| (Schema::hasTable('budget_distributions') && DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $requisition->id)->where('phase', '!=', 'preparing')->exists()));
|
||||||
|
$stages[] = ['label' => 'Controlo orçamental', 'state' => $finance ? ($budgetRecorded ? 'recorded' : 'not_started') : 'restricted', 'owner' => 'Finanças', 'detail' => 'Lançamentos associados ao processo. A presença de registos não certifica o orçamento nem a política da empresa.', 'href' => $finance ? '/orcamentos' : null];
|
||||||
$award = $purchases ? PurchaseAward::query()->where('requisition_id', $requisition->id)->with('approvals')->first() : null;
|
$award = $purchases ? PurchaseAward::query()->where('requisition_id', $requisition->id)->with('approvals')->first() : null;
|
||||||
$order = $inventory ? PurchaseOrder::query()->visibleTo($actor)->where('requisition_id', $requisition->id)->first(['id', 'number']) : null;
|
$order = $inventory ? PurchaseOrder::query()->visibleTo($actor)->where('requisition_id', $requisition->id)->first(['id', 'number']) : null;
|
||||||
$quoteCount = $purchases ? Quotation::query()->where('requisition_id', $requisition->id)->count() : 0;
|
$quoteCount = $purchases ? Quotation::query()->where('requisition_id', $requisition->id)->count() : 0;
|
||||||
@@ -90,10 +95,13 @@ class PurchaseProcessController extends Controller
|
|||||||
}
|
}
|
||||||
$invoices = $finance && $order ? Invoice::query()->where('purchase_order_id', $order->id)->get(['id', 'number', 'status']) : collect();
|
$invoices = $finance && $order ? Invoice::query()->where('purchase_order_id', $order->id)->get(['id', 'number', 'status']) : collect();
|
||||||
$payments = $finance ? ExternalPayment::query()->whereIn('invoice_id', $invoices->pluck('id'))->get(['id', 'status']) : collect();
|
$payments = $finance ? ExternalPayment::query()->whereIn('invoice_id', $invoices->pluck('id'))->get(['id', 'status']) : collect();
|
||||||
$stages[] = ['label' => 'Facturas', 'state' => $finance ? ($invoices->isNotEmpty() ? 'recorded' : 'not_started') : 'restricted', 'owner' => 'Finanças e conferente independente', 'detail' => $finance ? $invoices->count().' registadas; '.$invoices->where('status', 'validated')->count().' validadas. O registo não equivale a validação.' : 'Disponível a Finanças e Administração.', 'href' => $finance ? '/facturas' : null];
|
$stages[] = ['label' => 'Facturas', 'state' => $finance ? ($invoices->isNotEmpty() ? 'recorded' : 'not_started') : 'restricted', 'owner' => 'Finanças e conferente independente', 'detail' => $finance ? $invoices->count().' registadas; '.$invoices->where('status', 'validated')->count().' validadas. O registo não equivale a validação.' : 'Disponível a Finanças e Administração.', 'href' => $finance && $order ? '/facturas?purchase_order_id='.$order->id : null];
|
||||||
$stages[] = ['label' => 'Pagamentos externos', 'state' => $finance ? ($payments->isNotEmpty() ? 'recorded' : 'not_started') : 'restricted', 'owner' => 'Finanças e conferente independente', 'detail' => $finance ? $payments->count().' registos; '.$payments->where('status', 'confirmed')->count().' confirmados. Não comprova liquidação integral e não executa transferências.' : 'Disponível a Finanças e Administração.', 'href' => $finance ? '/pagamentos' : null];
|
$stages[] = ['label' => 'Pagamentos externos', 'state' => $finance ? ($payments->isNotEmpty() ? 'recorded' : 'not_started') : 'restricted', 'owner' => 'Finanças e conferente independente', 'detail' => $finance ? $payments->count().' registos; '.$payments->where('status', 'confirmed')->count().' confirmados. Não comprova liquidação integral e não executa transferências.' : 'Disponível a Finanças e Administração.', 'href' => $finance ? '/pagamentos' : null];
|
||||||
foreach ($invoices as $invoice) {
|
foreach ($invoices as $invoice) {
|
||||||
$documents[] = ['label' => $invoice->number, 'kind' => 'Factura', 'href' => '/facturas'];
|
$documents[] = ['label' => $invoice->number, 'kind' => 'Factura', 'href' => '/facturas?invoice_id='.$invoice->id.'#invoice-'.$invoice->id];
|
||||||
|
}
|
||||||
|
foreach ($payments as $payment) {
|
||||||
|
$documents[] = ['label' => 'Registo externo #'.$payment->id, 'kind' => 'Pagamento externo', 'href' => '/pagamentos?payment_id='.$payment->id.'#payment-'.$payment->id];
|
||||||
}
|
}
|
||||||
$cancellation = $award ? AwardCancellation::query()->where('purchase_award_id', $award->id)->first(['id', 'status']) : null;
|
$cancellation = $award ? AwardCancellation::query()->where('purchase_award_id', $award->id)->first(['id', 'status']) : null;
|
||||||
$actors = User::query()->where('tenant_id', $actor->tenant_id)->whereIn('id', array_column($decisions, 'actor_id'))->pluck('name', 'id');
|
$actors = User::query()->where('tenant_id', $actor->tenant_id)->whereIn('id', array_column($decisions, 'actor_id'))->pluck('name', 'id');
|
||||||
@@ -110,7 +118,7 @@ class PurchaseProcessController extends Controller
|
|||||||
$related[] = ['label' => $other->number, 'href' => '/requisicoes/'.$other->id.'/processo'];
|
$related[] = ['label' => $other->number, 'href' => '/requisicoes/'.$other->id.'/processo'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$actions = ['requisition.created', 'requisition.updated', 'requisition.submitted', 'approval.approved', 'approval.rejected', 'equipment.technical_approved', 'equipment.technical_rejected', 'requisition.revision_created'];
|
$actions = ['requisition.created', 'requisition.updated', 'requisition.submitted', 'requisition.allocations_prepared', 'approval.approved', 'approval.rejected', 'equipment.technical_approved', 'equipment.technical_rejected', 'requisition.revision_created'];
|
||||||
if ($purchases) {
|
if ($purchases) {
|
||||||
$actions = [...$actions, 'recommendation.adopted', 'recommendation.proposed', 'recommendation.reviewed', 'admission.adopted', 'admission.proposed', 'admission.reviewed', 'qualification.defined', 'qualification.assessed', 'opening.recorded', 'award.created', 'award.approved', 'award.rejected', 'purchase_order.issued', 'cancellation.requested', 'cancellation.approved', 'cancellation.rejected'];
|
$actions = [...$actions, 'recommendation.adopted', 'recommendation.proposed', 'recommendation.reviewed', 'admission.adopted', 'admission.proposed', 'admission.reviewed', 'qualification.defined', 'qualification.assessed', 'opening.recorded', 'award.created', 'award.approved', 'award.rejected', 'purchase_order.issued', 'cancellation.requested', 'cancellation.approved', 'cancellation.rejected'];
|
||||||
}
|
}
|
||||||
@@ -118,7 +126,8 @@ class PurchaseProcessController extends Controller
|
|||||||
$actions[] = 'receipt.confirmed';
|
$actions[] = 'receipt.confirmed';
|
||||||
}
|
}
|
||||||
if ($finance) {
|
if ($finance) {
|
||||||
$actions = [...$actions, 'invoice.created', 'invoice.validated', 'payment.registered', 'payment.confirmed', 'payment.rejected', 'budget.reserve', 'budget.award', 'budget.commit', 'budget.release'];
|
$actions = [...$actions, 'invoice.created', 'invoice.validated', 'payment.registered', 'payment.confirmed', 'payment.rejected', 'budget.reserve', 'budget.award', 'budget.commit', 'budget.release',
|
||||||
|
'budget.distribution_reserve', 'budget.distribution_award', 'budget.distribution_commit', 'budget.distribution_release', 'budget.distribution_cancel', 'budget.distribution_amended'];
|
||||||
}
|
}
|
||||||
|
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
|
|||||||
@@ -8,58 +8,88 @@ use App\Models\PurchaseAward;
|
|||||||
use App\Models\Quotation;
|
use App\Models\Quotation;
|
||||||
use App\Models\Requisition;
|
use App\Models\Requisition;
|
||||||
use App\Models\Supplier;
|
use App\Models\Supplier;
|
||||||
|
use App\Models\User;
|
||||||
use App\Services\ComparisonPolicy;
|
use App\Services\ComparisonPolicy;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
|
use App\Services\CurrentActor;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
use App\Services\ProposalComparison;
|
use App\Services\ProposalComparison;
|
||||||
|
use App\Services\QuotationExchange;
|
||||||
|
use App\Services\QuotationParticipation;
|
||||||
use App\Services\QuotationPricing;
|
use App\Services\QuotationPricing;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
|
use App\Services\UrgentQuotationBasis;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
use Brick\Math\RoundingMode;
|
use Brick\Math\RoundingMode;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Inertia\Response;
|
||||||
|
use Symfony\Component\HttpFoundation\Response as HttpResponse;
|
||||||
|
|
||||||
class QuotationController extends Controller
|
class QuotationController extends Controller
|
||||||
{
|
{
|
||||||
private function access(Request $request): void
|
private function access(Request $request): User
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function index(Request $request): Response
|
public function index(Request $request): Response
|
||||||
{
|
{
|
||||||
$this->access($request);
|
$actor = $this->access($request);
|
||||||
|
|
||||||
return Inertia::render('quotations/index', ['requisitions' => Requisition::query()->visibleTo($request->user())->where('status', 'approved')->with('department:id,name')->latest()->paginate(15)]);
|
return Inertia::render('quotations/index', ['requisitions' => Requisition::query()->visibleTo($actor)->where('status', 'approved')->with('department:id,name')->latest()->paginate(15)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Request $request, Requisition $requisition): Response
|
public function show(Request $request, Requisition $requisition): HttpResponse
|
||||||
{
|
{
|
||||||
$this->access($request);
|
$actor = $this->access($request);
|
||||||
Requisition::query()->visibleTo($request->user())->findOrFail($requisition->id);
|
Requisition::query()->visibleTo($actor)->findOrFail($requisition->id);
|
||||||
|
$filters = $request->validate(['quotation_id' => ['nullable', 'integer', Rule::exists('quotations', 'id')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $requisition->id)], 'prepare' => 'nullable|boolean']);
|
||||||
|
$access = app(QuotationParticipation::class);
|
||||||
|
$quotes = Quotation::query()->where('requisition_id', $requisition->id)->with('supplier')->get()->keyBy('id');
|
||||||
$guard = app(ConflictGuard::class);
|
$guard = app(ConflictGuard::class);
|
||||||
$result = app(ProposalComparison::class)->inspect($requisition);
|
$result = app(ProposalComparison::class)->inspect($requisition);
|
||||||
$scores = array_map(fn ($row) => [...$row, 'conflict_blocked' => $guard->processBlocked($requisition, $row['supplier_id'], $request->user())], $result['rows']);
|
$scores = array_map(function ($row) use ($quotes, $actor, $access, $requisition, $guard) {
|
||||||
$closed = PurchaseAward::query()->where('requisition_id', $requisition->id)->exists();
|
$quote = $quotes->get($row['id']);
|
||||||
|
|
||||||
return Inertia::render('quotations/show', [
|
return [...$row, 'conflict_blocked' => $guard->processBlocked($requisition, $row['supplier_id'], $actor), 'canEvaluate' => $row['eligible'] && $quote !== null && $access->canEvaluate($actor, $requisition, $quote)];
|
||||||
|
}, $result['rows']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
|
$response = Inertia::render('quotations/show', [
|
||||||
'requisition' => $requisition->load('items'), 'quotations' => $scores,
|
'requisition' => $requisition->load('items'), 'quotations' => $scores,
|
||||||
'suppliers' => Supplier::query()->where('status', 'active')->where('blocked', false)->whereDate('next_review', '>=', today())->orderBy('name')->get(['id', 'name']),
|
'suppliers' => Supplier::query()->where('status', 'active')->where('blocked', false)->whereDate('next_review', '>=', today())->orderBy('name')->get(['id', 'name']),
|
||||||
'canCreate' => ! $closed && $request->user()->hasFunctions([PurchasingRole::Procurement]) && $requisition->status === 'approved' && ! $guard->participationBlocked($request->user(), $requisition),
|
'canCreate' => $access->canPrepare($actor, $requisition),
|
||||||
'canEvaluate' => ! $closed && $request->user()->hasFunctions([PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]) && $request->user()->id !== $requisition->requester_id && $requisition->status === 'approved' && ! $guard->participationBlocked($request->user(), $requisition),
|
'canEvaluate' => $access->canEvaluateProcess($actor, $requisition),
|
||||||
|
'focusQuotationId' => isset($filters['quotation_id']) ? (int) $filters['quotation_id'] : null,
|
||||||
|
'prepare' => (bool) ($filters['prepare'] ?? false),
|
||||||
'ready' => $result['ready'],
|
'ready' => $result['ready'],
|
||||||
'topIds' => $result['top_ids'],
|
'topIds' => $result['top_ids'],
|
||||||
'comparisonPolicy' => $result['policy'],
|
'comparisonPolicy' => $result['policy'],
|
||||||
]);
|
'urgentQuotationReady' => app(UrgentQuotationBasis::class)->ready(),
|
||||||
|
'exchangeRates' => app(QuotationExchange::class)->rates($requisition),
|
||||||
|
'exchangeAvailable' => app(QuotationExchange::class)->ready(),
|
||||||
|
'canRecordExchange' => $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||||
|
&& $requisition->status === 'approved' && ! PurchaseAward::query()->where('requisition_id', $requisition->id)->exists(),
|
||||||
|
])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function store(Request $request, Requisition $requisition, RequisitionWorkflow $workflow): RedirectResponse
|
public function store(Request $request, Requisition $requisition, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Procurement]), 403);
|
$actor = $this->access($request);
|
||||||
|
abort_unless($actor->hasFunctions([PurchasingRole::Procurement]), 403);
|
||||||
$data = $request->validate([
|
$data = $request->validate([
|
||||||
|
'currency' => ['sometimes', 'required', 'regex:/^[A-Z]{3}$/'],
|
||||||
'supplier_id' => 'required|integer', 'reference' => 'required|string|max:100',
|
'supplier_id' => 'required|integer', 'reference' => 'required|string|max:100',
|
||||||
'delivery_days' => 'required|integer|min:1|max:3650', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:today',
|
'delivery_days' => 'required|integer|min:1|max:3650', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:today',
|
||||||
'payment_terms' => 'required|string|min:3|max:500', 'no_conflict' => 'accepted',
|
'payment_terms' => 'required|string|min:3|max:500', 'no_conflict' => 'accepted',
|
||||||
@@ -68,17 +98,14 @@ class QuotationController extends Controller
|
|||||||
'items.*.discount_type' => 'sometimes|required|in:none,percent,amount',
|
'items.*.discount_type' => 'sometimes|required|in:none,percent,amount',
|
||||||
'items.*.discount_value' => 'required_with:items.*.discount_type|numeric|decimal:0,2|min:0|max:1000000000',
|
'items.*.discount_value' => 'required_with:items.*.discount_type|numeric|decimal:0,2|min:0|max:1000000000',
|
||||||
]);
|
]);
|
||||||
DB::transaction(function () use ($request, $requisition, $data, $workflow) {
|
DB::transaction(function () use ($actor, $requisition, $data, $workflow) {
|
||||||
$guard = app(ConflictGuard::class);
|
$guard = app(ConflictGuard::class);
|
||||||
$guard->lockCompany($request->user());
|
$guard->lockCompany($actor);
|
||||||
|
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
|
||||||
$requisition = Requisition::query()->lockForUpdate()->findOrFail($requisition->id);
|
$requisition = Requisition::query()->lockForUpdate()->findOrFail($requisition->id);
|
||||||
abort_unless($requisition->status === 'approved', 403);
|
app(QuotationParticipation::class)->assertPrepare($actor, $requisition);
|
||||||
if (PurchaseAward::query()->where('requisition_id', $requisition->id)->exists()) {
|
|
||||||
throw ValidationException::withMessages(['award' => 'As propostas estão fechadas pela adjudicação deste processo.']);
|
|
||||||
}
|
|
||||||
$guard->assertParticipation($request->user(), $requisition);
|
|
||||||
$supplier = Supplier::query()->whereKey($data['supplier_id'])->lockForUpdate()->firstOrFail();
|
$supplier = Supplier::query()->whereKey($data['supplier_id'])->lockForUpdate()->firstOrFail();
|
||||||
$guard->assertProcess($requisition, $supplier->id, $request->user());
|
$guard->assertProcess($requisition, $supplier->id, $actor);
|
||||||
if (! $supplier->eligible()) {
|
if (! $supplier->eligible()) {
|
||||||
throw ValidationException::withMessages(['supplier_id' => 'O fornecedor precisa de estar activo, sem impedimento e com revisão válida.']);
|
throw ValidationException::withMessages(['supplier_id' => 'O fornecedor precisa de estar activo, sem impedimento e com revisão válida.']);
|
||||||
}
|
}
|
||||||
@@ -86,6 +113,8 @@ class QuotationController extends Controller
|
|||||||
throw ValidationException::withMessages(['supplier_id' => 'Já existe uma proposta deste fornecedor neste processo.']);
|
throw ValidationException::withMessages(['supplier_id' => 'Já existe uma proposta deste fornecedor neste processo.']);
|
||||||
}
|
}
|
||||||
$lines = $requisition->items()->get()->keyBy('id');
|
$lines = $requisition->items()->get()->keyBy('id');
|
||||||
|
$currency = $data['currency'] ?? 'MZN';
|
||||||
|
$exchange = app(QuotationExchange::class)->basis($requisition, $currency);
|
||||||
if ($lines->count() !== count($data['items'])) {
|
if ($lines->count() !== count($data['items'])) {
|
||||||
throw ValidationException::withMessages(['items' => 'A proposta deve conter todas as linhas da requisição.']);
|
throw ValidationException::withMessages(['items' => 'A proposta deve conter todas as linhas da requisição.']);
|
||||||
}
|
}
|
||||||
@@ -108,20 +137,22 @@ class QuotationController extends Controller
|
|||||||
if ($subtotal + $tax > 100000000000000) {
|
if ($subtotal + $tax > 100000000000000) {
|
||||||
throw ValidationException::withMessages(['items' => 'Valor total acima do limite suportado.']);
|
throw ValidationException::withMessages(['items' => 'Valor total acima do limite suportado.']);
|
||||||
}
|
}
|
||||||
$items[] = ['tenant_id' => $request->user()->tenant_id, 'requisition_item_id' => $line->id, 'description' => $line->description, 'quantity' => $line->quantity, 'unit_price_minor' => $price, 'tax_rate' => $line->tax_rate, 'subtotal_minor' => $amount, 'tax_minor' => $vat, 'total_minor' => $amount + $vat];
|
$items[] = ['tenant_id' => $actor->tenant_id, 'requisition_item_id' => $line->id, 'description' => $line->description, 'quantity' => $line->quantity, 'unit_price_minor' => $price, 'tax_rate' => $line->tax_rate, 'subtotal_minor' => $amount, 'tax_minor' => $vat, 'total_minor' => $amount + $vat];
|
||||||
}
|
}
|
||||||
if ($subtotal <= 0) {
|
if ($subtotal <= 0) {
|
||||||
throw ValidationException::withMessages(['items' => 'O total arredondado deve ser pelo menos 0,01 MZN.']);
|
throw ValidationException::withMessages(['items' => 'O total arredondado deve ser pelo menos 0,01 na moeda da proposta.']);
|
||||||
}
|
}
|
||||||
$quote = Quotation::query()->create([
|
$quote = Quotation::query()->create([
|
||||||
'tenant_id' => $request->user()->tenant_id, 'requisition_id' => $requisition->id, 'supplier_id' => $supplier->id, 'created_by' => $request->user()->id,
|
'tenant_id' => $actor->tenant_id, 'requisition_id' => $requisition->id, 'supplier_id' => $supplier->id, 'created_by' => $actor->id,
|
||||||
'reference' => $data['reference'], 'delivery_days' => $data['delivery_days'], 'valid_until' => $data['valid_until'], 'payment_terms' => $data['payment_terms'],
|
'reference' => $data['reference'], 'delivery_days' => $data['delivery_days'], 'valid_until' => $data['valid_until'], 'payment_terms' => $data['payment_terms'],
|
||||||
'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax, 'currency' => 'MZN',
|
'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax, 'currency' => $currency,
|
||||||
|
...($exchange === null ? [] : ['exchange_basis' => $exchange]),
|
||||||
'weights' => app(ComparisonPolicy::class)->forRequest($requisition)['weights'],
|
'weights' => app(ComparisonPolicy::class)->forRequest($requisition)['weights'],
|
||||||
'commercial_terms' => array_filter($terms, fn ($term) => $term['discount_type'] !== 'none') === [] ? null : ['version' => 1, 'discount_basis' => 'unit_before_vat', 'rounding' => 'net_unit_half_up_cent', 'lines' => $terms],
|
'commercial_terms' => array_filter($terms, fn ($term) => $term['discount_type'] !== 'none') === [] ? null : ['version' => 1, 'discount_basis' => 'unit_before_vat', 'rounding' => 'net_unit_half_up_cent', 'lines' => $terms],
|
||||||
]);
|
]);
|
||||||
$quote->items()->createMany($items);
|
$quote->items()->createMany($items);
|
||||||
$workflow->audit($request->user(), 'quotation.created', $requisition, null, [...$quote->load('items')->toArray(), 'no_conflict' => true]);
|
app(QuotationExchange::class)->amounts($quote);
|
||||||
|
$workflow->audit($actor, 'quotation.created', $requisition, null, [...$quote->load('items')->toArray(), 'no_conflict' => true]);
|
||||||
});
|
});
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
@@ -129,30 +160,28 @@ class QuotationController extends Controller
|
|||||||
|
|
||||||
public function evaluate(Request $request, Quotation $quotation, RequisitionWorkflow $workflow): RedirectResponse
|
public function evaluate(Request $request, Quotation $quotation, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$this->access($request);
|
$actor = $this->access($request);
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
abort_unless($actor->hasFunctions([PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||||
$data = $request->validate(['quality' => 'required|numeric|decimal:0,2|between:0,10', 'history' => 'required|numeric|decimal:0,2|between:0,10', 'payment' => 'required|numeric|decimal:0,2|between:0,10', 'comment' => 'required|string|min:10|max:2000', 'no_conflict' => 'accepted']);
|
$data = $request->validate(['quality' => 'required|numeric|decimal:0,2|between:0,10', 'history' => 'required|numeric|decimal:0,2|between:0,10', 'payment' => 'required|numeric|decimal:0,2|between:0,10', 'comment' => 'required|string|min:10|max:2000', 'no_conflict' => 'accepted']);
|
||||||
DB::transaction(function () use ($request, $quotation, $data, $workflow) {
|
DB::transaction(function () use ($actor, $quotation, $data, $workflow) {
|
||||||
$guard = app(ConflictGuard::class);
|
$guard = app(ConflictGuard::class);
|
||||||
$guard->lockCompany($request->user());
|
$guard->lockCompany($actor);
|
||||||
$requisition = Requisition::query()->visibleTo($request->user())->lockForUpdate()->findOrFail($quotation->requisition_id);
|
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]);
|
||||||
abort_unless($requisition->status === 'approved' && $requisition->requester_id !== $request->user()->id, 403);
|
$requisition = Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($quotation->requisition_id);
|
||||||
if (PurchaseAward::query()->where('requisition_id', $requisition->id)->exists()) {
|
|
||||||
throw ValidationException::withMessages(['award' => 'As avaliações estão fechadas pela adjudicação deste processo.']);
|
|
||||||
}
|
|
||||||
$guard->assertParticipation($request->user(), $requisition);
|
|
||||||
$quotation = Quotation::query()->lockForUpdate()->findOrFail($quotation->id);
|
$quotation = Quotation::query()->lockForUpdate()->findOrFail($quotation->id);
|
||||||
$guard->assertProcess($requisition, $quotation->supplier_id, $request->user());
|
app(QuotationParticipation::class)->assertEvaluate($actor, $requisition, $quotation);
|
||||||
if ($quotation->valid_until < today() || ! $quotation->supplier?->eligible()) {
|
$evaluation = ProposalEvaluation::query()->create([...$data, 'no_conflict' => true, 'tenant_id' => $actor->tenant_id, 'quotation_id' => $quotation->id, 'evaluator_id' => $actor->id]);
|
||||||
throw ValidationException::withMessages(['evaluation' => 'Proposta expirada ou fornecedor não elegível.']);
|
$workflow->audit($actor, 'quotation.evaluated', $requisition, null, $evaluation->toArray());
|
||||||
}
|
|
||||||
if ($quotation->evaluations()->where('evaluator_id', $request->user()->id)->exists()) {
|
|
||||||
throw ValidationException::withMessages(['evaluation' => 'Já avaliou esta proposta.']);
|
|
||||||
}
|
|
||||||
$evaluation = ProposalEvaluation::query()->create([...$data, 'no_conflict' => true, 'tenant_id' => $request->user()->tenant_id, 'quotation_id' => $quotation->id, 'evaluator_id' => $request->user()->id]);
|
|
||||||
$workflow->audit($request->user(), 'quotation.evaluated', $requisition, null, $evaluation->toArray());
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function recordExchange(Request $request, Requisition $requisition, QuotationExchange $exchange): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $this->access($request);
|
||||||
|
$exchange->record($actor, $requisition, $request->only(['operation_id', 'currency', 'rate', 'quoted_on', 'source']));
|
||||||
|
|
||||||
|
return back();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\GoodsReceipt;
|
||||||
|
use App\Models\ReceiptDocument;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ReceiptDocuments;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Illuminate\Support\Facades\Gate;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
|
|
||||||
|
class ReceiptDocumentController extends Controller
|
||||||
|
{
|
||||||
|
public function store(Request $request, GoodsReceipt $receipt, ReceiptDocuments $documents): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
Gate::authorize('view', $receipt);
|
||||||
|
abort_unless($documents->canRead($actor, $receipt), 403);
|
||||||
|
abort_unless($documents->canAdd($actor, $receipt), 403);
|
||||||
|
$file = $request->file('file');
|
||||||
|
abort_unless($file instanceof UploadedFile, 422);
|
||||||
|
$documents->add($actor, $receipt, $request->only(['operation_key', 'document_type']), $file);
|
||||||
|
|
||||||
|
return redirect('/recepcoes/'.$receipt->id.'#receipt-documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function download(Request $request, GoodsReceipt $receipt, int $document, ReceiptDocuments $documents): StreamedResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $documents->canRead($actor, $receipt), 403);
|
||||||
|
Gate::authorize('view', $receipt);
|
||||||
|
abort_unless($documents->ready(), 503);
|
||||||
|
$file = ReceiptDocument::query()->where('goods_receipt_id', $receipt->id)->findOrFail($document);
|
||||||
|
$disk = Storage::disk('receipt_documents');
|
||||||
|
abort_unless($disk->exists($file->path), 404);
|
||||||
|
$stream = $disk->readStream($file->path);
|
||||||
|
abort_unless(is_resource($stream), 404);
|
||||||
|
$hash = hash_init('sha256');
|
||||||
|
hash_update_stream($hash, $stream);
|
||||||
|
if (! hash_equals($file->sha256, hash_final($hash))) {
|
||||||
|
fclose($stream);
|
||||||
|
abort(409, 'Documento indisponível para descarga. Solicite conferência ao responsável.');
|
||||||
|
}
|
||||||
|
rewind($stream);
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($stream) {
|
||||||
|
try {
|
||||||
|
fpassthru($stream);
|
||||||
|
} finally {
|
||||||
|
fclose($stream);
|
||||||
|
}
|
||||||
|
}, $file->original_name, ['Content-Type' => 'application/octet-stream', 'X-Content-Type-Options' => 'nosniff',
|
||||||
|
'Cache-Control' => 'private, no-store', 'Content-Security-Policy' => "default-src 'none'; sandbox"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\RequisitionAccountAssignments;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class RequisitionAccountsController extends Controller
|
||||||
|
{
|
||||||
|
public function show(Request $request, Requisition $requisition, RequisitionAccountAssignments $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$filters = $request->validate(['account_search' => 'nullable|string|max:100', 'accounts_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'history_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('requisitions/accounts', $service->workspace($actor, $requisition, $filters['account_search'] ?? ''))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, Requisition $requisition, RequisitionAccountAssignments $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Imputação contabilística preservada.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
|
use App\Services\RequisitionAuditTrail;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
|
|
||||||
|
class RequisitionAuditController extends Controller
|
||||||
|
{
|
||||||
|
public function csv(Request $request, int $requisition, RequisitionAuditTrail $trail): StreamedResponse
|
||||||
|
{
|
||||||
|
$this->visible($request, $requisition);
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($request, $requisition, $trail) {
|
||||||
|
DB::transaction(function () use ($request, $requisition, $trail) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
$source = $this->visible($request, $requisition);
|
||||||
|
$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 do histórico da requisição', $text($source->number), 'Conferido em', now()->toIso8601String()], ';', '"', '');
|
||||||
|
fputcsv($out, ['Registo', 'Data registada', 'Acção', 'Utilizador (id)', 'Modo de execução'], ';', '"', '');
|
||||||
|
foreach ($trail->query($source)->lazyById(100) as $record) {
|
||||||
|
$row = $trail->row($record);
|
||||||
|
fputcsv($out, array_map($text, [$row['id'], $row['created_at'], $row['action'], $row['user_id'], $row['execution']]), ';', '"', '');
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
fclose($out);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, 'historico-requisicao-'.$requisition.'-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function visible(Request $request, int $id): Requisition
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$actor = User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($actor->id);
|
||||||
|
$access = app(OrganizationAccess::class);
|
||||||
|
abort_unless(! $access->maintenanceOnly($actor) && $access->permissions($actor) !== [], 403);
|
||||||
|
|
||||||
|
return Requisition::query()->visibleTo($actor)->findOrFail($id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,15 +14,15 @@ class RequisitionCatalogueController extends Controller
|
|||||||
{
|
{
|
||||||
public function index(Request $request, RequisitionCatalogue $catalogue): Response
|
public function index(Request $request, RequisitionCatalogue $catalogue): Response
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions(['admin', 'warehouse']), 403);
|
abort_unless($this->staffIdentity($request)->hasFunctions(['admin', 'warehouse']), 403);
|
||||||
$filter = $request->validate(['search' => 'nullable|string|max:100']);
|
$filter = $request->validate(['search' => 'nullable|string|max:100']);
|
||||||
$ready = Schema::hasTable('requisition_catalogue');
|
$ready = Schema::hasTable('requisition_catalogue');
|
||||||
$query = StockItem::query()->where('tenant_id', $request->user()->tenant_id);
|
$query = StockItem::query()->where('tenant_id', $this->staffIdentity($request)->tenant_id);
|
||||||
if (($filter['search'] ?? '') !== '') {
|
if (($filter['search'] ?? '') !== '') {
|
||||||
$query->where(fn ($q) => $q->whereLike('name', '%'.$filter['search'].'%')->orWhereLike('code', '%'.$filter['search'].'%'));
|
$query->where(fn ($q) => $q->whereLike('name', '%'.$filter['search'].'%')->orWhereLike('code', '%'.$filter['search'].'%'));
|
||||||
}
|
}
|
||||||
$records = $query->orderBy('code')->paginate(15)->withQueryString();
|
$records = $query->orderBy('code')->paginate(15)->withQueryString();
|
||||||
$entries = $ready ? DB::table('requisition_catalogue')->where('tenant_id', $request->user()->tenant_id)->whereIn('stock_item_id', $records->pluck('id'))->get()->keyBy('stock_item_id') : collect();
|
$entries = $ready ? DB::table('requisition_catalogue')->where('tenant_id', $this->staffIdentity($request)->tenant_id)->whereIn('stock_item_id', $records->pluck('id'))->get()->keyBy('stock_item_id') : collect();
|
||||||
$records->through(function (StockItem $stock) use ($entries, $catalogue) {
|
$records->through(function (StockItem $stock) use ($entries, $catalogue) {
|
||||||
$entry = $entries->get($stock->id);
|
$entry = $entries->get($stock->id);
|
||||||
|
|
||||||
@@ -31,7 +31,7 @@ class RequisitionCatalogueController extends Controller
|
|||||||
'source_current' => $entry === null || json_decode($entry->source_snapshot, true, 16, JSON_THROW_ON_ERROR) === $catalogue->source($stock)];
|
'source_current' => $entry === null || json_decode($entry->source_snapshot, true, 16, JSON_THROW_ON_ERROR) === $catalogue->source($stock)];
|
||||||
});
|
});
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('stock/catalogue', ['records' => $records, 'ready' => $ready, 'canManage' => $catalogue->canManage($request->user()), 'filters' => $filter])->toResponse($request);
|
$response = Inertia::render('stock/catalogue', ['records' => $records, 'ready' => $ready, 'canManage' => $catalogue->canManage($this->staffIdentity($request)), 'filters' => $filter])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
return $response;
|
return $response;
|
||||||
@@ -40,7 +40,7 @@ class RequisitionCatalogueController extends Controller
|
|||||||
public function save(Request $request, int $stock, RequisitionCatalogue $catalogue): Response
|
public function save(Request $request, int $stock, RequisitionCatalogue $catalogue): Response
|
||||||
{
|
{
|
||||||
abort_unless(Schema::hasTable('requisition_catalogue'), 503, 'Instalação do catálogo pendente.');
|
abort_unless(Schema::hasTable('requisition_catalogue'), 503, 'Instalação do catálogo pendente.');
|
||||||
$catalogue->save($request->user(), $stock, $request->all());
|
$catalogue->save($this->staffIdentity($request), $stock, $request->all());
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Http\Requests\StoreRequisitionRequest;
|
use App\Http\Requests\StoreRequisitionRequest;
|
||||||
use App\Models\AuditLog;
|
|
||||||
use App\Models\CostCenter;
|
use App\Models\CostCenter;
|
||||||
use App\Models\Equipment;
|
use App\Models\Equipment;
|
||||||
use App\Models\EquipmentSparePart;
|
use App\Models\EquipmentSparePart;
|
||||||
@@ -12,32 +11,59 @@ use App\Models\SparePart;
|
|||||||
use App\Models\StockItem;
|
use App\Models\StockItem;
|
||||||
use App\Models\TechnicalReview;
|
use App\Models\TechnicalReview;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ApprovalRouting;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
use App\Services\ComparisonPolicy;
|
use App\Services\ComparisonPolicy;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
use App\Services\EquipmentWorkflow;
|
use App\Services\EquipmentWorkflow;
|
||||||
|
use App\Services\ImportEstimates;
|
||||||
|
use App\Services\ImportTariffCodes;
|
||||||
|
use App\Services\InternalSupplyTrace;
|
||||||
|
use App\Services\OperationalOrders;
|
||||||
use App\Services\OrganizationAccess;
|
use App\Services\OrganizationAccess;
|
||||||
|
use App\Services\RequisitionAuditTrail;
|
||||||
|
use App\Services\RequisitionBudgetDistributions;
|
||||||
use App\Services\RequisitionCatalogue;
|
use App\Services\RequisitionCatalogue;
|
||||||
|
use App\Services\RequisitionCategories;
|
||||||
|
use App\Services\RequisitionDraftInput;
|
||||||
|
use App\Services\RequisitionDuplicateHints;
|
||||||
|
use App\Services\RequisitionExpiry;
|
||||||
|
use App\Services\RequisitionLedgerAccounts;
|
||||||
|
use App\Services\RequisitionSubmissionPreview;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
|
use App\Services\SupplySuggestions;
|
||||||
|
use App\Services\WorkContext;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Inertia\Response;
|
||||||
|
|
||||||
class RequisitionController extends Controller
|
class RequisitionController extends Controller
|
||||||
{
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
public function index(Request $request): Response
|
public function index(Request $request): Response
|
||||||
{
|
{
|
||||||
$filters = $request->validate(['search' => 'nullable|string|max:100', 'status' => ['nullable', Rule::in(['draft', 'pending', 'approved', 'rejected', 'cancelled'])], 'view' => ['nullable', Rule::in(['all', 'mine', 'approvals', 'decided'])]]);
|
$filters = $request->validate(['search' => 'nullable|string|max:100', 'status' => ['nullable', Rule::in(['draft', 'pending', 'approved', 'rejected', 'cancelled'])], 'view' => ['nullable', Rule::in(['all', 'mine', 'approvals', 'decided'])]]);
|
||||||
$query = Requisition::query()->visibleTo($request->user())->with(['requester:id,name', 'department:id,name', 'steps']);
|
$query = Requisition::query()->visibleTo($this->actor($request))->with(['requester:id,name', 'department:id,name', 'steps']);
|
||||||
if (($filters['view'] ?? 'all') === 'mine') {
|
if (($filters['view'] ?? 'all') === 'mine') {
|
||||||
$query->where('requester_id', $request->user()->id);
|
$query->where('requester_id', $this->actor($request)->id);
|
||||||
} elseif (($filters['view'] ?? 'all') === 'approvals') {
|
} elseif (($filters['view'] ?? 'all') === 'approvals') {
|
||||||
$eligible = (clone $query)->where('status', 'pending')->get()
|
$eligible = (clone $query)->where('status', 'pending')->get()
|
||||||
->filter(fn (Requisition $requisition) => $requisition->canDecide($request->user()))->modelKeys();
|
->filter(fn (Requisition $requisition) => $requisition->canDecide($this->actor($request)))->modelKeys();
|
||||||
$query->whereIn('id', $eligible);
|
$query->whereIn('id', $eligible);
|
||||||
} elseif (($filters['view'] ?? 'all') === 'decided') {
|
} elseif (($filters['view'] ?? 'all') === 'decided') {
|
||||||
$query->whereHas('steps', fn ($steps) => $steps->where('approver_id', $request->user()->id)->whereIn('decision', ['approved', 'rejected']));
|
$query->whereHas('allSteps', fn ($steps) => $steps->where('approver_id', $this->actor($request)->id)->whereIn('decision', ['approved', 'rejected']));
|
||||||
}
|
}
|
||||||
if (! empty($filters['search'])) {
|
if (! empty($filters['search'])) {
|
||||||
$query->where('number', 'like', '%'.$filters['search'].'%');
|
$query->where('number', 'like', '%'.$filters['search'].'%');
|
||||||
@@ -54,12 +80,15 @@ class RequisitionController extends Controller
|
|||||||
|
|
||||||
public function create(Request $request): Response
|
public function create(Request $request): Response
|
||||||
{
|
{
|
||||||
abort_unless(app(OrganizationAccess::class)->canRequest($request->user()), 403);
|
abort_unless(app(OrganizationAccess::class)->canRequest($this->actor($request)), 403);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
return Inertia::render('requisitions/form', [
|
return Inertia::render('requisitions/form', [
|
||||||
'costCenters' => CostCenter::query()->where('department_id', $request->user()->department_id)->orderBy('code')->get(),
|
'costCenters' => CostCenter::query()->where('department_id', $this->actor($request)->department_id)->orderBy('code')->get(),
|
||||||
'requisition' => null,
|
'requisition' => null,
|
||||||
'defaultTaxRate' => (string) (Tenant::query()->findOrFail($request->user()->tenant_id)->default_tax_rate ?? '16.00'),
|
'requisitionCategories' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
||||||
|
'incompleteDraftsAvailable' => app(RequisitionDraftInput::class)->available(),
|
||||||
|
'defaultTaxRate' => (string) (Tenant::query()->findOrFail($this->actor($request)->tenant_id)->default_tax_rate ?? '16.00'),
|
||||||
...$this->equipmentOptions($request),
|
...$this->equipmentOptions($request),
|
||||||
'catalogue' => $this->catalogueOptions($request),
|
'catalogue' => $this->catalogueOptions($request),
|
||||||
]);
|
]);
|
||||||
@@ -67,40 +96,101 @@ class RequisitionController extends Controller
|
|||||||
|
|
||||||
public function store(StoreRequisitionRequest $request, RequisitionWorkflow $workflow): RedirectResponse
|
public function store(StoreRequisitionRequest $request, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$requisition = $workflow->save($request->user(), $request->validated());
|
$requisition = $workflow->save($this->actor($request), $request->validated());
|
||||||
|
|
||||||
return to_route('requisitions.show', $requisition);
|
return to_route('requisitions.show', $requisition);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Request $request, Requisition $requisition): Response
|
public function show(Request $request, Requisition $requisition): Response
|
||||||
{
|
{
|
||||||
Requisition::query()->visibleTo($request->user())->findOrFail($requisition->id);
|
return DB::transaction(function () use ($request, $requisition) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->detail($request, $requisition);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function detail(Request $request, Requisition $requisition): Response
|
||||||
|
{
|
||||||
|
$requisition = Requisition::query()->visibleTo($this->actor($request))->findOrFail($requisition->id);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$request->validate(['audit_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$trail = app(RequisitionAuditTrail::class);
|
||||||
|
$audit = $trail->query($requisition)->orderBy('id')->paginate(25, ['*'], 'audit_page')->withQueryString();
|
||||||
$requisition->load(['items', 'steps', 'requester:id,name', 'department:id,name', 'costCenter']);
|
$requisition->load(['items', 'steps', 'requester:id,name', 'department:id,name', 'costCenter']);
|
||||||
|
|
||||||
return Inertia::render('requisitions/show', [
|
return Inertia::render('requisitions/show', [
|
||||||
'requisition' => $requisition,
|
'requisition' => $requisition,
|
||||||
|
'submissionPreview' => app(RequisitionSubmissionPreview::class)->for($this->actor($request), $requisition),
|
||||||
|
'duplicateHints' => app(RequisitionDuplicateHints::class)->for($this->actor($request), $requisition),
|
||||||
|
'canReadAuditMetadata' => ! app(OrganizationAccess::class)->maintenanceOnly($this->actor($request))
|
||||||
|
&& in_array('audit_metadata_read', app(OrganizationAccess::class)->permissions($this->actor($request)), true),
|
||||||
|
'approvalRouting' => app(ApprovalRouting::class)->current($requisition, $this->actor($request)),
|
||||||
|
'canRefreshRouting' => $requisition->status === 'pending' && $this->actor($request)->hasFunctions(['admin', 'procurement']) && ! app(OrganizationAccess::class)->maintenanceOnly($this->actor($request)) && Schema::hasTable('workflow_notices'),
|
||||||
|
'replenishmentSource' => app(SupplySuggestions::class)->origin($requisition),
|
||||||
|
'automaticSource' => app(InternalSupplyTrace::class)->purchaseOrigin($this->actor($request), $requisition),
|
||||||
'comparisonPolicy' => app(ComparisonPolicy::class)->forRequest($requisition),
|
'comparisonPolicy' => app(ComparisonPolicy::class)->forRequest($requisition),
|
||||||
'canEdit' => app(OrganizationAccess::class)->canRequest($request->user()) && $requisition->requester_id === $request->user()->id && $requisition->status === 'draft',
|
'canEdit' => app(OrganizationAccess::class)->canRequest($this->actor($request)) && $requisition->requester_id === $this->actor($request)->id && $requisition->status === 'draft',
|
||||||
'canDecide' => $requisition->canDecide($request->user()),
|
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
|
||||||
'conflictBlocked' => app(ConflictGuard::class)->participationBlocked($request->user(), $requisition),
|
'importEstimatesReady' => app(ImportEstimates::class)->ready(),
|
||||||
'audit' => AuditLog::query()->where('requisition_id', $requisition->id)->orderBy('id')->get(['id', 'action', 'user_id', 'created_at']),
|
'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
|
||||||
|
'operationalOrdersReady' => app(OperationalOrders::class)->ready(),
|
||||||
|
'accountsReady' => app(RequisitionLedgerAccounts::class)->ready(),
|
||||||
|
'expiryReady' => app(RequisitionExpiry::class)->ready(),
|
||||||
|
'canDecide' => $requisition->canDecide($this->actor($request)),
|
||||||
|
'canPrepareDistributions' => app(RequisitionBudgetDistributions::class)->ready() && $requisition->status === 'draft'
|
||||||
|
&& $requisition->requester_id === $this->actor($request)->id && app(OrganizationAccess::class)->canRequest($this->actor($request)),
|
||||||
|
'conflictBlocked' => app(ConflictGuard::class)->participationBlocked($this->actor($request), $requisition),
|
||||||
|
'audit' => $audit->getCollection()->map(fn ($a) => $trail->row($a)),
|
||||||
|
'auditPagination' => ['total' => $audit->total(), 'current_page' => $audit->currentPage(), 'last_page' => $audit->lastPage(),
|
||||||
|
'prev_page_url' => $audit->previousPageUrl(), 'next_page_url' => $audit->nextPageUrl()],
|
||||||
'technical' => [
|
'technical' => [
|
||||||
'canReview' => app(EquipmentWorkflow::class)->canReview($request->user(), $requisition),
|
'canReview' => app(EquipmentWorkflow::class)->canReview($this->actor($request), $requisition),
|
||||||
'basis_hash' => app(EquipmentWorkflow::class)->basis($requisition),
|
'basis_hash' => app(EquipmentWorkflow::class)->basis($requisition),
|
||||||
'reviews' => TechnicalReview::query()->where('requisition_id', $requisition->id)->orderBy('id')->get(),
|
'reviews' => TechnicalReview::query()->where('requisition_id', $requisition->id)->orderBy('id')->get(),
|
||||||
],
|
],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function distributions(Request $request, Requisition $requisition): Response
|
||||||
|
{
|
||||||
|
abort_unless(app(RequisitionBudgetDistributions::class)->ready(), 503);
|
||||||
|
$actor = $this->actor($request);
|
||||||
|
$requisition = Requisition::query()->visibleTo($actor)->findOrFail($requisition->id);
|
||||||
|
abort_unless($requisition->requester_id === $actor->id && $requisition->status === 'draft' && app(OrganizationAccess::class)->canRequest($actor), 403);
|
||||||
|
app(ConflictGuard::class)->assertParticipation($actor, $requisition);
|
||||||
|
app(RequisitionBudgetDistributions::class)->requestLines($requisition);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
|
return Inertia::render('requisitions/distributions', ['requisition' => $requisition->load('items'),
|
||||||
|
'centres' => CostCenter::query()->where('department_id', $requisition->department_id)->orderBy('code')->get(['id', 'code', 'name']),
|
||||||
|
'preparation' => $requisition->budget_distribution_preparation]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function prepareDistributions(Request $request, Requisition $requisition): RedirectResponse
|
||||||
|
{
|
||||||
|
abort_unless(app(RequisitionBudgetDistributions::class)->ready(), 503);
|
||||||
|
$data = $request->validate([...app(RequisitionBudgetDistributions::class)->rules($requisition),
|
||||||
|
'operation_key' => 'required|uuid', 'process_version' => 'required|integer|min:1']);
|
||||||
|
app(RequisitionWorkflow::class)->save($this->actor($request), $data, $requisition);
|
||||||
|
|
||||||
|
return to_route('requisitions.show', $requisition);
|
||||||
|
}
|
||||||
|
|
||||||
public function edit(Request $request, Requisition $requisition): Response
|
public function edit(Request $request, Requisition $requisition): Response
|
||||||
{
|
{
|
||||||
abort_unless(app(OrganizationAccess::class)->canRequest($request->user()), 403);
|
abort_unless(app(OrganizationAccess::class)->canRequest($this->actor($request)), 403);
|
||||||
abort_unless($requisition->requester_id === $request->user()->id && $requisition->status === 'draft', 403);
|
abort_unless($requisition->requester_id === $this->actor($request)->id && $requisition->status === 'draft', 403);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
return Inertia::render('requisitions/form', [
|
return Inertia::render('requisitions/form', [
|
||||||
'requisition' => $requisition->load('items'),
|
'requisition' => $requisition->load('items'),
|
||||||
'defaultTaxRate' => (string) (Tenant::query()->findOrFail($request->user()->tenant_id)->default_tax_rate ?? '16.00'),
|
'requisitionCategories' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
||||||
'costCenters' => CostCenter::query()->where('department_id', $request->user()->department_id)->orderBy('code')->get(),
|
'incompleteDraftsAvailable' => app(RequisitionDraftInput::class)->available(),
|
||||||
|
'defaultTaxRate' => (string) (Tenant::query()->findOrFail($this->actor($request)->tenant_id)->default_tax_rate ?? '16.00'),
|
||||||
|
'costCenters' => CostCenter::query()->where('department_id', $this->actor($request)->department_id)->orderBy('code')->get(),
|
||||||
...$this->equipmentOptions($request),
|
...$this->equipmentOptions($request),
|
||||||
'catalogue' => $this->catalogueOptions($request),
|
'catalogue' => $this->catalogueOptions($request),
|
||||||
]);
|
]);
|
||||||
@@ -109,7 +199,7 @@ class RequisitionController extends Controller
|
|||||||
/** @return array<string,mixed> */
|
/** @return array<string,mixed> */
|
||||||
private function equipmentOptions(Request $request): array
|
private function equipmentOptions(Request $request): array
|
||||||
{
|
{
|
||||||
$equipment = Equipment::query()->where('department_id', $request->user()->department_id)->orderBy('code')->get(['id', 'code', 'description']);
|
$equipment = Equipment::query()->where('department_id', $this->actor($request)->department_id)->orderBy('code')->get(['id', 'code', 'description']);
|
||||||
$parts = SparePart::query()->whereIn('id', EquipmentSparePart::query()->whereIn('equipment_id', $equipment->pluck('id'))->select('spare_part_id'))->get(['id', 'stock_item_id']);
|
$parts = SparePart::query()->whereIn('id', EquipmentSparePart::query()->whereIn('equipment_id', $equipment->pluck('id'))->select('spare_part_id'))->get(['id', 'stock_item_id']);
|
||||||
|
|
||||||
return ['equipment' => $equipment, 'spareParts' => $parts, 'stockItems' => StockItem::query()->whereIn('id', $parts->pluck('stock_item_id'))->get(['id', 'code', 'name', 'unit'])];
|
return ['equipment' => $equipment, 'spareParts' => $parts, 'stockItems' => StockItem::query()->whereIn('id', $parts->pluck('stock_item_id'))->get(['id', 'code', 'name', 'unit'])];
|
||||||
@@ -120,27 +210,28 @@ class RequisitionController extends Controller
|
|||||||
{
|
{
|
||||||
$search = $request->validate(['catalogo' => 'nullable|string|max:100'])['catalogo'] ?? '';
|
$search = $request->validate(['catalogo' => 'nullable|string|max:100'])['catalogo'] ?? '';
|
||||||
|
|
||||||
return app(RequisitionCatalogue::class)->options($request->user(), $search);
|
return app(RequisitionCatalogue::class)->options($this->actor($request), $search);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function technical(Request $request, Requisition $requisition): RedirectResponse
|
public function technical(Request $request, Requisition $requisition): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['basis_hash' => 'required|string|size:64', 'decision' => ['required', Rule::in(['approved', 'rejected'])], 'reason' => 'required|string|max:4000']);
|
$data = $request->validate(['basis_hash' => 'required|string|size:64', 'decision' => ['required', Rule::in(['approved', 'rejected'])], 'reason' => 'required|string|max:4000']);
|
||||||
app(EquipmentWorkflow::class)->review($request->user(), $requisition, $data['basis_hash'], $data['decision'], $data['reason']);
|
app(EquipmentWorkflow::class)->review($this->actor($request), $requisition, $data['basis_hash'], $data['decision'], $data['reason']);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function update(StoreRequisitionRequest $request, Requisition $requisition, RequisitionWorkflow $workflow): RedirectResponse
|
public function update(StoreRequisitionRequest $request, Requisition $requisition, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$workflow->save($request->user(), $request->validated(), $requisition);
|
$workflow->save($this->actor($request), $request->validated(), $requisition);
|
||||||
|
|
||||||
return to_route('requisitions.show', $requisition);
|
return to_route('requisitions.show', $requisition);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function submit(Request $request, Requisition $requisition, RequisitionWorkflow $workflow): RedirectResponse
|
public function submit(Request $request, Requisition $requisition, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$workflow->submit($request->user(), $requisition);
|
$command = $request->validate(['operation_key' => 'nullable|uuid', 'process_version' => 'nullable|integer|min:1']);
|
||||||
|
$workflow->submit($this->actor($request), $requisition, $command['operation_key'] ?? null, $command['process_version'] ?? null);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -150,28 +241,35 @@ class RequisitionController extends Controller
|
|||||||
$data = $request->validate([
|
$data = $request->validate([
|
||||||
'decision' => ['required', Rule::in(['approved', 'rejected'])],
|
'decision' => ['required', Rule::in(['approved', 'rejected'])],
|
||||||
'comment' => ['nullable', 'required_if:decision,rejected', 'string', 'max:2000'],
|
'comment' => ['nullable', 'required_if:decision,rejected', 'string', 'max:2000'],
|
||||||
|
'operation_key' => 'nullable|uuid', 'process_version' => 'nullable|integer|min:1',
|
||||||
]);
|
]);
|
||||||
$workflow->decide($request->user(), $requisition, $data['decision'], $data['comment'] ?? null);
|
$workflow->decide($this->actor($request), $requisition, $data['decision'], $data['comment'] ?? null, $data['operation_key'] ?? null, $data['process_version'] ?? null);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function dashboard(Request $request): Response
|
public function dashboard(Request $request): Response
|
||||||
{
|
{
|
||||||
$visible = Requisition::query()->visibleTo($request->user());
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$contexts = app(WorkContext::class);
|
||||||
|
if ($contexts->enforced($actor)) {
|
||||||
|
return Inertia::render('work-context', ['context' => $contexts->shared($request)]);
|
||||||
|
}
|
||||||
|
$visible = Requisition::query()->visibleTo($this->actor($request));
|
||||||
$pending = (clone $visible)->where('status', 'pending')->with('steps')->get();
|
$pending = (clone $visible)->where('status', 'pending')->with('steps')->get();
|
||||||
|
|
||||||
return Inertia::render('dashboard', [
|
return Inertia::render('dashboard', [
|
||||||
'company' => $request->user()->tenant_id ? Tenant::query()->find($request->user()->tenant_id) : null,
|
'company' => $this->actor($request)->tenant_id ? Tenant::query()->find($this->actor($request)->tenant_id) : null,
|
||||||
'stats' => [
|
'stats' => [
|
||||||
'total' => (clone $visible)->count(),
|
'total' => (clone $visible)->count(),
|
||||||
'pending' => $pending->count(),
|
'pending' => $pending->count(),
|
||||||
'approved' => (clone $visible)->where('status', 'approved')->count(),
|
'approved' => (clone $visible)->where('status', 'approved')->count(),
|
||||||
'approvedMinor' => (clone $visible)->where('status', 'approved')->sum('total_minor'),
|
'approvedMinor' => (clone $visible)->where('status', 'approved')->sum('total_minor'),
|
||||||
'awaitingMe' => $pending->filter(fn (Requisition $r) => $r->canDecide($request->user()))->count(),
|
'awaitingMe' => $pending->filter(fn (Requisition $r) => $r->canDecide($this->actor($request)))->count(),
|
||||||
],
|
],
|
||||||
'recent' => (clone $visible)->with(['requester:id,name', 'department:id,name'])->latest()->limit(6)->get(),
|
'recent' => (clone $visible)->with(['requester:id,name', 'department:id,name'])->latest()->limit(6)->get(),
|
||||||
'approvals' => $pending->filter(fn (Requisition $r) => $r->canDecide($request->user()))->take(5)->values(),
|
'approvals' => $pending->filter(fn (Requisition $r) => $r->canDecide($this->actor($request)))->take(5)->values(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\RequisitionExpiry;
|
||||||
|
use App\Services\RequisitionWorkflow;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class RequisitionExpiryController extends Controller
|
||||||
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $props */
|
||||||
|
private function page(Request $request, string $component, array $props): Response
|
||||||
|
{
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render($component, $props)->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function settings(Request $request, RequisitionExpiry $service): Response
|
||||||
|
{
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
|
||||||
|
return $this->page($request, 'organization/approval-timeouts', $service->settings($this->actor($request)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function saveSettings(Request $request, RequisitionExpiry $service): Response
|
||||||
|
{
|
||||||
|
$service->savePolicy($this->actor($request), $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Política preservada para novas submissões.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(Request $request, Requisition $requisition, RequisitionExpiry $service): Response
|
||||||
|
{
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
|
||||||
|
return $this->page($request, 'requisitions/expiry', $service->workspace($this->actor($request), $requisition));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function expire(Request $request, Requisition $requisition, RequisitionWorkflow $workflow): Response
|
||||||
|
{
|
||||||
|
$data = $request->validate(['operation_key' => 'required|uuid', 'process_version' => 'required|integer|min:1',
|
||||||
|
'basis_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'comment' => 'nullable|string|max:2000']);
|
||||||
|
$workflow->expire($this->actor($request), $requisition, $data['basis_hash'], $data['operation_key'], (int) $data['process_version'], $data['comment'] ?? null);
|
||||||
|
|
||||||
|
return back()->with('success', 'Pedido devolvido ao requisitante; decisões e reservas anteriores preservadas no histórico.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function check(Request $request, Requisition $requisition, RequisitionExpiry $service): Response
|
||||||
|
{
|
||||||
|
$result = $service->check($this->actor($request), $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', $result['action'] === 'returned'
|
||||||
|
? 'Prazo terminado: pedido devolvido ao requisitante.'
|
||||||
|
: 'Prazos conferidos; avisos devidos registados sem duplicação.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\SavedProcurementSearches;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
final class SavedProcurementSearchController extends Controller
|
||||||
|
{
|
||||||
|
public function store(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
return $this->change($request, 'save');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(Request $request, int $search): RedirectResponse
|
||||||
|
{
|
||||||
|
return $this->change($request, 'save', $search);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function archive(Request $request, int $search): RedirectResponse
|
||||||
|
{
|
||||||
|
return $this->change($request, 'archive', $search);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function restore(Request $request, int $search): RedirectResponse
|
||||||
|
{
|
||||||
|
return $this->change($request, 'restore', $search);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function change(Request $request, string $action, ?int $id = null): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$query = $request->validate(['q' => 'nullable|string|max:100']);
|
||||||
|
app(SavedProcurementSearches::class)->command($actor, $action, $id, $request->all());
|
||||||
|
|
||||||
|
return to_route('procurement.search', ['q' => $query['q'] ?? '']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,12 +3,17 @@
|
|||||||
namespace App\Http\Controllers\Settings;
|
namespace App\Http\Controllers\Settings;
|
||||||
|
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Http\Middleware\RequireTwoFactorForSensitiveRoles;
|
||||||
use App\Http\Requests\Settings\PasswordUpdateRequest;
|
use App\Http\Requests\Settings\PasswordUpdateRequest;
|
||||||
use App\Http\Requests\Settings\TwoFactorAuthenticationRequest;
|
use App\Http\Requests\Settings\TwoFactorAuthenticationRequest;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Auth\Middleware\RequirePassword;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Validation\Rules\Password;
|
use Illuminate\Validation\Rules\Password;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Laravel\Fortify\Features;
|
||||||
|
use Laravel\Fortify\Fortify;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class SecurityController extends Controller
|
class SecurityController extends Controller
|
||||||
{
|
{
|
||||||
@@ -17,11 +22,35 @@ class SecurityController extends Controller
|
|||||||
*/
|
*/
|
||||||
public function edit(TwoFactorAuthenticationRequest $request): Response
|
public function edit(TwoFactorAuthenticationRequest $request): Response
|
||||||
{
|
{
|
||||||
|
if (Features::enabled(Features::twoFactorAuthentication())) {
|
||||||
|
return app(RequirePassword::class)->handle($request, fn () => $this->page($request));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->page($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function page(TwoFactorAuthenticationRequest $request): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
$props = [
|
$props = [
|
||||||
'passwordRules' => Password::defaults()->toPasswordRulesString(),
|
'passwordRules' => Password::defaults()->toPasswordRulesString(),
|
||||||
];
|
];
|
||||||
|
if (Features::enabled(Features::twoFactorAuthentication())) {
|
||||||
|
$props += [
|
||||||
|
'canManageTwoFactor' => true,
|
||||||
|
'twoFactorEnabled' => $actor->hasEnabledTwoFactorAuthentication(),
|
||||||
|
'twoFactorPending' => $actor->two_factor_secret !== null && ! $actor->hasEnabledTwoFactorAuthentication(),
|
||||||
|
'requiresConfirmation' => Fortify::confirmsTwoFactorAuthentication(),
|
||||||
|
'mfaRequired' => RequireTwoFactorForSensitiveRoles::requiredFor($actor),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
return Inertia::render('settings/security', $props);
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('settings/security', $props)->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\SgfInvoiceDispatches;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Response;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
final class SgfInvoiceDispatchController extends Controller
|
||||||
|
{
|
||||||
|
private function actor(Request $r, SgfInvoiceDispatches $service): User
|
||||||
|
{
|
||||||
|
$user = $r->user('web');
|
||||||
|
abort_unless($user instanceof User, 403);
|
||||||
|
|
||||||
|
return $service->actor($user);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function index(Request $r, SgfInvoiceDispatches $service): Response
|
||||||
|
{
|
||||||
|
$user = $this->actor($r, $service);
|
||||||
|
$d = $r->validate(['page' => 'sometimes|integer|min:1|max:100000', 'phase' => 'nullable|in:draft,previewing,previewed,sending,uncertain,received_pending,blocked,review_required,not_sent', 'connection' => 'nullable|string|max:64', 'mapping' => 'nullable|string|max:64']);
|
||||||
|
abort_if(array_diff(array_keys($r->query()), array_keys($d)) !== [], 422);
|
||||||
|
$rows = DB::table('sgf_invoice_dispatches')->where('tenant_id', $user->tenant_id)->when($d['phase'] ?? null, fn ($q, $v) => $q->where('phase', $v))
|
||||||
|
->orderByDesc('id')->paginate(25, ['id', 'reference', 'number', 'phase', 'version', 'updated_at'])->withQueryString();
|
||||||
|
$mapping = null;
|
||||||
|
foreach ($service->mappings($user) as $m) {
|
||||||
|
if ($m['connection'] === ($d['connection'] ?? null) && $m['id'] === ($d['mapping'] ?? null)) {
|
||||||
|
$mapping = $m;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response()->view('sgf-invoices.index', ['rows' => $rows, 'options' => $service->mappings($user), 'selection' => $mapping])->header('Cache-Control', 'private, no-store');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(int $id, Request $r, SgfInvoiceDispatches $service): Response
|
||||||
|
{
|
||||||
|
$user = $this->actor($r, $service);
|
||||||
|
$d = $r->validate(['events_page' => 'sometimes|integer|min:1|max:100000']);
|
||||||
|
abort_if(array_diff(array_keys($r->query()), array_keys($d)) !== [], 422);
|
||||||
|
$row = $service->row($user, $id);
|
||||||
|
$events = DB::table('sgf_invoice_dispatch_events')->where('tenant_id', $user->tenant_id)->where('dispatch_id', $id)->orderByDesc('id')
|
||||||
|
->paginate(25, ['actor_id', 'action', 'reason', 'before_state', 'after_state', 'created_at'], 'events_page')->withQueryString();
|
||||||
|
|
||||||
|
return response()->view('sgf-invoices.show', ['row' => $service->presentation($user, $row), 'events' => $events, 'options' => $service->mappings($user), 'transportEnabled' => config('sgf_invoice.enabled') === true])->header('Cache-Control', 'private, no-store');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function create(Request $r, SgfInvoiceDispatches $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$user = $this->actor($r, $service);
|
||||||
|
$input = $r->except('_token');
|
||||||
|
$id = $service->create($user, $input);
|
||||||
|
|
||||||
|
return redirect('/facturas/envio-sgf/'.$id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function revise(int $id, Request $r, SgfInvoiceDispatches $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$user = $this->actor($r, $service);
|
||||||
|
$d = $r->validate(['version' => 'required|integer|min:1']);
|
||||||
|
$service->revise($user, $id, (int) $d['version'], $r->except('_token', 'version'));
|
||||||
|
|
||||||
|
return redirect('/facturas/envio-sgf/'.$id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function dispatch(int $id, Request $r, SgfInvoiceDispatches $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$user = $this->actor($r, $service);
|
||||||
|
$d = $r->validate(['version' => 'required|integer|min:1', 'action' => 'required|in:preview,confirm,recover', 'reason' => 'required|string|min:10|max:2000', 'approval_hash' => 'nullable|string|size:64']);
|
||||||
|
abort_if(array_diff(array_keys($r->except('_token')), array_keys($d)) !== [], 422);
|
||||||
|
$service->dispatch($user, $id, (int) $d['version'], $d['action'], $d['reason'], $d['approval_hash'] ?? null);
|
||||||
|
|
||||||
|
return redirect('/facturas/envio-sgf/'.$id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,23 +5,39 @@ namespace App\Http\Controllers;
|
|||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\StockItem;
|
use App\Models\StockItem;
|
||||||
use App\Models\StockMovement;
|
use App\Models\StockMovement;
|
||||||
|
use App\Models\User;
|
||||||
use App\Models\Warehouse;
|
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 App\Services\RequisitionWorkflow;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class StockController extends Controller
|
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
|
private function access(Request $request, bool $manage = false): void
|
||||||
{
|
{
|
||||||
$roles = $manage ? [PurchasingRole::Admin, PurchasingRole::Warehouse] : [PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance];
|
$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
|
public function index(Request $request): Response
|
||||||
@@ -29,28 +45,50 @@ class StockController extends Controller
|
|||||||
$this->access($request);
|
$this->access($request);
|
||||||
$filters = $request->validate([
|
$filters = $request->validate([
|
||||||
'search' => 'nullable|string|max:100',
|
'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']);
|
$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();
|
$selected = StockItem::query();
|
||||||
if (! empty($filters['search'])) {
|
if (! empty($filters['search'])) {
|
||||||
$selected->where(fn ($q) => $q->where('code', 'like', '%'.$filters['search'].'%')->orWhere('name', 'like', '%'.$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'));
|
$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'])) {
|
if (! empty($filters['warehouse_id'])) {
|
||||||
$movements->where('warehouse_id', $filters['warehouse_id']);
|
$movements->where('warehouse_id', $filters['warehouse_id']);
|
||||||
}
|
}
|
||||||
$balances = (clone $movements)->selectRaw('stock_item_id, warehouse_id, SUM(quantity_milli) as quantity_milli')->groupBy('stock_item_id', 'warehouse_id')->get()->map(fn ($balance) => [
|
$balances = (clone $movements)->selectRaw('stock_item_id, warehouse_id, SUM(quantity_milli) as quantity_milli')->groupBy('stock_item_id', 'warehouse_id')->get()->map(fn ($balance) => [
|
||||||
'stock_item_id' => $balance->stock_item_id, 'warehouse_id' => $balance->warehouse_id,
|
'stock_item_id' => $balance->stock_item_id, 'warehouse_id' => $balance->warehouse_id,
|
||||||
'quantity_milli' => BigDecimal::of($balance->quantity_milli)->toInt(),
|
'quantity_milli' => BigDecimal::of($balance->quantity_milli)->toInt(),
|
||||||
|
'lot_control' => app(InventoryLots::class)->summary($balance->stock_item_id, $balance->warehouse_id),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return Inertia::render('stock/index', [
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('stock/index', [
|
||||||
'items' => $items, 'warehouses' => $warehouses, 'balances' => $balances,
|
'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,
|
'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]),
|
||||||
]);
|
])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function item(Request $request, RequisitionWorkflow $audit): RedirectResponse
|
public function item(Request $request, RequisitionWorkflow $audit): RedirectResponse
|
||||||
@@ -58,12 +96,12 @@ class StockController extends Controller
|
|||||||
$this->access($request, true);
|
$this->access($request, true);
|
||||||
$request->merge(['code' => Str::upper(trim($request->string('code')->toString())), 'unit' => Str::lower(trim($request->string('unit')->toString()))]);
|
$request->merge(['code' => Str::upper(trim($request->string('code')->toString())), 'unit' => Str::lower(trim($request->string('unit')->toString()))]);
|
||||||
$data = $request->validate([
|
$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',
|
'name' => 'required|string|max:200', 'unit' => 'required|string|max:30',
|
||||||
]);
|
]);
|
||||||
DB::transaction(function () use ($request, $audit, $data) {
|
DB::transaction(function () use ($request, $audit, $data) {
|
||||||
$item = StockItem::query()->create([...$data, 'tenant_id' => $request->user()->tenant_id, 'created_by' => $request->user()->id]);
|
$item = StockItem::query()->create([...$data, 'tenant_id' => $this->actor($request)->tenant_id, 'created_by' => $this->actor($request)->id]);
|
||||||
$audit->audit($request->user(), 'stock.item_created', null, null, $item->toArray());
|
$audit->audit($this->actor($request), 'stock.item_created', null, null, $item->toArray());
|
||||||
});
|
});
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
@@ -74,12 +112,44 @@ class StockController extends Controller
|
|||||||
$this->access($request, true);
|
$this->access($request, true);
|
||||||
$request->merge(['code' => Str::upper(trim($request->string('code')->toString()))]);
|
$request->merge(['code' => Str::upper(trim($request->string('code')->toString()))]);
|
||||||
$data = $request->validate([
|
$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',
|
'name' => 'required|string|max:200',
|
||||||
|
...app(AdministrativeGeography::class)->referenceRules('warehouses'),
|
||||||
]);
|
]);
|
||||||
DB::transaction(function () use ($request, $audit, $data) {
|
DB::transaction(function () use ($request, $audit, $data) {
|
||||||
$warehouse = Warehouse::query()->create([...$data, 'tenant_id' => $request->user()->tenant_id, 'created_by' => $request->user()->id]);
|
app(ConflictGuard::class)->lockCompany($this->actor($request));
|
||||||
$audit->audit($request->user(), 'stock.warehouse_created', null, null, $warehouse->toArray());
|
$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();
|
return back();
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ use App\Models\StockItem;
|
|||||||
use App\Models\StockOperation;
|
use App\Models\StockOperation;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Models\Warehouse;
|
use App\Models\Warehouse;
|
||||||
|
use App\Services\InventoryCounts;
|
||||||
|
use App\Services\InventoryLots;
|
||||||
|
use App\Services\InventoryReversals;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
use App\Services\StockWorkflow;
|
use App\Services\StockWorkflow;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
@@ -15,38 +19,60 @@ use Illuminate\Http\RedirectResponse;
|
|||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class StockOperationController extends Controller
|
class StockOperationController extends Controller
|
||||||
{
|
{
|
||||||
public function index(Request $request, StockWorkflow $workflow): Response
|
public function index(Request $request, StockWorkflow $workflow): Response
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Warehouse, PurchasingRole::Admin, PurchasingRole::Finance, PurchasingRole::Procurement]), 403);
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
abort_unless($actor->hasFunctions([PurchasingRole::Warehouse, PurchasingRole::Admin, PurchasingRole::Finance, PurchasingRole::Procurement, 'inventory_adjust_review']), 403);
|
||||||
$items = StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']);
|
$items = StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']);
|
||||||
$warehouses = Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']);
|
$warehouses = Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']);
|
||||||
$balances = [];
|
$balances = [];
|
||||||
|
$lotCounts = [];
|
||||||
foreach ($items as $item) {
|
foreach ($items as $item) {
|
||||||
foreach ($warehouses as $warehouse) {
|
foreach ($warehouses as $warehouse) {
|
||||||
$balances[] = ['stock_item_id' => $item->id, 'warehouse_id' => $warehouse->id, ...$workflow->balance($item->id, $warehouse->id)];
|
$balances[] = ['stock_item_id' => $item->id, 'warehouse_id' => $warehouse->id, ...$workflow->balance($item->id, $warehouse->id),
|
||||||
|
'lot_control' => app(InventoryLots::class)->summary($item->id, $warehouse->id)];
|
||||||
|
if ($actor->hasFunctions([PurchasingRole::Warehouse]) && app(InventoryLots::class)->setup($item->id, $warehouse->id) !== null) {
|
||||||
|
try {
|
||||||
|
$source = app(InventoryCounts::class)->source($item->id, $warehouse->id);
|
||||||
|
$lotCounts[] = ['stock_item_id' => $item->id, 'warehouse_id' => $warehouse->id, ...$source];
|
||||||
|
} catch (ValidationException) {
|
||||||
|
// The summary still reports the divergence; no count can use an invented baseline.
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Inertia::render('stock/operations', [
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('stock/operations', [
|
||||||
|
'canViewReturns' => config('stock_returns.enabled') && $actor->hasFunctions(['warehouse_return_read']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor),
|
||||||
|
'correctedOperations' => collect(app(InventoryReversals::class)->corrections('operation'))->map(fn ($r) => $r->data['reference']),
|
||||||
'items' => $items, 'warehouses' => $warehouses, 'balances' => $balances,
|
'items' => $items, 'warehouses' => $warehouses, 'balances' => $balances,
|
||||||
'users' => User::query()->where('tenant_id', $request->user()->tenant_id)->orderBy('name')->get(['id', 'name']),
|
'users' => User::query()->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
|
||||||
'operations' => StockOperation::query()->latest('id')->paginate(20),
|
'operations' => StockOperation::query()->latest('id')->paginate(20),
|
||||||
'counts' => StockOperation::query()->where('kind', 'count')->whereNotIn('id', StockOperation::query()->whereNotNull('count_id')->select('count_id'))->latest('id')->get(),
|
'counts' => StockOperation::query()->where('kind', 'count')->whereNotIn('id', StockOperation::query()->whereNotNull('count_id')->select('count_id'))->latest('id')->get(),
|
||||||
'canOperate' => $request->user()->hasFunctions([PurchasingRole::Warehouse]),
|
'canOperate' => $actor->hasFunctions([PurchasingRole::Warehouse]),
|
||||||
|
'canAdjust' => app(InventoryLots::class)->allows($actor, 'inventory_adjust_review'), 'lotCounts' => $lotCounts,
|
||||||
'equipment' => Equipment::query()->orderBy('code')->get(['id', 'code', 'description']),
|
'equipment' => Equipment::query()->orderBy('code')->get(['id', 'code', 'description']),
|
||||||
]);
|
])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function store(Request $request, StockWorkflow $workflow): JsonResponse|RedirectResponse
|
public function store(Request $request, StockWorkflow $workflow): JsonResponse|RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Warehouse]), 403);
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
abort_unless($actor->hasFunctions($request->input('kind') === 'adjustment' ? [PurchasingRole::Warehouse, 'inventory_adjust_review'] : [PurchasingRole::Warehouse]), 403);
|
||||||
$request->merge(['reference' => Str::upper(Str::squish($request->string('reference')->toString())), 'reason' => trim($request->string('reason')->toString()), 'destination' => trim($request->string('destination')->toString())]);
|
$request->merge(['reference' => Str::upper(Str::squish($request->string('reference')->toString())), 'reason' => trim($request->string('reason')->toString()), 'destination' => trim($request->string('destination')->toString())]);
|
||||||
$tenant = $request->user()->tenant_id;
|
$tenant = $actor->tenant_id;
|
||||||
$data = $request->validate([
|
$data = $request->validate([
|
||||||
'kind' => ['required', Rule::in(['issue', 'transfer', 'count', 'adjustment'])],
|
'kind' => ['required', Rule::in(['issue', 'transfer', 'count', 'adjustment'])],
|
||||||
'reference' => 'required|string|max:100', 'idempotency_key' => 'required|uuid', 'reason' => 'required|string|max:4000',
|
'reference' => 'required|string|max:100', 'idempotency_key' => 'required|uuid', 'reason' => 'required|string|max:4000',
|
||||||
@@ -59,10 +85,31 @@ class StockOperationController extends Controller
|
|||||||
'quantity' => ['exclude_if:kind,adjustment', 'required', 'regex:/^\d{1,9}(\.\d{1,3})?$/', $request->input('kind') === 'count' ? 'gte:0' : 'gt:0'],
|
'quantity' => ['exclude_if:kind,adjustment', 'required', 'regex:/^\d{1,9}(\.\d{1,3})?$/', $request->input('kind') === 'count' ? 'gte:0' : 'gt:0'],
|
||||||
'ledger_version' => 'exclude_unless:kind,count|required|integer|min:0',
|
'ledger_version' => 'exclude_unless:kind,count|required|integer|min:0',
|
||||||
'count_id' => ['exclude_unless:kind,adjustment', 'required', 'integer', Rule::exists('stock_operations', 'id')->where('tenant_id', $tenant)->where('kind', 'count')],
|
'count_id' => ['exclude_unless:kind,adjustment', 'required', 'integer', Rule::exists('stock_operations', 'id')->where('tenant_id', $tenant)->where('kind', 'count')],
|
||||||
|
'lot_version' => 'exclude_unless:kind,count|nullable|string|size:64',
|
||||||
|
'lot_counts' => 'exclude_unless:kind,count|sometimes|array|max:500',
|
||||||
|
'lot_counts.*.lot_id' => 'nullable|integer|min:1', 'lot_counts.*.new_key' => 'nullable|uuid',
|
||||||
|
'lot_counts.*.quantity' => ['required', 'string', 'regex:/^\d{1,9}(\.\d{1,3})?$/'],
|
||||||
|
'lot_counts.*.code' => 'nullable|string|max:100', 'lot_counts.*.expires_on' => 'nullable|date_format:Y-m-d', 'lot_counts.*.no_expiry' => 'sometimes|boolean',
|
||||||
]);
|
]);
|
||||||
if (empty($data['equipment_id'])) {
|
if (empty($data['equipment_id'])) {
|
||||||
unset($data['equipment_id']);
|
unset($data['equipment_id']);
|
||||||
}
|
}
|
||||||
|
if (empty($data['lot_version'])) {
|
||||||
|
unset($data['lot_version']);
|
||||||
|
}
|
||||||
|
if (empty($data['lot_counts']) && empty($data['lot_version'])) {
|
||||||
|
unset($data['lot_counts']);
|
||||||
|
}
|
||||||
|
if (isset($data['lot_counts'])) {
|
||||||
|
$data['lot_counts'] = array_map(function (array $row) {
|
||||||
|
if (! empty($row['lot_id'])) {
|
||||||
|
$row['lot_id'] = (int) $row['lot_id'];
|
||||||
|
}
|
||||||
|
$row['quantity'] = (string) BigDecimal::of($row['quantity'])->toScale(3);
|
||||||
|
|
||||||
|
return $row;
|
||||||
|
}, $data['lot_counts']);
|
||||||
|
}
|
||||||
foreach (['responsible_id', 'warehouse_id', 'stock_item_id', 'destination_warehouse_id', 'ledger_version', 'count_id', 'equipment_id'] as $key) {
|
foreach (['responsible_id', 'warehouse_id', 'stock_item_id', 'destination_warehouse_id', 'ledger_version', 'count_id', 'equipment_id'] as $key) {
|
||||||
if (isset($data[$key])) {
|
if (isset($data[$key])) {
|
||||||
$data[$key] = (int) $data[$key];
|
$data[$key] = (int) $data[$key];
|
||||||
@@ -70,7 +117,7 @@ class StockOperationController extends Controller
|
|||||||
}
|
}
|
||||||
$data['quantity'] = isset($data['quantity']) ? (string) BigDecimal::of($data['quantity'])->toScale(3) : '0.000';
|
$data['quantity'] = isset($data['quantity']) ? (string) BigDecimal::of($data['quantity'])->toScale(3) : '0.000';
|
||||||
ksort($data);
|
ksort($data);
|
||||||
$operation = $workflow->record($request->user(), $data);
|
$operation = $workflow->record($actor, $data);
|
||||||
|
|
||||||
return $request->expectsJson() ? response()->json(['id' => $operation->id, 'created' => $operation->wasRecentlyCreated], $operation->wasRecentlyCreated ? 201 : 200) : back();
|
return $request->expectsJson() ? response()->json(['id' => $operation->id, 'created' => $operation->wasRecentlyCreated], $operation->wasRecentlyCreated ? 201 : 200) : back();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ class SubmissionFormsController extends Controller
|
|||||||
{
|
{
|
||||||
public function index(Request $request, SubmissionForms $forms, OrganizationConfiguration $configuration): Response
|
public function index(Request $request, SubmissionForms $forms, OrganizationConfiguration $configuration): Response
|
||||||
{
|
{
|
||||||
$actor = $configuration->administrator($request->user());
|
$actor = $configuration->administrator($this->staffIdentity($request));
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('company/submission-forms', ['forms' => $forms->listing($actor), 'canManage' => $forms->canManage($actor),
|
$response = Inertia::render('company/submission-forms', ['forms' => $forms->listing($actor), 'canManage' => $forms->canManage($actor),
|
||||||
'ready' => Schema::hasTable('submission_forms'), 'externalPortalAvailable' => false])->toResponse($request);
|
'ready' => Schema::hasTable('submission_forms'), 'externalPortalAvailable' => false])->toResponse($request);
|
||||||
@@ -24,7 +24,7 @@ class SubmissionFormsController extends Controller
|
|||||||
|
|
||||||
public function save(Request $request, SubmissionForms $forms): Response
|
public function save(Request $request, SubmissionForms $forms): Response
|
||||||
{
|
{
|
||||||
$forms->save($request->user(), $request->all());
|
$forms->save($this->staffIdentity($request), $request->all());
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,18 +18,31 @@ class SupplierBankController extends Controller
|
|||||||
{
|
{
|
||||||
public function show(Request $request, Supplier $supplier, SupplierBankWorkflow $workflow): Response
|
public function show(Request $request, Supplier $supplier, SupplierBankWorkflow $workflow): Response
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance]), 403);
|
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance]), 403);
|
||||||
$details = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->get();
|
$filters = $request->validate(['account' => 'nullable|uuid']);
|
||||||
|
$key = isset($filters['account']) ? strtolower($filters['account']) : null;
|
||||||
|
$details = $workflow->account($supplier, $key)->latest('revision')->get();
|
||||||
$current = $details->first();
|
$current = $details->first();
|
||||||
$canRead = $request->user()->hasFunctions([PurchasingRole::Procurement, PurchasingRole::Finance]);
|
abort_unless($key === null || $current !== null, 404);
|
||||||
|
$canRead = $this->staffIdentity($request)->hasFunctions([PurchasingRole::Procurement, PurchasingRole::Finance]);
|
||||||
$data = null;
|
$data = null;
|
||||||
if ($current && $canRead) {
|
if ($current && $canRead) {
|
||||||
app(RequisitionWorkflow::class)->audit($request->user(), 'supplier.bank_viewed', null, null, ['supplier_id' => $supplier->id, 'bank_detail_id' => $current->id]);
|
app(RequisitionWorkflow::class)->audit($this->staffIdentity($request), 'supplier.bank_viewed', null, null, ['supplier_id' => $supplier->id, 'bank_detail_id' => $current->id]);
|
||||||
$data = [...$current->toArray(), ...$current->only(['account_identifier', 'beneficiary', 'evidence_reference', 'reason'])];
|
$data = [...$current->toArray(), ...$current->only(['account_identifier', 'beneficiary', 'evidence_reference', 'reason'])];
|
||||||
}
|
}
|
||||||
|
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('suppliers/bank', ['supplier' => $supplier->only(['id', 'name']), 'current' => $data, 'currentId' => $current->id ?? 0, 'state' => $workflow->state($supplier), 'history' => $details->map(fn ($detail) => $detail->only(['id', 'revision', 'created_by', 'created_at'])), 'reviews' => SupplierBankReview::query()->whereIn('supplier_bank_detail_id', $details->pluck('id'))->orderBy('id')->get(), 'canPropose' => $request->user()->hasFunctions([PurchasingRole::Procurement]), 'canReview' => $current && $request->user()->hasFunctions([PurchasingRole::Finance]) && $current->created_by !== $request->user()->id && ! SupplierBankReview::query()->where('supplier_bank_detail_id', $current->id)->where('reviewed_by', $request->user()->id)->exists()])->toResponse($request);
|
$response = Inertia::render('suppliers/bank', ['supplier' => $supplier->only(['id', 'name']), 'current' => $data, 'currentId' => $current->id ?? 0,
|
||||||
|
'accountKey' => $key, 'actorId' => $this->staffIdentity($request)->id, 'multiAccountsAvailable' => $workflow->multipleReady(),
|
||||||
|
'accounts' => $workflow->currentAccounts($supplier)->map(fn (SupplierBankDetail $detail) => [
|
||||||
|
'id' => $detail->id, 'key' => $detail->account_key, 'revision' => $detail->revision,
|
||||||
|
'label' => $canRead ? $detail->bank_name.' · '.$detail->currency.' · v'.$detail->revision : 'Conta #'.$detail->id.' · v'.$detail->revision,
|
||||||
|
'state' => $workflow->state($supplier, $detail->account_key),
|
||||||
|
]),
|
||||||
|
'state' => $workflow->state($supplier, $key), 'history' => $details->map(fn ($detail) => $detail->only(['id', 'revision', 'created_by', 'created_at'])),
|
||||||
|
'reviews' => SupplierBankReview::query()->whereIn('supplier_bank_detail_id', $details->pluck('id'))->orderBy('id')->get(),
|
||||||
|
'canPropose' => $this->staffIdentity($request)->hasFunctions([PurchasingRole::Procurement]),
|
||||||
|
'canReview' => $current !== null && $workflow->canReview($this->staffIdentity($request), $current)])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
return $response;
|
return $response;
|
||||||
@@ -38,8 +51,11 @@ class SupplierBankController extends Controller
|
|||||||
public function store(Request $request, Supplier $supplier, SupplierBankWorkflow $workflow): RedirectResponse
|
public function store(Request $request, Supplier $supplier, SupplierBankWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$request->merge(['country' => Str::upper(trim($request->string('country')->toString())), 'currency' => Str::upper(trim($request->string('currency')->toString())), 'account_identifier' => Str::upper(preg_replace('/\s+/', '', $request->string('account_identifier')->toString()) ?? '')]);
|
$request->merge(['country' => Str::upper(trim($request->string('country')->toString())), 'currency' => Str::upper(trim($request->string('currency')->toString())), 'account_identifier' => Str::upper(preg_replace('/\s+/', '', $request->string('account_identifier')->toString()) ?? '')]);
|
||||||
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'bank_name' => 'required|string|max:200', 'country' => ['required', 'regex:/^[A-Z]{2}$/'], 'currency' => ['required', 'regex:/^[A-Z]{3}$/'], 'beneficiary' => 'required|string|max:200', 'account_identifier' => ['required', 'regex:/^[A-Z0-9.\/-]{4,100}$/'], 'evidence_reference' => 'required|string|max:1000', 'reason' => 'required|string|max:2000']);
|
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'account_key' => 'nullable|uuid', 'bank_name' => 'required|string|max:200', 'country' => ['required', 'regex:/^[A-Z]{2}$/'], 'currency' => ['required', 'regex:/^[A-Z]{3}$/'], 'beneficiary' => 'required|string|max:200', 'account_identifier' => ['required', 'regex:/^[A-Z0-9.\/-]{4,100}$/'], 'evidence_reference' => 'required|string|max:1000', 'reason' => 'required|string|max:2000']);
|
||||||
$workflow->propose($request->user(), $supplier, $data);
|
$detail = $workflow->propose($this->staffIdentity($request), $supplier, $data);
|
||||||
|
if ($detail->account_key !== null) {
|
||||||
|
return redirect('/fornecedores/'.$supplier->id.'/dados-bancarios?account='.rawurlencode($detail->account_key));
|
||||||
|
}
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
@@ -48,7 +64,7 @@ class SupplierBankController extends Controller
|
|||||||
{
|
{
|
||||||
abort_unless($detail->supplier_id === $supplier->id, 404);
|
abort_unless($detail->supplier_id === $supplier->id, 404);
|
||||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|max:2000', 'independently_verified' => 'accepted']);
|
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|max:2000', 'independently_verified' => 'accepted']);
|
||||||
$workflow->review($request->user(), $detail, $data['decision'], $data['reason']);
|
$workflow->review($this->staffIdentity($request), $detail, $data['decision'], $data['reason']);
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,13 @@ namespace App\Http\Controllers;
|
|||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Http\Requests\SaveSupplierRequest;
|
use App\Http\Requests\SaveSupplierRequest;
|
||||||
use App\Models\Supplier;
|
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\RequisitionWorkflow;
|
||||||
|
use App\Services\SupplierGeography;
|
||||||
|
use App\Services\SupplierParticipation;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -14,51 +20,82 @@ use Illuminate\Validation\Rule;
|
|||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Inertia\Response;
|
||||||
|
use Symfony\Component\HttpFoundation\Response as HttpResponse;
|
||||||
|
|
||||||
class SupplierController extends Controller
|
class SupplierController extends Controller
|
||||||
{
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function currentActor(Request $request, PurchasingRole $role): User
|
||||||
|
{
|
||||||
|
$actor = $this->actor($request);
|
||||||
|
app(ConflictGuard::class)->lockCompany($actor);
|
||||||
|
|
||||||
|
return app(CurrentActor::class)->lock($actor, [$role]);
|
||||||
|
}
|
||||||
|
|
||||||
public function index(Request $request): Response
|
public function index(Request $request): Response
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
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();
|
$query = Supplier::query();
|
||||||
|
if (! empty($filters['location'])) {
|
||||||
|
$query = app(SupplierGeography::class)->matching($filters['location']);
|
||||||
|
}
|
||||||
if (! empty($filters['search'])) {
|
if (! empty($filters['search'])) {
|
||||||
$query->where(fn ($q) => $q->where('name', 'like', '%'.$filters['search'].'%')->orWhere('nuit', 'like', '%'.$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' => $request->user()->hasFunctions([PurchasingRole::Procurement]), 'canReview' => $request->user()->hasFunctions([PurchasingRole::Finance])]);
|
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
|
public function store(SaveSupplierRequest $request, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validated();
|
$data = $request->validated();
|
||||||
DB::transaction(function () use ($request, $data, $workflow) {
|
DB::transaction(function () use ($request, $data, $workflow) {
|
||||||
$supplier = Supplier::query()->create([...$data, 'tenant_id' => $request->user()->tenant_id, 'created_by' => $request->user()->id, 'last_changed_by' => $request->user()->id, 'status' => 'pending']);
|
$actor = $this->currentActor($request, PurchasingRole::Procurement);
|
||||||
$workflow->audit($request->user(), 'supplier.created', null, null, $supplier->toArray());
|
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());
|
||||||
});
|
});
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Request $request, Supplier $supplier): Response
|
public function show(Request $request, Supplier $supplier): HttpResponse
|
||||||
{
|
{
|
||||||
Gate::authorize('view', $supplier);
|
Gate::authorize('view', $supplier);
|
||||||
$canDocuments = $request->user()->can('viewDocuments', $supplier);
|
$canDocuments = $this->actor($request)->can('viewDocuments', $supplier);
|
||||||
|
|
||||||
return Inertia::render('suppliers/show', [
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('suppliers/show', [
|
||||||
'supplier' => $supplier,
|
'supplier' => $supplier,
|
||||||
|
'geography' => app(AdministrativeGeography::class)->describe($supplier->geography_reference),
|
||||||
'documents' => $canDocuments ? $supplier->documents()->latest('id')->get() : [],
|
'documents' => $canDocuments ? $supplier->documents()->latest('id')->get() : [],
|
||||||
'canEdit' => $request->user()->can('update', $supplier),
|
'canEdit' => $this->actor($request)->can('update', $supplier),
|
||||||
'canDocuments' => $canDocuments,
|
'canDocuments' => $canDocuments,
|
||||||
'canReview' => $request->user()->hasFunctions([PurchasingRole::Finance]),
|
'canReview' => app(SupplierParticipation::class)->canReview($this->actor($request), $supplier),
|
||||||
]);
|
])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function edit(Supplier $supplier): Response
|
public function edit(Supplier $supplier): Response
|
||||||
{
|
{
|
||||||
Gate::authorize('update', $supplier);
|
Gate::authorize('update', $supplier);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
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
|
public function update(SaveSupplierRequest $request, Supplier $supplier, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
@@ -66,6 +103,11 @@ class SupplierController extends Controller
|
|||||||
Gate::authorize('update', $supplier);
|
Gate::authorize('update', $supplier);
|
||||||
$data = $request->validated();
|
$data = $request->validated();
|
||||||
DB::transaction(function () use ($request, $supplier, $workflow, $data) {
|
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);
|
$supplier = Supplier::query()->lockForUpdate()->findOrFail($supplier->id);
|
||||||
if ($supplier->version !== (int) $data['version']) {
|
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.']);
|
throw ValidationException::withMessages(['version' => 'A ficha foi alterada por outro utilizador. Reabra a edição para carregar os dados actuais.']);
|
||||||
@@ -74,8 +116,8 @@ class SupplierController extends Controller
|
|||||||
unset($data['version']);
|
unset($data['version']);
|
||||||
$supplier->fill($data);
|
$supplier->fill($data);
|
||||||
if ($supplier->isDirty()) {
|
if ($supplier->isDirty()) {
|
||||||
$supplier->fill(['status' => 'pending', 'reviewed_by' => null, 'review_comment' => null, 'last_changed_by' => $request->user()->id, 'version' => $supplier->version + 1])->save();
|
$supplier->fill(['status' => 'pending', 'reviewed_by' => null, 'review_comment' => null, 'last_changed_by' => $actor->id, 'version' => $supplier->version + 1])->save();
|
||||||
$workflow->audit($request->user(), 'supplier.updated', null, $before, $supplier->toArray());
|
$workflow->audit($actor, 'supplier.updated', null, $before, $supplier->toArray());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -84,12 +126,12 @@ class SupplierController extends Controller
|
|||||||
|
|
||||||
public function review(Request $request, Supplier $supplier, RequisitionWorkflow $workflow): RedirectResponse
|
public function review(Request $request, Supplier $supplier, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Finance]), 403);
|
abort_unless($this->actor($request)->hasFunctions([PurchasingRole::Finance]), 403);
|
||||||
$data = $request->validate(['status' => ['required', Rule::in(['active', 'suspended'])], 'comment' => 'required|string|min:10|max:2000', 'version' => 'required|integer|min:1']);
|
$data = $request->validate(['status' => ['required', Rule::in(['active', 'suspended'])], 'comment' => 'required|string|min:10|max:2000', 'version' => 'required|integer|min:1']);
|
||||||
DB::transaction(function () use ($request, $supplier, $data, $workflow) {
|
DB::transaction(function () use ($request, $supplier, $data, $workflow) {
|
||||||
|
$actor = $this->currentActor($request, PurchasingRole::Finance);
|
||||||
$supplier = Supplier::query()->lockForUpdate()->findOrFail($supplier->id);
|
$supplier = Supplier::query()->lockForUpdate()->findOrFail($supplier->id);
|
||||||
abort_if($supplier->created_by === $request->user()->id, 403);
|
abort_unless(app(SupplierParticipation::class)->canReview($actor, $supplier), 403);
|
||||||
abort_if($supplier->last_changed_by === $request->user()->id, 403);
|
|
||||||
if ($supplier->version !== (int) $data['version']) {
|
if ($supplier->version !== (int) $data['version']) {
|
||||||
throw ValidationException::withMessages(['version' => 'A ficha ou os documentos foram alterados. Reabra a ficha antes de validar.']);
|
throw ValidationException::withMessages(['version' => 'A ficha ou os documentos foram alterados. Reabra a ficha antes de validar.']);
|
||||||
}
|
}
|
||||||
@@ -97,8 +139,8 @@ class SupplierController extends Controller
|
|||||||
throw ValidationException::withMessages(['status' => 'Fornecedor impedido ou com revisão vencida. Não pode ser activado.']);
|
throw ValidationException::withMessages(['status' => 'Fornecedor impedido ou com revisão vencida. Não pode ser activado.']);
|
||||||
}
|
}
|
||||||
$before = $supplier->toArray();
|
$before = $supplier->toArray();
|
||||||
$supplier->update(['status' => $data['status'], 'review_comment' => $data['comment'], 'reviewed_by' => $request->user()->id, 'version' => $supplier->version + 1]);
|
$supplier->update(['status' => $data['status'], 'review_comment' => $data['comment'], 'reviewed_by' => $actor->id, 'version' => $supplier->version + 1]);
|
||||||
$workflow->audit($request->user(), 'supplier.reviewed', null, $before, $supplier->toArray());
|
$workflow->audit($actor, 'supplier.reviewed', null, $before, $supplier->toArray());
|
||||||
});
|
});
|
||||||
|
|
||||||
return back();
|
return back();
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Models\Supplier;
|
use App\Models\Supplier;
|
||||||
use App\Models\SupplierDocument;
|
use App\Models\SupplierDocument;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ConflictGuard;
|
||||||
|
use App\Services\CurrentActor;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -20,6 +23,8 @@ class SupplierDocumentController extends Controller
|
|||||||
{
|
{
|
||||||
public function store(Request $request, Supplier $supplier, RequisitionWorkflow $workflow): RedirectResponse
|
public function store(Request $request, Supplier $supplier, RequisitionWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
Gate::authorize('update', $supplier);
|
Gate::authorize('update', $supplier);
|
||||||
$data = $request->validate([
|
$data = $request->validate([
|
||||||
'document_type' => ['required', Rule::in(['license', 'tax', 'conflict', 'other'])],
|
'document_type' => ['required', Rule::in(['license', 'tax', 'conflict', 'other'])],
|
||||||
@@ -30,18 +35,21 @@ class SupplierDocumentController extends Controller
|
|||||||
$path = $file->store($supplier->tenant_id.'/'.$supplier->id, 'supplier_documents');
|
$path = $file->store($supplier->tenant_id.'/'.$supplier->id, 'supplier_documents');
|
||||||
abort_if($path === false, 500);
|
abort_if($path === false, 500);
|
||||||
try {
|
try {
|
||||||
DB::transaction(function () use ($request, $supplier, $workflow, $data, $file, $path) {
|
DB::transaction(function () use ($actor, $supplier, $workflow, $data, $file, $path) {
|
||||||
|
app(ConflictGuard::class)->lockCompany($actor);
|
||||||
|
$actor = app(CurrentActor::class)->lock($actor);
|
||||||
$supplier = Supplier::query()->lockForUpdate()->findOrFail($supplier->id);
|
$supplier = Supplier::query()->lockForUpdate()->findOrFail($supplier->id);
|
||||||
|
Gate::forUser($actor)->authorize('update', $supplier);
|
||||||
$before = $supplier->toArray();
|
$before = $supplier->toArray();
|
||||||
$name = Str::substr(Str::replaceMatches('/[^\pL\pN ._()-]/u', '_', basename(str_replace('\\', '/', $file->getClientOriginalName()))), 0, 180);
|
$name = Str::substr(Str::replaceMatches('/[^\pL\pN ._()-]/u', '_', basename(str_replace('\\', '/', $file->getClientOriginalName()))), 0, 180);
|
||||||
$document = $supplier->documents()->create([
|
$document = $supplier->documents()->create([
|
||||||
'tenant_id' => $supplier->tenant_id, 'uploaded_by' => $request->user()->id,
|
'tenant_id' => $supplier->tenant_id, 'uploaded_by' => $actor->id,
|
||||||
'document_type' => $data['document_type'], 'original_name' => $name,
|
'document_type' => $data['document_type'], 'original_name' => $name,
|
||||||
'path' => $path, 'mime_type' => $file->getMimeType(), 'size' => $file->getSize(),
|
'path' => $path, 'mime_type' => $file->getMimeType(), 'size' => $file->getSize(),
|
||||||
'sha256' => hash_file('sha256', $file->getPathname()),
|
'sha256' => hash_file('sha256', $file->getPathname()),
|
||||||
]);
|
]);
|
||||||
$supplier->update(['status' => 'pending', 'reviewed_by' => null, 'review_comment' => null, 'last_changed_by' => $request->user()->id, 'version' => $supplier->version + 1]);
|
$supplier->update(['status' => 'pending', 'reviewed_by' => null, 'review_comment' => null, 'last_changed_by' => $actor->id, 'version' => $supplier->version + 1]);
|
||||||
$workflow->audit($request->user(), 'supplier.document_uploaded', null, $before, ['supplier' => $supplier->toArray(), 'document' => $document->toArray()]);
|
$workflow->audit($actor, 'supplier.document_uploaded', null, $before, ['supplier' => $supplier->toArray(), 'document' => $document->toArray()]);
|
||||||
});
|
});
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
Storage::disk('supplier_documents')->delete($path);
|
Storage::disk('supplier_documents')->delete($path);
|
||||||
@@ -53,13 +61,35 @@ class SupplierDocumentController extends Controller
|
|||||||
|
|
||||||
public function download(Request $request, Supplier $supplier, SupplierDocument $document, RequisitionWorkflow $workflow): StreamedResponse
|
public function download(Request $request, Supplier $supplier, SupplierDocument $document, RequisitionWorkflow $workflow): StreamedResponse
|
||||||
{
|
{
|
||||||
Gate::authorize('viewDocuments', $supplier);
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$actor = User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($actor->id);
|
||||||
|
Gate::forUser($actor)->authorize('viewDocuments', $supplier);
|
||||||
abort_unless($document->supplier_id === $supplier->id, 404);
|
abort_unless($document->supplier_id === $supplier->id, 404);
|
||||||
|
$prefix = $supplier->tenant_id.'/'.$supplier->id.'/';
|
||||||
|
abort_unless(str_starts_with($document->path, $prefix)
|
||||||
|
&& preg_match('/\A[A-Za-z0-9_-]+\.[A-Za-z0-9]+\z/D', substr($document->path, strlen($prefix))), 409,
|
||||||
|
'Documento indisponível para descarga. Solicite conferência ao responsável.');
|
||||||
$disk = Storage::disk('supplier_documents');
|
$disk = Storage::disk('supplier_documents');
|
||||||
abort_unless($disk->exists($document->path), 404);
|
abort_unless($disk->exists($document->path), 404);
|
||||||
$workflow->audit($request->user(), 'supplier.document_downloaded', null, null, ['supplier_id' => $supplier->id, 'document_id' => $document->id, 'name' => $document->original_name]);
|
$stream = $disk->readStream($document->path);
|
||||||
|
abort_unless(is_resource($stream), 404);
|
||||||
|
try {
|
||||||
|
// Capture at most the accepted upload size plus one byte. The response uses
|
||||||
|
// these verified bytes even if the underlying file subsequently changes.
|
||||||
|
$content = stream_get_contents($stream, 2097153);
|
||||||
|
} finally {
|
||||||
|
fclose($stream);
|
||||||
|
}
|
||||||
|
abort_unless(is_string($content) && strlen($content) > 0 && strlen($content) <= 2097152
|
||||||
|
&& strlen($content) === (int) $document->size
|
||||||
|
&& hash_equals($document->sha256, hash('sha256', $content)), 409,
|
||||||
|
'Documento indisponível para descarga. Solicite conferência ao responsável.');
|
||||||
|
$workflow->audit($actor, 'supplier.document_downloaded', null, null, ['supplier_id' => $supplier->id, 'document_id' => $document->id, 'name' => $document->original_name]);
|
||||||
|
|
||||||
return $disk->download($document->path, $document->original_name, [
|
return response()->streamDownload(static function () use ($content): void {
|
||||||
|
echo $content;
|
||||||
|
}, $document->original_name, [
|
||||||
'Content-Type' => 'application/octet-stream',
|
'Content-Type' => 'application/octet-stream',
|
||||||
'X-Content-Type-Options' => 'nosniff',
|
'X-Content-Type-Options' => 'nosniff',
|
||||||
'Cache-Control' => 'private, no-store',
|
'Cache-Control' => 'private, no-store',
|
||||||
|
|||||||
@@ -20,6 +20,14 @@ use Symfony\Component\HttpFoundation\Response;
|
|||||||
|
|
||||||
class SupplierEvaluationController extends Controller
|
class SupplierEvaluationController extends Controller
|
||||||
{
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
private function ready(): void
|
private function ready(): void
|
||||||
{
|
{
|
||||||
abort_unless(Schema::hasTable('supplier_evaluations'), 503, 'A instalação do módulo de avaliações ainda não foi concluída.');
|
abort_unless(Schema::hasTable('supplier_evaluations'), 503, 'A instalação do módulo de avaliações ainda não foi concluída.');
|
||||||
@@ -43,7 +51,7 @@ class SupplierEvaluationController extends Controller
|
|||||||
|
|
||||||
public function index(Request $request, SupplierEvaluationWorkflow $workflow): Response
|
public function index(Request $request, SupplierEvaluationWorkflow $workflow): Response
|
||||||
{
|
{
|
||||||
$actor = $workflow->reader($request->user());
|
$actor = $workflow->reader($this->actor($request));
|
||||||
$filters = $request->validate(['supplier_id' => 'nullable|integer|min:1', 'status' => 'nullable|in:draft,review,returned,approved']);
|
$filters = $request->validate(['supplier_id' => 'nullable|integer|min:1', 'status' => 'nullable|in:draft,review,returned,approved']);
|
||||||
$ready = Schema::hasTable('supplier_evaluations');
|
$ready = Schema::hasTable('supplier_evaluations');
|
||||||
$records = $ready ? SupplierEvaluation::query()->visibleTo($actor)
|
$records = $ready ? SupplierEvaluation::query()->visibleTo($actor)
|
||||||
@@ -54,7 +62,7 @@ class SupplierEvaluationController extends Controller
|
|||||||
'title' => $e->payload['title'], 'period_start' => $e->payload['period_start'], 'period_end' => $e->payload['period_end'],
|
'title' => $e->payload['title'], 'period_start' => $e->payload['period_start'], 'period_end' => $e->payload['period_end'],
|
||||||
]) : null;
|
]) : null;
|
||||||
|
|
||||||
return $this->render($request, 'suppliers/evaluations', ['ready' => $ready, 'records' => $records, 'filters' => $filters,
|
return $this->render($request, 'suppliers/evaluations', ['ready' => $ready, 'canCreate' => $ready && $workflow->canPrepare($actor), 'records' => $records, 'filters' => $filters,
|
||||||
'suppliers' => Supplier::query()->orderBy('name')->get(['id', 'name', 'nuit']),
|
'suppliers' => Supplier::query()->orderBy('name')->get(['id', 'name', 'nuit']),
|
||||||
'orders' => PurchaseOrder::query()->visibleTo($actor)->orderByDesc('id')->get(['id', 'number', 'supplier_id'])]);
|
'orders' => PurchaseOrder::query()->visibleTo($actor)->orderByDesc('id')->get(['id', 'number', 'supplier_id'])]);
|
||||||
}
|
}
|
||||||
@@ -71,7 +79,7 @@ class SupplierEvaluationController extends Controller
|
|||||||
|
|
||||||
private function view(Request $request, int $id, SupplierEvaluationWorkflow $workflow, bool $report): Response
|
private function view(Request $request, int $id, SupplierEvaluationWorkflow $workflow, bool $report): Response
|
||||||
{
|
{
|
||||||
$actor = $workflow->reader($request->user());
|
$actor = $workflow->reader($this->actor($request));
|
||||||
$this->ready();
|
$this->ready();
|
||||||
$evaluation = SupplierEvaluation::query()->visibleTo($actor)->findOrFail($id);
|
$evaluation = SupplierEvaluation::query()->visibleTo($actor)->findOrFail($id);
|
||||||
$improvementWorkflow = app(SupplierImprovementWorkflow::class);
|
$improvementWorkflow = app(SupplierImprovementWorkflow::class);
|
||||||
@@ -82,28 +90,28 @@ class SupplierEvaluationController extends Controller
|
|||||||
$responses = $responsesReady ? SupplierResponse::query()->where('supplier_evaluation_id', $id)->orderBy('id')->get() : collect();
|
$responses = $responsesReady ? SupplierResponse::query()->where('supplier_evaluation_id', $id)->orderBy('id')->get() : collect();
|
||||||
$responseHistory = $responsesReady ? AuditLog::query()->where('action', 'like', 'supplier_response.%')->where('after->supplier_evaluation_id', $id)->latest('id')->paginate(10, ['id', 'action', 'user_id', 'after', 'created_at'], 'responses_history_page')->withQueryString() : null;
|
$responseHistory = $responsesReady ? AuditLog::query()->where('action', 'like', 'supplier_response.%')->where('after->supplier_evaluation_id', $id)->latest('id')->paginate(10, ['id', 'action', 'user_id', 'after', 'created_at'], 'responses_history_page')->withQueryString() : null;
|
||||||
$history = AuditLog::query()->where('action', 'like', 'supplier_evaluation.%')->where('after->evaluation_id', $id)->latest('id')->paginate(10, ['id', 'action', 'user_id', 'after', 'created_at'], 'history_page')->withQueryString();
|
$history = AuditLog::query()->where('action', 'like', 'supplier_evaluation.%')->where('after->evaluation_id', $id)->latest('id')->paginate(10, ['id', 'action', 'user_id', 'after', 'created_at'], 'history_page')->withQueryString();
|
||||||
$peopleIds = collect($evaluation->contributors)->merge($history->pluck('user_id'))->merge($measures->flatMap(fn (SupplierImprovement $m) => $m->contributors))->merge($measures->pluck('reviewed_by'))->merge($measureHistory?->pluck('user_id') ?? []);
|
$peopleIds = collect($evaluation->contributors)->push($evaluation->reviewed_by)->merge($history->pluck('user_id'))->merge($measures->flatMap(fn (SupplierImprovement $m) => $m->contributors))->merge($measures->pluck('reviewed_by'))->merge($measureHistory?->pluck('user_id') ?? []);
|
||||||
$peopleIds = $peopleIds->merge($responses->flatMap(fn (SupplierResponse $r) => $r->contributors))->merge($responses->pluck('reviewed_by'))->merge($responseHistory?->pluck('user_id') ?? []);
|
$peopleIds = $peopleIds->merge($responses->flatMap(fn (SupplierResponse $r) => $r->contributors))->merge($responses->pluck('reviewed_by'))->merge($responseHistory?->pluck('user_id') ?? []);
|
||||||
$people = User::query()->where('tenant_id', $actor->tenant_id)->whereIn('id', $peopleIds)->pluck('name', 'id');
|
$people = User::query()->where('tenant_id', $actor->tenant_id)->whereIn('id', $peopleIds)->pluck('name', 'id');
|
||||||
$writable = $improvementWorkflow->canParticipate($actor, $evaluation);
|
$writable = $improvementWorkflow->canParticipate($actor, $evaluation);
|
||||||
$next = SupplierEvaluation::query()->visibleTo($actor)->where('previous_id', $id)->value('id');
|
$next = SupplierEvaluation::query()->visibleTo($actor)->where('previous_id', $id)->value('id');
|
||||||
|
|
||||||
return $this->render($request, 'suppliers/evaluation', ['evaluation' => $workflow->snapshot($evaluation), 'reportOnly' => $report,
|
return $this->render($request, 'suppliers/evaluation', ['evaluation' => $workflow->snapshot($evaluation), 'reportOnly' => $report,
|
||||||
'canEdit' => ! $report && $writable && in_array($evaluation->status, ['draft', 'returned'], true),
|
'canEdit' => ! $report && $workflow->canAct($actor, $evaluation, 'edit'),
|
||||||
'canReview' => ! $report && $writable && $evaluation->status === 'review' && ! in_array($actor->id, $evaluation->contributors, true),
|
'canReview' => ! $report && $workflow->canAct($actor, $evaluation, 'review'),
|
||||||
'canRevise' => ! $report && $writable && $evaluation->status === 'approved' && $next === null,
|
'canRevise' => ! $report && $workflow->canAct($actor, $evaluation, 'revise') && $next === null,
|
||||||
'nextRevisionId' => $next, 'history' => $history, 'people' => $people,
|
'nextRevisionId' => $next, 'history' => $history, 'people' => $people,
|
||||||
'responses' => ['ready' => $responsesReady, 'canCreate' => ! $report && $responsesReady && $writable && $evaluation->status === 'approved',
|
'responses' => ['ready' => $responsesReady, 'canCreate' => ! $report && $responsesReady && $writable && $evaluation->status === 'approved',
|
||||||
'history' => $responseHistory,
|
'history' => $responseHistory,
|
||||||
'records' => $responses->map(fn (SupplierResponse $r) => [...app(SupplierResponseWorkflow::class)->snapshot($r),
|
'records' => $responses->map(fn (SupplierResponse $r) => [...app(SupplierResponseWorkflow::class)->snapshot($r),
|
||||||
'canEdit' => ! $report && $writable && in_array($r->status, ['draft', 'returned'], true),
|
'canEdit' => ! $report && app(SupplierResponseWorkflow::class)->canAct($actor, $evaluation, $r, 'edit'),
|
||||||
'canReview' => ! $report && $writable && $r->status === 'review' && ! in_array($actor->id, $r->contributors, true)])],
|
'canReview' => ! $report && app(SupplierResponseWorkflow::class)->canAct($actor, $evaluation, $r, 'review')])],
|
||||||
'improvements' => ['ready' => $measuresReady, 'canCreate' => ! $report && $measuresReady && $writable && $evaluation->status === 'approved',
|
'improvements' => ['ready' => $measuresReady, 'canCreate' => ! $report && $measuresReady && $writable && $evaluation->status === 'approved',
|
||||||
'today' => today()->toDateString(),
|
'today' => today()->toDateString(),
|
||||||
'records' => $measures->map(fn (SupplierImprovement $m) => [...$improvementWorkflow->snapshot($m),
|
'records' => $measures->map(fn (SupplierImprovement $m) => [...$improvementWorkflow->snapshot($m),
|
||||||
'canPlan' => ! $report && $writable && in_array($m->status, ['open', 'returned'], true),
|
'canPlan' => ! $report && $improvementWorkflow->canAct($actor, $evaluation, $m, 'plan'),
|
||||||
'canExecute' => ! $report && $writable && $actor->id === $m->responsible_id && in_array($m->status, ['open', 'returned'], true),
|
'canExecute' => ! $report && $improvementWorkflow->canAct($actor, $evaluation, $m, 'execute'),
|
||||||
'canReview' => ! $report && $writable && $m->status === 'review' && ! in_array($actor->id, $m->contributors, true)]),
|
'canReview' => ! $report && $improvementWorkflow->canAct($actor, $evaluation, $m, 'review')]),
|
||||||
'history' => $measureHistory,
|
'history' => $measureHistory,
|
||||||
'assignees' => $report ? [] : User::query()->where('tenant_id', $actor->tenant_id)->orderBy('name')->get()->filter(fn (User $u) => $u->hasFunctions(SupplierEvaluationWorkflow::ROLES) && (! $u->departmentScoped() || ($u->department_id !== null && $u->department_id === $evaluation->department_id)))->map(fn (User $u) => $u->only(['id', 'name']))->values()],
|
'assignees' => $report ? [] : User::query()->where('tenant_id', $actor->tenant_id)->orderBy('name')->get()->filter(fn (User $u) => $u->hasFunctions(SupplierEvaluationWorkflow::ROLES) && (! $u->departmentScoped() || ($u->department_id !== null && $u->department_id === $evaluation->department_id)))->map(fn (User $u) => $u->only(['id', 'name']))->values()],
|
||||||
'orders' => PurchaseOrder::query()->visibleTo($actor)->where('supplier_id', $evaluation->supplier_id)->orderByDesc('id')->get(['id', 'number', 'supplier_id']),
|
'orders' => PurchaseOrder::query()->visibleTo($actor)->where('supplier_id', $evaluation->supplier_id)->orderByDesc('id')->get(['id', 'number', 'supplier_id']),
|
||||||
@@ -124,7 +132,7 @@ class SupplierEvaluationController extends Controller
|
|||||||
{
|
{
|
||||||
$this->ready();
|
$this->ready();
|
||||||
$data = $request->validate(['supplier_id' => 'required|integer|min:1', 'operation_key' => 'required|uuid']);
|
$data = $request->validate(['supplier_id' => 'required|integer|min:1', 'operation_key' => 'required|uuid']);
|
||||||
$evaluation = $workflow->create($request->user(), (int) $data['supplier_id'], $data['operation_key'], $this->payload($request));
|
$evaluation = $workflow->create($this->actor($request), (int) $data['supplier_id'], $data['operation_key'], $this->payload($request));
|
||||||
|
|
||||||
return to_route('supplier-evaluations.show', $evaluation->id)->with('supplier_evaluation_notice', 'Rascunho guardado. Os dados podem ser recuperados nesta avaliação.');
|
return to_route('supplier-evaluations.show', $evaluation->id)->with('supplier_evaluation_notice', 'Rascunho guardado. Os dados podem ser recuperados nesta avaliação.');
|
||||||
}
|
}
|
||||||
@@ -133,7 +141,7 @@ class SupplierEvaluationController extends Controller
|
|||||||
{
|
{
|
||||||
$this->ready();
|
$this->ready();
|
||||||
$data = $request->validate(['version' => 'required|integer|min:1']);
|
$data = $request->validate(['version' => 'required|integer|min:1']);
|
||||||
$workflow->save($request->user(), $evaluation, (int) $data['version'], $this->payload($request));
|
$workflow->save($this->actor($request), $evaluation, (int) $data['version'], $this->payload($request));
|
||||||
|
|
||||||
return to_route('supplier-evaluations.show', $evaluation)->with('supplier_evaluation_notice', 'Alterações guardadas no histórico.');
|
return to_route('supplier-evaluations.show', $evaluation)->with('supplier_evaluation_notice', 'Alterações guardadas no histórico.');
|
||||||
}
|
}
|
||||||
@@ -143,7 +151,7 @@ class SupplierEvaluationController extends Controller
|
|||||||
$this->ready();
|
$this->ready();
|
||||||
$data = $request->validate(['version' => 'required|integer|min:1', 'reason' => $action === 'submit' ? 'nullable|string|max:4000' : 'required|string|min:10|max:4000',
|
$data = $request->validate(['version' => 'required|integer|min:1', 'reason' => $action === 'submit' ? 'nullable|string|max:4000' : 'required|string|min:10|max:4000',
|
||||||
'payload' => 'prohibited', 'supplier_id' => 'prohibited', 'tenant_id' => 'prohibited', 'reviewed_by' => 'prohibited']);
|
'payload' => 'prohibited', 'supplier_id' => 'prohibited', 'tenant_id' => 'prohibited', 'reviewed_by' => 'prohibited']);
|
||||||
$workflow->transition($request->user(), $evaluation, (int) $data['version'], $action, $data['reason'] ?? null);
|
$workflow->transition($this->actor($request), $evaluation, (int) $data['version'], $action, $data['reason'] ?? null);
|
||||||
|
|
||||||
return to_route('supplier-evaluations.show', $evaluation)->with('supplier_evaluation_notice', 'Estado e decisão registados.');
|
return to_route('supplier-evaluations.show', $evaluation)->with('supplier_evaluation_notice', 'Estado e decisão registados.');
|
||||||
}
|
}
|
||||||
@@ -152,7 +160,7 @@ class SupplierEvaluationController extends Controller
|
|||||||
{
|
{
|
||||||
$this->ready();
|
$this->ready();
|
||||||
$data = $request->validate(['version' => 'required|integer|min:1']);
|
$data = $request->validate(['version' => 'required|integer|min:1']);
|
||||||
$revision = $workflow->revise($request->user(), $evaluation, (int) $data['version']);
|
$revision = $workflow->revise($this->actor($request), $evaluation, (int) $data['version']);
|
||||||
|
|
||||||
return to_route('supplier-evaluations.show', $revision->id)->with('supplier_evaluation_notice', 'Nova revisão preparada. A avaliação aprovada anterior mantém-se preservada.');
|
return to_route('supplier-evaluations.show', $revision->id)->with('supplier_evaluation_notice', 'Nova revisão preparada. A avaliação aprovada anterior mantém-se preservada.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ class SupplierImprovementController extends Controller
|
|||||||
$rules += ['result' => 'prohibited', 'evidence' => 'prohibited'];
|
$rules += ['result' => 'prohibited', 'evidence' => 'prohibited'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$workflow->execute($request->user(), $evaluation, $measure, $command, $request->validate($rules));
|
$workflow->execute($this->staffIdentity($request), $evaluation, $measure, $command, $request->validate($rules));
|
||||||
|
|
||||||
return to_route('supplier-evaluations.show', $evaluation)->with('supplier_evaluation_notice', 'Medida de melhoria e histórico actualizados.');
|
return to_route('supplier-evaluations.show', $evaluation)->with('supplier_evaluation_notice', 'Medida de melhoria e histórico actualizados.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ namespace App\Http\Controllers;
|
|||||||
use App\Models\SupplierEvaluation;
|
use App\Models\SupplierEvaluation;
|
||||||
use App\Models\SupplierImprovement;
|
use App\Models\SupplierImprovement;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\AdministrativeGeography;
|
||||||
use App\Services\SupplierEvaluationWorkflow;
|
use App\Services\SupplierEvaluationWorkflow;
|
||||||
|
use App\Services\SupplierGeography;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -16,6 +18,22 @@ use Symfony\Component\HttpFoundation\Response;
|
|||||||
|
|
||||||
class SupplierImprovementReportController extends Controller
|
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
|
private function snapshot(\Closure $read): mixed
|
||||||
{
|
{
|
||||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() !== 0) {
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() !== 0) {
|
||||||
@@ -34,12 +52,12 @@ class SupplierImprovementReportController extends Controller
|
|||||||
/** @return array<string,mixed> */
|
/** @return array<string,mixed> */
|
||||||
private function filters(Request $request): array
|
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);
|
$request->setUserResolver(fn () => $actor);
|
||||||
abort_unless(Schema::hasTable('supplier_improvements'), 503, 'A instalação das medidas de melhoria ainda não está concluída.');
|
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',
|
$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',
|
'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']) {
|
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.']);
|
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
|
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'])) {
|
if (! empty($filters['supplier_id'])) {
|
||||||
$query->whereHas('evaluation', fn ($q) => $q->where('supplier_id', $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
|
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> */
|
/** @return array<string,mixed> */
|
||||||
@@ -99,17 +121,17 @@ class SupplierImprovementReportController extends Controller
|
|||||||
$props = $this->snapshot(function () use ($request): array {
|
$props = $this->snapshot(function () use ($request): array {
|
||||||
$filters = $this->filters($request);
|
$filters = $this->filters($request);
|
||||||
$today = today()->toDateString();
|
$today = today()->toDateString();
|
||||||
$all = SupplierImprovement::query()->visibleTo($request->user());
|
$all = SupplierImprovement::query()->visibleTo($this->actor($request));
|
||||||
$query = $this->query($request, $filters, $today);
|
$query = $this->query($request, $filters, $today);
|
||||||
$counts = (clone $query)->selectRaw('status, COUNT(*) AS count')->groupBy('status')->pluck('count', 'status')->map(fn ($n) => (int) $n);
|
$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();
|
$overdue = (clone $query)->where('status', '!=', 'closed')->where('due_on', '<', $today)->count();
|
||||||
// Choices derive only from visible measures, including prior revisions and former assignees.
|
// 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)),
|
'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(),
|
'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();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('reports/supplier-improvements', $props)->toResponse($request);
|
$response = Inertia::render('reports/supplier-improvements', $props)->toResponse($request);
|
||||||
@@ -121,6 +143,9 @@ class SupplierImprovementReportController extends Controller
|
|||||||
public function csv(Request $request): Response
|
public function csv(Request $request): Response
|
||||||
{
|
{
|
||||||
$filters = $this->filters($request);
|
$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 ?? '');
|
$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) {
|
return response()->streamDownload(fn () => $this->snapshot(function () use ($request, $filters, $text) {
|
||||||
@@ -133,7 +158,12 @@ class SupplierImprovementReportController extends Controller
|
|||||||
}
|
}
|
||||||
fwrite($out, "\xEF\xBB\xBF");
|
fwrite($out, "\xEF\xBB\xBF");
|
||||||
fputcsv($out, ['Medidas de melhoria de fornecedores', 'Consulta', now()->toIso8601String(), 'Data de referência', $today], ';', '"', '');
|
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'], ';', '"', '');
|
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) {
|
foreach ($this->records($this->query($request, $filters, $today), $request)->lazyById(200) as $m) {
|
||||||
$row = $this->row($m, $today);
|
$row = $this->row($m, $today);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
use App\Services\SupplierPayables;
|
use App\Services\SupplierPayables;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -11,20 +12,42 @@ use Tempo\Finance\Payables\Workspace;
|
|||||||
|
|
||||||
final class SupplierPayablesController extends Controller
|
final class SupplierPayablesController extends Controller
|
||||||
{
|
{
|
||||||
|
private function actor(Request $r): User
|
||||||
|
{
|
||||||
|
$user = $r->user();
|
||||||
|
abort_unless($user instanceof User, 403);
|
||||||
|
|
||||||
|
return $user;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
private function filters(Request $r): array
|
||||||
|
{
|
||||||
|
$filter = $r->validate(['invoice' => 'sometimes|required|integer|min:1', 'page' => 'sometimes|integer|min:1|max:100000',
|
||||||
|
'proposal_page' => 'sometimes|integer|min:1|max:100000', 'event_page' => 'sometimes|integer|min:1|max:100000',
|
||||||
|
'per_page' => 'sometimes|integer|in:25,100', 'q' => 'sometimes|nullable|string|max:100', 'recognition' => 'sometimes|in:all,recognised,unrecognised']);
|
||||||
|
abort_if(array_diff(array_keys($r->query()), array_keys($filter)) !== [], 422);
|
||||||
|
|
||||||
|
return $filter;
|
||||||
|
}
|
||||||
|
|
||||||
public function index(Request $r, SupplierPayables $s): JsonResponse
|
public function index(Request $r, SupplierPayables $s): JsonResponse
|
||||||
{
|
{
|
||||||
$filter = $r->validate(['invoice' => 'sometimes|required|integer|min:1']);
|
$filter = $this->filters($r);
|
||||||
|
$options = array_diff_key($filter, ['invoice' => true]);
|
||||||
|
|
||||||
return response()->json($s->listing($r->user(), isset($filter['invoice']) ? (int) $filter['invoice'] : null))->header('Cache-Control', 'no-store');
|
return response()->json($s->listing($this->actor($r), isset($filter['invoice']) ? (int) $filter['invoice'] : null, $options))->header('Cache-Control', 'no-store');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function page(Request $r, SupplierPayables $s): Response
|
public function page(Request $r, SupplierPayables $s): Response
|
||||||
{
|
{
|
||||||
$filter = $r->validate(['invoice' => 'sometimes|required|integer|min:1']);
|
$filter = $this->filters($r);
|
||||||
$data = $s->listing($r->user(), isset($filter['invoice']) ? (int) $filter['invoice'] : null);
|
$options = array_diff_key($filter, ['invoice' => true]);
|
||||||
$company = Tenant::query()->findOrFail($r->user()->tenant_id)->name;
|
$actor = $this->actor($r);
|
||||||
|
$data = $s->listing($actor, isset($filter['invoice']) ? (int) $filter['invoice'] : null, $options);
|
||||||
|
$company = Tenant::query()->findOrFail($actor->tenant_id)->name;
|
||||||
|
|
||||||
return response(Workspace::render($data, ['host' => 'Compras autónomo', 'actor' => $r->user()->name, 'organisation' => $company, 'api' => '/api/supplier-payables', 'csrf' => csrf_token(), 'return_url' => '/facturas', 'return_label' => 'Voltar às facturas']))->header('Cache-Control', 'no-store');
|
return response(Workspace::render($data, ['host' => 'Compras autónomo', 'actor' => $actor->name, 'organisation' => $company, 'api' => '/api/supplier-payables', 'page_url' => '/obrigacoes-fornecedores', 'csrf' => csrf_token(), 'return_url' => '/facturas', 'return_label' => 'Voltar às facturas']))->header('Cache-Control', 'no-store');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function command(Request $r, string $action, SupplierPayables $s): JsonResponse
|
public function command(Request $r, string $action, SupplierPayables $s): JsonResponse
|
||||||
@@ -33,7 +56,7 @@ final class SupplierPayablesController extends Controller
|
|||||||
$d = $r->validate(['id' => 'required|integer|min:1', 'reason' => 'required|string|min:3|max:2000']);
|
$d = $r->validate(['id' => 'required|integer|min:1', 'reason' => 'required|string|min:3|max:2000']);
|
||||||
abort_if(array_diff(array_keys($r->all()), ['id', 'reason']) !== [], 422);
|
abort_if(array_diff(array_keys($r->all()), ['id', 'reason']) !== [], 422);
|
||||||
try {
|
try {
|
||||||
return response()->json($s->engine($r->user())->command($action, $d['id'], $d['reason'], (string) $r->header('Idempotency-Key')));
|
return response()->json($s->engine($this->actor($r))->command($action, $d['id'], $d['reason'], (string) $r->header('Idempotency-Key')));
|
||||||
} catch (\DomainException $e) {
|
} catch (\DomainException $e) {
|
||||||
abort(409, $e->getMessage());
|
abort(409, $e->getMessage());
|
||||||
} catch (\InvalidArgumentException $e) {
|
} catch (\InvalidArgumentException $e) {
|
||||||
|
|||||||
@@ -2,12 +2,58 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ExpenseAllocations;
|
||||||
|
use App\Services\GeneralLedger;
|
||||||
|
use App\Services\StandaloneRuntime;
|
||||||
|
use App\Services\StandaloneSchema;
|
||||||
use App\Services\SupplierPayables;
|
use App\Services\SupplierPayables;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
use Tempo\Finance\Payables\SettlementHttp;
|
use Tempo\Finance\Payables\SettlementHttp;
|
||||||
|
use Tempo\Finance\Payables\SupplierSettlements;
|
||||||
|
|
||||||
final class SupplierPaymentsController extends SettlementHttp
|
final class SupplierPaymentsController extends SettlementHttp
|
||||||
{
|
{
|
||||||
protected const MODE = 'compras';
|
protected const MODE = 'compras';
|
||||||
|
|
||||||
protected const SERVICE = SupplierPayables::class;
|
protected const SERVICE = SupplierPayables::class;
|
||||||
|
|
||||||
|
protected function settlementEngine(Request $request): SupplierSettlements
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
abort_unless($user instanceof User, 403);
|
||||||
|
|
||||||
|
return app(SupplierPayables::class)->settlements($user);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function guard(): void
|
||||||
|
{
|
||||||
|
if (! app(StandaloneRuntime::class)->enabled()) {
|
||||||
|
parent::guard();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
abort_unless(app(StandaloneRuntime::class)->feature('supplier-settlements', DB::connection()), 403);
|
||||||
|
StandaloneSchema::verify(DB::getSchemaBuilder(), ['supplier-payables' => true, 'supplier-settlements' => true]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
protected function ledgerSettings(Request $request): array
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
abort_unless($user instanceof User, 403);
|
||||||
|
$settings = app(StandaloneRuntime::class)->enabled() ? [
|
||||||
|
'host_settlement_policy' => true, 'synthetic_only' => app(StandaloneRuntime::class)->syntheticOnly(),
|
||||||
|
'return_url' => '/dashboard',
|
||||||
|
] : [];
|
||||||
|
if (app(StandaloneRuntime::class)->enabled() && app(ExpenseAllocations::class)->ready() && $user->hasFunctions(['admin', 'finance'])) {
|
||||||
|
$settings['expense_allocation_base_url'] = '/afectacoes-fornecedores/';
|
||||||
|
}
|
||||||
|
if (app(GeneralLedger::class)->cycleEnabled() && app(GeneralLedger::class)->can($user, 'view')) {
|
||||||
|
$settings['ledger_cycle_url'] = '/general-ledger/cycle';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $settings;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ class SupplierResponseController extends Controller
|
|||||||
} else {
|
} else {
|
||||||
$rules += ['outcome' => 'prohibited', 'follow_up' => 'prohibited', 'response_reference' => 'prohibited'];
|
$rules += ['outcome' => 'prohibited', 'follow_up' => 'prohibited', 'response_reference' => 'prohibited'];
|
||||||
}
|
}
|
||||||
$workflow->execute($request->user(), $evaluation, $record, $command, $request->validate($rules));
|
$workflow->execute($this->staffIdentity($request), $evaluation, $record, $command, $request->validate($rules));
|
||||||
|
|
||||||
return to_route('supplier-evaluations.show', $evaluation)->with('supplier_evaluation_notice', 'Contraditório e histórico actualizados.');
|
return to_route('supplier-evaluations.show', $evaluation)->with('supplier_evaluation_notice', 'Contraditório e histórico actualizados.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\SupplyCoordination;
|
||||||
|
use App\Services\SupplyCoordinationRead;
|
||||||
|
use Brick\Math\BigDecimal;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
|
|
||||||
|
class SupplyCoordinationReportController extends Controller
|
||||||
|
{
|
||||||
|
public function csv(Request $request, SupplyCoordinationRead $read): StreamedResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$view = $request->validate(['view' => 'required|in:reservations,deliveries,alternatives'])['view'];
|
||||||
|
$kind = $read->kind($actor, $view);
|
||||||
|
$filters = $read->filters($request, $kind);
|
||||||
|
abort_unless(Schema::hasTable('supply_records'), 503, 'Instalação do fornecimento pendente.');
|
||||||
|
// Validate the same focus as the page, without silently exporting other records.
|
||||||
|
$focus = $request->validate(['record_id' => ['nullable', 'integer', 'min:1', Rule::exists('supply_records', 'id')->where('tenant_id', $actor->tenant_id)->where('kind', $kind)]]);
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($read, $actor, $view, $kind, $filters, $focus) {
|
||||||
|
DB::transaction(function () use ($read, $actor, $view, $kind, $filters, $focus) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
// Recheck access when the response is consumed.
|
||||||
|
$read->kind($actor, $view);
|
||||||
|
$query = $read->query($kind, isset($focus['record_id']) ? ['record_search' => '', 'record_state' => ''] : $filters);
|
||||||
|
if (isset($focus['record_id'])) {
|
||||||
|
$key = SupplyRecord::query()->whereKey($focus['record_id'])->value('record_key');
|
||||||
|
$query->where('record_key', $key);
|
||||||
|
}
|
||||||
|
$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, ['Acompanhamento de fornecimentos', $view, 'Conferido em', now()->toIso8601String()], ';', '"', '');
|
||||||
|
fputcsv($out, ['Filtros', $text(json_encode($filters, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)), 'Registo em foco', $focus['record_id'] ?? ''], ';', '"', '');
|
||||||
|
fputcsv($out, ['Registo', 'Versão', 'Estado registado', 'Artigo', 'Designação preservada', 'Local preservado', 'Referência', 'Encomenda', 'Quantidade', 'Unidade', 'Data prevista/necessidade', 'Quantidade por satisfazer (ver estado)', 'Substituto', 'Aplicação', 'Validade', 'Processo', 'Unidade da quantidade pendente', 'Factor físico', 'Fonte da conversão', 'Versão da conversão'], ';', '"', '');
|
||||||
|
foreach ($query->lazyById(100) as $record) {
|
||||||
|
$pending = match ($kind) {
|
||||||
|
'reservation' => app(SupplyCoordination::class)->remainingReservation($record),
|
||||||
|
'delivery' => app(SupplyCoordination::class)->remainingDelivery($record),
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
$basis = $record->snapshot['quantity_conversion'] ?? null;
|
||||||
|
$quantity = static fn (int|string $milli): string => (string) BigDecimal::of($milli)->dividedBy(1000, 3)->strippedOfTrailingZeros();
|
||||||
|
fputcsv($out, array_map($text, [$record->record_key, $record->version, $record->state,
|
||||||
|
$record->snapshot['item']['code'] ?? '', $record->snapshot['item']['name'] ?? '', $record->snapshot['warehouse']['name'] ?? '',
|
||||||
|
$record->data['reference'] ?? '', $record->snapshot['order']['number'] ?? '',
|
||||||
|
isset($record->data['quantity_milli']) ? $quantity($record->data['quantity_milli']) : '', $basis['document_unit'] ?? $record->snapshot['item']['unit'] ?? '',
|
||||||
|
$record->data['needed_on'] ?? $record->data['expected_on'] ?? '', $pending === null ? '' : $quantity($pending),
|
||||||
|
$record->snapshot['substitute']['code'] ?? '', $record->data['application'] ?? '', $record->data['valid_until'] ?? '',
|
||||||
|
url('/compras/fornecimento?view='.$view.'&record_id='.$record->id).'#supply-record-'.$record->id,
|
||||||
|
$pending === null ? '' : ($record->snapshot['item']['unit'] ?? ''), $basis === null ? '' : $basis['numerator'].'/'.$basis['denominator'],
|
||||||
|
$basis['source'] ?? '', $basis['version'] ?? '']), ';', '"', '');
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
fclose($out);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, 'fornecimentos-'.$view.'-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,405 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\CostCenter;
|
||||||
|
use App\Models\PurchaseOrder;
|
||||||
|
use App\Models\PurchaseOrderItem;
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\RequisitionItem;
|
||||||
|
use App\Models\StockItem;
|
||||||
|
use App\Models\StockOperation;
|
||||||
|
use App\Models\Supplier;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Models\Warehouse;
|
||||||
|
use App\Services\AgreementOrderLimits;
|
||||||
|
use App\Services\ImportDossier;
|
||||||
|
use App\Services\ImportLandedCosts;
|
||||||
|
use App\Services\InventoryConversionRuntime;
|
||||||
|
use App\Services\InventoryReversals;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
|
use App\Services\ReceiptWorkflow;
|
||||||
|
use App\Services\SupplyCoordination;
|
||||||
|
use App\Services\SupplyCoordinationRead;
|
||||||
|
use App\Services\SupplyHistory;
|
||||||
|
use App\Services\SupplyPlanning;
|
||||||
|
use App\Services\SupplySuggestions;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Inertia\Response;
|
||||||
|
use Symfony\Component\HttpFoundation\Response as HttpResponse;
|
||||||
|
|
||||||
|
class SupplyPlanningController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, SupplyPlanning $planning): HttpResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($request, $planning, $actor) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->page($request, $planning, $actor);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function page(Request $request, SupplyPlanning $planning, User $actor): HttpResponse
|
||||||
|
{
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$view = $request->validate(['view' => 'nullable|in:contracts,agreements,calendar,imports,alternatives,reservations,deliveries,suggestions,history'])['view'] ?? 'agreements';
|
||||||
|
if ($view === 'contracts') {
|
||||||
|
abort_unless(app(AgreementOrderLimits::class)->ready(), 503);
|
||||||
|
}
|
||||||
|
if ($view === 'history') {
|
||||||
|
return $this->privateResponse($request, $this->history($request, $actor, $planning));
|
||||||
|
}
|
||||||
|
if ($view === 'suggestions') {
|
||||||
|
return $this->privateResponse($request, $this->suggestions($request, $actor, $planning));
|
||||||
|
}
|
||||||
|
if (in_array($view, ['alternatives', 'reservations', 'deliveries'], true)) {
|
||||||
|
return $this->privateResponse($request, $this->coordination($request, $actor, $view, $planning));
|
||||||
|
}
|
||||||
|
$import = $view === 'imports';
|
||||||
|
$capabilities = $import ? ['import_read', 'import_prepare', 'import_customs'] : ['supply_read', 'supply_prepare', 'supply_review'];
|
||||||
|
abort_unless(collect($capabilities)->contains(fn ($p) => $planning->allows($actor, $p)), 403);
|
||||||
|
$ready = Schema::hasTable('supply_records');
|
||||||
|
$kind = $import ? 'import' : ($view === 'calendar' ? 'policy' : ($view === 'contracts' ? 'contract' : 'agreement'));
|
||||||
|
$focus = $this->focusedRecord($request, $actor, $kind);
|
||||||
|
[$records, $page] = $this->recordPage($request, $planning, $ready, $kind, $focus);
|
||||||
|
$projections = [];
|
||||||
|
if ($view === 'calendar' && $ready) {
|
||||||
|
foreach ($records->where('state', 'approved') as $record) {
|
||||||
|
$projections[$record->record_key] = $planning->calendar($record, today()->toDateString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$prepare = $planning->allows($actor, $import ? 'import_prepare' : 'supply_prepare');
|
||||||
|
$orderFilters = $import ? $request->validate([
|
||||||
|
'order_search' => 'nullable|string|max:100',
|
||||||
|
'selected_order_id' => ['nullable', 'integer', 'min:1', Rule::exists('purchase_orders', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||||
|
]) : [];
|
||||||
|
$historyFilters = $kind === 'policy' ? $request->validate([
|
||||||
|
'history_stock_item_id' => ['nullable', 'required_with:history_period_from,history_period_until,selected_history_key', 'integer', Rule::exists('stock_items', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||||
|
'history_warehouse_id' => ['nullable', 'required_with:history_stock_item_id', 'integer', Rule::exists('warehouses', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||||
|
'history_purpose' => 'nullable|required_with:history_stock_item_id|in:internal,resale',
|
||||||
|
'history_period_from' => 'nullable|date_format:Y-m-d',
|
||||||
|
'history_period_until' => ['nullable', 'date_format:Y-m-d', $request->filled('history_period_from') ? 'after_or_equal:history_period_from' : 'nullable'],
|
||||||
|
'selected_history_key' => ['nullable', 'uuid', Rule::exists('supply_records', 'record_key')->where('tenant_id', $actor->tenant_id)->where('kind', 'history')],
|
||||||
|
'history_form_key' => 'nullable|string|max:80',
|
||||||
|
]) : [];
|
||||||
|
|
||||||
|
$agreementFilters = $kind === 'policy' ? $request->validate([
|
||||||
|
'agreement_search' => 'nullable|string|max:100',
|
||||||
|
'agreement_stock_item_id' => ['nullable', 'required_with:agreement_search,selected_agreement_key', 'integer', Rule::exists('stock_items', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||||
|
'agreement_warehouse_id' => ['nullable', 'required_with:agreement_stock_item_id', 'integer', Rule::exists('warehouses', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||||
|
'selected_agreement_key' => ['nullable', 'uuid', Rule::exists('supply_records', 'record_key')->where('tenant_id', $actor->tenant_id)->where('kind', 'agreement')],
|
||||||
|
'agreement_form_key' => 'nullable|string|max:80',
|
||||||
|
]) : [];
|
||||||
|
|
||||||
|
$contractFilters = $request->validate(['contract_search' => 'nullable|string|max:100', 'selected_contract_key' => 'nullable|uuid']);
|
||||||
|
|
||||||
|
return $this->privateResponse($request, Inertia::render('supply/index', ['view' => $view, 'kind' => $kind, 'ready' => $ready,
|
||||||
|
'contractSearch' => $contractFilters['contract_search'] ?? '',
|
||||||
|
'contracts' => $ready && $prepare && $kind === 'agreement' && app(AgreementOrderLimits::class)->ready()
|
||||||
|
? $this->approvedOptions($planning, 'contract', $records->pluck('data.contract_key')->push($contractFilters['selected_contract_key'] ?? null), ['agreement_search' => $contractFilters['contract_search'] ?? ''])->map(fn ($r) => $r->only(['record_key', 'version', 'data', 'snapshot'])) : [],
|
||||||
|
'orderLimitsReady' => app(AgreementOrderLimits::class)->ready(),
|
||||||
|
'importCostsReady' => $import && $actor->hasFunctions([PurchasingRole::Finance]) && app(ImportLandedCosts::class)->ready(),
|
||||||
|
'importDossierReady' => $import && $actor->hasFunctions(['import_read', 'import_prepare', 'finance']) && app(ImportDossier::class)->ready(),
|
||||||
|
'linkedAgreementKey' => $kind === 'policy' ? $request->query('linked_agreement_key') : null,
|
||||||
|
'linkedContractKey' => $kind === 'agreement' ? $request->query('linked_contract_key') : null,
|
||||||
|
'agreementSearch' => $agreementFilters['agreement_search'] ?? '', 'agreementFormKey' => $agreementFilters['agreement_form_key'] ?? null,
|
||||||
|
'recordPagination' => $this->pagination($page),
|
||||||
|
'focusRecordId' => $focus->id ?? null, 'focusChanged' => $focus !== null && $records->first()?->id !== $focus->id,
|
||||||
|
'records' => $records->map(fn (SupplyRecord $record) => [...$record->toArray(), 'canApprove' => $planning->canReview($actor, $record), 'canReturn' => $planning->canReview($actor, $record, 'return'), 'canSuspend' => $planning->canReview($actor, $record, 'suspend')]), 'projections' => $projections,
|
||||||
|
'asOf' => today()->toDateString(),
|
||||||
|
'historyFormKey' => $historyFilters['history_form_key'] ?? null,
|
||||||
|
'histories' => $ready && $prepare && $kind === 'policy' ? $this->approvedOptions($planning, 'history', $records->pluck('data.history_key')->push($historyFilters['selected_history_key'] ?? null), $historyFilters)->map(fn ($r) => [
|
||||||
|
'key' => $r->record_key, 'version' => $r->version, 'stock_item_id' => $r->stock_item_id, 'warehouse_id' => $r->warehouse_id, 'purpose' => $r->data['purpose'],
|
||||||
|
'period_from' => $r->data['period_from'], 'period_until' => $r->data['period_until'], 'quality' => $r->data['quality'], 'pattern' => $r->data['pattern'], 'days' => $r->snapshot['analysis']['days'], 'daily_mean_milli' => $r->snapshot['analysis']['daily_mean_milli'],
|
||||||
|
]) : [],
|
||||||
|
'agreements' => $ready && $prepare && $kind === 'policy' ? $this->approvedOptions($planning, 'agreement', $records->pluck('data.agreement_key')->push($agreementFilters['selected_agreement_key'] ?? null), $agreementFilters)->map(fn ($r) => $r->only(['record_key', 'version', 'stock_item_id', 'warehouse_id', 'data', 'snapshot'])) : [],
|
||||||
|
'history' => $ready ? SupplyRecord::query()->where('kind', $kind)->whereIn('record_key', $records->pluck('record_key'))->orderByDesc('id')->get()->groupBy('record_key') : [],
|
||||||
|
'canPrepare' => $prepare, 'canReview' => $planning->allows($actor, 'supply_review'), 'canCustoms' => $planning->allows($actor, 'import_customs'),
|
||||||
|
'items' => $prepare && ! $import ? StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']) : [],
|
||||||
|
'warehouses' => $prepare && ! $import ? Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']) : [],
|
||||||
|
'suppliers' => $prepare && $kind === 'agreement' ? Supplier::query()->where('status', 'active')->orderBy('name')->get(['id', 'name']) : [],
|
||||||
|
'orderSearch' => $orderFilters['order_search'] ?? '',
|
||||||
|
'orders' => $prepare && $import ? $this->orderOptions($records->pluck('purchase_order_id')->push($orderFilters['selected_order_id'] ?? null), $orderFilters['order_search'] ?? '') : [],
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function privateResponse(Request $request, Response $page): HttpResponse
|
||||||
|
{
|
||||||
|
$response = $page->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function focusedRecord(Request $request, User $actor, string $kind): ?SupplyRecord
|
||||||
|
{
|
||||||
|
$filter = $request->validate(['record_id' => ['nullable', 'integer', 'min:1', Rule::exists('supply_records', 'id')->where('tenant_id', $actor->tenant_id)->where('kind', $kind)]]);
|
||||||
|
|
||||||
|
return isset($filter['record_id']) ? SupplyRecord::query()->where('tenant_id', $actor->tenant_id)->where('kind', $kind)->findOrFail((int) $filter['record_id']) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array{Collection<int,SupplyRecord>,LengthAwarePaginator<int,SupplyRecord>|null} */
|
||||||
|
private function recordPage(Request $request, SupplyPlanning $planning, bool $ready, string $kind, ?SupplyRecord $focus): array
|
||||||
|
{
|
||||||
|
$request->validate(['records_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
if (! $ready) {
|
||||||
|
return [collect(), null];
|
||||||
|
}
|
||||||
|
$query = $planning->latest($kind)->latest('id');
|
||||||
|
if ($kind === 'agreement') {
|
||||||
|
$linked = $request->validate(['linked_contract_key' => 'nullable|uuid']);
|
||||||
|
if (! empty($linked['linked_contract_key'])) {
|
||||||
|
$query->where('data->contract_key', $linked['linked_contract_key']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($kind === 'policy') {
|
||||||
|
$linked = $request->validate(['linked_agreement_key' => 'nullable|uuid']);
|
||||||
|
if (! empty($linked['linked_agreement_key'])) {
|
||||||
|
$query->where('data->agreement_key', $linked['linked_agreement_key']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($focus !== null) {
|
||||||
|
return [$query->where('record_key', $focus->record_key)->get(), null];
|
||||||
|
}
|
||||||
|
$page = $query->paginate(25, ['*'], 'records_page')->withQueryString();
|
||||||
|
|
||||||
|
return [$page->getCollection(), $page];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param LengthAwarePaginator<int,SupplyRecord>|null $page
|
||||||
|
* @return array<string,mixed>|null
|
||||||
|
*/
|
||||||
|
private function pagination(?LengthAwarePaginator $page): ?array
|
||||||
|
{
|
||||||
|
return $page === null ? null : ['current_page' => $page->currentPage(), 'last_page' => $page->lastPage(), 'total' => $page->total(),
|
||||||
|
'prev_page_url' => $page->previousPageUrl(), 'next_page_url' => $page->nextPageUrl()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Preserve already selected sources even outside the recent choices.
|
||||||
|
* @param Collection<array-key,mixed> $selected
|
||||||
|
* @param array<string,mixed> $filters
|
||||||
|
* @return Collection<int,SupplyRecord>
|
||||||
|
*/
|
||||||
|
private function approvedOptions(SupplyPlanning $planning, string $kind, Collection $selected, array $filters = []): Collection
|
||||||
|
{
|
||||||
|
$query = $planning->latest($kind)->where('state', 'approved');
|
||||||
|
if ($kind === 'agreement' && isset($filters['agreement_stock_item_id'])) {
|
||||||
|
$query->where('stock_item_id', $filters['agreement_stock_item_id'])->where('warehouse_id', $filters['agreement_warehouse_id']);
|
||||||
|
}
|
||||||
|
if ($kind === 'history' && isset($filters['history_stock_item_id'])) {
|
||||||
|
$query->where('stock_item_id', $filters['history_stock_item_id'])->where('warehouse_id', $filters['history_warehouse_id'])->where('data->purpose', $filters['history_purpose']);
|
||||||
|
}
|
||||||
|
$recent = (clone $query)
|
||||||
|
->when(trim($filters['agreement_search'] ?? '') !== '', fn ($q) => $q->where(fn ($match) => $match
|
||||||
|
->whereLike('data->reference', '%'.trim($filters['agreement_search']).'%')
|
||||||
|
->orWhereLike('snapshot->supplier->name', '%'.trim($filters['agreement_search']).'%')))
|
||||||
|
->when(trim($filters['policy_search'] ?? '') !== '', fn ($q) => $q->where(fn ($match) => $match
|
||||||
|
->whereLike('snapshot->item->code', '%'.trim($filters['policy_search']).'%')
|
||||||
|
->orWhereLike('snapshot->item->name', '%'.trim($filters['policy_search']).'%')
|
||||||
|
->orWhereLike('snapshot->warehouse->name', '%'.trim($filters['policy_search']).'%')))
|
||||||
|
->when($filters['history_period_from'] ?? null, fn ($q, $date) => $q->where('data->period_from', '>=', $date))
|
||||||
|
->when($filters['history_period_until'] ?? null, fn ($q, $date) => $q->where('data->period_until', '<=', $date))
|
||||||
|
->latest('id')->limit(100)->pluck('id');
|
||||||
|
|
||||||
|
return $query->where(fn ($q) => $q->whereIn('id', $recent)->orWhereIn('record_key', $selected->filter()->unique()))->latest('id')->get();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Collection<array-key,mixed> $selected
|
||||||
|
* @return Collection<int,PurchaseOrder>
|
||||||
|
*/
|
||||||
|
private function orderOptions(Collection $selected, string $search = ''): Collection
|
||||||
|
{
|
||||||
|
$recent = PurchaseOrder::query()->when(trim($search) !== '', fn ($q) => $q->whereRaw('LOWER(number) LIKE ?', ['%'.mb_strtolower(trim($search)).'%']))->latest('id')->limit(100)->pluck('id');
|
||||||
|
|
||||||
|
return PurchaseOrder::query()->where(fn ($q) => $q->whereIn('id', $recent)->orWhereIn('id', $selected->filter()->unique()))->latest('id')->get(['id', 'number']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function history(Request $request, User $actor, SupplyPlanning $planning): Response
|
||||||
|
{
|
||||||
|
$prepare = $planning->allows($actor, 'supply_history_prepare');
|
||||||
|
$review = $planning->allows($actor, 'supply_history_review');
|
||||||
|
abort_unless($prepare || $review || $planning->allows($actor, 'supply_read'), 403);
|
||||||
|
$ready = Schema::hasTable('supply_records');
|
||||||
|
$focus = $this->focusedRecord($request, $actor, 'history');
|
||||||
|
[$records, $page] = $this->recordPage($request, $planning, $ready, 'history', $focus);
|
||||||
|
$service = app(SupplyHistory::class);
|
||||||
|
|
||||||
|
return Inertia::render('supply/history', ['ready' => $ready, 'actorId' => $actor->id,
|
||||||
|
'recordPagination' => $this->pagination($page),
|
||||||
|
'focusRecordId' => $focus->id ?? null, 'focusChanged' => $focus !== null && $records->first()?->id !== $focus->id,
|
||||||
|
'records' => $records->map(fn (SupplyRecord $record) => [...$record->toArray(), 'canApprove' => $service->canReview($actor, $record), 'canReturn' => $service->canReview($actor, $record, 'return'), 'canSuspend' => $service->canReview($actor, $record, 'suspend')]), 'canPrepare' => $prepare, 'canReview' => $review,
|
||||||
|
'defaultPeriod' => ['from' => today()->subDays(30)->toDateString(), 'until' => today()->subDay()->toDateString()],
|
||||||
|
'items' => $prepare ? StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']) : [], 'warehouses' => $prepare ? Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']) : [],
|
||||||
|
'history' => $ready ? SupplyRecord::query()->where('kind', 'history')->whereIn('record_key', $records->pluck('record_key'))->orderByDesc('id')->get()->groupBy('record_key') : [],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function suggestions(Request $request, User $actor, SupplyPlanning $planning): Response
|
||||||
|
{
|
||||||
|
$prepare = $planning->allows($actor, 'supply_suggest_prepare');
|
||||||
|
$review = $planning->allows($actor, 'supply_suggest_review');
|
||||||
|
$convertPermission = $planning->allows($actor, 'supply_suggest_convert');
|
||||||
|
$convert = $convertPermission && app(OrganizationAccess::class)->canRequest($actor);
|
||||||
|
abort_unless($planning->allows($actor, 'supply_read') || $prepare || $review || $convertPermission, 403);
|
||||||
|
$ready = Schema::hasTable('supply_records');
|
||||||
|
$focus = $this->focusedRecord($request, $actor, 'suggestion');
|
||||||
|
[$records, $page] = $this->recordPage($request, $planning, $ready, 'suggestion', $focus);
|
||||||
|
$filters = $request->validate([
|
||||||
|
'policy_search' => 'nullable|string|max:100',
|
||||||
|
'selected_policy_key' => ['nullable', 'uuid', Rule::exists('supply_records', 'record_key')->where('tenant_id', $actor->tenant_id)->where('kind', 'policy')],
|
||||||
|
'policy_form_key' => 'nullable|string|max:80',
|
||||||
|
]);
|
||||||
|
$policies = [];
|
||||||
|
if ($ready && $prepare) {
|
||||||
|
foreach ($this->approvedOptions($planning, 'policy', $records->pluck('data.policy_key')->push($filters['selected_policy_key'] ?? null), $filters) as $policy) {
|
||||||
|
$option = ['key' => $policy->record_key, 'version' => $policy->version, 'label' => $policy->snapshot['item']['code'].' · '.$policy->snapshot['item']['name'].' · '.$policy->snapshot['warehouse']['name'], 'issue' => null];
|
||||||
|
try {
|
||||||
|
$basis = app(SupplySuggestions::class)->basis($policy->record_key, today()->toDateString());
|
||||||
|
$option += ['unit_price' => $basis['unit_price'], 'tax_rate' => $basis['tax_rate'], 'quantity_milli' => $basis['projection']['quantity_milli'] ?? 0,
|
||||||
|
'delivery_on' => $basis['projection']['risk_date'] ?? null, 'unit' => $basis['item']['unit']];
|
||||||
|
} catch (ValidationException $e) {
|
||||||
|
$option['issue'] = $e->getMessage();
|
||||||
|
}
|
||||||
|
$policies[] = $option;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$requests = Requisition::query()->visibleTo($actor)->whereIn('id', $records->pluck('data.requisition_id')->filter())->get(['id', 'number'])->keyBy('id');
|
||||||
|
|
||||||
|
$service = app(SupplySuggestions::class);
|
||||||
|
|
||||||
|
return Inertia::render('supply/suggestions', ['ready' => $ready, 'actorId' => $actor->id,
|
||||||
|
'policySearch' => $filters['policy_search'] ?? '', 'policyFormKey' => $filters['policy_form_key'] ?? null,
|
||||||
|
'recordPagination' => $this->pagination($page),
|
||||||
|
'focusRecordId' => $focus->id ?? null, 'focusChanged' => $focus !== null && $records->first()?->id !== $focus->id,
|
||||||
|
'records' => $records->map(fn (SupplyRecord $record) => [...$record->toArray(),
|
||||||
|
'canApprove' => $service->canAct($actor, $record, 'approve'), 'canReturn' => $service->canAct($actor, $record, 'return'),
|
||||||
|
'canConvert' => $service->canAct($actor, $record, 'convert'), 'canCancel' => $service->canAct($actor, $record, 'cancel'), 'canClose' => $service->canAct($actor, $record, 'close')]),
|
||||||
|
'policies' => $policies, 'canPrepare' => $prepare, 'canReview' => $review, 'canConvert' => $convert,
|
||||||
|
'costCenters' => $convert ? CostCenter::query()->where('department_id', $actor->department_id)->orderBy('code')->get(['id', 'code', 'name']) : [],
|
||||||
|
'requestLinks' => $requests,
|
||||||
|
'excess' => $records->mapWithKeys(fn ($r) => [$r->record_key => app(SupplySuggestions::class)->hasExcess($r)]),
|
||||||
|
'history' => $ready ? SupplyRecord::query()->where('kind', 'suggestion')->whereIn('record_key', $records->pluck('record_key'))->orderByDesc('id')->get()->groupBy('record_key') : [],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function coordination(Request $request, User $actor, string $view, SupplyPlanning $planning): Response
|
||||||
|
{
|
||||||
|
[$kind, $prepare, $review] = match ($view) {
|
||||||
|
'alternatives' => ['alternative', 'supply_technical_prepare', 'supply_technical_review'],
|
||||||
|
'reservations' => ['reservation', 'supply_reserve', 'supply_reserve'],
|
||||||
|
'deliveries' => ['delivery', 'supply_delivery', 'supply_delivery'],
|
||||||
|
default => abort(404),
|
||||||
|
};
|
||||||
|
$read = app(SupplyCoordinationRead::class);
|
||||||
|
$read->kind($actor, $view);
|
||||||
|
$ready = Schema::hasTable('supply_records');
|
||||||
|
$focus = $this->focusedRecord($request, $actor, $kind);
|
||||||
|
$request->validate(['records_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$filters = $read->filters($request, $kind);
|
||||||
|
$query = $ready ? ($focus === null ? $read->query($kind, $filters) : $planning->latest($kind))->latest('id') : null;
|
||||||
|
$page = $focus === null ? $query?->paginate(25, ['*'], 'records_page')->withQueryString() : null;
|
||||||
|
$records = $focus !== null ? $query?->where('record_key', $focus->record_key)->get() ?? collect() : $page?->getCollection() ?? collect();
|
||||||
|
$canPrepare = $planning->allows($actor, $prepare);
|
||||||
|
$lineFilters = in_array($kind, ['reservation', 'delivery'], true) ? $request->validate([
|
||||||
|
'line_search' => 'nullable|string|max:100', 'line_form_key' => 'nullable|string|max:80',
|
||||||
|
'selected_order_line_id' => ['nullable', 'integer', 'min:1', Rule::exists('purchase_order_items', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||||
|
'selected_request_line_id' => ['nullable', 'integer', 'min:1', Rule::exists('requisition_items', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||||
|
]) : [];
|
||||||
|
$lineSearch = trim($lineFilters['line_search'] ?? '');
|
||||||
|
$reversedIds = $ready && $kind === 'reservation' ? array_keys(app(InventoryReversals::class)->corrections('operation')) : [];
|
||||||
|
$orders = collect();
|
||||||
|
if ($canPrepare && $kind === 'delivery') {
|
||||||
|
$recentOrders = PurchaseOrder::query()->where('status', 'issued')->when($lineSearch !== '', fn ($q) => $q->whereLike('number', '%'.$lineSearch.'%'))->latest('id')->limit(100)->pluck('id');
|
||||||
|
$selectedOrders = $records->pluck('purchase_order_id')->filter();
|
||||||
|
if (isset($lineFilters['selected_order_line_id'])) {
|
||||||
|
$selectedOrders->push(PurchaseOrderItem::query()->whereKey($lineFilters['selected_order_line_id'])->value('purchase_order_id'));
|
||||||
|
}
|
||||||
|
$orders = PurchaseOrder::query()->where('status', 'issued')->where(fn ($q) => $q->whereIn('id', $recentOrders)->orWhereIn('id', $selectedOrders))->latest('id')->get()->keyBy('id');
|
||||||
|
}
|
||||||
|
$orderLines = PurchaseOrderItem::query()->whereIn('purchase_order_id', $orders->keys())->get()->map(fn ($line) => [
|
||||||
|
'id' => $line->id, 'label' => $orders[$line->purchase_order_id]->number.' · '.$line->description.' · '.$line->quantity.' '.$line->unit,
|
||||||
|
'stock_item_id' => $orders[$line->purchase_order_id]->snapshot['catalogue_sources'][$line->requisition_item_id]['stock_item_id'] ?? null,
|
||||||
|
'quantity_milli' => ReceiptWorkflow::milli($line->quantity),
|
||||||
|
'unit' => $line->unit,
|
||||||
|
]);
|
||||||
|
$requests = collect();
|
||||||
|
if ($canPrepare && $kind === 'reservation') {
|
||||||
|
$recentRequests = Requisition::query()->where('status', 'approved')->when($lineSearch !== '', fn ($q) => $q->whereLike('number', '%'.$lineSearch.'%'))->latest('id')->limit(100)->pluck('id');
|
||||||
|
$selectedRequests = RequisitionItem::query()->whereIn('id', $records->pluck('data.requisition_item_id')->push($lineFilters['selected_request_line_id'] ?? null)->filter())->pluck('requisition_id');
|
||||||
|
$requests = Requisition::query()->where('status', 'approved')->where(fn ($q) => $q->whereIn('id', $recentRequests)->orWhereIn('id', $selectedRequests))->latest('id')->get()->keyBy('id');
|
||||||
|
}
|
||||||
|
$requestLines = RequisitionItem::query()->whereIn('requisition_id', $requests->keys())->get()->filter(fn ($line) => isset($line->catalogue_snapshot['stock_item_id']))->map(fn ($line) => [
|
||||||
|
'id' => $line->id, 'label' => $requests[$line->requisition_id]->number.' · '.$line->description,
|
||||||
|
'stock_item_id' => $line->catalogue_snapshot['stock_item_id'], 'quantity_milli' => ReceiptWorkflow::milli($line->quantity),
|
||||||
|
'reference' => $requests[$line->requisition_id]->number.' / '.$line->id, 'needed_on' => $requests[$line->requisition_id]->needed_by->toDateString(),
|
||||||
|
])->values();
|
||||||
|
|
||||||
|
$coordination = app(SupplyCoordination::class);
|
||||||
|
$issueFilters = $kind === 'reservation' ? $request->validate([
|
||||||
|
'issue_search' => 'nullable|string|max:100',
|
||||||
|
'issue_record_id' => ['nullable', 'required_with:issue_search,selected_issue_id', 'integer', 'min:1', Rule::exists('supply_records', 'id')->where('tenant_id', $actor->tenant_id)->where('kind', 'reservation')],
|
||||||
|
'selected_issue_id' => ['nullable', 'integer', 'min:1', Rule::exists('stock_operations', 'id')->where('tenant_id', $actor->tenant_id)->where('kind', 'issue')],
|
||||||
|
]) : [];
|
||||||
|
$operations = collect();
|
||||||
|
if ($ready && $canPrepare && $kind === 'reservation') {
|
||||||
|
$issueRecord = isset($issueFilters['issue_record_id']) ? SupplyRecord::query()->findOrFail((int) $issueFilters['issue_record_id']) : null;
|
||||||
|
if ($issueRecord !== null) {
|
||||||
|
$issueRecord = $planning->latest('reservation')->where('record_key', $issueRecord->record_key)->firstOrFail();
|
||||||
|
abort_unless($coordination->canManage($actor, $issueRecord, 'fulfil'), 403);
|
||||||
|
}
|
||||||
|
$query = StockOperation::query()->where('kind', 'issue')->whereNotIn('id', $reversedIds)
|
||||||
|
->when($issueRecord !== null, fn ($q) => $q->where('stock_item_id', $issueRecord->stock_item_id)->where('warehouse_id', $issueRecord->warehouse_id));
|
||||||
|
$search = trim($issueFilters['issue_search'] ?? '');
|
||||||
|
$recent = (clone $query)->when($search !== '', fn ($q) => $q->whereLike('reference', '%'.$search.'%'))->latest('id')->limit(100)->pluck('id');
|
||||||
|
$operations = $query->where(fn ($q) => $q->whereIn('id', $recent)->orWhere('id', $issueFilters['selected_issue_id'] ?? 0))
|
||||||
|
->latest('id')->get(['id', 'reference', 'stock_item_id', 'warehouse_id', 'quantity_milli']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Inertia::render('supply/coordination', ['kind' => $kind, 'ready' => $ready,
|
||||||
|
'conversionQaEnabled' => app(InventoryConversionRuntime::class)->available(),
|
||||||
|
'recordFilters' => ['record_search' => trim($filters['record_search'] ?? ''), 'record_state' => $filters['record_state'] ?? ''],
|
||||||
|
'recordPagination' => $page === null ? null : ['current_page' => $page->currentPage(), 'last_page' => $page->lastPage(), 'total' => $page->total(),
|
||||||
|
'prev_page_url' => $page->previousPageUrl(), 'next_page_url' => $page->nextPageUrl()],
|
||||||
|
'focusRecordId' => $focus->id ?? null, 'focusChanged' => $focus !== null && $records->first()?->id !== $focus->id,
|
||||||
|
'records' => $records->map(fn (SupplyRecord $record) => [...$record->toArray(), 'canApprove' => $coordination->canReviewAlternative($actor, $record),
|
||||||
|
'canReturn' => $coordination->canReviewAlternative($actor, $record, 'return'), 'canSuspend' => $coordination->canReviewAlternative($actor, $record, 'suspend'),
|
||||||
|
'canEdit' => $coordination->canManage($actor, $record, 'edit'), 'canFulfil' => $coordination->canManage($actor, $record, 'fulfil'),
|
||||||
|
'canCancel' => $coordination->canManage($actor, $record, 'cancel')]),
|
||||||
|
'eligible' => $kind === 'alternative' ? $records->mapWithKeys(fn ($r) => [$r->record_key => app(SupplyCoordination::class)->eligibleAlternative($r)]) : [],
|
||||||
|
'pending' => $kind === 'delivery' ? $records->mapWithKeys(fn ($r) => [$r->record_key => app(SupplyCoordination::class)->remainingDelivery($r)]) : ($kind === 'reservation' ? $records->mapWithKeys(fn ($r) => [$r->record_key => app(SupplyCoordination::class)->remainingReservation($r)]) : []),
|
||||||
|
'reversedOperations' => $reversedIds,
|
||||||
|
'canPrepare' => $canPrepare, 'canReview' => $planning->allows($actor, $review),
|
||||||
|
'items' => $canPrepare ? StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']) : [],
|
||||||
|
'warehouses' => $canPrepare ? Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']) : [],
|
||||||
|
'orderLines' => $orderLines, 'requestLines' => $requestLines,
|
||||||
|
'lineSearch' => $lineSearch, 'lineFormKey' => $lineFilters['line_form_key'] ?? null,
|
||||||
|
'operations' => $operations, 'issueSearch' => $issueFilters['issue_search'] ?? '',
|
||||||
|
'issueRecordId' => isset($issueFilters['issue_record_id']) ? (int) $issueFilters['issue_record_id'] : null,
|
||||||
|
'history' => $ready ? SupplyRecord::query()->where('kind', $kind)->whereIn('record_key', $records->pluck('record_key'))->orderByDesc('id')->get()->groupBy('record_key') : [],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function save(Request $request, string $kind, SupplyPlanning $planning): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$planning->save($actor, $kind, $request->all());
|
||||||
|
|
||||||
|
return back();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Services\UrgentQuotationBasis;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class UrgentQuotationController extends Controller
|
||||||
|
{
|
||||||
|
public function show(Request $request, Requisition $requisition, UrgentQuotationBasis $service): Response
|
||||||
|
{
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('requisitions/urgent-stock', $service->workspace($this->staffIdentity($request), $requisition))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, Requisition $requisition, UrgentQuotationBasis $service): Response
|
||||||
|
{
|
||||||
|
$service->record($this->staffIdentity($request), $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Stock mínimo documentado para esta linha e ciclo.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\UrgentRequisitionReviews;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class UrgentRequisitionReviewController extends Controller
|
||||||
|
{
|
||||||
|
private function actor(Request $request): User
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $props */
|
||||||
|
private function page(Request $request, string $name, array $props): Response
|
||||||
|
{
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render($name, $props)->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function index(Request $request, UrgentRequisitionReviews $service): Response
|
||||||
|
{
|
||||||
|
$filters = $request->validate(['page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'state' => ['nullable', Rule::in(['all', 'pending', 'reviewed', 'indeterminate'])]]);
|
||||||
|
|
||||||
|
return $this->page($request, 'requisitions/urgent-reviews', $service->queue($this->actor($request), (int) ($filters['page'] ?? 1), $filters['state'] ?? 'pending'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(Request $request, Requisition $requisition, int $cycle, UrgentRequisitionReviews $service): Response
|
||||||
|
{
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
|
||||||
|
return $this->page($request, 'requisitions/urgent-review', $service->workspace($this->actor($request), $requisition->id, $cycle));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, Requisition $requisition, int $cycle, UrgentRequisitionReviews $service): Response
|
||||||
|
{
|
||||||
|
$service->review($this->actor($request), $requisition->id, $cycle, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Revisão posterior preservada para este ciclo.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function settings(Request $request, UrgentRequisitionReviews $service): Response
|
||||||
|
{
|
||||||
|
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
|
||||||
|
return $this->page($request, 'organization/urgent-review-policy', $service->settings($this->actor($request)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function saveSettings(Request $request, UrgentRequisitionReviews $service): Response
|
||||||
|
{
|
||||||
|
$service->savePolicy($this->actor($request), $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Designação dos perfis de revisão preservada.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\StockItem;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Models\Warehouse;
|
||||||
|
use App\Services\WarehouseAvailability;
|
||||||
|
use App\Services\WarehouseReservations;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class WarehouseAvailabilityController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, WarehouseAvailability $availability): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions(['admin', 'warehouse', 'procurement', 'finance', 'warehouse_availability_read']), 403);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($request, $actor, $availability) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
$filters = $request->validate(['warehouse_id' => ['nullable', 'integer', Rule::exists('warehouses', 'id')->where('tenant_id', $actor->tenant_id)],
|
||||||
|
'search' => 'nullable|string|max:100', 'page' => 'nullable|integer|min:1|max:100000']);
|
||||||
|
$warehouse = empty($filters['warehouse_id']) ? null : Warehouse::query()->whereKey($filters['warehouse_id'])->firstOrFail();
|
||||||
|
$planning = $actor->hasFunctions(['admin', 'supply_read', 'supply_reserve', 'warehouse_availability_read']);
|
||||||
|
$query = StockItem::query();
|
||||||
|
if (! empty($filters['search'])) {
|
||||||
|
$query->where(fn ($q) => $q->whereLike('code', '%'.$filters['search'].'%')->orWhereLike('name', '%'.$filters['search'].'%'));
|
||||||
|
}
|
||||||
|
$page = $warehouse === null ? null : $query->orderBy('code')->paginate(25)->withQueryString()->through(fn ($item) => $availability->row($item, $warehouse, $planning));
|
||||||
|
$response = Inertia::render('stock/availability', ['filters' => $filters, 'planningVisible' => $planning, 'reservationsAvailable' => app(WarehouseReservations::class)->ready(), 'rows' => $page,
|
||||||
|
'warehouse' => $warehouse?->only(['id', 'code', 'name']), 'checkedAt' => now()->toIso8601String(),
|
||||||
|
'warehouses' => Warehouse::query()->orderBy('code')->get(['id', 'code', 'name'])])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\WarehouseExchange;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class WarehouseExchangeController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, WarehouseExchange $exchange): JsonResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$input = $request->validate(['cursor' => 'nullable|string|max:4096', 'limit' => 'sometimes|integer|min:1|max:100']);
|
||||||
|
|
||||||
|
return response()->json($exchange->page($actor, $input['cursor'] ?? null, (int) ($input['limit'] ?? 50)))
|
||||||
|
->header('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\WarehousePilotReadiness;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class WarehousePilotController extends Controller
|
||||||
|
{
|
||||||
|
public function export(Request $request, WarehousePilotReadiness $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions(['admin']), 403);
|
||||||
|
$report = DB::transaction(function () use ($actor, $service) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $service->inspect($actor);
|
||||||
|
});
|
||||||
|
$rows = [['Conferido em', 'Âmbito', 'Conferência', 'Resultado', 'Observação', 'Onde configurar']];
|
||||||
|
foreach ($report['checks'] as $check) {
|
||||||
|
$rows[] = [$report['checked_at'], 'SGC autónomo · diagnóstico de configuração', $check['label'], $check['ok'] ? 'Conferido' : 'A preparar', $check['detail'], $check['path'] ?? ''];
|
||||||
|
}
|
||||||
|
|
||||||
|
return response()->streamDownload(static function () use ($rows) {
|
||||||
|
$stream = fopen('php://output', 'wb');
|
||||||
|
if ($stream === false) {
|
||||||
|
throw new \RuntimeException('Não foi possível preparar a exportação.');
|
||||||
|
}
|
||||||
|
fwrite($stream, "\xEF\xBB\xBF");
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$safe = array_map(static fn (string $value) => preg_match('/^[\s\x{FEFF}]*[=+@-]/u', $value) ? "'".$value : $value, $row);
|
||||||
|
fputcsv($stream, $safe, ';', '"', '');
|
||||||
|
}
|
||||||
|
fclose($stream);
|
||||||
|
}, 'preparacao-piloto-sgc-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function index(Request $request, WarehousePilotReadiness $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions(['admin']), 403);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($actor, $request, $service) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('stock/pilot', ['report' => $service->inspect($actor), 'syntheticEvaluation' => app()->environment(['testing', 'payable-testing'])])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\CostCenter;
|
||||||
|
use App\Models\Equipment;
|
||||||
|
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;
|
||||||
|
use App\Services\WarehouseRequests;
|
||||||
|
use App\Services\WarehouseWorkdesk;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
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');
|
||||||
|
abort_unless($actor instanceof User && $actor->hasFunctions(['admin', 'warehouse_request_read', 'warehouse_request_prepare', 'warehouse_request_review', 'warehouse_request_deliver']), 403);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($request, $actor, $desk) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
$filters = $this->filters($request, $actor);
|
||||||
|
$prepare = $actor->hasFunctions(['warehouse_request_prepare']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor);
|
||||||
|
$ready = Schema::hasTable('warehouse_requests');
|
||||||
|
$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') : [];
|
||||||
|
if (($filters['state'] ?? 'all') !== 'all') {
|
||||||
|
$query->whereRaw($desk->stateExpression().' = ?', [$filters['state']]);
|
||||||
|
}
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('stock/requests', ['ready' => $ready, 'canPrepare' => $prepare, 'fulfilmentReady' => Schema::hasTable('warehouse_request_events'),
|
||||||
|
'filters' => ['view' => $filters['view'] ?? 'all', 'state' => $filters['state'] ?? 'all', 'search' => $filters['search'] ?? '', 'warehouse_id' => $filters['warehouse_id'] ?? null], 'views' => $views, 'states' => $states, 'checkedAt' => now()->toIso8601String(),
|
||||||
|
'records' => $ready ? $query->oldest('id')->paginate(15, ['id', 'tenant_id', 'warehouse_id', 'created_by', 'status', 'snapshot', 'created_at'])->withQueryString()->through(function ($r) use ($desk, $actor) {
|
||||||
|
$p = app(WarehouseFulfilment::class)->progress($r);
|
||||||
|
|
||||||
|
return ['id' => $r->id, 'status' => $r->status, 'snapshot' => $r->snapshot, 'progress' => $p, 'health' => $desk->health($r, $p), 'actions' => $desk->actions($actor, $r, $p)];
|
||||||
|
}) : null,
|
||||||
|
'warehouses' => Warehouse::query()->when(! $prepare, fn ($q) => $q->whereIn('id', $ready ? $desk->visible($actor)->select('warehouse_id') : []))->orderBy('code')->get(['id', 'code', 'name']),
|
||||||
|
'items' => $prepare ? StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']) : [],
|
||||||
|
'costCenters' => $prepare ? CostCenter::query()->where('department_id', $actor->department_id)->orderBy('code')->get(['id', 'code', 'name']) : [],
|
||||||
|
'equipment' => $prepare ? Equipment::query()->where('department_id', $actor->department_id)->orderBy('code')->get(['id', 'code', 'description']) : []])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
$usage = $line['destination'];
|
||||||
|
if (($line['use'] ?? null) === 'production') {
|
||||||
|
$usage .= ' · Insumos para produção';
|
||||||
|
if (($line['production']['reference'] ?? null) !== null && $line['production']['reference'] !== '') {
|
||||||
|
$usage .= ' · Referência declarada: '.$line['production']['reference'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$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'], $usage, $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');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->draft($actor, $request->all());
|
||||||
|
|
||||||
|
return redirect('/stock/requisicoes');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(Request $request, int $id, WarehouseFulfilment $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($request, $id, $service, $actor) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
$r = WarehouseRequest::query()->findOrFail($id);
|
||||||
|
$desk = app(WarehouseWorkdesk::class);
|
||||||
|
abort_unless($desk->canView($actor, $r), 403);
|
||||||
|
$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),
|
||||||
|
'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');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function command(Request $request, int $id, WarehouseFulfilment $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->command($actor, $id, $request->all());
|
||||||
|
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ReceiptWorkflow;
|
||||||
|
use App\Services\WarehouseReturns;
|
||||||
|
use Illuminate\Database\QueryException;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class WarehouseReturnController extends Controller
|
||||||
|
{
|
||||||
|
private function actor(Request $r): User
|
||||||
|
{
|
||||||
|
$actor = $r->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
|
||||||
|
return $actor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function page(Request $r, WarehouseReturns $flow): Response
|
||||||
|
{
|
||||||
|
$flow->authorize($this->actor($r), 'read');
|
||||||
|
$d = $r->validate(['request_id' => 'sometimes|integer|min:1']);
|
||||||
|
$actor = $this->actor($r);
|
||||||
|
$source = isset($d['request_id']) ? $flow->availableDeliveries($actor, (int) $d['request_id'], 1) : null;
|
||||||
|
$response = Inertia::render('stock/returns', ['requestId' => isset($d['request_id']) ? (int) $d['request_id'] : null, 'canPrepare' => $source['can_prepare'] ?? false, 'canWithdraw' => $flow->allows($actor, 'prepare'), 'canConfirm' => $flow->allows($actor, 'confirm'), 'actorId' => $actor->id])->toResponse($r);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function sources(Request $r, WarehouseReturns $flow): JsonResponse
|
||||||
|
{
|
||||||
|
$d = $r->validate(['request_id' => 'required|integer|min:1', 'source_page' => 'sometimes|integer|min:1|max:100000']);
|
||||||
|
abort_if(array_diff(array_keys($r->query()), array_keys($d)) !== [], 422);
|
||||||
|
|
||||||
|
return $this->response(fn () => $flow->availableDeliveries($this->actor($r), (int) $d['request_id'], (int) ($d['source_page'] ?? 1)), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param callable():array<string,mixed> $run */
|
||||||
|
private function response(callable $run, bool $readOnly = false): JsonResponse
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$result = $readOnly ? DB::transaction(function () use ($run) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $run();
|
||||||
|
}) : $run();
|
||||||
|
|
||||||
|
return response()->json($result)->header('Cache-Control', 'no-store');
|
||||||
|
} catch (QueryException $e) {
|
||||||
|
if (($e->errorInfo[0] ?? null) === '55P03') {
|
||||||
|
return response()->json(['code' => 'warehouse_return_busy', 'message' => 'Devolução ocupada. Aguarde e repita manualmente a conferência.'], 423)->header('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
throw $e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function index(Request $r, WarehouseReturns $flow): JsonResponse
|
||||||
|
{
|
||||||
|
$d = $r->validate(['page' => 'sometimes|integer|min:1|max:100000', 'state' => 'sometimes|in:all,prepared,confirmed,withdrawn,rejected']);
|
||||||
|
abort_if(array_diff(array_keys($r->query()), array_keys($d)) !== [], 422);
|
||||||
|
|
||||||
|
return $this->response(fn () => $flow->listing($this->actor($r), (int) ($d['page'] ?? 1), $d['state'] ?? 'all'), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function prepare(Request $r, WarehouseReturns $flow): JsonResponse
|
||||||
|
{
|
||||||
|
$d = $r->validate(['operation_key' => 'required|uuid', 'delivery_event_id' => 'required|integer|min:1', 'line_index' => 'required|integer|min:0|max:49', 'quantity' => 'required|string|regex:/^[0-9]{1,6}(\.[0-9]{1,3})?$/D', 'declared_unused' => 'required|accepted', 'evidence' => 'required|string|min:10|max:1000', 'reason' => 'required|string|min:10|max:1000']);
|
||||||
|
abort_if(array_diff(array_keys($r->all()), array_keys($d)) !== [], 422);
|
||||||
|
$d['quantity_milli'] = ReceiptWorkflow::milli($d['quantity']);
|
||||||
|
$d['line_index'] = (int) $d['line_index'];
|
||||||
|
$d['delivery_event_id'] = (int) $d['delivery_event_id'];
|
||||||
|
$d['declared_unused'] = true;
|
||||||
|
|
||||||
|
return $this->response(fn () => $flow->prepare($this->actor($r), $d));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function confirm(Request $r, int $id, WarehouseReturns $flow): JsonResponse
|
||||||
|
{
|
||||||
|
$d = $r->validate(['version' => 'required|integer|min:1', 'received_in_warehouse' => 'required|accepted', 'reason' => 'required|string|min:10|max:1000']);
|
||||||
|
abort_if(array_diff(array_keys($r->all()), array_keys($d)) !== [], 422);
|
||||||
|
$d['version'] = (int) $d['version'];
|
||||||
|
$d['received_in_warehouse'] = true;
|
||||||
|
|
||||||
|
return $this->response(fn () => $flow->confirm($this->actor($r), $id, $d));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function withdraw(Request $r, int $id, WarehouseReturns $flow): JsonResponse
|
||||||
|
{
|
||||||
|
return $this->close($r, $id, $flow, 'withdrawn');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function reject(Request $r, int $id, WarehouseReturns $flow): JsonResponse
|
||||||
|
{
|
||||||
|
return $this->close($r, $id, $flow, 'rejected');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function close(Request $r, int $id, WarehouseReturns $flow, string $state): JsonResponse
|
||||||
|
{
|
||||||
|
$d = $r->validate(['version' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:1000']);
|
||||||
|
abort_if(array_diff(array_keys($r->all()), array_keys($d)) !== [], 422);
|
||||||
|
$d['version'] = (int) $d['version'];
|
||||||
|
|
||||||
|
return $this->response(fn () => $flow->close($this->actor($r), $id, $d, $state));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\RequisitionWorkflow;
|
||||||
|
use App\Services\WorkContext;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
|
||||||
|
class WorkContextController extends Controller
|
||||||
|
{
|
||||||
|
public function select(Request $request, WorkContext $contexts): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$data = $request->validate(['area' => ['required', Rule::in(['procurement', 'people'])], 'option' => ['nullable', Rule::in(array_keys(WorkContext::OPTIONS))]]);
|
||||||
|
$available = array_values(array_filter($contexts->available($actor), fn ($key) => WorkContext::OPTIONS[$key]['area'] === $data['area']));
|
||||||
|
$key = $data['option'] ?? (count($available) === 1 ? $available[0] : null);
|
||||||
|
abort_unless($key !== null && in_array($key, $available, true), 403, 'Escolha uma opção configurada, contratada e autorizada.');
|
||||||
|
$state = ['user_id' => $actor->id, 'tenant_id' => $actor->tenant_id, 'key' => $key];
|
||||||
|
app(RequisitionWorkflow::class)->audit($actor, 'work_context.selected', null, $request->session()->get('work_context'), $state);
|
||||||
|
$request->session()->put('work_context', $state);
|
||||||
|
|
||||||
|
return redirect('/dashboard');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\WorkflowNotices;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class WorkflowNoticeController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, WorkflowNotices $notices): Response
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($request, $notices) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->page($request, $notices);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,mixed> */
|
||||||
|
private function filters(Request $request): array
|
||||||
|
{
|
||||||
|
return $request->validate(['view' => 'nullable|in:all,unread,tasks,outcomes', 'page' => 'nullable|integer|min:1|max:100000', 'search' => 'nullable|string|max:100']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function page(Request $request, WorkflowNotices $notices): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$filter = $this->filters($request);
|
||||||
|
$visible = collect($notices->visible($actor));
|
||||||
|
$unread = $visible->whereNull('read_at')->count();
|
||||||
|
$items = ($filter['view'] ?? 'all') === 'unread' ? $visible->whereNull('read_at')->values() : $visible;
|
||||||
|
if (in_array($filter['view'] ?? '', ['tasks', 'outcomes'], true)) {
|
||||||
|
$items = $filter['view'] === 'tasks' ? $visible->whereIn('kind', ['task', 'reminder'])->values() : $visible->where('kind', 'outcome')->values();
|
||||||
|
}
|
||||||
|
$search = trim($filter['search'] ?? '');
|
||||||
|
if ($search !== '') {
|
||||||
|
$items = $items->filter(fn ($notice) => mb_stripos($notice['reference'], $search) !== false)->values();
|
||||||
|
}
|
||||||
|
$page = min((int) ($filter['page'] ?? 1), max(1, (int) ceil($items->count() / 25)));
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('workflow/notices', ['ready' => Schema::hasTable('workflow_notices'), 'unread' => $unread, 'view' => $filter['view'] ?? 'all',
|
||||||
|
'search' => $search,
|
||||||
|
'notices' => (new LengthAwarePaginator($items->slice(($page - 1) * 25, 25)->values(), $items->count(), 25, $page, ['path' => $request->url()]))->withQueryString()])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function read(Request $request, int $notice, WorkflowNotices $notices): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$filters = $this->filters($request);
|
||||||
|
$notices->read($actor, $notice);
|
||||||
|
|
||||||
|
return redirect('/requisicoes/avisos'.($filters === [] ? '' : '?'.http_build_query($filters)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function refresh(Request $request, int $requisition, WorkflowNotices $notices): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$notices->refresh($actor, $requisition, $request->all());
|
||||||
|
|
||||||
|
return redirect('/requisicoes/'.$requisition);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\UrgentRequisitionReviews;
|
||||||
|
use App\Services\WorkflowTaskInbox;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class WorkflowTaskInboxController extends Controller
|
||||||
|
{
|
||||||
|
public function procurement(Request $request, WorkflowTaskInbox $inbox): Response
|
||||||
|
{
|
||||||
|
return $this->page($request, $inbox, 'procurement');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function people(Request $request, WorkflowTaskInbox $inbox): Response
|
||||||
|
{
|
||||||
|
return $this->page($request, $inbox, 'people');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function page(Request $request, WorkflowTaskInbox $inbox, string $area): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$modules = $area === 'people' ? ['people' => 'Pessoas e contratações'] : ['purchases' => 'Compras', 'warehouse' => 'Armazém', 'supply' => 'Fornecimentos e reposição', 'finance' => 'Finanças'];
|
||||||
|
$filters = $request->validate(['module' => ['nullable', Rule::in(['all', ...array_keys($modules)])],
|
||||||
|
'search' => 'nullable|string|max:100', 'page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'due' => 'nullable|in:all,overdue,today,upcoming,undated']);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($request, $actor, $area, $inbox, $modules, $filters) {
|
||||||
|
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||||
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||||
|
}
|
||||||
|
$today = today()->toDateString();
|
||||||
|
$all = collect($inbox->build($actor, $area))->map(function ($row) use ($today) {
|
||||||
|
$date = $row['due_on'] ?? null;
|
||||||
|
$row['due_status'] = $date === null ? 'undated' : ($date < $today ? 'overdue' : ($date === $today ? 'today' : 'upcoming'));
|
||||||
|
|
||||||
|
return $row;
|
||||||
|
});
|
||||||
|
$counts = [];
|
||||||
|
foreach ($modules as $key => $label) {
|
||||||
|
$counts[$key] = $all->where('module', $key)->count();
|
||||||
|
}
|
||||||
|
$rows = $all->filter(fn ($row) => (($filters['module'] ?? 'all') === 'all' || $row['module'] === $filters['module'])
|
||||||
|
&& (($filters['search'] ?? '') === '' || mb_stripos($row['reference'].' '.$row['label'], trim($filters['search'])) !== false))->values();
|
||||||
|
$deadlineCounts = [];
|
||||||
|
foreach (['overdue', 'today', 'upcoming', 'undated'] as $status) {
|
||||||
|
$deadlineCounts[$status] = $rows->where('due_status', $status)->count();
|
||||||
|
}
|
||||||
|
if (($filters['due'] ?? 'all') !== 'all') {
|
||||||
|
$rows = $rows->where('due_status', $filters['due'])->values();
|
||||||
|
}
|
||||||
|
$page = (int) ($filters['page'] ?? 1);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('workflow/tasks', ['area' => $area, 'modules' => $modules, 'counts' => $counts,
|
||||||
|
'urgentReviewsReady' => $area === 'procurement' && app(UrgentRequisitionReviews::class)->ready() && $actor->hasFunctions(['admin', 'procurement']),
|
||||||
|
'checkedAt' => now()->toIso8601String(), 'asOf' => $today, 'deadlineCounts' => $deadlineCounts,
|
||||||
|
'filters' => ['module' => $filters['module'] ?? 'all', 'search' => $filters['search'] ?? '', 'due' => $filters['due'] ?? 'all'],
|
||||||
|
'tasks' => (new LengthAwarePaginator($rows->slice(($page - 1) * 25, 25)->values(), $rows->count(), 25, $page, ['path' => $request->url()]))->withQueryString()])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
|
use App\Services\ProductModules;
|
||||||
|
use Closure;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Routing\Route;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
/** Rotas de módulos desligados nesta instalação respondem como inexistentes. */
|
||||||
|
class EnsureModuleEnabled
|
||||||
|
{
|
||||||
|
public function handle(Request $request, Closure $next): Response
|
||||||
|
{
|
||||||
|
$route = $request->route();
|
||||||
|
abort_if($route instanceof Route && ! app(ProductModules::class)->allows($route), 404);
|
||||||
|
|
||||||
|
return $next($request);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Http\Middleware;
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
use App\Services\OrganizationAccess;
|
use App\Services\OrganizationAccess;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
use Closure;
|
use Closure;
|
||||||
@@ -12,14 +13,15 @@ class EnsureOrganizationAccess
|
|||||||
{
|
{
|
||||||
public function handle(Request $request, Closure $next): Response
|
public function handle(Request $request, Closure $next): Response
|
||||||
{
|
{
|
||||||
$user = $request->user();
|
$user = $request->user('web');
|
||||||
if ($user !== null && $user->tenant_id !== null) {
|
if ($user instanceof User && $user->tenant_id !== null) {
|
||||||
abort_unless(app(OrganizationAccess::class)->permissions($user) !== [], 403, 'Não existe uma atribuição de acesso válida. Contacte os administradores da empresa.');
|
abort_unless(app(OrganizationAccess::class)->permissions($user) !== [], 403, 'Não existe uma atribuição de acesso válida. Contacte os administradores da empresa.');
|
||||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user) && ! $request->isMethodSafe(), 403, 'A manutenção temporária tem acesso de diagnóstico e consulta.');
|
$contextSelection = $request->isMethod('POST') && $request->routeIs('work-context.select');
|
||||||
|
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user) && ! $request->isMethodSafe() && ! $contextSelection, 403, 'A manutenção temporária tem acesso de diagnóstico e consulta.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$response = $next($request);
|
$response = $next($request);
|
||||||
if ($user !== null && app(OrganizationAccess::class)->maintenanceOnly($user)) {
|
if ($user instanceof User && app(OrganizationAccess::class)->maintenanceOnly($user)) {
|
||||||
app(RequisitionWorkflow::class)->audit($user, 'maintenance.consulted', null, null, ['path' => $request->path(), 'status' => $response->getStatusCode()]);
|
app(RequisitionWorkflow::class)->audit($user, 'maintenance.consulted', null, null, ['path' => $request->path(), 'status' => $response->getStatusCode()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\WorkContext;
|
||||||
|
use Closure;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class EnsureWorkContext
|
||||||
|
{
|
||||||
|
public function handle(Request $request, Closure $next): Response
|
||||||
|
{
|
||||||
|
$contexts = app(WorkContext::class);
|
||||||
|
$user = $request->user('web');
|
||||||
|
if ($user instanceof User && $contexts->enforced($user) && ($area = WorkContext::area($request->path())) !== null) {
|
||||||
|
$key = $contexts->active($request);
|
||||||
|
abort_unless($key !== null && WorkContext::OPTIONS[$key]['area'] === $area, 403, 'Seleccione uma área e opção autorizadas no Painel Inicial.');
|
||||||
|
if (! WorkContext::operational($key) && $request->isMethod('GET')) {
|
||||||
|
return redirect('/dashboard');
|
||||||
|
}
|
||||||
|
abort_unless(WorkContext::operational($key), 409, 'O percurso operacional desta opção ainda está em implementação.');
|
||||||
|
abort_unless(WorkContext::allowsPath($key, $request->path()), 403, 'Seleccione o contexto de origem desta operação.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $next($request);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user