commit melhorias sgf
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sgc;
|
||||
|
||||
use App\Models\Sgc\OrdemCompra;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class BudgetCommitmentService
|
||||
{
|
||||
/**
|
||||
* Verifica disponibilidade orçamental no SGF
|
||||
*/
|
||||
public function verificarSaldo(string $centroCustoId, string $rubrica, float $valor): array
|
||||
{
|
||||
// Em produção, isto chamaria uma API do SGF
|
||||
// Por agora, simulamos a resposta
|
||||
return [
|
||||
'disponivel' => true,
|
||||
'saldo_atual' => 500000.00,
|
||||
'valor_solicitado' => $valor,
|
||||
'saldo_apos_compromisso' => 500000.00 - $valor,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Cabimenta (compromete) orçamento no SGF
|
||||
*/
|
||||
public function cabimentar(OrdemCompra $oc): array
|
||||
{
|
||||
$verificacao = $this->verificarSaldo(
|
||||
$oc->centroCusto->sgf_centro_custo_id,
|
||||
$oc->categoria,
|
||||
$oc->valor_comprometido
|
||||
);
|
||||
|
||||
if (!$verificacao['disponivel']) {
|
||||
throw new \Exception('Saldo orçamental insuficiente');
|
||||
}
|
||||
|
||||
// Em produção, isto chamaria uma API do SGF para criar o compromisso
|
||||
// Simulamos o sucesso
|
||||
$compromissoId = 'COMP-' . strtoupper(substr(md5($oc->oc_id), 0, 8));
|
||||
|
||||
DB::transaction(function () use ($oc, $compromissoId) {
|
||||
$oc->update([
|
||||
'cabimentado' => true,
|
||||
'sgf_compromisso_id' => $compromissoId,
|
||||
]);
|
||||
});
|
||||
|
||||
Log::info('Cabimentação realizada', [
|
||||
'oc_id' => $oc->oc_id,
|
||||
'compromisso_id' => $compromissoId,
|
||||
'valor' => $oc->valor_comprometido,
|
||||
]);
|
||||
|
||||
return [
|
||||
'sucesso' => true,
|
||||
'compromisso_id' => $compromissoId,
|
||||
'saldo_apos_compromisso' => $verificacao['saldo_apos_compromisso'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancela cabimentação (quando OC é cancelada)
|
||||
*/
|
||||
public function cancelarCabimentacao(OrdemCompra $oc): bool
|
||||
{
|
||||
if (!$oc->cabimentado) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Em produção, chamaria API do SGF para cancelar o compromisso
|
||||
DB::transaction(function () use ($oc) {
|
||||
$oc->update([
|
||||
'cabimentado' => false,
|
||||
'sgf_compromisso_id' => null,
|
||||
]);
|
||||
});
|
||||
|
||||
Log::info('Cabimentação cancelada', [
|
||||
'oc_id' => $oc->oc_id,
|
||||
'compromisso_id' => $oc->sgf_compromisso_id,
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sgc;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use Generator;
|
||||
use InvalidArgumentException;
|
||||
|
||||
final class CalendarDimension
|
||||
{
|
||||
/** Weekdays are a calendar approximation, not an official holiday calendar. */
|
||||
public static function days(int $startYear, int $years): Generator
|
||||
{
|
||||
if ($startYear < 1 || $years < 1 || $years > 100 || $startYear + $years > 10000) throw new InvalidArgumentException('Invalid calendar interval.');
|
||||
$months = [1=>'Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
|
||||
$weekdays = [1=>'Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo'];
|
||||
$date = new DateTimeImmutable(sprintf('%04d-01-01', $startYear), new DateTimeZone('Africa/Maputo'));
|
||||
while ((int)$date->format('Y') < $startYear + $years) {
|
||||
$month = (int)$date->format('n'); $weekday = (int)$date->format('N');
|
||||
yield ['data_id'=>(int)$date->format('Ymd'), 'data_completa'=>$date->format('Y-m-d'),
|
||||
'dia_semana'=>$weekday, 'nome_dia_semana'=>$weekdays[$weekday], 'dia_mes'=>(int)$date->format('j'),
|
||||
'mes'=>$month, 'nome_mes'=>$months[$month], 'trimestre'=>intdiv($month-1,3)+1,
|
||||
'ano'=>(int)$date->format('Y'), 'ano_mes'=>$date->format('Y-m'),
|
||||
'eh_dia_util'=>$weekday<=5, 'eh_feriado'=>false, 'semestre'=>$month<=6?1:2];
|
||||
$date = $date->modify('+1 day');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sgc;
|
||||
|
||||
use App\Models\Sgc\Fatura;
|
||||
use App\Models\Sgc\Fornecedor;
|
||||
use App\Models\Sgc\OrdemCompra;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class IntegrationService
|
||||
{
|
||||
private ThreeWayMatchService $matchService;
|
||||
private BudgetCommitmentService $budgetService;
|
||||
|
||||
public function __construct(
|
||||
ThreeWayMatchService $matchService,
|
||||
BudgetCommitmentService $budgetService
|
||||
) {
|
||||
$this->matchService = $matchService;
|
||||
$this->budgetService = $budgetService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recebe fatura do SGC e processa no SGF
|
||||
*/
|
||||
public function receberFatura(array $payload, string $idempotencyKey): array
|
||||
{
|
||||
// Verificar idempotência
|
||||
$logExistente = DB::table('sgc_integration_log')
|
||||
->where('idempotency_key', $idempotencyKey)
|
||||
->first();
|
||||
|
||||
if ($logExistente) {
|
||||
return [
|
||||
'status' => 'DUPLICATE',
|
||||
'original_receipt_id' => $logExistente->id,
|
||||
'message' => 'Idempotency key já processada',
|
||||
];
|
||||
}
|
||||
|
||||
try {
|
||||
$resultado = DB::transaction(function () use ($payload) {
|
||||
// Buscar ou criar fornecedor
|
||||
$fornecedor = $this->sincronizarFornecedor($payload['supplier']);
|
||||
|
||||
// Buscar OC
|
||||
$oc = OrdemCompra::where('oc_id', $payload['oc_reference'])->first();
|
||||
if (!$oc) {
|
||||
throw new \Exception('OC não encontrada: ' . $payload['oc_reference']);
|
||||
}
|
||||
|
||||
// Verificar se fornecedor bate
|
||||
if ($oc->fornecedor_id !== $fornecedor->id) {
|
||||
throw new \Exception('Fornecedor não corresponde à OC');
|
||||
}
|
||||
|
||||
// Criar fatura
|
||||
$fatura = Fatura::create([
|
||||
'fatura_id' => $payload['sgf_invoice_id'],
|
||||
'ordem_compra_id' => $oc->id,
|
||||
'fornecedor_id' => $fornecedor->id,
|
||||
'data_fatura' => $payload['dates']['invoice_date'],
|
||||
'data_vencimento' => $payload['dates']['due_date'],
|
||||
'valor_fatura' => $payload['amounts']['subtotal'],
|
||||
'iva_valor' => $payload['amounts']['iva_amount'],
|
||||
'moeda' => $payload['amounts']['currency'],
|
||||
'taxa_cambio' => $payload['amounts']['exchange_rate'],
|
||||
'status_3_way_match' => 'Pendente',
|
||||
'status_pagamento' => 'Aguardando',
|
||||
'sgf_doc_number' => $payload['sgf_doc_number'],
|
||||
]);
|
||||
|
||||
// Executar 3-Way Match
|
||||
$matchResult = $this->matchService->executarMatch($fatura);
|
||||
|
||||
return [
|
||||
'status' => 'ACCEPTED',
|
||||
'fatura_id' => $fatura->id,
|
||||
'sgf_doc_number' => $fatura->sgf_doc_number,
|
||||
'match_result' => $matchResult,
|
||||
];
|
||||
});
|
||||
|
||||
// Log de sucesso
|
||||
DB::table('sgc_integration_log')->insert([
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'endpoint' => '/api/v1/integration/sgc/invoices',
|
||||
'event_type' => 'INVOICE_CREATED',
|
||||
'payload' => json_encode($payload),
|
||||
'status' => 'ACCEPTED',
|
||||
'response' => json_encode($resultado),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
return $resultado;
|
||||
|
||||
} catch (\Exception $e) {
|
||||
// Log de erro
|
||||
DB::table('sgc_integration_log')->insert([
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'endpoint' => '/api/v1/integration/sgc/invoices',
|
||||
'event_type' => 'INVOICE_CREATED',
|
||||
'payload' => json_encode($payload),
|
||||
'status' => 'REJECTED',
|
||||
'error_code' => 'PROCESSING_ERROR',
|
||||
'error_message' => $e->getMessage(),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
Log::error('Erro ao processar fatura', [
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return [
|
||||
'status' => 'REJECTED',
|
||||
'error_code' => 'PROCESSING_ERROR',
|
||||
'message' => $e->getMessage(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recebe confirmação de pagamento do SGC
|
||||
*/
|
||||
public function receberPagamento(array $payload, string $idempotencyKey): array
|
||||
{
|
||||
// Verificar idempotência
|
||||
$logExistente = DB::table('sgc_integration_log')
|
||||
->where('idempotency_key', $idempotencyKey)
|
||||
->first();
|
||||
|
||||
if ($logExistente) {
|
||||
return [
|
||||
'status' => 'DUPLICATE',
|
||||
'original_receipt_id' => $logExistente->id,
|
||||
];
|
||||
}
|
||||
|
||||
try {
|
||||
$resultado = DB::transaction(function () use ($payload) {
|
||||
// Buscar fatura
|
||||
$fatura = Fatura::where('sgf_doc_number', $payload['sgf_doc_number'])->first();
|
||||
if (!$fatura) {
|
||||
throw new \Exception('Fatura não encontrada: ' . $payload['sgf_doc_number']);
|
||||
}
|
||||
|
||||
// Atualizar fatura com pagamento
|
||||
$fatura->update([
|
||||
'data_pagamento' => $payload['payment_date'],
|
||||
'valor_pago' => $payload['amount_paid'],
|
||||
'status_pagamento' => 'Pago',
|
||||
'numero_comprovativo' => $payload['bank_reference'],
|
||||
]);
|
||||
|
||||
// Atualizar OC se totalmente paga
|
||||
$oc = $fatura->ordemCompra;
|
||||
$totalPago = $oc->faturas()->where('status_pagamento', 'Pago')->sum('valor_pago');
|
||||
|
||||
if ($totalPago >= $oc->valor_comprometido) {
|
||||
$oc->update(['status' => 'Totalmente Paga']);
|
||||
}
|
||||
|
||||
return [
|
||||
'status' => 'ACCEPTED',
|
||||
'fatura_id' => $fatura->id,
|
||||
'payment_id' => $payload['payment_id'],
|
||||
];
|
||||
});
|
||||
|
||||
// Log de sucesso
|
||||
DB::table('sgc_integration_log')->insert([
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'endpoint' => '/api/v1/integration/sgc/payments',
|
||||
'event_type' => 'PAYMENT_EXECUTED',
|
||||
'payload' => json_encode($payload),
|
||||
'status' => 'ACCEPTED',
|
||||
'response' => json_encode($resultado),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
return $resultado;
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::table('sgc_integration_log')->insert([
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'endpoint' => '/api/v1/integration/sgc/payments',
|
||||
'event_type' => 'PAYMENT_EXECUTED',
|
||||
'payload' => json_encode($payload),
|
||||
'status' => 'REJECTED',
|
||||
'error_code' => 'PROCESSING_ERROR',
|
||||
'error_message' => $e->getMessage(),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
return [
|
||||
'status' => 'REJECTED',
|
||||
'error_code' => 'PROCESSING_ERROR',
|
||||
'message' => $e->getMessage(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sincroniza fornecedor do SGC para o SGF
|
||||
*/
|
||||
private function sincronizarFornecedor(array $supplierData): Fornecedor
|
||||
{
|
||||
return Fornecedor::updateOrCreate(
|
||||
['sgf_fornecedor_id' => $supplierData['sgf_supplier_id']],
|
||||
[
|
||||
'nuit' => $supplierData['nuit'],
|
||||
'nome_fornecedor' => $supplierData['name'],
|
||||
'categoria_fornecedor' => $supplierData['category'] ?? 'Geral',
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sgc;
|
||||
|
||||
use App\Models\Sgc\Fatura;
|
||||
use App\Models\Sgc\OrdemCompra;
|
||||
use App\Models\Sgc\Recebimento;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ThreeWayMatchService
|
||||
{
|
||||
private const TOLERANCIA_PERCENTUAL = 0.01; // 1%
|
||||
private const TOLERANCIA_VALOR = 50.00; // 50 MT
|
||||
|
||||
/**
|
||||
* Executa o 3-Way Match: OC + Recebimento + Fatura
|
||||
*/
|
||||
public function executarMatch(Fatura $fatura): array
|
||||
{
|
||||
$oc = $fatura->ordemCompra;
|
||||
$recebimentos = $oc->recebimentos;
|
||||
|
||||
// Calcular total recebido
|
||||
$valorTotalRecebido = $recebimentos->sum('valor_recebido');
|
||||
$valorFatura = $fatura->valor_fatura;
|
||||
$valorOC = $oc->valor_comprometido;
|
||||
|
||||
// Verificar divergências
|
||||
$divergenciaOC = abs($valorFatura - $valorOC);
|
||||
$divergenciaRecebimento = abs($valorFatura - $valorTotalRecebido);
|
||||
|
||||
// Aplicar tolerâncias
|
||||
$toleranciaOC = max($valorOC * self::TOLERANCIA_PERCENTUAL, self::TOLERANCIA_VALOR);
|
||||
$toleranciaRecebimento = max($valorTotalRecebido * self::TOLERANCIA_PERCENTUAL, self::TOLERANCIA_VALOR);
|
||||
|
||||
$matchOC = $divergenciaOC <= $toleranciaOC;
|
||||
$matchRecebimento = $divergenciaRecebimento <= $toleranciaRecebimento;
|
||||
|
||||
// Determinar status
|
||||
$status = 'Conforme';
|
||||
$motivo = null;
|
||||
|
||||
if (!$matchOC && !$matchRecebimento) {
|
||||
$status = 'Com Excecao';
|
||||
$motivo = "Divergência com OC ({$divergenciaOC} MT) e Recebimento ({$divergenciaRecebimento} MT)";
|
||||
} elseif (!$matchOC) {
|
||||
$status = 'Com Excecao';
|
||||
$motivo = "Divergência com OC: {$divergenciaOC} MT";
|
||||
} elseif (!$matchRecebimento) {
|
||||
$status = 'Com Excecao';
|
||||
$motivo = "Divergência com Recebimento: {$divergenciaRecebimento} MT";
|
||||
}
|
||||
|
||||
// Atualizar fatura
|
||||
DB::transaction(function () use ($fatura, $status, $motivo) {
|
||||
$fatura->update([
|
||||
'status_3_way_match' => $status,
|
||||
'motivo_excecao' => $motivo,
|
||||
]);
|
||||
});
|
||||
|
||||
Log::info('3-Way Match executado', [
|
||||
'fatura_id' => $fatura->fatura_id,
|
||||
'status' => $status,
|
||||
'valor_fatura' => $valorFatura,
|
||||
'valor_oc' => $valorOC,
|
||||
'valor_recebido' => $valorTotalRecebido,
|
||||
]);
|
||||
|
||||
return [
|
||||
'status' => $status,
|
||||
'motivo' => $motivo,
|
||||
'valor_fatura' => $valorFatura,
|
||||
'valor_oc' => $valorOC,
|
||||
'valor_recebido' => $valorTotalRecebido,
|
||||
'divergencia_oc' => $divergenciaOC,
|
||||
'divergencia_recebimento' => $divergenciaRecebimento,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Processa todas as faturas pendentes de match
|
||||
*/
|
||||
public function processarPendentes(): int
|
||||
{
|
||||
$faturasPendentes = Fatura::where('status_3_way_match', 'Pendente')->get();
|
||||
$processadas = 0;
|
||||
|
||||
foreach ($faturasPendentes as $fatura) {
|
||||
$this->executarMatch($fatura);
|
||||
$processadas++;
|
||||
}
|
||||
|
||||
return $processadas;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user