Compare commits
41
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 |
+10
-2
@@ -72,5 +72,13 @@ COMMON_PAYABLES_HISTORY_ENABLED=false
|
|||||||
COMMON_PAYABLES_HISTORY_DECISIONS_ENABLED=false
|
COMMON_PAYABLES_HISTORY_DECISIONS_ENABLED=false
|
||||||
PAYABLE_SOURCE_INSTANCE=
|
PAYABLE_SOURCE_INSTANCE=
|
||||||
|
|
||||||
# Adesão voluntária MFA, só depois da migração e validação da instalação.
|
# MFA ligado: obrigatório para as funções em SGC_MFA_REQUIRED_FUNCTIONS, voluntário
|
||||||
SGC_TWO_FACTOR_ENABLED=false
|
# 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).
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ class OperationsCheck extends Command
|
|||||||
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||||
} else {
|
} else {
|
||||||
$this->line($result['ok'] ? 'Operação: verificações concluídas sem divergências observadas.' : 'Operação: verificações requerem atenção.');
|
$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'];
|
$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'];
|
$states = ['passed' => 'sem divergências observadas', 'attention' => 'requer atenção', 'incomplete' => 'verificação incompleta', 'unavailable' => 'consulta indisponível'];
|
||||||
foreach ($result['checks'] as $key => $check) {
|
foreach ($result['checks'] as $key => $check) {
|
||||||
$this->line($labels[$key].': '.$states[$check['status']].'.');
|
$this->line($labels[$key].': '.$states[$check['status']].'.');
|
||||||
|
|||||||
@@ -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,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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -57,7 +57,7 @@ class SgcDeliveryCheck extends Command
|
|||||||
$clean = false;
|
$clean = false;
|
||||||
}
|
}
|
||||||
foreach ($enabled as $key) {
|
foreach ($enabled as $key) {
|
||||||
if (! (WorkContext::OPTIONS[$key]['operational'] ?? false)) {
|
if (! WorkContext::operational($key)) {
|
||||||
$this->error('Percurso operacional ainda pendente: '.$key);
|
$this->error('Percurso operacional ainda pendente: '.$key);
|
||||||
$clean = false;
|
$clean = false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,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']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\OrganizationAccess;
|
use App\Services\OrganizationAccess;
|
||||||
use Illuminate\Database\Query\Builder;
|
use Illuminate\Database\Query\Builder;
|
||||||
@@ -27,7 +28,7 @@ class AuditMetadataController extends Controller
|
|||||||
/** @return array<string,mixed> */
|
/** @return array<string,mixed> */
|
||||||
private function filters(Request $request): array
|
private function filters(Request $request): array
|
||||||
{
|
{
|
||||||
return $request->validate(['action' => 'nullable|string|max:100', 'actor_id' => 'nullable|integer|min:1',
|
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']);
|
'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']);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,7 +36,10 @@ class AuditMetadataController extends Controller
|
|||||||
private function query(User $actor, array $filters): Builder
|
private function query(User $actor, array $filters): Builder
|
||||||
{
|
{
|
||||||
return DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)
|
return DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)
|
||||||
->when(! empty($filters['action']), fn ($q) => $q->where('action', $filters['action']))
|
->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['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['from']), fn ($q) => $q->whereDate('created_at', '>=', $filters['from']))
|
||||||
->when(! empty($filters['to']), fn ($q) => $q->whereDate('created_at', '<=', $filters['to']))
|
->when(! empty($filters['to']), fn ($q) => $q->whereDate('created_at', '<=', $filters['to']))
|
||||||
@@ -51,8 +55,11 @@ class AuditMetadataController extends Controller
|
|||||||
$this->readOnly();
|
$this->readOnly();
|
||||||
$actor = $this->actor($request);
|
$actor = $this->actor($request);
|
||||||
Inertia::encryptHistory();
|
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,
|
$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);
|
'events' => $this->query($actor, $filters)->orderBy('id')->paginate(25)->withQueryString()])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
@@ -80,7 +87,9 @@ class AuditMetadataController extends Controller
|
|||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
fwrite($out, "\xEF\xBB\xBF");
|
fwrite($out, "\xEF\xBB\xBF");
|
||||||
fputcsv($out, ['Metadados de eventos da empresa', 'Consulta', now()->toIso8601String()], ';', '"', '');
|
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)'], ';', '"', '');
|
fputcsv($out, ['Registo', 'Data', 'Acção', 'Utilizador (id)'], ';', '"', '');
|
||||||
foreach ($this->query($actor, $filters)->lazyById(100) as $event) {
|
foreach ($this->query($actor, $filters)->lazyById(100) as $event) {
|
||||||
fputcsv($out, array_map($text, [$event->id, $event->created_at, $event->action, $event->user_id]), ';', '"', '');
|
fputcsv($out, array_map($text, [$event->id, $event->created_at, $event->action, $event->user_id]), ';', '"', '');
|
||||||
|
|||||||
@@ -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.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,45 +5,60 @@ namespace App\Http\Controllers;
|
|||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\OrganizationAccess;
|
use App\Services\OrganizationAccess;
|
||||||
|
use Illuminate\Database\QueryException;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Tempo\Inventory\InventoryReadSession;
|
||||||
|
|
||||||
final class CommonStockReadController extends Controller
|
final class CommonStockReadController extends Controller
|
||||||
{
|
{
|
||||||
public function index(Request $request)
|
public function index(Request $request): JsonResponse
|
||||||
{
|
{
|
||||||
// Native authority, reloaded on every request; no SGF grants or identity assumptions.
|
// Native authority, reloaded on every request; no SGF grants or identity assumptions.
|
||||||
$user=User::query()->findOrFail($request->user()->id);
|
$user = User::query()->findOrFail($this->staffIdentity($request)->id);
|
||||||
abort_unless($user->tenant_id!==null && $user->hasFunctions([PurchasingRole::Admin,PurchasingRole::Warehouse,PurchasingRole::Procurement,PurchasingRole::Finance])
|
abort_unless($user->tenant_id !== null && $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance])
|
||||||
&& !app(OrganizationAccess::class)->maintenanceOnly($user),403);
|
&& ! app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||||
$d=$request->validate(['view'=>'sometimes|in:items,warehouses,balances,movements','search'=>'nullable|string|max:100',
|
$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']);
|
'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);
|
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,
|
$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)];
|
'page' => (int) ($d['page'] ?? 1), 'per_page' => (int) ($d['per_page'] ?? 25)];
|
||||||
$binding=config('stock_read.synthetic_sources.'.$user->tenant_id.':'.$user->id);
|
$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');
|
if (! $binding) {
|
||||||
abort_unless(app()->environment('testing')&&DB::connection()->getDriverName()==='pgsql',403);
|
return response()->json(['status' => 'unavailable', 'message' => 'Fonte autorizada de stock ainda não ligada a este contexto.'], 503)->header('Cache-Control', 'no-store');
|
||||||
$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');
|
|
||||||
abort_unless(is_file($root.'/manifest.json')&&hash_equals(config('stock_read.package_manifest_sha256'),hash_file('sha256',$root.'/manifest.json')),503,'Pacote de consulta incompatível.');
|
|
||||||
$manifest=json_decode(file_get_contents($root.'/manifest.json'),true,512,JSON_THROW_ON_ERROR);
|
|
||||||
foreach(['bootstrap.php','src/InventoryReader.php','src/InventoryReadSession.php'] as $file)
|
|
||||||
abort_unless(is_file($root.'/'.$file)&&isset($manifest['files'][$file])&&hash_equals($manifest['files'][$file],hash_file('sha256',$root.'/'.$file)),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 \Tempo\Inventory\InventoryReadSession(DB::connection()))->read($binding,$fingerprint,$filters,$d['snapshot']??null); }
|
|
||||||
catch(\Illuminate\Database\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');
|
|
||||||
}
|
}
|
||||||
|
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');
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ use App\Models\StockMovement;
|
|||||||
use App\Models\StockOperation;
|
use App\Models\StockOperation;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\AdministrativeGeography;
|
use App\Services\AdministrativeGeography;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
use App\Services\CurrentActor;
|
use App\Services\CurrentActor;
|
||||||
use App\Services\EquipmentWarehouseRequests;
|
use App\Services\EquipmentWarehouseRequests;
|
||||||
@@ -28,7 +29,7 @@ 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
|
||||||
{
|
{
|
||||||
@@ -40,7 +41,7 @@ class EquipmentController extends Controller
|
|||||||
return $actor;
|
return $actor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Request $request, int $equipment): \Symfony\Component\HttpFoundation\Response
|
public function show(Request $request, int $equipment): Response
|
||||||
{
|
{
|
||||||
$actor = $request->user('web');
|
$actor = $request->user('web');
|
||||||
abort_unless($actor instanceof User, 403);
|
abort_unless($actor instanceof User, 403);
|
||||||
@@ -66,6 +67,7 @@ class EquipmentController extends Controller
|
|||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
$response = Inertia::render('equipment/show', ['equipment' => $asset->only(['id', 'code', 'description', 'area', 'status']),
|
$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),
|
'geography' => app(AdministrativeGeography::class)->describe($asset->geography_reference),
|
||||||
'warehouseRequests' => app(EquipmentWarehouseRequests::class)->page($actor, $asset),
|
'warehouseRequests' => app(EquipmentWarehouseRequests::class)->page($actor, $asset),
|
||||||
'purchases' => $purchases, 'movements' => $movements])->toResponse($request);
|
'purchases' => $purchases, 'movements' => $movements])->toResponse($request);
|
||||||
@@ -109,7 +111,8 @@ class EquipmentController extends Controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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(),
|
'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']),
|
'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(),
|
||||||
@@ -117,8 +120,12 @@ class EquipmentController extends Controller
|
|||||||
'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' => $this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]),
|
'canManage' => $this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]),
|
||||||
|
'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
|
||||||
'canConfigure' => $this->actor($request)->hasFunctions([PurchasingRole::Admin]),
|
'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
|
||||||
|
|||||||
@@ -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.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,10 +9,12 @@ 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\Models\User;
|
||||||
|
use App\Services\ExpenseAllocations;
|
||||||
use App\Services\ExternalPaymentWorkflow;
|
use App\Services\ExternalPaymentWorkflow;
|
||||||
use App\Services\OrganizationAccess;
|
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 Illuminate\Validation\Rule;
|
||||||
@@ -36,14 +38,23 @@ class ExternalPaymentController extends Controller
|
|||||||
if ($canManage && $payments->count() > 0) {
|
if ($canManage && $payments->count() > 0) {
|
||||||
app(RequisitionWorkflow::class)->audit($actor, '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 = $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) {
|
$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', ['focusPaymentId' => $focus, 'focusInvoiceId' => $focusInvoice, '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;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\GeneralLedger;
|
use App\Services\GeneralLedger;
|
||||||
|
use App\Services\StandaloneRuntime;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Response;
|
use Illuminate\Http\Response;
|
||||||
@@ -12,6 +13,14 @@ use Tempo\Finance\GeneralLedger\ReportsWorkspace;
|
|||||||
|
|
||||||
final class GeneralLedgerController extends Controller
|
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
|
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']);
|
$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']);
|
||||||
@@ -27,7 +36,7 @@ final class GeneralLedgerController extends Controller
|
|||||||
return response()->json($data)->header('Cache-Control', 'no-store');
|
return response()->json($data)->header('Cache-Control', 'no-store');
|
||||||
}
|
}
|
||||||
|
|
||||||
return response(ReportsWorkspace::render($data, ['host' => 'SGC autónomo', 'return_url' => '/general-ledger/cycle']))->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
|
private function actor(Request $r): User
|
||||||
@@ -44,12 +53,12 @@ final class GeneralLedgerController extends Controller
|
|||||||
abort_if(array_diff(array_keys($r->query()), ['page']) !== [], 422);
|
abort_if(array_diff(array_keys($r->query()), ['page']) !== [], 422);
|
||||||
$data = $ledger->workspace($this->actor($r), (int) ($d['page'] ?? 1));
|
$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']))->header('Cache-Control', 'no-store');
|
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
|
public function command(Request $r, string $action, GeneralLedger $ledger): JsonResponse
|
||||||
{
|
{
|
||||||
abort_unless(config('general-ledger.cycle_enabled') === true, 403);
|
abort_unless($ledger->cycleEnabled(), 403);
|
||||||
try {
|
try {
|
||||||
return response()->json($ledger->engine($this->actor($r))->command($action, $r->all(), (string) $r->header('Idempotency-Key')))->header('Cache-Control', 'no-store');
|
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) {
|
} catch (\InvalidArgumentException $e) {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
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;
|
||||||
@@ -11,6 +12,7 @@ use App\Models\StockItem;
|
|||||||
use App\Models\StockMovement;
|
use App\Models\StockMovement;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Models\Warehouse;
|
use App\Models\Warehouse;
|
||||||
|
use App\Services\InventoryConversionRuntime;
|
||||||
use App\Services\InventoryLots;
|
use App\Services\InventoryLots;
|
||||||
use App\Services\InventoryReversals;
|
use App\Services\InventoryReversals;
|
||||||
use App\Services\ReceiptDocuments;
|
use App\Services\ReceiptDocuments;
|
||||||
@@ -60,15 +62,19 @@ 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')
|
'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() : [],
|
? 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() : [],
|
||||||
]);
|
]);
|
||||||
@@ -95,6 +101,8 @@ class GoodsReceiptController extends Controller
|
|||||||
Inertia::encryptHistory();
|
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,
|
'documentsReady' => $ready,
|
||||||
'purchaseProcessHref' => $source === null ? null : '/requisicoes/'.$source->id.'/processo',
|
'purchaseProcessHref' => $source === null ? null : '/requisicoes/'.$source->id.'/processo',
|
||||||
'canAddDocuments' => $ready && $documents->canAdd($actor, $receipt),
|
'canAddDocuments' => $ready && $documents->canAdd($actor, $receipt),
|
||||||
|
|||||||
@@ -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.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ use App\Services\InventoryCorrectionPage;
|
|||||||
use App\Services\InventoryDispositions;
|
use App\Services\InventoryDispositions;
|
||||||
use App\Services\InventoryLots;
|
use App\Services\InventoryLots;
|
||||||
use App\Services\InventoryReversals;
|
use App\Services\InventoryReversals;
|
||||||
|
use App\Services\ReceiptQuantityConversion;
|
||||||
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;
|
||||||
@@ -54,7 +55,7 @@ class InventoryDispositionController extends Controller
|
|||||||
foreach (app(InventoryCorrectionPage::class)->receipts($records->pluck('data.receipt_item_id')->push($page['lookup']['receipt']), $page['lookup']['search']) as $line) {
|
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();
|
$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,
|
$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), 'label' => $receipt->number.' · '.$receipt->snapshot['supplier']['name'].' · '.$line->snapshot['stock_item']['name']];
|
'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) {
|
foreach (app(InventoryLots::class)->activeSetups()->get() as $setup) {
|
||||||
$context = app(InventoryLots::class)->context($setup->stock_item_id, $setup->warehouse_id);
|
$context = app(InventoryLots::class)->context($setup->stock_item_id, $setup->warehouse_id);
|
||||||
|
|||||||
@@ -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,11 +5,15 @@ 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\Models\User;
|
||||||
use App\Services\InventoryDispositions;
|
use App\Services\InventoryDispositions;
|
||||||
use App\Services\InventoryReversals;
|
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\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;
|
||||||
@@ -33,7 +37,11 @@ class InvoiceController extends Controller
|
|||||||
$response = Inertia::render('invoices/index', ['focusInvoiceId' => $focus, 'focusOrderId' => $focusOrder, 'stockReversals' => app(InventoryReversals::class)->financialNotices(), 'stockReturns' => app(InventoryDispositions::class)->financialNotices(),
|
$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()
|
'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)]),
|
->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, 'supplier' => $order->snapshot['supplier']['name'], 'items' => $order->items]),
|
'orders' => PurchaseOrder::query()->visibleTo($actor)->operational()->with('items')->latest('id')->get()->map(fn ($order) => ['id' => $order->id, 'number' => $order->number, '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);
|
'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');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
@@ -46,6 +54,11 @@ class InvoiceController extends Controller
|
|||||||
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Finance]), 403);
|
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' => 'sometimes|required|string|max:30', 'items.*.unit_price' => ['sometimes', ...$decimal], 'items.*.tax_rate' => ['sometimes', '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})?$/']]);
|
||||||
|
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);
|
$workflow->register($actor, $order, $data);
|
||||||
|
|
||||||
return to_route('invoices.index');
|
return to_route('invoices.index');
|
||||||
|
|||||||
@@ -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.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ use App\Models\PurchaseOrder;
|
|||||||
use App\Models\Requisition;
|
use App\Models\Requisition;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\OrderCancellationPolicyWorkflow;
|
use App\Services\OrderCancellationPolicyWorkflow;
|
||||||
|
use App\Services\OrderCancellationRuntime;
|
||||||
use App\Services\OrderCancellationWorkflow;
|
use App\Services\OrderCancellationWorkflow;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -22,6 +23,7 @@ class OrderCancellationController extends Controller
|
|||||||
$actor = $request->user('web');
|
$actor = $request->user('web');
|
||||||
abort_unless($actor instanceof User, 403);
|
abort_unless($actor instanceof User, 403);
|
||||||
abort_unless(config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'), 503, 'Cancelamento de ordens não activado.');
|
abort_unless(config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'), 503, 'Cancelamento de ordens não activado.');
|
||||||
|
app(OrderCancellationRuntime::class)->assertReady();
|
||||||
|
|
||||||
return $actor;
|
return $actor;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,11 +6,18 @@ use App\Models\Tenant;
|
|||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\AdministrativeGeography;
|
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\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\WorkContext;
|
||||||
use App\Services\WorkflowTasks;
|
use App\Services\WorkflowTasks;
|
||||||
use Brick\Math\BigDecimal;
|
use Brick\Math\BigDecimal;
|
||||||
@@ -40,8 +47,17 @@ class OrganizationConfigurationController extends Controller
|
|||||||
'activationPreview' => app(OrganizationActivationPreview::class)->build($actor),
|
'activationPreview' => app(OrganizationActivationPreview::class)->build($actor),
|
||||||
'geographyEnabled' => app(AdministrativeGeography::class)->enabled(),
|
'geographyEnabled' => app(AdministrativeGeography::class)->enabled(),
|
||||||
'geography' => app(AdministrativeGeography::class)->describe(Tenant::query()->findOrFail($actor->tenant_id)->geography_reference),
|
'geography' => app(AdministrativeGeography::class)->describe(Tenant::query()->findOrFail($actor->tenant_id)->geography_reference),
|
||||||
|
'companyDetailsReady' => Schema::hasColumn('tenants', 'company_details'),
|
||||||
|
'approvalLevelsReady' => app(RequisitionApprovalLevels::class)->ready(),
|
||||||
|
'expiryReady' => app(RequisitionExpiry::class)->ready(),
|
||||||
|
'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),
|
'companyRules' => $this->companyRules((int) $actor->tenant_id),
|
||||||
'comparisonPolicy' => app(ComparisonPolicy::class)->company(Tenant::query()->findOrFail($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)),
|
'intelligencePolicy' => app(IntelligencePolicy::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
||||||
'intelligenceReady' => Schema::hasColumn('tenants', 'intelligence_policy'),
|
'intelligenceReady' => Schema::hasColumn('tenants', 'intelligence_policy'),
|
||||||
'aiPlan' => app(AiPreparationPlan::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
'aiPlan' => app(AiPreparationPlan::class)->company(Tenant::query()->findOrFail($actor->tenant_id)),
|
||||||
@@ -68,7 +84,11 @@ class OrganizationConfigurationController extends Controller
|
|||||||
$actor = $service->administrator($user);
|
$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 += ['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))]];
|
||||||
@@ -84,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';
|
||||||
@@ -99,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,10 +7,12 @@ 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;
|
||||||
@@ -18,10 +20,12 @@ use App\Services\PeopleOperationalInsights;
|
|||||||
use App\Services\PeopleProcessProjection;
|
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\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;
|
||||||
@@ -37,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'])) {
|
||||||
@@ -47,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) {
|
||||||
@@ -67,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;
|
||||||
@@ -107,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');
|
||||||
@@ -126,8 +139,8 @@ class PeopleHiringController extends Controller
|
|||||||
$record = PeopleProcess::query()->findOrFail($process);
|
$record = PeopleProcess::query()->findOrFail($process);
|
||||||
$data = $projection->read($this->actor($request), $record);
|
$data = $projection->read($this->actor($request), $record);
|
||||||
|
|
||||||
return response()->json(['schema' => 'sgc.people.process-dossier.v1', 'exported_at' => now()->toIso8601String(),
|
return response()->json(['schema' => $record->status === 'contract_formalized' ? 'sgc.people.process-dossier.v2' : 'sgc.people.process-dossier.v1', 'exported_at' => now()->toIso8601String(),
|
||||||
'effect' => 'preparation_only',
|
'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']),
|
'process' => Arr::only($data['process'], ['id', 'kind', 'title', 'purpose', 'closes_on', 'status', 'version', 'selected_application_id', 'rules', 'selection', 'contract']),
|
||||||
'candidates' => $data['candidates']])
|
'candidates' => $data['candidates']])
|
||||||
->header('Content-Disposition', 'attachment; filename="PES-'.$record->id.'-dossier-v'.$record->version.'.json"')
|
->header('Content-Disposition', 'attachment; filename="PES-'.$record->id.'-dossier-v'.$record->version.'.json"')
|
||||||
@@ -167,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']));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ use App\Services\PeopleDeadlineReport;
|
|||||||
use App\Services\PeopleHiring;
|
use App\Services\PeopleHiring;
|
||||||
use App\Services\PeopleSelectionReport;
|
use App\Services\PeopleSelectionReport;
|
||||||
use App\Services\PeopleWorkdesk;
|
use App\Services\PeopleWorkdesk;
|
||||||
|
use App\Services\WorkContext;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Pagination\LengthAwarePaginator;
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -38,6 +39,7 @@ class PeopleReportController extends Controller
|
|||||||
'to' => ['nullable', 'date_format:Y-m-d', Rule::when($request->filled('from'), 'after_or_equal:from')],
|
'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);
|
$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) {
|
foreach (['kind', 'status'] as $field) {
|
||||||
if (! empty($filters[$field])) {
|
if (! empty($filters[$field])) {
|
||||||
$query->where($field, $filters[$field]);
|
$query->where($field, $filters[$field]);
|
||||||
@@ -45,8 +47,11 @@ class PeopleReportController extends Controller
|
|||||||
}
|
}
|
||||||
if (! empty($filters['search'])) {
|
if (! empty($filters['search'])) {
|
||||||
$search = $filters['search'];
|
$search = $filters['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)) {
|
||||||
$id = filter_var($matches[1], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
$id = filter_var($matches[1], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||||
if ($id !== false) {
|
if ($id !== false) {
|
||||||
@@ -61,7 +66,9 @@ class PeopleReportController extends Controller
|
|||||||
if (! empty($filters['to'])) {
|
if (! empty($filters['to'])) {
|
||||||
$query->whereDate('created_at', '<=', $filters['to']);
|
$query->whereDate('created_at', '<=', $filters['to']);
|
||||||
}
|
}
|
||||||
$columns = ['id', 'title', 'kind', 'status', 'closes_on', 'created_at'];
|
$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();
|
$page = $request->routeIs('people.reports.csv') ? null : (clone $query)->latest('id')->paginate(25, $columns)->withQueryString();
|
||||||
$applications = ($filters['view'] ?? 'processes') === 'applications';
|
$applications = ($filters['view'] ?? 'processes') === 'applications';
|
||||||
$selections = ($filters['view'] ?? 'processes') === 'selections';
|
$selections = ($filters['view'] ?? 'processes') === 'selections';
|
||||||
@@ -89,7 +96,7 @@ class PeopleReportController extends Controller
|
|||||||
} elseif ($request->routeIs('people.reports.csv')) {
|
} elseif ($request->routeIs('people.reports.csv')) {
|
||||||
// Materialise within the read-only snapshot; streaming runs after the transaction.
|
// Materialise within the read-only snapshot; streaming runs after the transaction.
|
||||||
$rows = (clone $query)->orderBy('id')->get($columns);
|
$rows = (clone $query)->orderBy('id')->get($columns);
|
||||||
$response = response()->streamDownload(function () use ($rows, $applications, $selections, $metrics) {
|
$response = response()->streamDownload(function () use ($rows, $applications, $selections, $metrics, $displayTitle) {
|
||||||
$file = fopen('php://output', 'w');
|
$file = fopen('php://output', 'w');
|
||||||
if ($file === false) {
|
if ($file === false) {
|
||||||
throw new \RuntimeException('Não foi possível abrir a exportação.');
|
throw new \RuntimeException('Não foi possível abrir a exportação.');
|
||||||
@@ -99,7 +106,8 @@ class PeopleReportController extends Controller
|
|||||||
$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'];
|
$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 : []))], ';', '"', '');
|
fputcsv($file, ['Referência', 'Título', 'Percurso', 'Estado', 'Fecho de candidaturas', 'Criado em', ...($applications ? $extra : ($selections ? $selectionColumns : []))], ';', '"', '');
|
||||||
foreach ($rows as $row) {
|
foreach ($rows as $row) {
|
||||||
$title = preg_match('/^[\s]*[=+@-]/u', $row->title) ? "'".$row->title : $row->title;
|
$title = $displayTitle($row);
|
||||||
|
$title = preg_match('/^[\s]*[=+@-]/u', $title) ? "'".$title : $title;
|
||||||
$counts = $metrics[$row->id] ?? [];
|
$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)) : [];
|
$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) {
|
if ($selections) {
|
||||||
@@ -111,6 +119,7 @@ class PeopleReportController extends Controller
|
|||||||
}, 'relatorio-pessoas.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
}, 'relatorio-pessoas.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||||
} else {
|
} else {
|
||||||
$summary = (clone $query)->selectRaw('kind, status, count(*) as total')->groupBy('kind', 'status')->get();
|
$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();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('people/reports', [
|
$response = Inertia::render('people/reports', [
|
||||||
'filters' => $filters, 'kinds' => $kinds, 'summary' => $summary,
|
'filters' => $filters, 'kinds' => $kinds, 'summary' => $summary,
|
||||||
@@ -151,6 +160,6 @@ class PeopleReportController extends Controller
|
|||||||
private static function states(): array
|
private static function states(): array
|
||||||
{
|
{
|
||||||
return ['draft' => 'Abertura por conferir', 'open' => 'Recepção de candidaturas', 'assessment' => 'Avaliação',
|
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'];
|
'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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,11 +9,16 @@ 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\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;
|
||||||
@@ -59,6 +64,10 @@ class ProcurementReportController extends Controller
|
|||||||
'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',
|
'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.']);
|
||||||
@@ -76,7 +85,16 @@ class ProcurementReportController extends Controller
|
|||||||
/** @return Builder<PurchaseOrder> */
|
/** @return Builder<PurchaseOrder> */
|
||||||
private function visibleOrders(User $actor): Builder
|
private function visibleOrders(User $actor): Builder
|
||||||
{
|
{
|
||||||
return PurchaseOrder::query()->visibleTo($actor)->whereColumn('purchase_orders.requisition_id', 'requisitions.id');
|
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
|
||||||
@@ -131,7 +149,7 @@ class ProcurementReportController extends Controller
|
|||||||
'created_at' => $record->created_at?->toIso8601String(),
|
'created_at' => $record->created_at?->toIso8601String(),
|
||||||
'needed_by' => $record->needed_by?->toDateString(),
|
'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'),
|
||||||
];
|
];
|
||||||
@@ -150,7 +168,14 @@ class ProcurementReportController extends Controller
|
|||||||
|
|
||||||
$insights = app(ProcurementOperationalInsights::class)->build($this->records(clone $query, $actor), $instant);
|
$insights = app(ProcurementOperationalInsights::class)->build($this->records(clone $query, $actor), $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();
|
||||||
|
|
||||||
@@ -160,6 +185,147 @@ 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
|
||||||
{
|
{
|
||||||
$this->filters($request);
|
$this->filters($request);
|
||||||
@@ -181,7 +347,7 @@ class ProcurementReportController extends Controller
|
|||||||
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', $row['needed_by']], ';', '"', '');
|
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,22 +7,30 @@ 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\Models\User;
|
||||||
|
use App\Services\AgreementOrderLimits;
|
||||||
use App\Services\FormalRecommendation;
|
use App\Services\FormalRecommendation;
|
||||||
use App\Services\OrderCancellationWorkflow;
|
use App\Services\OrderCancellationWorkflow;
|
||||||
|
use App\Services\OrderPartsAccess;
|
||||||
|
use App\Services\OrderPartsAmendments;
|
||||||
|
use App\Services\OrderPartsWorkflow;
|
||||||
use App\Services\OrganizationAccess;
|
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\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
|
||||||
{
|
{
|
||||||
@@ -37,6 +45,7 @@ class PurchaseController extends Controller
|
|||||||
|
|
||||||
public function award(Request $request, Requisition $requisition, ProposalComparison $comparison, PurchaseWorkflow $workflow): Response
|
public function award(Request $request, Requisition $requisition, ProposalComparison $comparison, PurchaseWorkflow $workflow): Response
|
||||||
{
|
{
|
||||||
|
Inertia::encryptHistory();
|
||||||
$actor = $this->access($request);
|
$actor = $this->access($request);
|
||||||
Requisition::query()->visibleTo($actor)->findOrFail($requisition->id);
|
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();
|
||||||
@@ -56,7 +65,14 @@ 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' => ! app(OrganizationAccess::class)->maintenanceOnly($actor) && $actor->hasFunctions([PurchasingRole::Procurement]) && $award === null && $actor->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],
|
||||||
@@ -70,6 +86,7 @@ class PurchaseController extends Controller
|
|||||||
{
|
{
|
||||||
$actor = $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',
|
||||||
@@ -81,6 +98,61 @@ class PurchaseController extends Controller
|
|||||||
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
|
||||||
{
|
{
|
||||||
$actor = $this->access($request);
|
$actor = $this->access($request);
|
||||||
@@ -93,11 +165,12 @@ class PurchaseController extends Controller
|
|||||||
public function issue(Request $request, PurchaseAward $award, PurchaseWorkflow $workflow): RedirectResponse
|
public function issue(Request $request, PurchaseAward $award, PurchaseWorkflow $workflow): RedirectResponse
|
||||||
{
|
{
|
||||||
$actor = $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($actor, $award);
|
$order = $workflow->issue($actor, $award, $validated['agreement_bindings'] ?? []);
|
||||||
|
|
||||||
return to_route('orders.show', $order);
|
return to_route('orders.show', $order);
|
||||||
}
|
}
|
||||||
@@ -107,6 +180,7 @@ class PurchaseController extends Controller
|
|||||||
$actor = $this->access($request);
|
$actor = $this->access($request);
|
||||||
|
|
||||||
return Inertia::render('purchases/index', [
|
return Inertia::render('purchases/index', [
|
||||||
|
'partsAvailable' => $actor->hasFunctions([PurchasingRole::Procurement]) && app(OrderPartsWorkflow::class)->ready(),
|
||||||
'orders' => PurchaseOrder::query()->visibleTo($actor)->latest('id')->paginate(15),
|
'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'),
|
'awards' => PurchaseAward::query()->whereIn('requisition_id', Requisition::query()->visibleTo($actor)->select('id'))->latest()->paginate(15, ['*'], 'awards_page'),
|
||||||
]);
|
]);
|
||||||
@@ -116,22 +190,38 @@ class PurchaseController extends Controller
|
|||||||
{
|
{
|
||||||
$actor = $this->access($request);
|
$actor = $this->access($request);
|
||||||
PurchaseOrder::query()->visibleTo($actor)->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'),
|
||||||
|
'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'),
|
'orderCancellation' => ['enabled' => (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
|
||||||
'state' => app(OrderCancellationWorkflow::class)->state($order),
|
'state' => app(OrderCancellationWorkflow::class)->state($order),
|
||||||
'canRequest' => app(OrderCancellationWorkflow::class)->canRequest($actor, $order)],
|
'canRequest' => app(OrderCancellationWorkflow::class)->canRequest($actor, $order)],
|
||||||
'history' => AuditLog::query()->where('requisition_id', $order->requisition_id)->whereIn('action', ['award.created', 'award.approved', 'award.rejected', 'purchase_order.issued'])->orderBy('id')->get(['id', 'user_id', 'action', 'created_at']),
|
'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
|
||||||
{
|
{
|
||||||
$actor = $this->access($request);
|
$actor = $this->access($request);
|
||||||
PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id);
|
PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id);
|
||||||
|
app(OrderPartsAccess::class)->origins($order);
|
||||||
|
|
||||||
|
if ($request->header('X-Inertia')) {
|
||||||
|
return Inertia::location(route('orders.print', $order, false));
|
||||||
|
}
|
||||||
|
|
||||||
return view('purchases.print', ['order' => $order->load('items'), 'snapshot' => $order->snapshot,
|
return view('purchases.print', ['order' => $order->load('items'), 'snapshot' => $order->snapshot,
|
||||||
|
'snapshotComplete' => $order->hasCompleteDocumentSnapshot(),
|
||||||
'operationalState' => app(OrderCancellationWorkflow::class)->state($order)]);
|
'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;
|
||||||
|
|
||||||
@@ -57,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();
|
||||||
@@ -65,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;
|
||||||
@@ -114,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'];
|
||||||
}
|
}
|
||||||
@@ -122,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();
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\ProposalEvaluation;
|
use App\Models\ProposalEvaluation;
|
||||||
|
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;
|
||||||
@@ -11,10 +12,13 @@ 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\CurrentActor;
|
||||||
|
use App\Services\OrganizationAccess;
|
||||||
use App\Services\ProposalComparison;
|
use App\Services\ProposalComparison;
|
||||||
|
use App\Services\QuotationExchange;
|
||||||
use App\Services\QuotationParticipation;
|
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;
|
||||||
@@ -69,6 +73,11 @@ class QuotationController extends Controller
|
|||||||
'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);
|
])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
@@ -80,6 +89,7 @@ class QuotationController extends Controller
|
|||||||
$actor = $this->access($request);
|
$actor = $this->access($request);
|
||||||
abort_unless($actor->hasFunctions([PurchasingRole::Procurement]), 403);
|
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',
|
||||||
@@ -103,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.']);
|
||||||
}
|
}
|
||||||
@@ -128,16 +140,18 @@ class QuotationController extends Controller
|
|||||||
$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];
|
$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' => $actor->tenant_id, 'requisition_id' => $requisition->id, 'supplier_id' => $supplier->id, 'created_by' => $actor->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);
|
||||||
|
app(QuotationExchange::class)->amounts($quote);
|
||||||
$workflow->audit($actor, 'quotation.created', $requisition, null, [...$quote->load('items')->toArray(), 'no_conflict' => true]);
|
$workflow->audit($actor, 'quotation.created', $requisition, null, [...$quote->load('items')->toArray(), 'no_conflict' => true]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -162,4 +176,12 @@ class QuotationController extends Controller
|
|||||||
|
|
||||||
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,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.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,13 +13,24 @@ use App\Models\TechnicalReview;
|
|||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\ApprovalRouting;
|
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\InternalSupplyTrace;
|
||||||
|
use App\Services\OperationalOrders;
|
||||||
use App\Services\OrganizationAccess;
|
use App\Services\OrganizationAccess;
|
||||||
use App\Services\RequisitionAuditTrail;
|
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\SupplySuggestions;
|
||||||
use App\Services\WorkContext;
|
use App\Services\WorkContext;
|
||||||
@@ -52,7 +63,7 @@ class RequisitionController extends Controller
|
|||||||
->filter(fn (Requisition $requisition) => $requisition->canDecide($this->actor($request)))->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', $this->actor($request)->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'].'%');
|
||||||
@@ -70,10 +81,13 @@ class RequisitionController extends Controller
|
|||||||
public function create(Request $request): Response
|
public function create(Request $request): Response
|
||||||
{
|
{
|
||||||
abort_unless(app(OrganizationAccess::class)->canRequest($this->actor($request)), 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', $this->actor($request)->department_id)->orderBy('code')->get(),
|
'costCenters' => CostCenter::query()->where('department_id', $this->actor($request)->department_id)->orderBy('code')->get(),
|
||||||
'requisition' => null,
|
'requisition' => null,
|
||||||
|
'requisitionCategories' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
|
||||||
|
'incompleteDraftsAvailable' => app(RequisitionDraftInput::class)->available(),
|
||||||
'defaultTaxRate' => (string) (Tenant::query()->findOrFail($this->actor($request)->tenant_id)->default_tax_rate ?? '16.00'),
|
'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),
|
||||||
@@ -109,13 +123,25 @@ class RequisitionController extends Controller
|
|||||||
|
|
||||||
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)),
|
'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'),
|
'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),
|
'replenishmentSource' => app(SupplySuggestions::class)->origin($requisition),
|
||||||
'automaticSource' => app(InternalSupplyTrace::class)->purchaseOrigin($this->actor($request), $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($this->actor($request)) && $requisition->requester_id === $this->actor($request)->id && $requisition->status === 'draft',
|
'canEdit' => app(OrganizationAccess::class)->canRequest($this->actor($request)) && $requisition->requester_id === $this->actor($request)->id && $requisition->status === 'draft',
|
||||||
|
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
|
||||||
|
'importEstimatesReady' => app(ImportEstimates::class)->ready(),
|
||||||
|
'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)),
|
'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),
|
'conflictBlocked' => app(ConflictGuard::class)->participationBlocked($this->actor($request), $requisition),
|
||||||
'audit' => $audit->getCollection()->map(fn ($a) => $trail->row($a)),
|
'audit' => $audit->getCollection()->map(fn ($a) => $trail->row($a)),
|
||||||
'auditPagination' => ['total' => $audit->total(), 'current_page' => $audit->currentPage(), 'last_page' => $audit->lastPage(),
|
'auditPagination' => ['total' => $audit->total(), 'current_page' => $audit->currentPage(), 'last_page' => $audit->lastPage(),
|
||||||
@@ -128,13 +154,41 @@ class RequisitionController extends Controller
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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($this->actor($request)), 403);
|
abort_unless(app(OrganizationAccess::class)->canRequest($this->actor($request)), 403);
|
||||||
abort_unless($requisition->requester_id === $this->actor($request)->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'),
|
||||||
|
'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'),
|
'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(),
|
'costCenters' => CostCenter::query()->where('department_id', $this->actor($request)->department_id)->orderBy('code')->get(),
|
||||||
...$this->equipmentOptions($request),
|
...$this->equipmentOptions($request),
|
||||||
|
|||||||
@@ -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,6 +3,7 @@
|
|||||||
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 App\Models\User;
|
||||||
@@ -41,6 +42,7 @@ class SecurityController extends Controller
|
|||||||
'twoFactorEnabled' => $actor->hasEnabledTwoFactorAuthentication(),
|
'twoFactorEnabled' => $actor->hasEnabledTwoFactorAuthentication(),
|
||||||
'twoFactorPending' => $actor->two_factor_secret !== null && ! $actor->hasEnabledTwoFactorAuthentication(),
|
'twoFactorPending' => $actor->two_factor_secret !== null && ! $actor->hasEnabledTwoFactorAuthentication(),
|
||||||
'requiresConfirmation' => Fortify::confirmsTwoFactorAuthentication(),
|
'requiresConfirmation' => Fortify::confirmsTwoFactorAuthentication(),
|
||||||
|
'mfaRequired' => RequireTwoFactorForSensitiveRoles::requiredFor($actor),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,7 +22,7 @@ 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 StockController extends Controller
|
class StockController extends Controller
|
||||||
{
|
{
|
||||||
@@ -78,13 +78,17 @@ class StockController extends Controller
|
|||||||
'lot_control' => app(InventoryLots::class)->summary($balance->stock_item_id, $balance->warehouse_id),
|
'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,
|
'geographyEnabled' => $geography->availableFor('warehouses'), 'warehouseGeography' => $warehouseGeography,
|
||||||
'geographyFilter' => empty($filters['location']) ? null : $geography->describe(['catalogue' => config('geography.source_sha256'), 'record_id' => $filters['location'], 'country' => 'MZ']),
|
'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' => $this->actor($request)->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
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ use App\Models\Warehouse;
|
|||||||
use App\Services\InventoryCounts;
|
use App\Services\InventoryCounts;
|
||||||
use App\Services\InventoryLots;
|
use App\Services\InventoryLots;
|
||||||
use App\Services\InventoryReversals;
|
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;
|
||||||
@@ -20,7 +21,7 @@ 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 StockOperationController extends Controller
|
class StockOperationController extends Controller
|
||||||
{
|
{
|
||||||
@@ -48,8 +49,9 @@ class StockOperationController extends Controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Inertia::render('stock/operations', [
|
Inertia::encryptHistory();
|
||||||
'canViewReturns' => config('stock_returns.enabled') && $actor->hasFunctions(['warehouse_return_read']) && ! app(\App\Services\OrganizationAccess::class)->maintenanceOnly($actor),
|
$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']),
|
'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', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
|
'users' => User::query()->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
|
||||||
@@ -58,7 +60,10 @@ class StockOperationController extends Controller
|
|||||||
'canOperate' => $actor->hasFunctions([PurchasingRole::Warehouse]),
|
'canOperate' => $actor->hasFunctions([PurchasingRole::Warehouse]),
|
||||||
'canAdjust' => app(InventoryLots::class)->allows($actor, 'inventory_adjust_review'), 'lotCounts' => $lotCounts,
|
'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
|
||||||
|
|||||||
@@ -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();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -93,6 +93,7 @@ class SupplierController extends Controller
|
|||||||
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, 'geographyEnabled' => app(AdministrativeGeography::class)->enabled(), 'geography' => app(AdministrativeGeography::class)->describe($supplier->geography_reference)]);
|
return Inertia::render('suppliers/edit', ['supplier' => $supplier, 'geographyEnabled' => app(AdministrativeGeography::class)->enabled(), 'geography' => app(AdministrativeGeography::class)->describe($supplier->geography_reference)]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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',
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ 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);
|
||||||
|
|||||||
@@ -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.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,10 +3,15 @@
|
|||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\ExpenseAllocations;
|
||||||
use App\Services\GeneralLedger;
|
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\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
|
||||||
{
|
{
|
||||||
@@ -14,15 +19,41 @@ final class SupplierPaymentsController extends SettlementHttp
|
|||||||
|
|
||||||
protected const SERVICE = SupplierPayables::class;
|
protected const SERVICE = SupplierPayables::class;
|
||||||
|
|
||||||
/** @return array<string,mixed> */
|
protected function settlementEngine(Request $request): SupplierSettlements
|
||||||
protected function ledgerSettings(Request $request): array
|
|
||||||
{
|
{
|
||||||
if (config('general-ledger.cycle_enabled') !== true) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
$user = $request->user();
|
$user = $request->user();
|
||||||
abort_unless($user instanceof User, 403);
|
abort_unless($user instanceof User, 403);
|
||||||
|
|
||||||
return app(GeneralLedger::class)->can($user, 'view') ? ['ledger_cycle_url' => '/general-ledger/cycle'] : [];
|
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.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ use App\Models\SupplyRecord;
|
|||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\SupplyCoordination;
|
use App\Services\SupplyCoordination;
|
||||||
use App\Services\SupplyCoordinationRead;
|
use App\Services\SupplyCoordinationRead;
|
||||||
|
use Brick\Math\BigDecimal;
|
||||||
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\Facades\Schema;
|
||||||
@@ -50,20 +51,24 @@ class SupplyCoordinationReportController extends Controller
|
|||||||
fwrite($out, "\xEF\xBB\xBF");
|
fwrite($out, "\xEF\xBB\xBF");
|
||||||
fputcsv($out, ['Acompanhamento de fornecimentos', $view, 'Conferido em', now()->toIso8601String()], ';', '"', '');
|
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, ['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'], ';', '"', '');
|
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) {
|
foreach ($query->lazyById(100) as $record) {
|
||||||
$pending = match ($kind) {
|
$pending = match ($kind) {
|
||||||
'reservation' => app(SupplyCoordination::class)->remainingReservation($record),
|
'reservation' => app(SupplyCoordination::class)->remainingReservation($record),
|
||||||
'delivery' => app(SupplyCoordination::class)->remainingDelivery($record),
|
'delivery' => app(SupplyCoordination::class)->remainingDelivery($record),
|
||||||
default => null,
|
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,
|
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->snapshot['item']['code'] ?? '', $record->snapshot['item']['name'] ?? '', $record->snapshot['warehouse']['name'] ?? '',
|
||||||
$record->data['reference'] ?? '', $record->snapshot['order']['number'] ?? '',
|
$record->data['reference'] ?? '', $record->snapshot['order']['number'] ?? '',
|
||||||
isset($record->data['quantity_milli']) ? $record->data['quantity_milli'] / 1000 : '', $record->snapshot['item']['unit'] ?? '',
|
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 ? '' : $pending / 1000,
|
$record->data['needed_on'] ?? $record->data['expected_on'] ?? '', $pending === null ? '' : $quantity($pending),
|
||||||
$record->snapshot['substitute']['code'] ?? '', $record->data['application'] ?? '', $record->data['valid_until'] ?? '',
|
$record->snapshot['substitute']['code'] ?? '', $record->data['application'] ?? '', $record->data['valid_until'] ?? '',
|
||||||
url('/compras/fornecimento?view='.$view.'&record_id='.$record->id).'#supply-record-'.$record->id]), ';', '"', '');
|
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 {
|
} finally {
|
||||||
fclose($out);
|
fclose($out);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\CostCenter;
|
use App\Models\CostCenter;
|
||||||
use App\Models\PurchaseOrder;
|
use App\Models\PurchaseOrder;
|
||||||
use App\Models\PurchaseOrderItem;
|
use App\Models\PurchaseOrderItem;
|
||||||
@@ -13,6 +14,10 @@ use App\Models\Supplier;
|
|||||||
use App\Models\SupplyRecord;
|
use App\Models\SupplyRecord;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Models\Warehouse;
|
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\InventoryReversals;
|
||||||
use App\Services\OrganizationAccess;
|
use App\Services\OrganizationAccess;
|
||||||
use App\Services\ReceiptWorkflow;
|
use App\Services\ReceiptWorkflow;
|
||||||
@@ -52,7 +57,10 @@ class SupplyPlanningController extends Controller
|
|||||||
private function page(Request $request, SupplyPlanning $planning, User $actor): HttpResponse
|
private function page(Request $request, SupplyPlanning $planning, User $actor): HttpResponse
|
||||||
{
|
{
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$view = $request->validate(['view' => 'nullable|in:agreements,calendar,imports,alternatives,reservations,deliveries,suggestions,history'])['view'] ?? 'agreements';
|
$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') {
|
if ($view === 'history') {
|
||||||
return $this->privateResponse($request, $this->history($request, $actor, $planning));
|
return $this->privateResponse($request, $this->history($request, $actor, $planning));
|
||||||
}
|
}
|
||||||
@@ -66,7 +74,7 @@ class SupplyPlanningController extends Controller
|
|||||||
$capabilities = $import ? ['import_read', 'import_prepare', 'import_customs'] : ['supply_read', 'supply_prepare', 'supply_review'];
|
$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);
|
abort_unless(collect($capabilities)->contains(fn ($p) => $planning->allows($actor, $p)), 403);
|
||||||
$ready = Schema::hasTable('supply_records');
|
$ready = Schema::hasTable('supply_records');
|
||||||
$kind = $import ? 'import' : ($view === 'calendar' ? 'policy' : 'agreement');
|
$kind = $import ? 'import' : ($view === 'calendar' ? 'policy' : ($view === 'contracts' ? 'contract' : 'agreement'));
|
||||||
$focus = $this->focusedRecord($request, $actor, $kind);
|
$focus = $this->focusedRecord($request, $actor, $kind);
|
||||||
[$records, $page] = $this->recordPage($request, $planning, $ready, $kind, $focus);
|
[$records, $page] = $this->recordPage($request, $planning, $ready, $kind, $focus);
|
||||||
$projections = [];
|
$projections = [];
|
||||||
@@ -98,7 +106,17 @@ class SupplyPlanningController extends Controller
|
|||||||
'agreement_form_key' => 'nullable|string|max:80',
|
'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,
|
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,
|
'agreementSearch' => $agreementFilters['agreement_search'] ?? '', 'agreementFormKey' => $agreementFilters['agreement_form_key'] ?? null,
|
||||||
'recordPagination' => $this->pagination($page),
|
'recordPagination' => $this->pagination($page),
|
||||||
'focusRecordId' => $focus->id ?? null, 'focusChanged' => $focus !== null && $records->first()?->id !== $focus->id,
|
'focusRecordId' => $focus->id ?? null, 'focusChanged' => $focus !== null && $records->first()?->id !== $focus->id,
|
||||||
@@ -143,6 +161,18 @@ class SupplyPlanningController extends Controller
|
|||||||
return [collect(), null];
|
return [collect(), null];
|
||||||
}
|
}
|
||||||
$query = $planning->latest($kind)->latest('id');
|
$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) {
|
if ($focus !== null) {
|
||||||
return [$query->where('record_key', $focus->record_key)->get(), null];
|
return [$query->where('record_key', $focus->record_key)->get(), null];
|
||||||
}
|
}
|
||||||
@@ -305,6 +335,7 @@ class SupplyPlanningController extends Controller
|
|||||||
'id' => $line->id, 'label' => $orders[$line->purchase_order_id]->number.' · '.$line->description.' · '.$line->quantity.' '.$line->unit,
|
'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,
|
'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),
|
'quantity_milli' => ReceiptWorkflow::milli($line->quantity),
|
||||||
|
'unit' => $line->unit,
|
||||||
]);
|
]);
|
||||||
$requests = collect();
|
$requests = collect();
|
||||||
if ($canPrepare && $kind === 'reservation') {
|
if ($canPrepare && $kind === 'reservation') {
|
||||||
@@ -340,6 +371,7 @@ class SupplyPlanningController extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
return Inertia::render('supply/coordination', ['kind' => $kind, 'ready' => $ready,
|
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'] ?? ''],
|
'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(),
|
'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()],
|
'prev_page_url' => $page->previousPageUrl(), 'next_page_url' => $page->nextPageUrl()],
|
||||||
|
|||||||
@@ -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.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ use App\Models\StockItem;
|
|||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Models\Warehouse;
|
use App\Models\Warehouse;
|
||||||
use App\Services\WarehouseAvailability;
|
use App\Services\WarehouseAvailability;
|
||||||
|
use App\Services\WarehouseReservations;
|
||||||
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\Rule;
|
||||||
@@ -32,7 +33,7 @@ class WarehouseAvailabilityController extends Controller
|
|||||||
$query->where(fn ($q) => $q->whereLike('code', '%'.$filters['search'].'%')->orWhereLike('name', '%'.$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));
|
$page = $warehouse === null ? null : $query->orderBy('code')->paginate(25)->withQueryString()->through(fn ($item) => $availability->row($item, $warehouse, $planning));
|
||||||
$response = Inertia::render('stock/availability', ['filters' => $filters, 'planningVisible' => $planning, 'rows' => $page,
|
$response = Inertia::render('stock/availability', ['filters' => $filters, 'planningVisible' => $planning, 'reservationsAvailable' => app(WarehouseReservations::class)->ready(), 'rows' => $page,
|
||||||
'warehouse' => $warehouse?->only(['id', 'code', 'name']), 'checkedAt' => now()->toIso8601String(),
|
'warehouse' => $warehouse?->only(['id', 'code', 'name']), 'checkedAt' => now()->toIso8601String(),
|
||||||
'warehouses' => Warehouse::query()->orderBy('code')->get(['id', 'code', 'name'])])->toResponse($request);
|
'warehouses' => Warehouse::query()->orderBy('code')->get(['id', 'code', 'name'])])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|||||||
@@ -98,7 +98,14 @@ class WarehouseRequestController extends Controller
|
|||||||
$p = app(WarehouseFulfilment::class)->progress($record);
|
$p = app(WarehouseFulfilment::class)->progress($record);
|
||||||
$s = $record->snapshot;
|
$s = $record->snapshot;
|
||||||
foreach ($s['lines'] as $index => $line) {
|
foreach ($s['lines'] as $index => $line) {
|
||||||
$row = ['RA-'.$record->id, $p['state'], (string) $p['version'], $s['requester']['name'], $s['warehouse']['code'], $s['cost_center']['code'], $s['destination'], $s['reason'], (string) ($index + 1), $line['item']['code'], $line['item']['name'], $line['item']['unit'], $line['destination'], $line['equipment']['code'] ?? '', ...array_map(fn ($quantity) => number_format($quantity / 1000, 3, '.', ''), [$line['quantity_milli'], $p['reserved'][$index], $p['delivered'][$index], $p['remaining'][$index], $p['cancelled'][$index]]), $p['reservation_ready'] ? 'Sim' : 'Não', url('/stock/requisicoes/'.$record->id)];
|
$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), ';', '"', '');
|
fputcsv($out, array_map($safe, $row), ';', '"', '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,14 +43,21 @@ final class WarehouseReturnController extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @param callable():array<string,mixed> $run */
|
/** @param callable():array<string,mixed> $run */
|
||||||
private function response(callable $run,bool $readOnly=false): JsonResponse
|
private function response(callable $run, bool $readOnly = false): JsonResponse
|
||||||
{
|
{
|
||||||
try {
|
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();
|
$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');
|
return response()->json($result)->header('Cache-Control', 'no-store');
|
||||||
} catch (QueryException $e) {
|
} catch (QueryException $e) {
|
||||||
if (($e->errorInfo[0] ?? null) === '55P03') {
|
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');
|
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;
|
throw $e;
|
||||||
}
|
}
|
||||||
@@ -83,12 +90,25 @@ final class WarehouseReturnController extends Controller
|
|||||||
$d['version'] = (int) $d['version'];
|
$d['version'] = (int) $d['version'];
|
||||||
$d['received_in_warehouse'] = true;
|
$d['received_in_warehouse'] = true;
|
||||||
|
|
||||||
return $this->response(fn () => $flow->confirm($this->actor($r),$id,$d));
|
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');}
|
public function withdraw(Request $r, int $id, WarehouseReturns $flow): JsonResponse
|
||||||
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));
|
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));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ class WorkflowNoticeController extends Controller
|
|||||||
$unread = $visible->whereNull('read_at')->count();
|
$unread = $visible->whereNull('read_at')->count();
|
||||||
$items = ($filter['view'] ?? 'all') === 'unread' ? $visible->whereNull('read_at')->values() : $visible;
|
$items = ($filter['view'] ?? 'all') === 'unread' ? $visible->whereNull('read_at')->values() : $visible;
|
||||||
if (in_array($filter['view'] ?? '', ['tasks', 'outcomes'], true)) {
|
if (in_array($filter['view'] ?? '', ['tasks', 'outcomes'], true)) {
|
||||||
$items = $visible->where('kind', $filter['view'] === 'tasks' ? 'task' : 'outcome')->values();
|
$items = $filter['view'] === 'tasks' ? $visible->whereIn('kind', ['task', 'reminder'])->values() : $visible->where('kind', 'outcome')->values();
|
||||||
}
|
}
|
||||||
$search = trim($filter['search'] ?? '');
|
$search = trim($filter['search'] ?? '');
|
||||||
if ($search !== '') {
|
if ($search !== '') {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\UrgentRequisitionReviews;
|
||||||
use App\Services\WorkflowTaskInbox;
|
use App\Services\WorkflowTaskInbox;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Pagination\LengthAwarePaginator;
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
@@ -59,6 +60,7 @@ class WorkflowTaskInboxController extends Controller
|
|||||||
$page = (int) ($filters['page'] ?? 1);
|
$page = (int) ($filters['page'] ?? 1);
|
||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$response = Inertia::render('workflow/tasks', ['area' => $area, 'modules' => $modules, 'counts' => $counts,
|
$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,
|
'checkedAt' => now()->toIso8601String(), 'asOf' => $today, 'deadlineCounts' => $deadlineCounts,
|
||||||
'filters' => ['module' => $filters['module'] ?? 'all', 'search' => $filters['search'] ?? '', 'due' => $filters['due'] ?? 'all'],
|
'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);
|
'tasks' => (new LengthAwarePaginator($rows->slice(($page - 1) * 25, 25)->values(), $rows->count(), 25, $page, ['path' => $request->url()]))->withQueryString()])->toResponse($request);
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,10 +17,11 @@ class EnsureWorkContext
|
|||||||
if ($user instanceof User && $contexts->enforced($user) && ($area = WorkContext::area($request->path())) !== null) {
|
if ($user instanceof User && $contexts->enforced($user) && ($area = WorkContext::area($request->path())) !== null) {
|
||||||
$key = $contexts->active($request);
|
$key = $contexts->active($request);
|
||||||
abort_unless($key !== null && WorkContext::OPTIONS[$key]['area'] === $area, 403, 'Seleccione uma área e opção autorizadas no Painel Inicial.');
|
abort_unless($key !== null && WorkContext::OPTIONS[$key]['area'] === $area, 403, 'Seleccione uma área e opção autorizadas no Painel Inicial.');
|
||||||
if (! WorkContext::OPTIONS[$key]['operational'] && $request->isMethod('GET')) {
|
if (! WorkContext::operational($key) && $request->isMethod('GET')) {
|
||||||
return redirect('/dashboard');
|
return redirect('/dashboard');
|
||||||
}
|
}
|
||||||
abort_unless(WorkContext::OPTIONS[$key]['operational'], 409, 'O percurso operacional desta opção ainda está em implementação.');
|
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);
|
return $next($request);
|
||||||
|
|||||||
@@ -3,10 +3,18 @@
|
|||||||
namespace App\Http\Middleware;
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
|
use App\Services\CommonFinanceAdministration;
|
||||||
|
use App\Services\GeneralLedger;
|
||||||
|
use App\Services\OperationalOrders;
|
||||||
use App\Services\OrganizationAccess;
|
use App\Services\OrganizationAccess;
|
||||||
|
use App\Services\PrivateAuditAccess;
|
||||||
|
use App\Services\ProductModules;
|
||||||
|
use App\Services\StandaloneRuntime;
|
||||||
use App\Services\SupplierPayables;
|
use App\Services\SupplierPayables;
|
||||||
use App\Services\WorkContext;
|
use App\Services\WorkContext;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Inertia\Middleware;
|
use Inertia\Middleware;
|
||||||
|
|
||||||
@@ -63,8 +71,31 @@ class HandleInertiaRequests extends Middleware
|
|||||||
'profileLabel' => app(OrganizationAccess::class)->profileLabel($actor),
|
'profileLabel' => app(OrganizationAccess::class)->profileLabel($actor),
|
||||||
],
|
],
|
||||||
'payablesAvailable' => $actor !== null && app(SupplierPayables::class)->can($actor, 'view'),
|
'payablesAvailable' => $actor !== null && app(SupplierPayables::class)->can($actor, 'view'),
|
||||||
|
'commonFinanceNavigation' => $this->financeNavigation($actor),
|
||||||
'orderCancellationAvailable' => $actor !== null && (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
|
'orderCancellationAvailable' => $actor !== null && (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
|
||||||
|
'operationalOrdersAvailable' => $actor !== null && app(OperationalOrders::class)->ready(),
|
||||||
|
'privateAuditAvailable' => $actor !== null && app(PrivateAuditAccess::class)->ready(),
|
||||||
|
'capitalRegisterAvailable' => $actor !== null && app(CapitalRegister::class)->searchQuery($actor) !== null,
|
||||||
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
|
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
|
||||||
|
'modules' => app(ProductModules::class)->states(),
|
||||||
|
'disabledModulePaths' => fn () => app(ProductModules::class)->disabledPaths(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array{payments:bool,ledger:bool,configuration:bool} */
|
||||||
|
private function financeNavigation(?User $actor): array
|
||||||
|
{
|
||||||
|
$hidden = ['payments' => false, 'ledger' => false, 'configuration' => false];
|
||||||
|
if ($actor === null || ! app(StandaloneRuntime::class)->enabled()
|
||||||
|
|| ! $actor->hasFunctions(['admin', 'finance']) || app(OrganizationAccess::class)->maintenanceOnly($actor)) {
|
||||||
|
return $hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'payments' => app(StandaloneRuntime::class)->feature('supplier-settlements', DB::connection())
|
||||||
|
&& app(SupplierPayables::class)->can($actor, 'view') && app(SupplierPayables::class)->can($actor, 'payments_view'),
|
||||||
|
'ledger' => app(GeneralLedger::class)->cycleEnabled() && app(GeneralLedger::class)->can($actor, 'view'),
|
||||||
|
'configuration' => $actor->hasFunctions(['admin']) && app(CommonFinanceAdministration::class)->ready(),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ class PublicDevelopmentNavigation
|
|||||||
}
|
}
|
||||||
$path = '/'.$request->path();
|
$path = '/'.$request->path();
|
||||||
if ($request->path() === '/') {
|
if ($request->path() === '/') {
|
||||||
return redirect('/dashboard');
|
return $next($request);
|
||||||
}
|
}
|
||||||
if (! isset(PublicNavigation::PAGES[$path])) {
|
if (! isset(PublicNavigation::PAGES[$path])) {
|
||||||
return $next($request);
|
return $next($request);
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\EvaluationNavigation;
|
||||||
|
use Closure;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Laravel\Fortify\Features;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
/** Perfis sensíveis (config/mfa.php) só usam a aplicação depois de confirmarem o MFA. */
|
||||||
|
class RequireTwoFactorForSensitiveRoles
|
||||||
|
{
|
||||||
|
/** Configurar o MFA, confirmar a palavra-passe e sair continuam sempre disponíveis. */
|
||||||
|
private const ALLOWED = ['settings', 'settings/*', 'user/*', 'two-factor-challenge', 'logout', 'login', 'up'];
|
||||||
|
|
||||||
|
public function handle(Request $request, Closure $next): Response
|
||||||
|
{
|
||||||
|
if (! self::applies($request) || $request->is(...self::ALLOWED)) {
|
||||||
|
return $next($request);
|
||||||
|
}
|
||||||
|
if ($request->expectsJson()) {
|
||||||
|
abort(403, 'Configure a autenticação de dois factores antes de continuar.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect()->route('security.edit');
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function applies(Request $request): bool
|
||||||
|
{
|
||||||
|
$user = $request->user('web');
|
||||||
|
|
||||||
|
return $user instanceof User
|
||||||
|
&& Features::enabled(Features::twoFactorAuthentication())
|
||||||
|
&& ! EvaluationNavigation::local($request)
|
||||||
|
&& self::requiredFor($user);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** O utilizador tem uma função que exige MFA e ainda não o confirmou. */
|
||||||
|
public static function requiredFor(User $user): bool
|
||||||
|
{
|
||||||
|
$functions = array_values(array_filter((array) config('mfa.required_functions', []), 'is_string'));
|
||||||
|
|
||||||
|
return $user->two_factor_confirmed_at === null && $functions !== [] && $user->hasFunctions($functions);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,6 +28,11 @@ class ConfirmReceiptRequest extends FormRequest
|
|||||||
'items.*.accepted_quantity' => ['required', 'string', 'numeric', 'min:0', 'max:1000000', 'regex:/^\d+(\.\d{1,3})?$/'],
|
'items.*.accepted_quantity' => ['required', 'string', 'numeric', 'min:0', 'max:1000000', 'regex:/^\d+(\.\d{1,3})?$/'],
|
||||||
'items.*.quality_status' => ['required', Rule::in(['compliant', 'reservations', 'nonconforming'])],
|
'items.*.quality_status' => ['required', Rule::in(['compliant', 'reservations', 'nonconforming'])],
|
||||||
'items.*.notes' => 'nullable|string|max:3000',
|
'items.*.notes' => 'nullable|string|max:3000',
|
||||||
|
'items.*.conversion' => 'sometimes|nullable|array:numerator,denominator,source,version',
|
||||||
|
'items.*.conversion.numerator' => ['required_with:items.*.conversion', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
|
||||||
|
'items.*.conversion.denominator' => ['required_with:items.*.conversion', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
|
||||||
|
'items.*.conversion.source' => 'required_with:items.*.conversion|string|max:500',
|
||||||
|
'items.*.conversion.version' => 'required_with:items.*.conversion|string|max:100',
|
||||||
'items.*.lots' => 'sometimes|array|max:100',
|
'items.*.lots' => 'sometimes|array|max:100',
|
||||||
'items.*.lots.*.code' => 'nullable|string|max:100',
|
'items.*.lots.*.code' => 'nullable|string|max:100',
|
||||||
'items.*.lots.*.expires_on' => 'nullable|date_format:Y-m-d',
|
'items.*.lots.*.expires_on' => 'nullable|date_format:Y-m-d',
|
||||||
|
|||||||
@@ -2,44 +2,26 @@
|
|||||||
|
|
||||||
namespace App\Http\Requests;
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\RequisitionDraftInput;
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
use Illuminate\Validation\Rule;
|
|
||||||
|
|
||||||
class StoreRequisitionRequest extends FormRequest
|
class StoreRequisitionRequest extends FormRequest
|
||||||
{
|
{
|
||||||
public function authorize(): bool
|
public function authorize(): bool
|
||||||
{
|
{
|
||||||
$user = $this->user();
|
$user = $this->user('web');
|
||||||
|
|
||||||
return $user !== null && $user->tenant_id !== null && $user->department_id !== null;
|
return $user instanceof User && $user->tenant_id !== null && $user->department_id !== null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
public function rules(): array
|
public function rules(): array
|
||||||
{
|
{
|
||||||
return [
|
$user = $this->user('web');
|
||||||
'operation_key' => 'nullable|uuid',
|
abort_unless($user instanceof User, 403);
|
||||||
'process_version' => 'nullable|integer|min:1',
|
|
||||||
'cost_center_id' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $this->user()?->tenant_id)->where('department_id', $this->user()?->department_id)],
|
return app(RequisitionDraftInput::class)->rules($user);
|
||||||
'priority' => ['required', Rule::in(['normal', 'high', 'urgent'])],
|
|
||||||
'needed_by' => ['required', 'date_format:Y-m-d', 'after_or_equal:today'],
|
|
||||||
'justification' => ['required', 'string', 'min:10', 'max:5000'],
|
|
||||||
'items' => ['required', 'array', 'min:1', 'max:50'],
|
|
||||||
'items.*.catalogue_entry_id' => 'nullable|integer|min:1',
|
|
||||||
'items.*.catalogue_version' => 'nullable|required_with:items.*.catalogue_entry_id|integer|min:1',
|
|
||||||
'items.*.source_line_id' => 'nullable|integer|min:1',
|
|
||||||
'items.*.description' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:255'],
|
|
||||||
'items.*.category' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:100'],
|
|
||||||
'items.*.purchase_type' => ['required_without:items.*.catalogue_entry_id', Rule::in(['consumable', 'service', 'other', 'equipment', 'spare_part'])],
|
|
||||||
'items.*.equipment_id' => ['exclude_unless:items.*.purchase_type,spare_part', 'required', 'integer', Rule::exists('equipment', 'id')->where('tenant_id', $this->user()?->tenant_id)->where('department_id', $this->user()?->department_id)],
|
|
||||||
'items.*.spare_part_id' => ['exclude_unless:items.*.purchase_type,spare_part', 'required', 'integer', Rule::exists('spare_parts', 'id')->where('tenant_id', $this->user()?->tenant_id)],
|
|
||||||
'items.*.production_area' => 'exclude_unless:items.*.purchase_type,equipment|required|string|max:200',
|
|
||||||
'items.*.downtime_started_at' => 'exclude_unless:items.*.purchase_type,spare_part|nullable|date_format:Y-m-d\TH:i|before_or_equal:now',
|
|
||||||
'items.*.quantity' => ['required', 'numeric', 'min:0.001', 'max:1000000', 'regex:/^\d+(\.\d{1,3})?$/'],
|
|
||||||
'items.*.unit' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:30'],
|
|
||||||
'items.*.unit_price' => ['required', 'numeric', 'min:0.01', 'max:100000000', 'regex:/^\d+(\.\d{1,2})?$/'],
|
|
||||||
'items.*.tax_rate' => ['required', 'numeric', 'between:0,100', 'regex:/^\d+(\.\d{1,2})?$/'],
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<string, string> */
|
/** @return array<string, string> */
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ use Illuminate\Database\Eloquent\Model;
|
|||||||
* @property string $role
|
* @property string $role
|
||||||
* @property string $decision
|
* @property string $decision
|
||||||
* @property int|null $approver_id
|
* @property int|null $approver_id
|
||||||
|
* @property array<string,mixed>|null $routing
|
||||||
*/
|
*/
|
||||||
class ApprovalStep extends Model
|
class ApprovalStep extends Model
|
||||||
{
|
{
|
||||||
@@ -17,4 +18,9 @@ class ApprovalStep extends Model
|
|||||||
public $timestamps = false;
|
public $timestamps = false;
|
||||||
|
|
||||||
protected $guarded = ['id'];
|
protected $guarded = ['id'];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return ['approval_cycle' => 'integer', 'routing' => 'array'];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
/** @property int $id
|
||||||
|
* @property int $tenant_id
|
||||||
|
* @property int $version
|
||||||
|
* @property bool $active
|
||||||
|
* @property string $client_key
|
||||||
|
* @property string $code
|
||||||
|
* @property string $name
|
||||||
|
* @property string|null $tax_number
|
||||||
|
* @property string $creation_hash
|
||||||
|
* @property int $created_by
|
||||||
|
*/
|
||||||
|
class BusinessClient extends Model
|
||||||
|
{
|
||||||
|
use BelongsToTenant;
|
||||||
|
|
||||||
|
protected $guarded = ['id'];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return ['active' => 'boolean', 'version' => 'integer'];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace App\Models\Concerns;
|
namespace App\Models\Concerns;
|
||||||
|
|
||||||
|
use App\Services\ReplenishmentRun;
|
||||||
|
use App\Services\RequisitionExpiryRun;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
|
||||||
trait BelongsToTenant
|
trait BelongsToTenant
|
||||||
@@ -9,7 +11,8 @@ trait BelongsToTenant
|
|||||||
protected static function bootBelongsToTenant(): void
|
protected static function bootBelongsToTenant(): void
|
||||||
{
|
{
|
||||||
static::addGlobalScope('tenant', function (Builder $query) {
|
static::addGlobalScope('tenant', function (Builder $query) {
|
||||||
$tenantId = auth()->check() ? auth()->user()->tenant_id : app(\App\Services\ReplenishmentRun::class)->tenantId();
|
$tenantId = auth()->check() ? auth()->user()->tenant_id : (app(ReplenishmentRun::class)->tenantId()
|
||||||
|
?? app(RequisitionExpiryRun::class)->tenantId());
|
||||||
$query->where($query->getModel()->qualifyColumn('tenant_id'), $tenantId ?? 0);
|
$query->where($query->getModel()->qualifyColumn('tenant_id'), $tenantId ?? 0);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ trait HasWorkContext
|
|||||||
if ($actor instanceof User && app(WorkContext::class)->enforced($actor)) {
|
if ($actor instanceof User && app(WorkContext::class)->enforced($actor)) {
|
||||||
$key = app(WorkContext::class)->active(request());
|
$key = app(WorkContext::class)->active(request());
|
||||||
$area = $model->getTable() === 'people_processes' ? 'people' : 'procurement';
|
$area = $model->getTable() === 'people_processes' ? 'people' : 'procurement';
|
||||||
abort_unless($key !== null && WorkContext::OPTIONS[$key]['operational'] && WorkContext::OPTIONS[$key]['area'] === $area, 403);
|
abort_unless($key !== null && WorkContext::operational($key) && WorkContext::OPTIONS[$key]['area'] === $area, 403);
|
||||||
$model->setAttribute('work_context_key', $key);
|
$model->setAttribute('work_context_key', $key);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace App\Models;
|
|||||||
|
|
||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\Concerns\BelongsToTenant;
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
|
use App\Services\ConflictReleases;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
@@ -41,7 +42,7 @@ class ConflictDeclaration extends Model
|
|||||||
/** @param Builder<ConflictDeclaration> $query */
|
/** @param Builder<ConflictDeclaration> $query */
|
||||||
public function scopeVisibleTo(Builder $query, User $user): void
|
public function scopeVisibleTo(Builder $query, User $user): void
|
||||||
{
|
{
|
||||||
if (! $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance])) {
|
if (! $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]) && ! app(ConflictReleases::class)->canAuthorise($user)) {
|
||||||
$query->where('user_id', $user->id);
|
$query->where('user_id', $user->id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use LogicException;
|
||||||
|
|
||||||
|
class ConflictRelease extends Model
|
||||||
|
{
|
||||||
|
use BelongsToTenant;
|
||||||
|
|
||||||
|
public $timestamps = false;
|
||||||
|
|
||||||
|
protected $guarded = ['id'];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return ['snapshot' => 'array', 'authorised_at' => 'datetime'];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static function booted(): void
|
||||||
|
{
|
||||||
|
static::updating(fn () => throw new LogicException('Preservar a autorização da direcção.'));
|
||||||
|
static::deleting(fn () => throw new LogicException('Preservar o histórico do levantamento.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,11 @@ namespace App\Models;
|
|||||||
use App\Models\Concerns\BelongsToTenant;
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
/** @property int $lot_id */
|
/**
|
||||||
|
* @property int $lot_id
|
||||||
|
* @property int $stock_item_id
|
||||||
|
* @property int $warehouse_id
|
||||||
|
*/
|
||||||
class InventoryLotAllocation extends Model
|
class InventoryLotAllocation extends Model
|
||||||
{
|
{
|
||||||
use BelongsToTenant;
|
use BelongsToTenant;
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use LogicException;
|
||||||
|
|
||||||
|
/** @property list<string> $families */
|
||||||
|
class PrivateAuditExport extends Model
|
||||||
|
{
|
||||||
|
use BelongsToTenant;
|
||||||
|
|
||||||
|
public $timestamps = false;
|
||||||
|
|
||||||
|
protected $guarded = ['id'];
|
||||||
|
|
||||||
|
protected $hidden = ['path', 'input_hash'];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return ['families' => 'array', 'manifest' => 'array', 'created_at' => 'datetime', 'size' => 'integer'];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static function booted(): void
|
||||||
|
{
|
||||||
|
static::updating(fn () => throw new LogicException('Preservar o pacote e o manifesto originais da auditoria.'));
|
||||||
|
static::deleting(fn () => throw new LogicException('Preservar o histórico da exportação privada.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,6 +29,18 @@ class PurchaseOrder extends Model
|
|||||||
return ['snapshot' => 'array', 'issued_at' => 'datetime'];
|
return ['snapshot' => 'array', 'issued_at' => 'datetime'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Older synthetic documents may predate the complete frozen document structure. */
|
||||||
|
public function hasCompleteDocumentSnapshot(): bool
|
||||||
|
{
|
||||||
|
foreach (['company', 'department', 'cost_center', 'requisition', 'issuer', 'requester', 'supplier', 'quotation', 'award', 'approval_rules', 'decision_matrix', 'final_approvals'] as $key) {
|
||||||
|
if (! is_array($this->snapshot[$key] ?? null)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/** @return HasMany<PurchaseOrderItem, $this> */
|
/** @return HasMany<PurchaseOrderItem, $this> */
|
||||||
public function items(): HasMany
|
public function items(): HasMany
|
||||||
{
|
{
|
||||||
@@ -39,6 +51,40 @@ class PurchaseOrder extends Model
|
|||||||
public function scopeVisibleTo(Builder $query, User $user): void
|
public function scopeVisibleTo(Builder $query, User $user): void
|
||||||
{
|
{
|
||||||
$query->whereIn('requisition_id', Requisition::query()->visibleTo($user)->select('id'));
|
$query->whereIn('requisition_id', Requisition::query()->visibleTo($user)->select('id'));
|
||||||
|
if (Schema::hasColumn('purchase_orders', 'order_key')) {
|
||||||
|
if (! Schema::hasTable('purchase_order_sources')) {
|
||||||
|
$query->whereNull('order_key');
|
||||||
|
} else {
|
||||||
|
$query->where(function ($orders) use ($user) {
|
||||||
|
$orders->whereNull('order_key')->orWhere(function ($parts) use ($user) {
|
||||||
|
$parts->whereExists(fn ($sources) => $sources->selectRaw('1')->from('purchase_order_sources as os')
|
||||||
|
->whereColumn('os.purchase_order_id', 'purchase_orders.id')->whereColumn('os.tenant_id', 'purchase_orders.tenant_id'))
|
||||||
|
->whereRaw('(select count(*) from purchase_order_sources os where os.purchase_order_id = purchase_orders.id and os.tenant_id = purchase_orders.tenant_id) = purchase_orders.order_source_count')
|
||||||
|
->whereNotExists(fn ($sources) => $sources->selectRaw('1')->from('purchase_order_sources as os')
|
||||||
|
->whereColumn('os.purchase_order_id', 'purchase_orders.id')->whereColumn('os.tenant_id', 'purchase_orders.tenant_id')
|
||||||
|
->whereNotIn('os.requisition_id', Requisition::query()->visibleTo($user)->select('id')));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Builder<PurchaseOrder> $query
|
||||||
|
* @param Builder<Requisition> $requests
|
||||||
|
*/
|
||||||
|
public function scopeForRequisitions(Builder $query, Builder $requests): void
|
||||||
|
{
|
||||||
|
$query->where(function ($orders) use ($requests) {
|
||||||
|
$orders->whereIn('purchase_orders.requisition_id', (clone $requests)->reorder()->select('requisitions.id'));
|
||||||
|
if (Schema::hasTable('purchase_order_sources') && Schema::hasColumn('purchase_orders', 'order_key')) {
|
||||||
|
$orders->orWhere(function ($parts) use ($requests) {
|
||||||
|
$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')
|
||||||
|
->whereIn('report_origin.requisition_id', (clone $requests)->reorder()->select('requisitions.id')));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param Builder<PurchaseOrder> $query */
|
/** @param Builder<PurchaseOrder> $query */
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
|||||||
/**
|
/**
|
||||||
* @property array<string, mixed> $weights
|
* @property array<string, mixed> $weights
|
||||||
* @property array<string, mixed>|null $commercial_terms Stored JSON is validated against the pricing contract before comparison.
|
* @property array<string, mixed>|null $commercial_terms Stored JSON is validated against the pricing contract before comparison.
|
||||||
|
* @property array<string, mixed>|null $exchange_basis Frozen process rate for original foreign-currency amounts.
|
||||||
*/
|
*/
|
||||||
class Quotation extends Model
|
class Quotation extends Model
|
||||||
{
|
{
|
||||||
@@ -19,7 +20,7 @@ class Quotation extends Model
|
|||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return ['weights' => 'array', 'commercial_terms' => 'array', 'valid_until' => 'date:Y-m-d'];
|
return ['weights' => 'array', 'commercial_terms' => 'array', 'exchange_basis' => 'array', 'valid_until' => 'date:Y-m-d'];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<Supplier, $this> */
|
/** @return BelongsTo<Supplier, $this> */
|
||||||
|
|||||||
+28
-11
@@ -6,12 +6,14 @@ use App\Enums\PurchasingRole;
|
|||||||
use App\Models\Concerns\BelongsToTenant;
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
use App\Models\Concerns\HasWorkContext;
|
use App\Models\Concerns\HasWorkContext;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
|
use App\Services\RequisitionApprovalLevels;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Database\Eloquent\Collection;
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
use Illuminate\Support\Carbon;
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Tempo\Purchasing\Internal\InternalRequisitions;
|
use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -21,12 +23,14 @@ use Tempo\Purchasing\Internal\InternalRequisitions;
|
|||||||
* @property int $requester_id
|
* @property int $requester_id
|
||||||
* @property string $number
|
* @property string $number
|
||||||
* @property string $status
|
* @property string $status
|
||||||
* @property int $subtotal_minor
|
* @property int|null $subtotal_minor
|
||||||
* @property int $tax_minor
|
* @property int|null $tax_minor
|
||||||
* @property int $total_minor
|
* @property int|null $total_minor
|
||||||
* @property Carbon|null $submitted_at
|
* @property Carbon|null $submitted_at
|
||||||
* @property Carbon|null $needed_by
|
* @property Carbon|null $needed_by
|
||||||
* @property array<string,mixed>|null $comparison_policy
|
* @property array<string,mixed>|null $comparison_policy
|
||||||
|
* @property array<string,mixed>|null $budget_distribution_preparation
|
||||||
|
* @property array<string,mixed>|null $approval_snapshot
|
||||||
* @property Collection<int, ApprovalStep> $steps
|
* @property Collection<int, ApprovalStep> $steps
|
||||||
* @property Collection<int, RequisitionItem> $items
|
* @property Collection<int, RequisitionItem> $items
|
||||||
*/
|
*/
|
||||||
@@ -37,9 +41,12 @@ class Requisition extends Model
|
|||||||
|
|
||||||
protected $guarded = ['id'];
|
protected $guarded = ['id'];
|
||||||
|
|
||||||
|
// Stage-specific controllers expose authorised preparation explicitly, never quotation details through generic request JSON.
|
||||||
|
protected $hidden = ['budget_distribution_preparation'];
|
||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return ['approval_snapshot' => 'array', 'comparison_policy' => 'array', 'submitted_at' => 'datetime', 'needed_by' => 'date:Y-m-d'];
|
return ['approval_cycle' => 'integer', 'draft_input' => 'array', 'budget_distribution_preparation' => 'array', 'approval_snapshot' => 'array', 'comparison_policy' => 'array', 'submitted_at' => 'datetime', 'needed_by' => 'date:Y-m-d'];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return HasMany<RequisitionItem, $this> */
|
/** @return HasMany<RequisitionItem, $this> */
|
||||||
@@ -51,7 +58,15 @@ class Requisition extends Model
|
|||||||
/** @return HasMany<ApprovalStep, $this> */
|
/** @return HasMany<ApprovalStep, $this> */
|
||||||
public function steps(): HasMany
|
public function steps(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(ApprovalStep::class)->orderBy('position');
|
return $this->hasMany(ApprovalStep::class)->when(Schema::hasColumn('approval_steps', 'approval_cycle'), fn ($query) => $query->whereExists(fn ($current) => $current
|
||||||
|
->selectRaw('1')->from('requisitions as current_cycle_request')->whereColumn('current_cycle_request.id', 'approval_steps.requisition_id')
|
||||||
|
->whereColumn('current_cycle_request.approval_cycle', 'approval_steps.approval_cycle')))->orderBy('position');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<ApprovalStep, $this> */
|
||||||
|
public function allSteps(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(ApprovalStep::class)->orderBy('id');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<User, $this> */
|
/** @return BelongsTo<User, $this> */
|
||||||
@@ -75,10 +90,11 @@ class Requisition extends Model
|
|||||||
/** @param Builder<Requisition> $query */
|
/** @param Builder<Requisition> $query */
|
||||||
public function scopeVisibleTo(Builder $query, User $user): void
|
public function scopeVisibleTo(Builder $query, User $user): void
|
||||||
{
|
{
|
||||||
if ($user->departmentScoped()) {
|
if ($user->departmentScoped() || ! $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance])) {
|
||||||
$query->where('department_id', $user->department_id);
|
$query->where(function ($visible) use ($user) {
|
||||||
} elseif (! $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance])) {
|
$visible->where($user->departmentScoped() ? 'department_id' : 'requester_id', $user->departmentScoped() ? $user->department_id : $user->id);
|
||||||
$query->where('requester_id', $user->id);
|
app(RequisitionApprovalLevels::class)->includeVisible($visible, $user);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,8 +106,9 @@ class Requisition extends Model
|
|||||||
|
|
||||||
$next = InternalRequisitions::nextStep(['status' => $this->status, 'requester_id' => $this->requester_id, 'steps' => $this->steps->toArray()], $user->id);
|
$next = InternalRequisitions::nextStep(['status' => $this->status, 'requester_id' => $this->requester_id, 'steps' => $this->steps->toArray()], $user->id);
|
||||||
|
|
||||||
return $next !== null && $user->hasFunctions([$next['role']])
|
return $next !== null && (str_starts_with($next['role'], 'configured_')
|
||||||
&& ($next['role'] !== 'department_head' || $this->department_id === $user->department_id)
|
? app(RequisitionApprovalLevels::class)->eligible($user, $this, $next)
|
||||||
|
: ($user->hasFunctions([$next['role']]) && ($next['role'] !== 'department_head' || $this->department_id === $user->department_id)))
|
||||||
&& ! app(ConflictGuard::class)->participationBlocked($user, $this);
|
&& ! app(ConflictGuard::class)->participationBlocked($user, $this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ use Illuminate\Database\Eloquent\Model;
|
|||||||
* @property int|null $spare_part_id
|
* @property int|null $spare_part_id
|
||||||
* @property int|null $catalogue_entry_id
|
* @property int|null $catalogue_entry_id
|
||||||
* @property array<string,mixed>|null $catalogue_snapshot
|
* @property array<string,mixed>|null $catalogue_snapshot
|
||||||
|
* @property array<string,mixed>|null $category_context
|
||||||
*/
|
*/
|
||||||
class RequisitionItem extends Model
|
class RequisitionItem extends Model
|
||||||
{
|
{
|
||||||
@@ -25,6 +26,6 @@ class RequisitionItem extends Model
|
|||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return ['quantity' => 'decimal:3', 'tax_rate' => 'decimal:2', 'catalogue_entry_id' => 'integer', 'catalogue_snapshot' => 'array'];
|
return ['quantity' => 'decimal:3', 'tax_rate' => 'decimal:2', 'catalogue_entry_id' => 'integer', 'catalogue_snapshot' => 'array', 'category_context' => 'array'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace App\Models;
|
|||||||
|
|
||||||
use App\Models\Concerns\AppendOnlyInventoryRecord;
|
use App\Models\Concerns\AppendOnlyInventoryRecord;
|
||||||
use App\Models\Concerns\BelongsToTenant;
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
|
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
/** @property int $id
|
/** @property int $id
|
||||||
@@ -13,6 +14,7 @@ use Illuminate\Database\Eloquent\Model;
|
|||||||
* @property int $revision
|
* @property int $revision
|
||||||
* @property string $account_identifier
|
* @property string $account_identifier
|
||||||
* @property string $beneficiary
|
* @property string $beneficiary
|
||||||
|
* @property string|null $account_key
|
||||||
*/
|
*/
|
||||||
class SupplierBankDetail extends Model
|
class SupplierBankDetail extends Model
|
||||||
{
|
{
|
||||||
@@ -28,4 +30,12 @@ class SupplierBankDetail extends Model
|
|||||||
{
|
{
|
||||||
return ['account_identifier' => 'encrypted', 'beneficiary' => 'encrypted', 'evidence_reference' => 'encrypted', 'reason' => 'encrypted'];
|
return ['account_identifier' => 'encrypted', 'beneficiary' => 'encrypted', 'evidence_reference' => 'encrypted', 'reason' => 'encrypted'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Missing column means the preserved legacy chain, including before installation.
|
||||||
|
* @return Attribute<string|null,never>
|
||||||
|
*/
|
||||||
|
protected function accountKey(): Attribute
|
||||||
|
{
|
||||||
|
return Attribute::get(fn (?string $value): ?string => $value);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,13 +4,14 @@ namespace App\Models;
|
|||||||
|
|
||||||
use App\Models\Concerns\BelongsToTenant;
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @property array<string,mixed> $data
|
* @property array<string,mixed> $data
|
||||||
* @property array<string,mixed> $snapshot
|
* @property array<string,mixed> $snapshot
|
||||||
* @property int $version
|
* @property int $version
|
||||||
* @property string $record_key
|
* @property string $record_key
|
||||||
* @property \Illuminate\Support\Carbon $created_at
|
* @property Carbon $created_at
|
||||||
*/
|
*/
|
||||||
class SupplyRecord extends Model
|
class SupplyRecord extends Model
|
||||||
{
|
{
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user