commit de compras

This commit is contained in:
2026-11-04 09:37:20 +02:00
parent fcf31e8d48
commit 0b05a1192c
741 changed files with 114127 additions and 116 deletions
@@ -0,0 +1,13 @@
<?php
namespace App\Modules\Accounting;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
final class CostLedgerController extends Controller
{
public function index(Request $r,GeneralLedger $ledger)
{
$d=$r->validate(['order_id'=>'sometimes|required|integer|min:1','page'=>'sometimes|integer|min:1|max:100000']);abort_if(array_diff(array_keys($r->query()),array_keys($d))!==[],422);
try{$data=$ledger->costs($r->user(),isset($d['order_id'])?(int)$d['order_id']:null,(int)($d['page']??1));}catch(\DomainException $e){abort(403,$e->getMessage());}catch(\InvalidArgumentException $e){abort(422,$e->getMessage());}
return $r->is('api/*')?response()->json($data)->header('Cache-Control','no-store'):response()->view('accounting.cost-ledger',['data'=>$data])->header('Cache-Control','no-store');
}
}
@@ -0,0 +1,68 @@
<?php
namespace App\Modules\Accounting;
use App\Models\User;
use App\Modules\Identity\Services\Permissions;
use App\Modules\Workshop\DirectCosts;
use App\Shared\Context\CompanyContext;
use Illuminate\Support\Facades\DB;
use Brick\Math\BigRational;
use Tempo\Finance\Payables\Payables;
/** Explicit composition of an actual cost conference; no technical, financial or outbox writes. */
final class CostLedgerSource
{
private function scope(User $u):array
{
abort_unless(config('cost_ledger.synthetic_enabled')===true,403);DirectCosts::guard();$ctx=app(CompanyContext::class);
abort_unless(auth()->id()===$u->id&&$ctx->userId()===$u->id&&$ctx->unitId(),403);$s=$ctx->identifiers()+['unit_id'=>$ctx->unitId()];
foreach(['workshop.view','direct_costs.view'] as $p)app(Permissions::class)->require($u->id,$s['tenant_id'],$s['company_id'],$p,$s['unit_id']);
foreach(['gl_cost_sources','wo_orders','wo_entries','wo_decisions','dc_rates','dc_calculations','dc_decisions'] as $t)abort_unless(DB::getSchemaBuilder()->hasTable($t),503,'Origem de custo não composta neste ensaio.');return $s;
}
private function hash(array $v):string{return hash('sha256',Payables::canonical($v));}
private function facts(User $u,array $s,object $map):array
{
$c=app(DirectCosts::class)->conference($map->order_id,$u->id);$lines=$c['snapshot']['lines']??[];$entries=array_column($lines,'entry_id');$rates=array_values(array_filter(array_column($lines,'rate_id'),fn($id)=>$id!==null));
return ['mapping'=>(array)$map,'conference'=>$c,'entries'=>DB::table('wo_entries')->where('order_id',$map->order_id)->whereIn('id',$entries)->orderBy('id')->get()->map(fn($r)=>(array)$r)->all(),'technical_decisions'=>DB::table('wo_decisions')->whereIn('entry_id',$entries)->orderBy('id')->get()->map(fn($r)=>(array)$r)->all(),'rates'=>DB::table('dc_rates')->where($s)->where('order_id',$map->order_id)->whereIn('id',$rates)->orderBy('id')->get()->map(fn($r)=>(array)$r)->all(),'rate_decisions'=>DB::table('dc_decisions')->whereIn('rate_id',$rates)->orderBy('id')->get()->map(fn($r)=>(array)$r)->all()];
}
private function eligible(array $facts):array
{
$m=$facts['mapping'];$c=$facts['conference'];$snap=$c['snapshot'];$decision=$c['decision'];
if(!$c['calculation']||!$c['current']||!$decision||$decision['decision']!=='approved'||$decision['actor_id']===$c['calculation']['actor_id']||$snap['currency']!=='MZN'||$snap['incomplete']||$snap['selected_direct_total_exact']===null)throw new \DomainException('Cálculo actual completo e validado distintamente obrigatório; custo conhecido parcial não é total.');
$origins=[];foreach($snap['lines'] as $line)$origins[$line['kind']]=$line['origin'];
if($origins!==['time'=>$m['time_origin'],'material'=>$m['material_origin']]&&$origins!==['material'=>$m['material_origin'],'time'=>$m['time_origin']])throw new \DomainException('Perímetro seleccionado mudou; não atribuir outra origem automaticamente.');
if(config('industrial_ledger.synthetic_enabled')===true){abort_unless(DB::getSchemaBuilder()->hasTable('gl_industrial_sources'),503);if(DB::table('ic_inputs as i')->join('gl_industrial_sources as m','m.lot_id','=','i.lot_id')->where('i.tenant_id',$m['tenant_id'])->where('i.company_id',$m['company_id'])->whereIn('i.source_ref',array_values($origins))->exists())throw new \DomainException('Origem já composta em lote industrial; não reconhecer novamente.');}
try{$amount=BigRational::of($snap['selected_direct_total_exact'])->multipliedBy(100)->toBigInteger()->toInt();}catch(\Brick\Math\Exception\MathException $e){throw new \DomainException('Custo exacto não representável em cêntimos; não arredondar.',0,$e);}
if($amount<=0)throw new \DomainException('Este ensaio exige custo seleccionado positivo.');
return ['effect_type'=>'workshop.direct_cost.validated','source_id'=>$m['order_id'],'cost_order_id'=>$m['order_id'],'obligation_id'=>$m['order_id'],'origin_key'=>$this->hash(['scope'=>array_intersect_key($m,array_flip(['tenant_id','company_id','unit_id'])),'order'=>$m['order_id'],'material_origin'=>$m['material_origin'],'time_origin'=>$m['time_origin']]),'recognition_revision'=>$this->hash($facts),'principal_minor'=>$amount,'currency'=>'MZN','tax_minor'=>0,'compatible'=>true,'history_imported'=>false,'permitted_period_key'=>$m['period_key'],'calculation_id'=>$c['calculation']['id'],'calculation_version'=>$c['calculation']['version'],'document_revision'=>$c['calculation']['fingerprint'],'cost_evidence'=>$facts,'label'=>'Custo directo conhecido do perímetro seleccionado; não custo completo, margem ou valorização de inventário'];
}
public function source(User $u,int $order):array
{
$s=$this->scope($u);$m=DB::table('gl_cost_sources')->where($s)->where('order_id',$order)->first()??throw new \DomainException('Ordem/perímetro de custo não composto neste âmbito.');return $this->eligible($this->facts($u,$s,$m));
}
public function period(User $u,array $period):array
{
$s=$this->scope($u);$h=hash_init('sha256');$facts=0;$pending=0;
foreach(DB::table('gl_cost_sources')->where($s)->where('period_key',$period['period_key'])->orderBy('id')->cursor() as $m){$v=$this->facts($u,$s,$m);hash_update($h,Payables::canonical($v));$facts++;try{$source=$this->eligible($v);$j=DB::table('gl_journals')->where($s)->where('snapshot->source->effect_type','workshop.direct_cost.validated')->where('snapshot->source->cost_order_id',$m->order_id)->first();if(!$j||!$this->resolved($s,$j,$source))$pending++;}catch(\DomainException){$pending++;}}
return ['facts'=>$facts,'pending'=>$pending,'hash'=>hash_final($h)];
}
public function correctionSource(User $u,string $kind,int $journal):array
{
abort_unless(config('cost_ledger.correction_enabled')===true,403,'Correcção de custo não composta neste ensaio.');$s=$this->scope($u);abort_unless(DB::getSchemaBuilder()->hasTable('gl_cost_correction_capability'),503,'Schema de correcção de custo não instalado.');
if(!in_array($kind,['workshop.direct_cost.reversal','workshop.direct_cost.replacement'],true))throw new \DomainException('Tipo de correcção fora do recorte.');$j=DB::table('gl_journals')->where($s)->where('id',$journal)->first()??throw new \DomainException('Original fora do âmbito.');$original=json_decode($j->snapshot,true,128,JSON_THROW_ON_ERROR);if($original['source']['effect_type']!=='workshop.direct_cost.validated')throw new \DomainException('Só o custo original admite esta correcção.');
$base=$this->source($u,(int)$original['source']['cost_order_id']);if($base['origin_key']!==$original['source']['origin_key']||$base['permitted_period_key']!==$original['period']['period_key'])throw new \DomainException('Perímetro/período original incompatível.');if($base['recognition_revision']===$original['source']['recognition_revision'])throw new \DomainException('Não há nova versão validada para substituir o original.');
return array_replace($base,['effect_type'=>$kind,'source_id'=>$journal,'amount_minor'=>$kind==='workshop.direct_cost.reversal'?(int)$j->debit_minor:$base['principal_minor'],'replacement_source_revision'=>$base['recognition_revision'],'recognition_revision'=>$this->hash(['current_source'=>$base,'original'=>(array)$j,'kind'=>$kind]),'original_journal_id'=>$journal,'original_journal_on'=>$j->journal_on,'original_journal_sha256'=>$this->hash((array)$j),'original_cost_source'=>$original['source']]);
}
private function resolved(array $s,object $original,array $source):bool
{
if(json_decode($original->snapshot,true)['source']['recognition_revision']===$source['recognition_revision'])return true;
if(config('cost_ledger.correction_enabled')!==true||!DB::getSchemaBuilder()->hasTable('gl_cost_correction_capability'))return false;
$r=DB::table('gl_correction_results')->where($s)->where('original_journal_id',$original->id)->first();if(!$r)return false;$j=DB::table('gl_journals')->where($s)->where('id',$r->replacement_journal_id)->first();if(!$j)return false;$current=json_decode($j->snapshot,true)['source'];return $current['effect_type']==='workshop.direct_cost.replacement'&&($current['cost_order_id']??null)===$source['cost_order_id']&&($current['replacement_source_revision']??null)===$source['recognition_revision'];
}
public function workspace(User $u,?int $order,int $page):array
{
$s=$this->scope($u);$q=DB::table('gl_cost_sources')->where($s);$p=$q->orderBy('id')->paginate(25,['*'],'page',$page);$chosen=null;$source=null;$pending=null;
if($order!==null){$m=DB::table('gl_cost_sources')->where($s)->where('order_id',$order)->first()??abort(403,'Ordem fora do âmbito composto.');$chosen=$this->facts($u,$s,$m);try{$source=$this->eligible($chosen);}catch(\DomainException $e){$pending=$e->getMessage();}}
$original=$order!==null?DB::table('gl_journals')->where($s)->where('snapshot->source->effect_type','workshop.direct_cost.validated')->where('snapshot->source->cost_order_id',$order)->first():null;$state=$original?($source&&$this->resolved($s,$original,$source)?'current':'requires_correction'):'unposted';
return ['scope'=>$s,'orders'=>$p->items(),'pagination'=>['page'=>$page,'total'=>$p->total(),'last_page'=>$p->lastPage()],'order_id'=>$order,'facts'=>$chosen,'source'=>$source,'pending'=>$pending,'original_journal'=>$original,'accounting_state'=>$state];
}
}
+143
View File
@@ -0,0 +1,143 @@
<?php
namespace App\Modules\Accounting;
use App\Models\User;
use App\Modules\Identity\Services\Permissions;
use App\Modules\Purchasing\SupplierPayables;
use App\Shared\Context\CompanyContext;
use Illuminate\Support\Facades\DB;
use Tempo\Finance\GeneralLedger\{LedgerSchema,PayableJournal};
use Tempo\Finance\Payables\Payables;
final class GeneralLedger
{
public static function guard():void
{
abort_unless((app()->environment('payable-testing')||(app()->environment(['testing','browser-testing'])&&(config('sales_ledger.synthetic_enabled')===true||config('cost_ledger.synthetic_enabled')===true||config('industrial_ledger.synthetic_enabled')===true)))&&config('general_ledger.synthetic_enabled')===true,403,'Lançamentos apenas na composição sintética explicitamente preparada.');
LedgerSchema::assertSynthetic(DB::connection());
foreach(LedgerSchema::TABLES as $table)abort_unless(DB::getSchemaBuilder()->hasTable($table),503,'Núcleo contabilístico não instalado neste ensaio.');
}
private function scope(User $user):array
{
self::guard();$context=app(CompanyContext::class);
abort_unless(auth()->id()===$user->id&&$context->userId()===$user->id&&$context->unitId(),403);
if(request()->hasSession())abort_unless(request()->session()->get('company_context.module_id')==='accounting',409,'Seleccione Contabilidade.');
else abort_unless(app()->runningInConsole(),403);
$scope=$context->identifiers()+['unit_id'=>$context->unitId()];
app(Permissions::class)->require($user->id,$scope['tenant_id'],$scope['company_id'],'general_ledger.view',$scope['unit_id']);return $scope;
}
public function can(User $user,string $action):bool
{
$scope=$this->scope($user);return app(Permissions::class)->has($user->id,$scope['tenant_id'],$scope['company_id'],'general_ledger.'.$action,$scope['unit_id']);
}
public function engine(User $user,?\Closure $checkpoint=null):PayableJournal
{
$scope=$this->scope($user);$person=DB::table('pa_access')->where($scope)->where(['user_id'=>$user->id,'action'=>'view'])->value('person');abort_unless(is_string($person)&&$person!=='',403);
$authorize=function(string $action,bool $lock=true)use($user,$scope,$person):void{
self::guard();
if($lock){DB::table('companies')->where('tenant_id',$scope['tenant_id'])->where('id',$scope['company_id'])->lockForUpdate()->firstOrFail();DB::table('users')->where('id',$user->id)->lockForUpdate()->firstOrFail();}
abort_unless($this->scope($user)===$scope,409,'Contexto alterado.');
app(CompanyContext::class)->selectFor($user->id,$scope['tenant_id'],$scope['company_id'],$scope['unit_id']);
abort_unless(DB::table('pa_access')->where($scope)->where(['user_id'=>$user->id,'action'=>'view'])->value('person')===$person,409,'Pessoa alterada; reabra a conferência.');
abort_unless($this->can($user,$action),403);
};
$sales=config('sales_ledger.synthetic_enabled')===true?app(SalesLedgerSource::class):null;
$cost=config('cost_ledger.synthetic_enabled')===true?app(CostLedgerSource::class):null;
$industrial=config('industrial_ledger.synthetic_enabled')===true?app(IndustrialLedgerSource::class):null;
$providers=array_values(array_filter([$sales,$cost,$industrial]));
$extra=$providers?function($kind,$id)use($sales,$cost,$industrial,$user){if(in_array($kind,['industry.cost.validated','industry.cost.reversal','industry.cost.replacement'],true)){if(!$industrial)throw new \DomainException('Origem industrial não composta.');return $kind==='industry.cost.validated'?$industrial->source($user,$id):$industrial->correctionSource($user,$kind,$id);}if(in_array($kind,['workshop.direct_cost.validated','workshop.direct_cost.reversal','workshop.direct_cost.replacement'],true)){if(!$cost)throw new \DomainException('Origem de custo não composta neste host.');return $kind==='workshop.direct_cost.validated'?$cost->source($user,$id):$cost->correctionSource($user,$kind,$id);}if(!$sales)throw new \DomainException('Origem comercial não composta neste host.');return $sales->source($user,$kind,$id);}:null;
$period=$providers?function($period)use($providers,$user){if(count($providers)===1)return $providers[0]->period($user,$period);$facts=0;$pending=0;$hash=hash_init('sha256');foreach($providers as $provider){$v=$provider->period($user,$period);$facts+=$v['facts'];$pending+=$v['pending'];hash_update($hash,$v['hash']);}return ['facts'=>$facts,'pending'=>$pending,'hash'=>hash_final($hash)];}:null;
return new PayableJournal(DB::connection(),$scope,$user->id,$person,fn(string $a)=>$authorize($a),fn()=>$authorize('view',false),fn(int $id)=>$this->source($user,$scope,$id),$checkpoint,$extra,$period);
}
public function industrial(User $user,?int $lot=null,int $page=1):array{
$own=DB::transactionLevel()===0;return DB::transaction(function()use($user,$lot,$page,$own){if($own)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');$this->scope($user);$origin=app(IndustrialLedgerSource::class)->workspace($user,$lot,$page);$data=$this->listing($user,['page'=>$page]+($lot!==null?['industrial_lot_id'=>$lot]:[]),false);if($lot===null){foreach(['journals','lines','proposals','reviews','events'] as $key)$data[$key]=[];$data['totals']=['debit_minor'=>0,'credit_minor'=>0,'net_minor'=>0];$data['pagination']=['page'=>$page,'last_page'=>1,'total'=>0];foreach($data['evidence_pagination'] as &$p)$p=['page'=>$page,'last_page'=>1,'total'=>0];unset($p);}$closed=DB::table('gl_periods')->where($origin['scope'])->where('period_key','QA-2026-10')->orderByDesc('version')->value('status')==='closed';$cycle=$lot!==null&&config('industrial_ledger.correction_enabled')===true?$this->cycle($user,$page,['industrial_lot_id'=>$lot]):['corrections'=>[],'correction_results'=>[],'pagination'=>[],'permissions'=>[]];foreach($cycle['corrections'] as $group){$v=json_decode($group->replacement_snapshot,true)['source'];$group->current=$group->current&&$origin['source']!==null&&($v['replacement_source_revision']??null)===$origin['source']['recognition_revision'];}return ['industrial'=>$origin,'book'=>$data,'closed'=>$closed,'corrections'=>$cycle['corrections'],'correction_results'=>$cycle['correction_results'],'pagination'=>$cycle['pagination'],'permissions'=>$cycle['permissions']];});
}
public function costs(User $user,?int $order=null,int $page=1):array
{
abort_unless(config('cost_ledger.synthetic_enabled')===true,403);$own=DB::transactionLevel()===0;
return DB::transaction(function()use($user,$order,$page,$own){if($own)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');$commercial=app(CostLedgerSource::class)->workspace($user,$order,$page);$data=$this->cycle($user,$page,$order!==null?['cost_order_id'=>$order]:[]);foreach($data['corrections'] as $group){$source=json_decode($group->replacement_snapshot,true)['source'];if(isset($source['cost_order_id']))$group->current=$group->current&&$commercial['source']!==null&&($source['replacement_source_revision']??null)===$commercial['source']['recognition_revision'];}return ['cost'=>$commercial]+$data;});
}
private function source(User $user,array $scope,int $id):array
{
$obligation=DB::table('pa_obligations')->where($scope)->where('id',$id)->lockForUpdate()->first()??throw new \DomainException('Obrigação indisponível neste âmbito.');
$origin=DB::table('pa_sources')->where($scope)->where('id',$obligation->source_id)->lockForUpdate()->first()??throw new \DomainException('Referência factual ausente.');
$finance=app(SupplierPayables::class);$document=$finance->document($user,(int)$origin->local_source_id);
$position=$finance->engine($user)->positionForSource((int)$origin->local_source_id);
if(!$position||(int)$position['id']!==$id||$position['source_conflict'])throw new \DomainException('Fonte financeira mudou ou não está conferida.');
$proposal=DB::table('pa_proposals')->where($scope)->where('id',$obligation->proposal_id)->first()??throw new \DomainException('Conferência original ausente.');
return ['effect_type'=>'supplier_payable.recognised','origin_key'=>$origin->source_key,'obligation_id'=>$id,'local_source_id'=>(int)$origin->local_source_id,
'document_revision'=>$obligation->source_revision,'recognition_revision'=>hash('sha256',Payables::canonical(['obligation'=>(array)$obligation,'recognition_snapshot'=>$proposal->snapshot])),
'principal_minor'=>(int)$obligation->principal_minor,'currency'=>$obligation->currency,'due_on'=>$obligation->due_on,'tax_minor'=>$document['tax_minor'],
'compatible'=>true,'history_imported'=>$position['history_imported']];
}
public function report(User $user,string $kind,array $options):array
{
if(!in_array($kind,['trial-balance','account-ledger'],true))throw new \InvalidArgumentException('Relatório desconhecido.');$own=DB::transactionLevel()===0;
return DB::transaction(function()use($user,$kind,$options,$own){
if($own)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');$engine=$this->engine($user);
return $kind==='trial-balance'?$engine->trialBalance($options):$engine->accountLedger($options);
});
}
public function financialReceipt(User $user,string $domain,string $key):?array
{
if(!in_array($domain,['recognition','settlement'],true))throw new \InvalidArgumentException('Domínio de comprovativo inválido.');$own=DB::transactionLevel()===0;return DB::transaction(function()use($user,$domain,$key,$own){if($own)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');$this->scope($user);$engine=app(SupplierPayables::class)->engine($user);return $domain==='recognition'?$engine->receipt($key):$engine->settlements()->receipt($key);});
}
public function receipt(User $user,string $key):?array
{
$own=DB::transactionLevel()===0;return DB::transaction(function()use($user,$key,$own){if($own)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');return $this->engine($user)->receipt($key);});
}
public function listing(User $user,array $options=[],bool $withAccounts=true):array
{
$own=DB::transactionLevel()===0;
return DB::transaction(function()use($user,$options,$own,$withAccounts){
if($own)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$data=$this->engine($user)->listing($options,$withAccounts);
$data['permissions']=array_combine(['prepare','validate','post'],array_map(fn($a)=>$this->can($user,$a),['prepare','validate','post']));return $data;
});
}
public function cycle(User $user,int $page=1,array $bookOptions=[]):array
{
abort_unless(config('general_ledger.cycle_enabled')===true,403);
$own=DB::transactionLevel()===0;
return DB::transaction(function()use($user,$page,$own,$bookOptions){
if($own)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$data=$this->engine($user)->cycleListing($page,$bookOptions['cost_order_id']??null,$bookOptions['industrial_lot_id']??null);
$data['book']=$this->listing($user,['page'=>$page]+$bookOptions);
$actions=['prepare','validate','post','correct_prepare','correct_validate','correct_post','period_prepare','period_validate','period_close'];
$data['permissions']=array_combine($actions,array_map(fn($a)=>$this->can($user,$a),$actions));return $data;
});
}
public function sales(User $user,?int $invoice=null,int $page=1):array
{
abort_unless(config('sales_ledger.synthetic_enabled')===true,403);$own=DB::transactionLevel()===0;
return DB::transaction(function()use($user,$invoice,$page,$own){
if($own)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$commercial=app(SalesLedgerSource::class)->workspace($user,$invoice,$page);$data=$this->cycle($user,$page,$invoice!==null?['sales_invoice_id'=>$invoice]:[]);$data['commercial']=$commercial;
if($invoice!==null){$account=DB::table('gl_accounts')->where($data['commercial']['scope'])->where('code','QA-CLIENTES')->value('id');$data['client_account']=$account?$this->listing($user,['page'=>$page,'sales_invoice_id'=>$invoice,'account_id'=>$account])['totals']:null;}return $data;
});
}
/** Read one factual chain. No command, inferred association or module switch. */
public function flow(User $user,int $sourceId):array
{
$own=DB::transactionLevel()===0;
return DB::transaction(function()use($user,$sourceId,$own){
if($own)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$scope=$this->scope($user);
$finance=app(SupplierPayables::class);
abort_unless($finance->can($user,'view'),403);
$page=$finance->listing($user,['source'=>$sourceId,'per_page'=>25]);
$document=$page['documents'][0]??abort(403);
$position=$page['obligations'][0]??null;
$proposal=null;$review=null;$journal=null;
if($position){
$proposal=DB::table('gl_proposals')->where($scope)->where('obligation_id',$position['id'])->where('snapshot->source->effect_type','supplier_payable.recognised')->orderByDesc('capture_version')->first();
if($proposal)$review=DB::table('gl_reviews')->where($scope)->where('proposal_id',$proposal->id)->first();
$journal=DB::table('gl_journals')->where($scope)->where('obligation_id',$position['id'])->where('snapshot->source->effect_type','supplier_payable.recognised')->first();
}
return compact('scope','document','position','proposal','review','journal')+['source_id'=>$sourceId,
'financial_proposals'=>$page['proposals'],'financial_events'=>$page['events'],
'source_conflict'=>$position['source_conflict']??false];
});
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Modules\Accounting;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
final class GeneralLedgerController extends Controller
{
public function financialReceipt(Request $r,string $domain,string $key,GeneralLedger $ledger)
{
abort_if($r->query()!==[],422);try{$data=$ledger->financialReceipt($r->user(),$domain,$key);}catch(\InvalidArgumentException $e){abort(422,$e->getMessage());}catch(\DomainException $e){abort(403,$e->getMessage());}abort_if($data===null,404,'Comprovativo não encontrado neste domínio, contexto e captura.');return response()->json($data)->header('Cache-Control','no-store');
}
public function receipt(Request $r,string $key,GeneralLedger $ledger)
{
abort_if($r->query()!==[],422);try{$data=$ledger->receipt($r->user(),$key);}catch(\InvalidArgumentException $e){abort(422,$e->getMessage());}catch(\DomainException $e){abort(403,$e->getMessage());}abort_if($data===null,404,'Comprovativo não encontrado neste contexto e nesta captura.');return response()->json($data)->header('Cache-Control','no-store');
}
public function report(Request $r,string $kind,GeneralLedger $ledger)
{
$d=$r->validate(['from_on'=>'required|date_format:Y-m-d','to_on'=>'required|date_format:Y-m-d|after_or_equal:from_on','account_id'=>'sometimes|required|integer|min:1','page'=>'sometimes|integer|min:1|max:100000','per_page'=>'sometimes|integer|in:25,100']);
abort_if(array_diff(array_keys($r->query()),array_keys($d))!==[],422);
try{$data=$ledger->report($r->user(),$kind,$d);}
catch(\InvalidArgumentException $e){abort(422,$e->getMessage());}
catch(\DomainException $e){abort(403,$e->getMessage());}
if($r->is('api/*'))return response()->json($data)->header('Cache-Control','no-store');
return response(\Tempo\Finance\GeneralLedger\ReportsWorkspace::render($data,['host'=>'ERP SGF','return_url'=>'/general-ledger','industrial_links'=>config('industrial_ledger.synthetic_enabled')===true,'cost_links'=>config('cost_ledger.synthetic_enabled')===true,'sales_links'=>config('sales_ledger.synthetic_enabled')===true]))->header('Cache-Control','no-store');
}
private function options(Request $r):array
{
$d=$r->validate(['industrial_lot_id'=>'sometimes|required|integer|min:1','cost_order_id'=>'sometimes|required|integer|min:1','sales_invoice_id'=>'sometimes|required|integer|min:1','obligation_id'=>'sometimes|required|integer|min:1','page'=>'sometimes|integer|min:1|max:100000','period_key'=>'sometimes|required|string|max:80','account_id'=>'sometimes|nullable|integer|min:1']);
abort_if(array_diff(array_keys($r->query()),array_keys($d))!==[],422);if(array_key_exists('account_id',$d)&&$d['account_id']===null)unset($d['account_id']);return $d;
}
public function index(Request $r,GeneralLedger $ledger)
{
try{return response()->json($ledger->listing($r->user(),$this->options($r)))->header('Cache-Control','no-store');}
catch(\DomainException $e){abort(403,$e->getMessage());}
}
public function page(Request $r,GeneralLedger $ledger)
{
try{return response()->view('accounting.general-ledger',['data'=>$ledger->listing($r->user(),$this->options($r))])->header('Cache-Control','no-store');}
catch(\DomainException $e){abort(403,$e->getMessage());}
}
public function command(Request $r,string $action,GeneralLedger $ledger)
{
if(!in_array($action,['prepare','validate','post'],true))abort_unless(config('general_ledger.cycle_enabled')===true,403);
try{return response()->json($ledger->engine($r->user())->command($action,$r->all(),(string)$r->header('Idempotency-Key')))->header('Cache-Control','no-store');}
catch(\InvalidArgumentException $e){abort(422,$e->getMessage());}
catch(\DomainException $e){abort(409,$e->getMessage());}
}
public function cycle(Request $r,GeneralLedger $ledger)
{
$d=$r->validate(['page'=>'sometimes|integer|min:1|max:100000']);abort_if(array_diff(array_keys($r->query()),['page'])!==[],422);
$page=(int)($d['page']??1);$data=$ledger->cycle($r->user(),$page);
return response(\Tempo\Finance\GeneralLedger\CycleWorkspace::render($data,['host'=>'ERP SGF','csrf'=>csrf_token(),'context'=>$r->session()->get('company_context.token'),'scope'=>$r->session()->get('company_context'),'financial_url'=>'/supplier-payments','return_url'=>'/general-ledger','page_url'=>'/general-ledger/cycle']))->header('Cache-Control','no-store');
}
public function cycleData(Request $r,GeneralLedger $ledger)
{
$d=$r->validate(['page'=>'sometimes|integer|min:1|max:100000']);abort_if(array_diff(array_keys($r->query()),['page'])!==[],422);
return response()->json($ledger->cycle($r->user(),(int)($d['page']??1)))->header('Cache-Control','no-store');
}
public function flow(Request $r,GeneralLedger $ledger)
{
$d=$r->validate(['source'=>'required|integer|min:1']);
abort_if(array_diff(array_keys($r->query()),['source'])!==[],422);
return response()->view('accounting.payable-flow',['flow'=>$ledger->flow($r->user(),(int)$d['source'])])->header('Cache-Control','no-store');
}
}
@@ -0,0 +1,7 @@
<?php
namespace App\Modules\Accounting;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
final class IndustrialLedgerController extends Controller{
public function index(Request $r,GeneralLedger $ledger){$d=$r->validate(['lot_id'=>'sometimes|required|integer|min:1','page'=>'sometimes|integer|min:1|max:100000']);abort_if(array_diff(array_keys($r->query()),array_keys($d)),422);try{$data=$ledger->industrial($r->user(),isset($d['lot_id'])?(int)$d['lot_id']:null,(int)($d['page']??1));}catch(\DomainException $e){abort(403,$e->getMessage());}return $r->is('api/*')?response()->json($data)->header('Cache-Control','no-store'):response()->view('accounting.industrial-ledger',['data'=>$data])->header('Cache-Control','no-store');}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Modules\Accounting;
use App\Models\User;
use App\Modules\Industry\IndustrialCosts;
use App\Modules\Identity\Services\Permissions;
use App\Shared\Context\CompanyContext;
use Illuminate\Support\Facades\DB;
use Brick\Math\BigRational;
use Tempo\Finance\Payables\Payables;
final class IndustrialLedgerSource
{
private function scope(User $u):array{
abort_unless(config('industrial_ledger.synthetic_enabled')===true,403);IndustrialCosts::guard();$c=app(CompanyContext::class);abort_unless(auth()->id()===$u->id&&$c->userId()===$u->id&&$c->unitId(),403);$s=$c->identifiers()+['unit_id'=>$c->unitId()];app(Permissions::class)->require($u->id,$s['tenant_id'],$s['company_id'],'industrial_costs.view',$s['unit_id']);foreach(['gl_industrial_sources','ic_lots','ic_results','ic_inputs','ic_decisions'] as $t)abort_unless(DB::getSchemaBuilder()->hasTable($t),503,'Origem industrial indisponível.');return $s;
}
private function facts(User $u,object $map):array{return ['mapping'=>(array)$map,'conference'=>app(IndustrialCosts::class)->conference($map->lot_id,$u->id)];}
private function eligible(array $s,array $facts):array{
$m=$facts['mapping'];$c=$facts['conference'];$snap=$c['snapshot'];$r=$c['result'];$d=$c['decision'];
if(!$r||!$c['product']||($c['product']['id']??null)!==$c['lot']['product_id']||!$c['current']||!$d||$d['decision']!=='approved'||$d['actor_id']===$r['actor_id']||!$snap||$snap['incomplete']||$snap['selected_total_exact']===null||$snap['currency']!=='MZN'||!$snap['reconciliation']['balanced'])throw new \DomainException('Resultado industrial actual completo e validado distintamente obrigatório.');
$origins=[];foreach(['material','labour','pool','machine','production'] as $kind)$origins[$kind]=$snap['origins'][$kind]['source_ref'];if(Payables::canonical($origins)!==Payables::canonical(json_decode($m['origins'],true)))throw new \DomainException('Perímetro industrial alterado; nova conferência necessária.');
if(count(array_unique($origins))!==5)throw new \DomainException('Origem industrial ambígua.');
if(DB::table('ic_inputs')->where('tenant_id',$s['tenant_id'])->where('company_id',$s['company_id'])->where('lot_id','<>',$m['lot_id'])->whereIn('source_ref',array_values($origins))->exists())throw new \DomainException('Origem reutilizada entre lotes.');
if(DB::getSchemaBuilder()->hasTable('gl_cost_sources')&&DB::table('gl_cost_sources')->where('tenant_id',$s['tenant_id'])->where('company_id',$s['company_id'])->where(fn($q)=>$q->whereIn('material_origin',array_values($origins))->orWhereIn('time_origin',array_values($origins)))->exists())throw new \DomainException('Origem já composta como custo directo; não reconhecer novamente.');
try{$amount=BigRational::of($snap['selected_total_exact'])->multipliedBy(100)->toBigInteger()->toInt();}catch(\Brick\Math\Exception\MathException $e){throw new \DomainException('Montante industrial não representável em cêntimos; sem arredondamento.',0,$e);}if($amount<=0)throw new \DomainException('Montante seleccionado deve ser positivo.');
return ['effect_type'=>'industry.cost.validated','source_id'=>$m['lot_id'],'industrial_lot_id'=>$m['lot_id'],'obligation_id'=>$m['lot_id'],'origin_key'=>hash('sha256',Payables::canonical(['scope'=>$s,'lot'=>$m['lot_id'],'origins'=>$origins])),'recognition_revision'=>hash('sha256',Payables::canonical($facts)),'principal_minor'=>$amount,'currency'=>'MZN','tax_minor'=>0,'compatible'=>true,'history_imported'=>false,'permitted_period_key'=>$m['period_key'],'period_start'=>$c['lot']['period_start'],'period_end'=>$c['lot']['period_end'],'result_id'=>$r['id'],'result_version'=>$r['version'],'document_revision'=>$r['fingerprint'],'good_units'=>$snap['good_units'],'unit_cost_exact'=>$snap['unit_cost_exact'],'residual_exact'=>$snap['residual_exact'],'industrial_evidence'=>$facts,'label'=>'Resultado industrial seleccionado de ensaio; residual separado, sem stock ou salários contabilizados'];
}
public function source(User $u,int $lot):array{$s=$this->scope($u);$m=DB::table('gl_industrial_sources')->where($s)->where('lot_id',$lot)->first()??throw new \DomainException('Lote fora do âmbito composto.');return $this->eligible($s,$this->facts($u,$m));}
public function correctionSource(User $u,string $kind,int $id):array{
abort_unless(config('industrial_ledger.correction_enabled')===true,403);$s=$this->scope($u);abort_unless(DB::getSchemaBuilder()->hasTable('gl_industrial_correction_capability'),503);if(!in_array($kind,['industry.cost.reversal','industry.cost.replacement'],true))throw new \DomainException('Tipo de correcção industrial inválido.');$j=DB::table('gl_journals')->where($s)->where('id',$id)->first()??throw new \DomainException('Original fora do âmbito.');$old=json_decode($j->snapshot,true);if($old['source']['effect_type']!=='industry.cost.validated')throw new \DomainException('Apenas o original industrial admite esta correcção.');$base=$this->source($u,(int)$old['source']['industrial_lot_id']);if($base['origin_key']!==$old['source']['origin_key']||$base['permitted_period_key']!==$old['period']['period_key']||$base['recognition_revision']===$old['source']['recognition_revision'])throw new \DomainException('Origem/perímetro/período sem sucessora compatível.');return array_replace($base,['effect_type'=>$kind,'source_id'=>$id,'amount_minor'=>$kind==='industry.cost.reversal'?(int)$j->debit_minor:$base['principal_minor'],'replacement_source_revision'=>$base['recognition_revision'],'recognition_revision'=>hash('sha256',Payables::canonical(['current_source'=>$base,'original'=>(array)$j,'kind'=>$kind])),'original_journal_id'=>$id,'original_journal_on'=>$j->journal_on,'original_journal_sha256'=>hash('sha256',Payables::canonical((array)$j)),'original_industrial_source'=>$old['source']]);
}
private function resolved(array $s,object $j,array $source):bool{
if($j->source_revision===$source['recognition_revision'])return true;if(config('industrial_ledger.correction_enabled')!==true||!DB::getSchemaBuilder()->hasTable('gl_industrial_correction_capability'))return false;$r=DB::table('gl_correction_results')->where($s)->where('original_journal_id',$j->id)->first();if(!$r)return false;$replacement=DB::table('gl_journals')->where($s)->where('id',$r->replacement_journal_id)->first();if(!$replacement)return false;$v=json_decode($replacement->snapshot,true)['source'];return $v['effect_type']==='industry.cost.replacement'&&($v['industrial_lot_id']??null)===$source['industrial_lot_id']&&($v['replacement_source_revision']??null)===$source['recognition_revision'];
}
public function period(User $u,array $period):array{
$s=$this->scope($u);$h=hash_init('sha256');$facts=0;$pending=0;foreach(DB::table('gl_industrial_sources')->where($s)->where('period_key',$period['period_key'])->orderBy('id')->cursor() as $m){$v=$this->facts($u,$m);hash_update($h,Payables::canonical($v));$facts++;try{$source=$this->eligible($s,$v);$j=DB::table('gl_journals')->where($s)->where('snapshot->source->effect_type','industry.cost.validated')->where('snapshot->source->industrial_lot_id',$m->lot_id)->first();if(!$j||!$this->resolved($s,$j,$source)||$source['period_start']<$period['starts_on']||$source['period_end']>$period['ends_on'])$pending++;}catch(\DomainException){$pending++;}}return ['facts'=>$facts,'pending'=>$pending,'hash'=>hash_final($h)];
}
public function workspace(User $u,?int $lot,int $page):array{
$s=$this->scope($u);$p=DB::table('gl_industrial_sources')->where($s)->orderBy('lot_id')->paginate(25,['lot_id','period_key'],'page',$page);$facts=null;$source=null;$pending=null;$journal=null;if($lot!==null){$m=DB::table('gl_industrial_sources')->where($s)->where('lot_id',$lot)->first()??abort(403,'Lote fora do âmbito.');$facts=$this->facts($u,$m);try{$source=$this->eligible($s,$facts);}catch(\DomainException $e){$pending=$e->getMessage();}$journal=DB::table('gl_journals')->where($s)->where('snapshot->source->effect_type','industry.cost.validated')->where('snapshot->source->industrial_lot_id',$lot)->first();}return ['scope'=>$s,'lots'=>$p->items(),'pagination'=>['page'=>$page,'total'=>$p->total(),'last_page'=>$p->lastPage()],'lot_id'=>$lot,'facts'=>$facts,'source'=>$source,'pending'=>$pending,'journal'=>$journal,'accounting_state'=>$journal?($source&&$this->resolved($s,$journal,$source)?'current':'requires_future_correction'):'unposted'];
}
public function cards(User $u,int $page):array{
$s=$this->scope($u);$p=DB::table('gl_industrial_sources')->where($s)->orderBy('lot_id')->paginate(25,['lot_id','period_key'],'industrial_page',$page);$ids=array_column($p->items(),'lot_id');$results=DB::table('ic_results as r')->where(array_combine(array_map(fn($k)=>'r.'.$k,array_keys($s)),array_values($s)))->whereIn('r.lot_id',$ids)->whereNotExists(fn($q)=>$q->selectRaw('1')->from('ic_results as n')->whereColumn('n.previous_id','r.id'))->get(['r.id','r.lot_id','r.version'])->keyBy('lot_id');$decisions=DB::table('ic_decisions')->whereIn('result_id',$results->pluck('id')->all())->get(['result_id','decision'])->keyBy('result_id');$posted=DB::table('gl_journals')->where($s)->where('snapshot->source->effect_type','industry.cost.validated')->whereIn('snapshot->source->industrial_lot_id',$ids)->select('id')->selectRaw("snapshot->'source'->>'industrial_lot_id' AS lot_id")->get()->keyBy('lot_id');$rows=[];foreach($p->items() as $m){$r=$results->get($m->lot_id);$rows[]=['lot_id'=>$m->lot_id,'period_key'=>$m->period_key,'result_id'=>$r?->id,'result_version'=>$r?->version,'recorded_decision'=>$r?$decisions->get($r->id)?->decision:null,'original_journal_id'=>$posted->get($m->lot_id)?->id,'current_dependency_conference_required'=>true];}return ['allowed'=>true,'rows'=>$rows,'pagination'=>['page'=>$page,'last_page'=>$p->lastPage(),'total'=>$p->total(),'per_page'=>25]];
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Modules\Accounting;
use App\Models\User;
use App\Modules\Identity\Services\Permissions;
use App\Shared\Context\{CompanyContext,ModuleRecords};
use Illuminate\Support\Facades\DB;
/** Bounded cross-source navigation. Recorded evidence never substitutes a current owner conference. */
final class LedgerComposition
{
private function requireTables(array $tables):void{foreach($tables as $t)abort_unless(DB::getSchemaBuilder()->hasTable($t),503,'Fonte composta indisponível; não interpretar como zero.');}
private function postings(array $scope,string $kind,string $key,array $ids):array
{
if(!$ids)return [];$rows=DB::table('gl_journals')->where($scope)->where('snapshot->source->effect_type',$kind)->whereIn('snapshot->source->'.$key,$ids)->select('id')->selectRaw("snapshot->'source'->>'$key' AS source_id")->get();$out=[];foreach($rows as $row)$out[(int)$row->source_id]=$row->id;return $out;
}
private function page($pager,array $rows):array{return ['allowed'=>true,'rows'=>$rows,'pagination'=>['page'=>$pager->currentPage(),'total'=>$pager->total(),'last_page'=>$pager->lastPage(),'per_page'=>25]];}
public function workspace(User $user,array $options=[]):array
{
abort_unless(config('general_ledger.composition_enabled')===true&&config('sales_ledger.synthetic_enabled')===true&&config('cost_ledger.synthetic_enabled')===true,403,'Composição disponível apenas no ensaio explicitamente preparado.');$own=DB::transactionLevel()===0;
return DB::transaction(function()use($user,$options,$own){
if($own)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');$ledger=app(GeneralLedger::class);$book=$ledger->listing($user,['page'=>(int)($options['journals_page']??1),'period_key'=>$options['period_key']??'QA-2026-10'],false);$ctx=app(CompanyContext::class);$scope=$ctx->identifiers()+['unit_id'=>$ctx->unitId()];$permissions=app(Permissions::class);$can=fn($right)=>$permissions->has($user->id,$scope['tenant_id'],$scope['company_id'],$right,$scope['unit_id']);$panels=['sales'=>['allowed'=>false],'costs'=>['allowed'=>false],'suppliers'=>['allowed'=>false]];
if($can('service_invoices.view')&&$can('service_receivables.view')){
$this->requireTables(['si_invoices','sr_records','sr_effects','gl_sales_capability']);$p=ModuleRecords::query('si_invoices')->where($scope)->orderBy('id')->paginate(25,['id','series_code','number','issued_at'],'invoices_page',(int)($options['invoices_page']??1));$ids=array_column($p->items(),'id');$posted=$this->postings($scope,'sales.invoice','invoice_id',$ids);$records=DB::table('sr_records')->where($scope)->whereIn('invoice_id',$ids)->where('kind','obligation')->get(['id','invoice_id'])->keyBy('invoice_id');$opened=DB::table('sr_effects')->whereIn('record_id',$records->pluck('id')->all())->where('kind','open')->pluck('record_id')->all();$rows=[];foreach($p->items() as $i){$ob=$records->get($i->id);$rows[]=['invoice_id'=>$i->id,'number'=>$i->series_code.'/'.$i->number,'issued_at'=>$i->issued_at,'confirmed_opening'=>$ob&&in_array($ob->id,$opened,true),'original_journal_id'=>$posted[$i->id]??null];}$panels['sales']=$this->page($p,$rows);
}
if($can('workshop.view')&&$can('direct_costs.view')){
$this->requireTables(['gl_cost_sources','wo_orders','dc_calculations','dc_decisions']);$p=DB::table('gl_cost_sources')->where($scope)->orderBy('order_id')->paginate(25,['order_id','period_key'],'costs_page',(int)($options['costs_page']??1));$ids=array_column($p->items(),'order_id');$calculations=DB::table('dc_calculations as c')->where(array_combine(array_map(fn($k)=>'c.'.$k,array_keys($scope)),array_values($scope)))->whereIn('c.order_id',$ids)->whereNotExists(fn($q)=>$q->selectRaw('1')->from('dc_calculations as n')->whereColumn('n.order_id','c.order_id')->whereColumn('n.version','>','c.version'))->get(['c.id','c.order_id','c.version'])->keyBy('order_id');$decisions=DB::table('dc_decisions')->whereIn('calculation_id',$calculations->pluck('id')->all())->get(['calculation_id','decision'])->keyBy('calculation_id');$posted=$this->postings($scope,'workshop.direct_cost.validated','cost_order_id',$ids);$results=DB::table('gl_correction_results')->where($scope)->whereIn('original_journal_id',array_values($posted))->get(['id','original_journal_id'])->keyBy('original_journal_id');$rows=[];foreach($p->items() as $m){$calc=$calculations->get($m->order_id);$j=$posted[$m->order_id]??null;$rows[]=['order_id'=>$m->order_id,'period_key'=>$m->period_key,'calculation_id'=>$calc?->id,'calculation_version'=>$calc?->version,'recorded_decision'=>$calc?$decisions->get($calc->id)?->decision:null,'original_journal_id'=>$j,'recorded_correction_result_id'=>$j?$results->get($j)?->id:null,'current_dependency_conference_required'=>true];}$panels['costs']=$this->page($p,$rows);
}
if($can('supplier_payables.view')){
$this->requireTables(['pa_obligations','pa_sources','pa_imported_sources']);$q=DB::table('pa_obligations as o')->join('pa_sources as s','s.id','=','o.source_id')->join('pa_imported_sources as r','r.id','=','s.local_source_id');foreach($scope as $k=>$v)$q->where('o.'.$k,$v)->where('s.'.$k,$v)->where('r.'.$k,$v);$p=$q->orderBy('o.id')->paginate(25,['o.id','o.principal_minor','o.currency','s.local_source_id','r.payload'],'suppliers_page',(int)($options['suppliers_page']??1));$posted=$this->postings($scope,'supplier_payable.recognised','obligation_id',array_column($p->items(),'id'));$rows=[];foreach($p->items() as $o)$rows[]=['obligation_id'=>$o->id,'source_id'=>$o->local_source_id,'document_number'=>json_decode($o->payload,true)['number']??'—','principal_minor'=>(int)$o->principal_minor,'currency'=>$o->currency,'original_journal_id'=>$posted[$o->id]??null];$panels['suppliers']=$this->page($p,$rows);
}
if(config('industrial_ledger.synthetic_enabled')===true)$panels['industrial']=$can('industrial_costs.view')?app(IndustrialLedgerSource::class)->cards($user,(int)($options['industrial_page']??1)):['allowed'=>false];
$key=$options['period_key']??'QA-2026-10';$period=DB::table('gl_periods')->where($scope)->where('period_key',$key)->orderByDesc('version')->first();$p=DB::table('gl_period_checks')->where($scope)->where('period_key',$key)->orderByDesc('id')->paginate(25,['*'],'checks_page',(int)($options['checks_page']??1));$ids=array_column($p->items(),'id');$reviews=DB::table('gl_period_reviews')->where($scope)->whereIn('check_id',$ids)->get()->keyBy('check_id');$closures=DB::table('gl_period_closures')->where($scope)->whereIn('check_id',$ids)->get()->keyBy('check_id');$checks=[];foreach($p->items() as $c)$checks[]=['capture'=>(array)$c,'review'=>$reviews->get($c->id),'closure'=>$closures->get($c->id)];$periodActions=[];foreach(['period_prepare','period_validate','period_close'] as $a)$periodActions[$a]=$ledger->can($user,$a);return ['synthetic_only'=>true,'scope'=>$scope,'panels'=>$panels,'book'=>$book,'period'=>$period,'checks'=>$this->page($p,$checks),'period_permissions'=>$periodActions,'all_current_source_views'=>!in_array(false,array_column($panels,'allowed'),true),'query'=>$options,'recorded_state_is_not_current_conference'=>true];
});
}
}
@@ -0,0 +1,13 @@
<?php
namespace App\Modules\Accounting;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
final class LedgerCompositionController extends Controller
{
public function index(Request $r,LedgerComposition $workspace)
{
$rules=['period_key'=>'sometimes|required|string|max:80'];foreach(['industrial_page','invoices_page','costs_page','suppliers_page','journals_page','checks_page'] as $k)$rules[$k]='sometimes|integer|min:1|max:100000';$d=$r->validate($rules);abort_if(array_diff(array_keys($r->query()),array_keys($d))!==[],422);
try{$data=$workspace->workspace($r->user(),$d);}catch(\DomainException $e){abort(403,$e->getMessage());}catch(\InvalidArgumentException $e){abort(422,$e->getMessage());}
return $r->is('api/*')?response()->json($data)->header('Cache-Control','no-store'):response()->view('accounting.ledger-composition',['data'=>$data])->header('Cache-Control','no-store');
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Modules\Accounting;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
final class SalesLedgerController extends Controller
{
private function data(Request $r,GeneralLedger $ledger):array
{
$d=$r->validate(['invoice_id'=>'sometimes|required|integer|min:1','page'=>'sometimes|integer|min:1|max:100000']);abort_if(array_diff(array_keys($r->query()),array_keys($d))!==[],422);
try{return $ledger->sales($r->user(),isset($d['invoice_id'])?(int)$d['invoice_id']:null,(int)($d['page']??1));}
catch(\DomainException $e){abort(403,$e->getMessage());}
catch(\InvalidArgumentException $e){abort(422,$e->getMessage());}
}
public function page(Request $r,GeneralLedger $ledger){return response()->view('accounting.sales-ledger',['data'=>$this->data($r,$ledger)])->header('Cache-Control','no-store');}
public function index(Request $r,GeneralLedger $ledger){return response()->json($this->data($r,$ledger))->header('Cache-Control','no-store');}
}
@@ -0,0 +1,80 @@
<?php
namespace App\Modules\Accounting;
use App\Models\User;
use App\Modules\Identity\Services\Permissions;
use App\Modules\Services\{ServiceInvoicing,ServiceReceivables};
use App\Shared\Context\CompanyContext;
use Illuminate\Support\Facades\DB;
use Brick\Math\BigDecimal;
use Tempo\Finance\Payables\Payables;
/** Reads immutable commercial/receivable facts. Never issues, opens, receives or allocates. */
final class SalesLedgerSource
{
private function scope(User $u):array
{
abort_unless(config('sales_ledger.synthetic_enabled')===true,403);ServiceReceivables::guard();foreach(['si_invoices','sr_records','sr_effects','gl_sales_capability'] as $table)abort_unless(DB::getSchemaBuilder()->hasTable($table),503,'Composição comercial contabilística não instalada.');$ctx=app(CompanyContext::class);
abort_unless(auth()->id()===$u->id&&$ctx->userId()===$u->id&&$ctx->unitId(),403);$scope=$ctx->identifiers()+['unit_id'=>$ctx->unitId()];
foreach(['service_invoices.view','service_receivables.view'] as $p)app(Permissions::class)->require($u->id,$scope['tenant_id'],$scope['company_id'],$p,$scope['unit_id']);return $scope;
}
private function hash(array $d):string{return hash('sha256',Payables::canonical($d));}
private function minor(string $value):int{return BigDecimal::of(ServiceReceivables::money($value,false))->multipliedBy(100)->toInt();}
private function effectQuery(array $s){return DB::table('sr_effects as e')->join('sr_records as r','r.id','=','e.record_id')->where(array_combine(array_map(fn($k)=>'r.'.$k,array_keys($s)),array_values($s)))->select('e.*');}
private function invoice(User $u,array $scope,int $id):array
{
$row=DB::table('si_invoices')->where($scope)->where('id',$id)->first()??abort(403,'Factura fora do âmbito.');
$shown=app(ServiceInvoicing::class)->show($id,$u->id);$snapshot=$shown['snapshot'];
if(($snapshot['simulation_only']??false)!==true||($snapshot['notice']??'')!==ServiceInvoicing::NOTICE||($snapshot['document']['data']['currency']??'')!=='MZN')throw new \DomainException('Só factura efectivamente emitida pelo circuito de teste.');
$ob=DB::table('sr_records')->where($scope)->where(['invoice_id'=>$id,'kind'=>'obligation'])->first();
$open=$ob?$this->effectQuery($scope)->where('e.record_id',$ob->id)->where('e.kind','open')->first():null;
if(!$ob||!$open)throw new \DomainException('Conferência financeira de abertura pendente; não presumir dívida aprovada.');
$origin=json_decode($ob->data,true)['origin']??[];
if(($origin['invoice_id']??null)!==$id||!hash_equals($origin['snapshot_sha256']??'',hash('sha256',$row->snapshot))||(int)$open->actor_id===(int)$ob->actor_id)throw new \DomainException('Abertura ou fotografia documental divergente.');
$calc=$snapshot['calculation'];$amount=$this->minor($calc['total_document_proposed']);
if($this->minor($ob->amount)!==$amount||$this->minor($open->amount)!==$amount)throw new \DomainException('Principal não coincide com o documento.');
return ['effect_type'=>'sales.invoice','origin_key'=>$this->hash(['scope'=>$scope,'invoice'=>$id,'series'=>$row->series_code,'number'=>$row->number]),'source_id'=>$id,'invoice_id'=>$id,'obligation_id'=>(int)$ob->id,'recognition_revision'=>$this->hash(['invoice_snapshot'=>$snapshot,'pdf_sha256'=>$row->pdf_sha256,'opening'=>(array)$open,'obligation'=>(array)$ob]),'principal_minor'=>$amount,'amount_minor'=>$amount,'base_minor'=>$this->minor($calc['base_exact']),'tax_minor'=>$this->minor($calc['vat_document_proposed']),'currency'=>'MZN','compatible'=>true,'history_imported'=>false,'due_on'=>json_decode($ob->data,true)['due_date']??null,'document_revision'=>hash('sha256',$row->snapshot),'document_snapshot'=>$snapshot,'opening_effect_id'=>$open->id];
}
public function source(User $u,string $kind,int $id):array
{
$scope=$this->scope($u);if($kind==='sales.invoice')return $this->invoice($u,$scope,$id);
$expected=match($kind){'receivable.allocated'=>'allocate','receivable.reversed'=>'reverse_allocation',default=>throw new \DomainException('Efeito comercial não suportado.')};
$e=$this->effectQuery($scope)->where('e.id',$id)->where('e.kind',$expected)->first()??throw new \DomainException('Afectação/reversão confirmada fora do âmbito.');
$ob=DB::table('sr_records')->where($scope)->where('id',$e->obligation_id)->where('kind','obligation')->first()??throw new \DomainException('Obrigação a receber indisponível.');
$base=$this->invoice($u,$scope,(int)$ob->invoice_id);
$receipt=DB::table('sr_records')->where($scope)->where('id',$e->receipt_id)->where(['kind'=>'receipt','obligation_id'=>$ob->id,'invoice_id'=>$ob->invoice_id])->first();
$confirmation=$receipt?$this->effectQuery($scope)->where('e.record_id',$receipt->id)->where('e.kind','receipt_confirm')->first():null;
if(!$receipt||!$confirmation||$receipt->actor_id===$confirmation->actor_id)throw new \DomainException('Recebimento não confirmado independentemente.');
if(!DB::table('gl_journals')->where($scope)->where('snapshot->source->effect_type','sales.invoice')->where('snapshot->source->source_id',(int)$ob->invoice_id)->exists())throw new \DomainException('Contabilize primeiro a factura original.');
if($kind==='receivable.reversed'){
$target=$this->effectQuery($scope)->where('e.id',$e->target_effect_id)->where('e.kind','allocate')->where('e.obligation_id',$ob->id)->first();
if(!$target||$target->amount!==$e->amount||!DB::table('gl_journals')->where($scope)->where('snapshot->source->effect_type','receivable.allocated')->where('snapshot->source->source_id',(int)$target->id)->exists())throw new \DomainException('Reversão exige a afectação original contabilizada integralmente.');
}
return array_replace($base,['effect_type'=>$kind,'source_id'=>$id,'amount_minor'=>$this->minor($e->amount),'tax_minor'=>0,'invoice_tax_minor'=>$base['tax_minor'],'recognition_revision'=>$this->hash(['invoice'=>$base['recognition_revision'],'effect'=>(array)$e,'receipt'=>(array)$receipt,'confirmation'=>(array)$confirmation]),'financial_effect'=>(array)$e,'receipt_confirmation_id'=>$confirmation->id]);
}
public function period(User $u,array $period):array
{
$scope=$this->scope($u);$h=hash_init('sha256');$facts=0;$pending=0;
foreach(DB::table('si_invoices')->where($scope)->orderBy('id')->cursor() as $i){$facts++;hash_update($h,$i->snapshot);hash_update($h,$i->pdf_sha256);if(!DB::table('gl_journals')->where($scope)->where('snapshot->source->effect_type','sales.invoice')->where('snapshot->source->source_id',(int)$i->id)->exists())$pending++;}
foreach(DB::table('sr_records')->where($scope)->orderBy('id')->cursor() as $r){hash_update($h,Payables::canonical((array)$r));if(!$this->effectQuery($scope)->where('e.record_id',$r->id)->where('e.kind','<>','allocate')->exists())$pending++;}
foreach($this->effectQuery($scope)->orderBy('e.id')->cursor() as $e){$facts++;hash_update($h,Payables::canonical((array)$e));
if(in_array($e->kind,['allocate','reverse_allocation'],true)){if(!DB::table('gl_journals')->where($scope)->where('snapshot->source->effect_type',$e->kind==='allocate'?'receivable.allocated':'receivable.reversed')->where('snapshot->source->source_id',(int)$e->id)->exists())$pending++;}
elseif(!in_array($e->kind,['open','receipt_confirm','refused'],true))$pending++; // Unsupported financial changes are visible blockers, never ignored.
}
return ['facts'=>$facts,'pending'=>$pending,'hash'=>hash_final($h)];
}
public function workspace(User $u,?int $invoice,int $page=1):array
{
$scope=$this->scope($u);$p=\App\Shared\Context\ModuleRecords::query('si_invoices')->where($scope)->orderByDesc('id')->paginate(25,['id','series_code','number','issued_at'],'page',$page);
$data=['scope'=>$scope,'invoices'=>$p->items(),'pagination'=>['page'=>$page,'last_page'=>$p->lastPage(),'total'=>$p->total()],'invoice'=>null];if($invoice===null)return $data;
$data['invoice']=app(ServiceInvoicing::class)->show($invoice,$u->id);
$row=DB::table('si_invoices')->where($scope)->where('id',$invoice)->first()??abort(403);
$records=DB::table('sr_records')->where($scope)->where('invoice_id',$invoice)->orderByDesc('id')->paginate(25,['*'],'records_page',$page);$data['records']=$records->items();$data['records_pagination']=['page'=>$page,'last_page'=>$records->lastPage(),'total'=>$records->total()];
$decisions=$this->effectQuery($scope)->whereIn('e.record_id',array_column($records->items(),'id'))->where('e.kind','<>','allocate')->get()->keyBy('record_id');foreach($data['records'] as $r){$r->decision_kind=$decisions->get($r->id)?->kind;$r->decision_id=$decisions->get($r->id)?->id;}
$ob=DB::table('sr_records')->where($scope)->where(['invoice_id'=>$invoice,'kind'=>'obligation'])->first();$data['obligation_id']=$ob?->id;
$data['position']=$ob?app(ServiceReceivables::class)->position($ob->id,$u->id):null;
if($data['position']){unset($data['position']['effects']);$data['position']['receipts']=array_intersect_key($data['position']['receipts'],array_fill_keys(array_column($records->items(),'id'),true));}
$effects=$this->effectQuery($scope)->where('r.invoice_id',$invoice)->orderByDesc('e.id')->paginate(25,['e.*'],'effects_page',$page);$data['effects']=$effects->items();$data['effects_pagination']=['page'=>$page,'last_page'=>$effects->lastPage(),'total'=>$effects->total()];
$data['finance_permissions']=[];foreach(['prepare','confirm','allocate','correction_request','correction_approve'] as $a)$data['finance_permissions'][$a]=app(Permissions::class)->has($u->id,$scope['tenant_id'],$scope['company_id'],'service_receivables.'.$a,$scope['unit_id']);
return $data;
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Modules\Accounting;
use App\Modules\Identity\Services\Permissions;
use App\Shared\Context\CompanyContext;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/** SGF observes the canonical physical/valuation book with a SELECT-only QA role. */
final class StockValuationRead
{
public function index(Request $r,CompanyContext $context,Permissions $permissions)
{
$d=$r->validate(['page'=>'sometimes|integer|min:1|max:100000','per_page'=>'sometimes|integer|in:25,100']);abort_if(array_diff(array_keys($r->query()),array_keys($d))!==[],422);
$s=$context->identifiers();$unit=$context->unitId();abort_unless($unit,403);
foreach(['stock.view','general_ledger.view']as$p)$permissions->require($context->userId(),$s['tenant_id'],$s['company_id'],$p,$unit);
$binding=config('stock_ledger.read_sources.'.$s['tenant_id'].':'.$s['company_id'].':'.$unit);
if(!$binding)return response()->json(['status'=>'unavailable','message'=>'Livro de valorização autorizado ainda não ligado a este contexto.'],503)->header('Cache-Control','no-store');
abort_unless(app()->environment('budget-testing'),403);
$host=DB::connection();$h=$host->getConfig();$run=(string)getenv('SGF_ISOLATED_REGRESSION_RUN');
abort_unless(preg_match('/^[a-f0-9]{12}$/D',$run)&&($h['driver']??null)==='pgsql'&&($h['host']??null)==='127.0.0.1'&&(string)($h['port']??'')==='55439'&&preg_match('/^budget_core_sgf_([a-f0-9]{12})$/D',$h['database']??'',$hm)&&($h['username']??null)==='stock_ledger_sgf_'.$hm[1]&&empty($h['url'])&&empty($h['read'])&&empty($h['write']),403);
$hi=$host->selectOne("SELECT current_database() db,current_user role,current_setting('cluster_name') cluster");abort_unless($hi->db===$h['database']&&$hi->role===$h['username']&&$hi->cluster==='sgf_modular_regression_'.$run,403);
abort_unless(($binding['connection']??null)==='stock_valuation_source'&&is_int($binding['book_id']??null)&&($binding['book_id']??0)>0,503);
$c=DB::connection('stock_valuation_source');$cfg=$c->getConfig();
abort_unless(($cfg['driver']??null)==='pgsql'&&($cfg['host']??null)==='127.0.0.1'&&(string)($cfg['port']??'')==='55439'&&preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D',$cfg['database']??'',$m)&&($cfg['username']??null)==='stock_valuation_read_'.$m[1]&&empty($cfg['url'])&&empty($cfg['read'])&&empty($cfg['write'])&&($cfg['search_path']??'public')==='public',403);
$native=$binding['native_scope']??[];abort_unless(array_keys($native)===['tenant_id','company_id','unit_id']&&is_int($native['tenant_id'])&&$native['tenant_id']>0&&$native['company_id']===0&&$native['unit_id']===0,503);
try{$data=$c->transaction(function()use($c,$cfg,$run,$native,$binding,$d){
abort_unless($c->transactionLevel()===1,503);$c->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$i=$c->selectOne("SELECT current_database() db,current_user role,current_setting('cluster_name') cluster,current_setting('default_transaction_read_only') ro,rolsuper OR rolcreatedb OR rolcreaterole OR rolreplication OR rolbypassrls elevated FROM pg_roles WHERE rolname=current_user");
abort_unless($i->db===$cfg['database']&&$i->role===$cfg['username']&&$i->cluster==='sgf_modular_regression_'.$run&&$i->ro==='on'&&!$i->elevated,403);
foreach(['stock_movements','gl_journals','gl_lines','gl_stock_rates','gl_stock_books']as$table)abort_if($c->selectOne("SELECT has_table_privilege(current_user,?,'INSERT,UPDATE,DELETE') writes",[$table])->writes,403);
$book=$c->table('gl_stock_books')->where($native)->where('id',$binding['book_id'])->first();abort_unless($book,503,'Livro composto incompatível.');
abort_unless($c->table('stock_items')->where(['tenant_id'=>$native['tenant_id'],'id'=>$book->stock_item_id,'unit'=>$book->unit_code])->exists()
&&$c->table('warehouses')->where(['tenant_id'=>$native['tenant_id'],'id'=>$book->warehouse_id])->exists(),503,'Artigo/armazém/unidade da origem incompatíveis.');
$page=(int)($d['page']??1);$size=(int)($d['per_page']??25);
$physical=$c->table('stock_movements')->where(['tenant_id'=>$native['tenant_id'],'stock_item_id'=>$book->stock_item_id,'warehouse_id'=>$book->warehouse_id]);
$journals=$c->table('gl_journals')->where($native)->where('snapshot->source->stock_book_id',$book->id);$count=(clone$journals)->count();
$rows=(clone$journals)->orderBy('id')->offset(($page-1)*$size)->limit($size)->get();$ids=$rows->pluck('id')->all();$lines=$c->table('gl_lines')->where($native)->whereIn('journal_id',$ids)->orderBy('journal_id')->orderBy('line_no')->get();
$postedIds=(clone$journals)->selectRaw("(snapshot->'source'->>'stock_movement_id')::bigint");
$unposted=(clone$physical)->whereNotIn('id',$postedIds)->count();
$rate=$c->table('gl_stock_rates')->where($native)->where('book_id',$book->id)->orderByDesc('version')->first();$review=$rate?$c->table('gl_stock_rate_reviews')->where($native)->where('rate_id',$rate->id)->first():null;
$stale=$rate?(clone$journals)->where('snapshot->source->stock_rate_id','<>',$rate->id)->count():$count;
$net=$c->table('gl_lines as l')->join('gl_accounts as a','a.id','=','l.account_id')->where(['l.tenant_id'=>$native['tenant_id'],'l.company_id'=>0,'l.unit_id'=>0,'a.code'=>'QA-STOCK'])->whereIn('l.journal_id',(clone$journals)->select('id'))->selectRaw('coalesce(sum(l.debit_minor-l.credit_minor),0) net')->first();
return ['synthetic_only'=>true,'single_canonical_book'=>true,'status'=>$rate&&$review&&$review->decision==='approved'&&$unposted===0&&$stale===0?'reconciled':'pending','reconciliation_scope'=>'physical_movement_coverage_and_rate_ids_only','current_source_dependencies_validated'=>false,'book'=>['id'=>$book->id,'stock_item_id'=>$book->stock_item_id,'warehouse_id'=>$book->warehouse_id,'unit'=>$book->unit_code,'period_key'=>$book->period_key],'physical_quantity_milli'=>(int)(clone$physical)->sum('quantity_milli'),'physical_revision'=>(int)(clone$physical)->max('id'),'posted_stock_value_minor'=>(int)$net->net,'currency'=>'MZN','unposted_movements'=>$unposted,'stale_rate_journals'=>$stale,'journals'=>$rows->all(),'lines'=>$lines->all(),'pagination'=>['page'=>$page,'per_page'=>$size,'total'=>$count],'source_identity'=>['database'=>$i->db,'role'=>$i->role],'operation_executed'=>false];
});}catch(\PDOException $e){$state=$e->errorInfo[0]??$e->getCode();if(str_starts_with((string)$state,'08')||in_array($state,['28P01','3D000','42P01','42703','57014'],true))return response()->json(['status'=>'unavailable','message'=>'Livro de valorização indisponível ou incompatível.'],503)->header('Cache-Control','no-store');throw$e;}
if($r->is('api/*'))return response()->json($data)->header('Cache-Control','no-store');
return response()->view('accounting.stock-valuation-read',['data'=>$data])->header('Cache-Control','no-store');
}
}