commit melhorias sgf
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
namespace App\Modules\Accounting;
|
||||
use App\Models\User;use App\Modules\Finance\CashWorkspace;use Illuminate\Support\Facades\DB;use Tempo\Finance\Payables\Payables;
|
||||
final class CashLedgerSource
|
||||
{
|
||||
public function source(User $u,string $kind,int $id):array
|
||||
{
|
||||
$cash=app(CashWorkspace::class);$s=$cash->scope($u->id,'view',true);$b=$cash->binding();$row=DB::table('cash_events')->where($s)->where(['id'=>$id,'session_key'=>$b['session_key'],'action'=>'review','state'=>'approved','kind'=>$kind==='cash.receipt_classified'?'receipt':'expense'])->first()??throw new \DomainException('Origem de Caixa fora do âmbito.');
|
||||
$p=DB::table('cash_events')->where($s)->where(['id'=>$row->proposal_id,'action'=>'prepare','kind'=>$row->kind])->first();$data=json_decode($row->data,true);$deps=json_decode($row->dependencies,true);$receipt=$cash->receipt($s,$b);$hash=hash('sha256',Payables::canonical($receipt));
|
||||
if(!$p||$p->actor_id===$row->actor_id||Payables::canonical(json_decode($p->data,true))!==Payables::canonical($data)||($deps['source']??null)!==$hash||!($deps['open']??false)||$data['amount_minor']!==($row->kind==='receipt'?100000:5000))throw new \DomainException('Caixa sem proposta, origem e revisão distintas.');
|
||||
if($row->kind==='receipt'&&!SourceBook::table('gl_journals')->where($s)->where('snapshot->source->effect_type','receivable.allocated')->where('snapshot->source->source_id',$receipt['allocation']['id'])->exists())throw new \DomainException('Contabilize primeiro a afectação original; a Caixa só reclassifica a liquidez já reconhecida.');
|
||||
return ['effect_type'=>$kind,'source_id'=>$id,'obligation_id'=>$id,'origin_key'=>hash('sha256',Payables::canonical([$s,$b['session_key']])),'amount_minor'=>$data['amount_minor'],'principal_minor'=>$data['amount_minor'],'tax_minor'=>0,'currency'=>'MZN','compatible'=>true,'history_imported'=>false,'cash_effect_on'=>$data['date'],'permitted_period_key'=>$b['period_key'],'recognition_revision'=>hash('sha256',Payables::canonical(['event'=>(array)$row,'proposal'=>(array)$p,'source'=>$receipt])),'cash_event'=>(array)$row];
|
||||
}
|
||||
public function period(User $u,array $period):array
|
||||
{
|
||||
if(config('cash_qa.enabled')!==true)return ['facts'=>0,'pending'=>0,'hash'=>hash('sha256','cash-disabled')];$cash=app(CashWorkspace::class);$s=$cash->scope($u->id,'view',true);$b=$cash->binding();$facts=0;$pending=0;$h=hash_init('sha256');$q=DB::table('cash_events')->where($s);
|
||||
foreach((clone$q)->orderBy('id')->cursor() as $row){$facts++;hash_update($h,Payables::canonical((array)$row));if($row->session_key!==$b['session_key']){$pending++;continue;}if($row->action==='prepare'&&!(clone$q)->where('proposal_id',$row->id)->where('action','review')->exists())$pending++;
|
||||
if($row->action==='review'&&$row->state==='approved'&&in_array($row->kind,['receipt','expense'],true)){try{$type=$row->kind==='receipt'?'cash.receipt_classified':'cash.expense_confirmed';$source=$this->source($u,$type,$row->id);if(!SourceBook::table('gl_journals')->where($s)->where('snapshot->source->effect_type',$type)->where('snapshot->source->source_id',$row->id)->where('snapshot->source->recognition_revision',$source['recognition_revision'])->exists())$pending++;}catch(\DomainException|\Symfony\Component\HttpKernel\Exception\HttpExceptionInterface){$pending++;}}
|
||||
}
|
||||
if($facts>0&&!(clone$q)->where(['session_key'=>$b['session_key'],'state'=>'closed'])->exists())$pending++;return ['facts'=>$facts,'pending'=>$pending,'hash'=>hash_final($h)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Accounting;
|
||||
|
||||
use App\Modules\Purchasing\{ReceiptRuntime,RequisitionAccess};
|
||||
use App\Shared\Context\CompanyContext;
|
||||
use App\Shared\Installation\CompositionRuntime;
|
||||
use Illuminate\Support\Facades\{DB,Auth,Schema};
|
||||
use Tempo\Finance\GeneralLedger\{LedgerSchema,PayableJournal,StockValuation};
|
||||
use Tempo\Finance\Payables\Payables;
|
||||
use Tempo\Purchasing\Embedded\Models\{Invoice,PurchaseOrder};
|
||||
use Tempo\Purchasing\Embedded\Services\{CurrentActor,OrganizationAccess,SupplierPayables};
|
||||
|
||||
/** Host authority and immutable commercial/cost sources; one native financial writer/book. */
|
||||
final class ComposedLedger
|
||||
{
|
||||
private function withHost(object $host,object $user,\Closure $work):mixed
|
||||
{
|
||||
$default=DB::getDefaultConnection();$guard=Auth::getDefaultDriver();$nativeUser=Auth::user();$environment=app()->environment();
|
||||
DB::setDefaultConnection($host->getName());Schema::clearResolvedInstance('db.schema');Auth::shouldUse('web');Auth::guard('web')->setUser($user);app()->instance('env','budget-testing');
|
||||
try{return $work();}finally{DB::setDefaultConnection($default);Schema::clearResolvedInstance('db.schema');Auth::shouldUse($guard);if($nativeUser)Auth::guard($guard)->setUser($nativeUser);app()->instance('env',$environment);}
|
||||
}
|
||||
private function source(object $actor,array $binding,array $financialScope,int $id):array
|
||||
{
|
||||
$o=DB::table('pa_obligations')->where($financialScope)->where('id',$id)->first()??throw new \DomainException('Obrigação fora da origem financeira autorizada.');
|
||||
$s=DB::table('pa_sources')->where($financialScope)->where('id',$o->source_id)->first()??throw new \DomainException('Origem financeira ausente.');
|
||||
$orders=PurchaseOrder::visibleTo($actor)->where(fn($q)=>$q->whereIn('id',$binding['order_ids']??[])->orWhereIn('requisition_id',RequisitionAccess::ids($binding)));
|
||||
abort_unless(Invoice::where('tenant_id',$actor->tenant_id)->whereIn('purchase_order_id',$orders->select('id'))->where('id',$s->local_source_id)->exists(),403);
|
||||
$service=app(SupplierPayables::class);$service->readContext($actor);$document=$service->document($actor,(int)$s->local_source_id);$position=$service->engine($actor)->positionForSource((int)$s->local_source_id);
|
||||
if(!$position||(int)$position['id']!==$id||$position['source_conflict'])throw new \DomainException('A fonte financeira mudou; exige nova conferência.');
|
||||
$proposal=DB::table('pa_proposals')->where($financialScope)->where('id',$o->proposal_id)->first()??throw new \DomainException('Reconhecimento sem conferência.');
|
||||
return ['effect_type'=>'supplier_payable.recognised','origin_key'=>$s->source_key,'obligation_id'=>$id,'local_source_id'=>(int)$s->local_source_id,'document_revision'=>$o->source_revision,'recognition_revision'=>hash('sha256',Payables::canonical(['obligation'=>(array)$o,'recognition_snapshot'=>$proposal->snapshot])),'principal_minor'=>(int)$o->principal_minor,'currency'=>$o->currency,'due_on'=>$o->due_on,'tax_minor'=>$document['tax_minor'],'compatible'=>true,'history_imported'=>$position['history_imported']];
|
||||
}
|
||||
|
||||
public function run(string $action,\Closure $work):mixed
|
||||
{
|
||||
CompositionRuntime::assert();abort_unless(config('sgf_single_installation.ledger_enabled')===true,404);
|
||||
abort_unless(request()->session()->get('company_context.module_id')==='accounting',409,'Seleccione Contabilidade.');
|
||||
$context=app(CompanyContext::class);$scope=$context->identifiers()+['unit_id'=>$context->unitId()];$hostUser=$context->userId();$host=DB::connection();$hostIdentity=CompositionRuntime::physical($host);
|
||||
$generation=request()->session()->get('company_context.token');$hostActor=\App\Models\User::findOrFail($hostUser);
|
||||
try{return $host->transaction(function()use($action,$work,$context,$scope,$hostUser,$hostActor,$host,$hostIdentity,$generation){
|
||||
$host->statement("SET LOCAL lock_timeout='5s'");$host->table('companies')->where('tenant_id',$scope['tenant_id'])->where('id',$scope['company_id'])->lockForUpdate()->firstOrFail();
|
||||
return app(ReceiptRuntime::class)->run('general_ledger.'.$action,function($actor,$binding,$revision,$origin)use($action,$work,$context,$scope,$hostUser,$hostActor,$host,$hostIdentity,$generation){
|
||||
$native=DB::connection();LedgerSchema::assertSynthetic($native);$r=$native->table('gl_sgf_composition')->where('tenant_id',$actor->tenant_id)->first();
|
||||
abort_unless($r&&$r->host_database===$hostIdentity['database']&&(int)$r->company_id===$scope['company_id']&&(int)$r->unit_id===$scope['unit_id'],403,'Livro financeiro ligado a outro contexto SGF.');
|
||||
$ledgerScope=['tenant_id'=>(int)$actor->tenant_id,'company_id'=>$scope['company_id'],'unit_id'=>$scope['unit_id']];$financialScope=['tenant_id'=>(int)$actor->tenant_id,'company_id'=>0,'unit_id'=>0];
|
||||
// The legacy payable book has no SGF unit column. Never expose its
|
||||
// listings or settlement facts until every obligation is qualified.
|
||||
$orders=PurchaseOrder::visibleTo($actor)->where(fn($q)=>$q->whereIn('id',$binding['order_ids']??[])->orWhereIn('requisition_id',RequisitionAccess::ids($binding)));
|
||||
$unqualified=$native->table('pa_obligations as o')->where(['o.tenant_id'=>$actor->tenant_id,'o.company_id'=>0,'o.unit_id'=>0])->whereNotExists(function($q)use($orders,$actor){
|
||||
$q->selectRaw('1')->from('pa_sources as s')->join('invoices as i','i.id','=','s.local_source_id')->whereColumn('s.id','o.source_id')->whereColumn('s.tenant_id','o.tenant_id')->whereColumn('s.company_id','o.company_id')->whereColumn('s.unit_id','o.unit_id')->where('i.tenant_id',$actor->tenant_id)->whereIn('i.purchase_order_id',$orders->select('id'));
|
||||
})->exists();
|
||||
abort_if($unqualified,503,'Há origens financeiras sem unidade conferida; a partição exige decisão explícita.');
|
||||
$identity=app(SupplierPayables::class)->readContext($actor);$person=$identity['person'];
|
||||
$authorize=function(string $right)use($host,$hostUser,$scope,$context,$actor,$person,$ledgerScope,$generation){
|
||||
abort_unless($context->userId()===$hostUser&&$context->identifiers()+['unit_id'=>$context->unitId()]===$scope&&request()->session()->get('company_context.token')===$generation,409,'Contexto SGF alterado.');
|
||||
foreach(['general_ledger.view','general_ledger.'.$right] as $permission)abort_unless($host->table('permission_grants')->where($scope+['user_id'=>$hostUser,'permission'=>$permission])->exists(),403);
|
||||
$fresh=app(CurrentActor::class)->lock($actor,['finance']);abort_if(app(OrganizationAccess::class)->maintenanceOnly($fresh),403);
|
||||
abort_unless(DB::table('pa_access')->where($ledgerScope)->where(['user_id'=>$actor->id,'action'=>'general_ledger.'.$right,'person'=>$person])->exists(),403);
|
||||
};
|
||||
$authorize('view');
|
||||
$isolation=fn()=>app(ComposedMaterialIsolation::class)->check($host,$native,$ledgerScope);
|
||||
$stock=new StockValuation($native,$ledgerScope,$actor->id,$person,$authorize,fn()=>$authorize('view'),$isolation);
|
||||
$additional=function($kind,$id)use($host,$hostActor,$stock,$isolation){
|
||||
if(str_starts_with($kind,'stock.'))return $stock->source($kind,$id);
|
||||
if(str_starts_with($kind,'workshop.')||str_starts_with($kind,'industry.'))$isolation();
|
||||
return $this->withHost($host,$hostActor,function()use($hostActor,$kind,$id){
|
||||
if(str_starts_with($kind,'cash.'))return app(CashLedgerSource::class)->source($hostActor,$kind,$id);if(str_starts_with($kind,'workshop.'))return $kind==='workshop.direct_cost.validated'?app(CostLedgerSource::class)->source($hostActor,$id):app(CostLedgerSource::class)->correctionSource($hostActor,$kind,$id);
|
||||
if(str_starts_with($kind,'industry.'))return $kind==='industry.cost.validated'?app(IndustrialLedgerSource::class)->source($hostActor,$id):app(IndustrialLedgerSource::class)->correctionSource($hostActor,$kind,$id);
|
||||
return app(SalesLedgerSource::class)->source($hostActor,$kind,$id);
|
||||
});
|
||||
};
|
||||
$period=function($p)use($host,$hostActor,$stock){$extra=$this->withHost($host,$hostActor,function()use($p,$hostActor){$facts=0;$pending=0;$h=hash_init('sha256');foreach([SalesLedgerSource::class,CostLedgerSource::class,IndustrialLedgerSource::class,CashLedgerSource::class] as $class){$v=app($class)->period($hostActor,$p);$facts+=$v['facts'];$pending+=$v['pending'];hash_update($h,$v['hash']);}return ['facts'=>$facts,'pending'=>$pending,'hash'=>hash_final($h)];});$physical=$stock->period($p);return ['facts'=>$extra['facts']+$physical['facts'],'pending'=>$extra['pending']+$physical['pending'],'hash'=>hash('sha256',$extra['hash'].$physical['hash'])];};
|
||||
$engine=new PayableJournal($native,$ledgerScope,$actor->id,$person,$authorize,fn()=>$authorize('view'),fn(int $id)=>$this->source($actor,$binding,$financialScope,$id),null,$additional,$period,$financialScope);
|
||||
return $work($engine,$actor,$binding,$origin+['sgf_host_user'=>$hostUser,'sgf_host_scope'=>$scope,'binding_revision'=>$revision],$ledgerScope,$stock,fn(\Closure $read)=>$this->withHost($host,$hostActor,$read));
|
||||
});
|
||||
});}catch(\Illuminate\Database\QueryException $e){if(!in_array($e->errorInfo[0]??null,['55P03','57014'],true))throw $e;return response()->json(['message'=>'Livro ocupado. Recupere a mesma operação, sem gerar outra chave.'],503)->header('Retry-After','5')->header('Cache-Control','no-store');}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
namespace App\Modules\Accounting;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Shared\Context\ModuleRecords;
|
||||
|
||||
/** Bounded candidates per source family; conferences remain individual and current. */
|
||||
final class ComposedLedgerCandidates
|
||||
{
|
||||
public const KINDS=['all','supplier_payable.recognised','allocation.confirmed','allocation.reversed','sales.invoice','receivable.allocated','receivable.reversed','receivable.reduced','receivable.reduction_reversed','cash.receipt_classified','cash.expense_confirmed','workshop.direct_cost.validated','industry.cost.validated','stock.receipt','stock.issue','stock.return','stock.adjustment','stock.supplier_return'];
|
||||
public function read(array $d,object $actor,array $scope,object $stock,\Closure $hostRead):array
|
||||
{
|
||||
$page=(int)($d['source_page']??1);$size=(int)($d['source_per_page']??25);$kind=$d['source_kind']??'all';$sources=[];$last=1;$totals=[];
|
||||
$accept=fn($k)=>$kind==='all'||$kind===$k;
|
||||
$append=function($query,$type,$columns,\Closure $map)use(&$sources,&$last,&$totals,$page,$size,$accept){if(!$accept($type))return;$p=$query->paginate($size,$columns,'source_page',$page);$last=max($last,$p->lastPage());$totals[$type]=$p->total();foreach($p->items() as $row)$sources[]=['kind'=>$type]+$map($row);};
|
||||
$financial=['tenant_id'=>$actor->tenant_id,'company_id'=>0,'unit_id'=>0];
|
||||
$append(DB::table('pa_obligations as o')->join('pa_sources as s','s.id','=','o.source_id')->join('invoices as i','i.id','=','s.local_source_id')->where(['o.tenant_id'=>$actor->tenant_id,'o.company_id'=>0,'o.unit_id'=>0])->orderBy('o.id'),'supplier_payable.recognised',['o.id','o.principal_minor','i.number'],fn($o)=>['id'=>$o->id,'label'=>'Compra '.$o->number,'amount'=>$o->principal_minor]);
|
||||
foreach(['ps_allocations'=>'allocation.confirmed','ps_reversals'=>'allocation.reversed'] as $table=>$type)$append(DB::table($table)->where($financial)->orderBy('id'),$type,['id','amount_minor'],fn($o)=>['id'=>$o->id,'label'=>($type==='allocation.confirmed'?'Afectação':'Reversão').' fornecedor #'.$o->id,'amount'=>$o->amount_minor]);
|
||||
$hostRead(function()use($scope,$append){
|
||||
$append(ModuleRecords::query('si_invoices')->where($scope)->orderBy('id'),'sales.invoice',['id','series_code','number'],fn($i)=>['id'=>$i->id,'label'=>'Venda '.$i->series_code.'/'.$i->number,'amount'=>null]);
|
||||
foreach(['allocate'=>'receivable.allocated','reverse_allocation'=>'receivable.reversed','reduction'=>'receivable.reduced','reverse_reduction'=>'receivable.reduction_reversed'] as $event=>$type)$append(DB::table('sr_effects as e')->join('sr_records as r','r.id','=','e.record_id')->where(['r.tenant_id'=>$scope['tenant_id'],'r.company_id'=>$scope['company_id'],'r.unit_id'=>$scope['unit_id']])->whereIn('r.invoice_id',ModuleRecords::query('si_invoices')->select('id'))->where('e.kind',$event)->orderBy('e.id'),$type,['e.id'],fn($e)=>['id'=>$e->id,'label'=>'Afectação/reversão cliente #'.$e->id,'amount'=>null]);
|
||||
if(config('cash_qa.enabled')===true)foreach(['receipt'=>'cash.receipt_classified','expense'=>'cash.expense_confirmed'] as $kind=>$type)$append(DB::table('cash_events')->where($scope)->where(['action'=>'review','state'=>'approved','kind'=>$kind])->orderBy('id'),$type,['id'],fn($r)=>['id'=>$r->id,'label'=>'Caixa QA #'.$r->id,'amount'=>null]);
|
||||
});
|
||||
foreach(['gl_cost_sources'=>['order_id','workshop.direct_cost.validated','Custo de oficina'],'gl_industrial_sources'=>['lot_id','industry.cost.validated','Custo industrial']] as $table=>[$column,$type,$label])$append(DB::table($table)->where($scope)->orderBy('id'),$type,[$column],fn($o)=>['id'=>$o->$column,'label'=>$label.' #'.$o->$column,'amount'=>null]);
|
||||
$stockData=[];if($kind==='all'||str_starts_with($kind,'stock.'))foreach(DB::table('gl_stock_books')->where($scope)->orderBy('id')->cursor() as $book){$value=$stock->page($book->id,$page,$size);$stockData[]=$value;$last=max($last,(int)ceil($value['pagination']['total']/$size));foreach($value['rows'] as $movement){$m=$movement['movement'];$type=\Tempo\Finance\GeneralLedger\StockValuation::TYPES[$m['movement_type']]??null;if($type&&$accept($type))$sources[]=['kind'=>$type,'id'=>$m['id'],'label'=>'Movimento físico #'.$m['id'],'amount'=>null];}}
|
||||
return ['sources'=>$sources,'stock'=>$stockData,'source_pagination'=>['page'=>$page,'last_page'=>$last,'per_page'=>$size,'kind'=>$kind,'totals_by_family'=>$totals,'independent_family_pages'=>true]];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
namespace App\Modules\Accounting;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Shared\Context\CompanyContext;
|
||||
use Tempo\Finance\Payables\Payables;
|
||||
use Tempo\Finance\GeneralLedger\ReportsWorkspace;
|
||||
use Tempo\Purchasing\Embedded\Models\AuditLog;
|
||||
use Tempo\Purchasing\Embedded\Services\RequisitionWorkflow;
|
||||
|
||||
final class ComposedLedgerController
|
||||
{
|
||||
public function focused(Request $r,string $family)
|
||||
{
|
||||
[$alias,$target,$kind]=match($family){'sales'=>['invoice_id','sales_invoice_id','sales.invoice'],'cost'=>['order_id','cost_order_id','workshop.direct_cost.validated'],'industrial'=>['lot_id','industrial_lot_id','industry.cost.validated']};
|
||||
$d=$r->validate([$alias=>'sometimes|required|integer|min:1','page'=>'sometimes|integer|min:1|max:100000']);abort_if(array_diff(array_keys($r->query()),array_keys($d)),422);$query=['source_kind'=>$kind];if(isset($d[$alias]))$query[$target]=(int)$d[$alias];if(isset($d['page']))$query['page']=(int)$d['page'];$r->query->replace($query);return $this->page($r,app(ComposedLedger::class));
|
||||
}
|
||||
public function receipt(Request $r,string $key,?string $domain=null)
|
||||
{
|
||||
abort_if($r->query()!==[],422);abort_unless($domain===null||in_array($domain,['recognition','settlement'],true),422);
|
||||
try{return app(ComposedLedger::class)->run('view',function($engine,$actor)use($key,$domain){if($domain===null)$data=$engine->receipt($key);else{$service=app(\Tempo\Purchasing\Embedded\Services\SupplierPayables::class);$service->readContext($actor);$marker=DB::table('gl_sgf_composition')->where('tenant_id',$actor->tenant_id)->first();$financialScope=['tenant_id'=>(int)$actor->tenant_id,'company_id'=>(int)$marker->financial_company_id,'unit_id'=>(int)$marker->financial_unit_id];$data=\Tempo\Finance\Payables\ReceiptReader::read(DB::connection(),$domain,$financialScope,(int)$actor->id,$key,fn()=>$service->readContext($actor));}abort_if($data===null,404,'Comprovativo não encontrado para esta pessoa e contexto.');return response()->json($data)->header('Cache-Control','no-store');});}catch(\InvalidArgumentException $e){abort(422,$e->getMessage());}catch(\DomainException $e){abort(403,$e->getMessage());}
|
||||
}
|
||||
public function flow(Request $r)
|
||||
{
|
||||
$d=$r->validate(['source'=>'required|integer|min:1']);abort_if(array_diff(array_keys($r->query()),['source']),422);
|
||||
return app(ComposedLedger::class)->run('view',function($engine,$actor)use($d){$id=DB::table('pa_obligations as o')->join('pa_sources as s','s.id','=','o.source_id')->where(['o.tenant_id'=>$actor->tenant_id,'o.company_id'=>0,'o.unit_id'=>0,'s.local_source_id'=>(int)$d['source']])->value('o.id');abort_unless($id,404,'Origem sem obrigação reconhecida neste contexto.');return redirect('/general-ledger?obligation_id='.$id);});
|
||||
}
|
||||
private function rights():array
|
||||
{
|
||||
$ctx=app(CompanyContext::class);$scope=$ctx->identifiers()+['unit_id'=>$ctx->unitId(),'user_id'=>$ctx->userId()];$permissions=DB::table('permission_grants')->where($scope)->pluck('permission')->all();$out=[];
|
||||
foreach(['view','prepare','validate','post','correct_prepare','correct_validate','correct_post','period_prepare','period_validate','period_close'] as $right)$out[$right]=in_array('general_ledger.'.$right,$permissions,true);return $out;
|
||||
}
|
||||
|
||||
public function page(Request $r,ComposedLedger $ledger)
|
||||
{
|
||||
$d=$r->validate(['page'=>'sometimes|integer|min:1|max:100000','accounts_page'=>'sometimes|integer|min:1|max:100000','accounts_per_page'=>'sometimes|integer|in:25,100','account_q'=>'sometimes|nullable|string|max:80','source_page'=>'sometimes|integer|min:1|max:100000','source_per_page'=>'sometimes|integer|in:25,100','source_kind'=>'sometimes|in:'.implode(',',ComposedLedgerCandidates::KINDS),'period_key'=>'sometimes|string|max:80','account_id'=>'sometimes|nullable|integer|min:1','obligation_id'=>'sometimes|integer|min:1','sales_invoice_id'=>'sometimes|integer|min:1','cost_order_id'=>'sometimes|integer|min:1','industrial_lot_id'=>'sometimes|integer|min:1']);abort_if(array_diff(array_keys($r->query()),array_keys($d)),422);if(($d['account_id']??null)===null)unset($d['account_id']);$rights=$this->rights();
|
||||
return $ledger->run('view',function($engine,$actor,$binding,$origin,$scope,$stock,$hostRead)use($r,$d,$rights){
|
||||
if(isset($d['sales_invoice_id']))abort_unless($hostRead(fn()=>\App\Shared\Context\ModuleRecords::query('si_invoices')->where($scope)->where('id',$d['sales_invoice_id'])->exists()),403,'Documento fora do contexto e módulo.');
|
||||
$data=$engine->listing(array_diff_key($d,['source_page'=>true,'source_per_page'=>true,'source_kind'=>true,'accounts_page'=>true,'accounts_per_page'=>true,'account_q'=>true]));$data['cycle']=$engine->cycleListing((int)($d['page']??1));$data['permissions']=$rights;$data['current_actor']=$actor->id;$data['sgf_scope']=$origin['sgf_host_scope'];
|
||||
$data=array_merge($data,app(ComposedLedgerCandidates::class)->read($d,$actor,$scope,$stock,$hostRead));
|
||||
$accounts=DB::table('gl_accounts')->where($scope);if(($d['account_q']??'')!==''){$needle='%'.str_replace(['!','%','_'],['!!','!%','!_'],$d['account_q']).'%';$accounts->where(fn($q)=>$q->whereRaw("code ILIKE ? ESCAPE '!'",[$needle])->orWhereRaw("label ILIKE ? ESCAPE '!'",[$needle]));}
|
||||
$chart=$accounts->orderBy('code')->paginate((int)($d['accounts_per_page']??25),['id','code','label','currency','is_movement'],'accounts_page',(int)($d['accounts_page']??1));$data['chart_accounts']=$chart->items();$data['chart_pagination']=['page'=>$chart->currentPage(),'last_page'=>$chart->lastPage(),'per_page'=>$chart->perPage(),'total'=>$chart->total()];
|
||||
if($r->is('api/*'))return response()->json($data)->header('Cache-Control','no-store');
|
||||
return response()->view('accounting.composed-ledger',['data'=>$data,'context'=>$r->session()->get('company_context.token'),'csrf'=>csrf_token()])->header('Cache-Control','no-store');
|
||||
});
|
||||
}
|
||||
|
||||
public function command(Request $r,string $action,ComposedLedger $ledger)
|
||||
{
|
||||
$allowed=['prepare','validate','post','effect-prepare','correct-prepare','correct-validate','correct-post','period-prepare','period-validate','period-close'];abort_unless(in_array($action,$allowed,true),404);
|
||||
$right=$action==='effect-prepare'?'prepare':str_replace('-','_',$action);$key=strtolower((string)$r->header('Idempotency-Key'));abort_unless(preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/D',$key),422);$data=$r->all();abort_if(strlen(json_encode($data))>65536,422);
|
||||
try{return $ledger->run($right,function($engine,$actor,$binding,$origin)use($action,$data,$key){$hash=hash('sha256',Payables::canonical([$action,$data]));$old=AuditLog::where('tenant_id',$actor->tenant_id)->where('action','sgf.ledger.command')->where('after->operation_key',$key)->first();if($old)abort_unless(($old->after['sgf_context_key']??null)===$origin['sgf_context_key']&&($old->after['request_hash']??null)===$hash,409,'Chave utilizada noutro contexto/conteúdo.');$result=$engine->command($action,$data,$key);if(!$old)app(RequisitionWorkflow::class)->audit($actor,'sgf.ledger.command',null,null,$origin+['operation_key'=>$key,'request_hash'=>$hash,'command'=>$action,'reason'=>$data['reason']??'','result'=>$result]);return response()->json($result)->header('Cache-Control','no-store');});}catch(\InvalidArgumentException $e){abort(422,$e->getMessage());}catch(\DomainException $e){abort(409,$e->getMessage());}
|
||||
}
|
||||
|
||||
public function report(Request $r,string $kind,ComposedLedger $ledger)
|
||||
{
|
||||
abort_unless(in_array($kind,['trial-balance','account-ledger'],true),404);$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|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{return $ledger->run('view',function($engine)use($r,$kind,$d){$data=$kind==='trial-balance'?$engine->trialBalance($d):$engine->accountLedger($d);return $r->is('api/*')?response()->json($data)->header('Cache-Control','no-store'):response(ReportsWorkspace::render($data,['host'=>'SGF · livro integrado','return_url'=>'/general-ledger']))->header('Cache-Control','no-store');});}
|
||||
catch(\InvalidArgumentException $e){abort(422,$e->getMessage());}
|
||||
catch(\DomainException $e){abort(403,$e->getMessage());}
|
||||
}
|
||||
public function stockCommand(Request $r,string $action,ComposedLedger $ledger)
|
||||
{
|
||||
abort_unless(in_array($action,['rate-prepare','rate-review'],true),404);$right=$action==='rate-prepare'?'prepare':'validate';$key=strtolower((string)$r->header('Idempotency-Key'));abort_unless(preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/D',$key),422);
|
||||
$data=$r->all();abort_if(strlen(json_encode($data))>65536,422);
|
||||
try{return $ledger->run($right,function($e,$actor,$b,$origin,$s,$stock)use($action,$data,$key){
|
||||
$hash=hash('sha256',Payables::canonical([$action,$data]));
|
||||
$old=AuditLog::where('tenant_id',$actor->tenant_id)->where('action','sgf.ledger.stock-command')->where('after->operation_key',$key)->first();
|
||||
if($old)abort_unless(($old->after['sgf_context_key']??null)===$origin['sgf_context_key']&&($old->after['request_hash']??null)===$hash,409,'Chave utilizada noutro contexto/conteúdo.');
|
||||
// The public review label maps to the original engine's validation command.
|
||||
$result=$stock->command($action==='rate-review'?'rate-validate':$action,$data,$key);
|
||||
if(!$old)app(RequisitionWorkflow::class)->audit($actor,'sgf.ledger.stock-command',null,null,$origin+['operation_key'=>$key,'request_hash'=>$hash,'command'=>$action,'reason'=>$data['reason']??'','result'=>$result]);
|
||||
return response()->json($result)->header('Cache-Control','no-store');
|
||||
});}catch(\InvalidArgumentException $e){abort(422,$e->getMessage());}catch(\DomainException $e){abort(409,$e->getMessage());}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
namespace App\Modules\Accounting;
|
||||
|
||||
use App\Shared\Installation\CompositionRuntime;
|
||||
use Tempo\Finance\Payables\Payables;
|
||||
|
||||
/** Explicit, fixed synthetic material perimeter. Unknown or shared origins fail closed. */
|
||||
final class ComposedMaterialIsolation
|
||||
{
|
||||
public function check($host,$native,array $scope):void
|
||||
{
|
||||
$physical=CompositionRuntime::physical($host);$path='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/receipt-composition-'.$physical['composition'].'/single-material-perimeter.json';
|
||||
$pin=config('sgf_single_installation.material_perimeter_sha256');
|
||||
if(!is_string($pin)||!preg_match('/^[a-f0-9]{64}$/D',$pin)||!is_file($path)||is_link($path)||!hash_equals($pin,hash_file('sha256',$path)))throw new \DomainException('Perímetro de materiais não conferido; não combinar custos e valorização.');
|
||||
$p=json_decode(file_get_contents($path),true,32,JSON_THROW_ON_ERROR);
|
||||
if(($p['contract']??null)!=='SGF-QA-DISJOINT-MATERIALS-v1'||($p['scope']??null)!==$scope||($p['host_database']??null)!==$host->getDatabaseName()||($p['composition']??null)!==$physical['composition'])throw new \DomainException('Perímetro pertence a outro contexto.');
|
||||
$stocks=$native->table('gl_stock_books')->where($scope)->orderBy('id')->get(['stock_item_id','warehouse_id']);
|
||||
$actual=$stocks->map(fn($r)=>(array)$r)->all();if(Payables::canonical($actual)!==Payables::canonical($p['valued_stock']))throw new \DomainException('Artigo/armazém de valorização mudou; nova conferência obrigatória.');
|
||||
$codes=$native->table('stock_items')->where('tenant_id',$scope['tenant_id'])->whereIn('id',$stocks->pluck('stock_item_id'))->pluck('code')->all();
|
||||
foreach($native->table('gl_cost_sources')->where($scope)->orderBy('id')->cursor() as $map){
|
||||
$claim=$p['direct_costs'][(string)$map->order_id]??null;
|
||||
if(!$claim||$claim['material_origin']!==$map->material_origin)throw new \DomainException('Custo sem declaração individual de exclusão do Stock valorizado.');
|
||||
if(!$host->table('wo_orders')->where($scope)->where('id',$map->order_id)->exists())throw new \DomainException('Ordem de custo fora da empresa/unidade.');
|
||||
$entry=$host->table('wo_entries')->where('order_id',$map->order_id)->where('origin',$map->material_origin)->orderByDesc('version')->first();$data=$entry?json_decode($entry->data,true):null;
|
||||
if(!$entry||$entry->kind!=='material'||($data['resource']??null)!==$claim['resource']||in_array($claim['resource'],$codes,true)||!str_starts_with($claim['resource'],'QA-MATERIAL-DIRECTO-')||isset($data['stock_item_id'])||isset($data['delivery_movement_id']))throw new \DomainException('Material directo partilhado, alterado ou sem fronteira física explícita.');
|
||||
}
|
||||
foreach($native->table('gl_industrial_sources')->where($scope)->orderBy('id')->cursor() as $map){
|
||||
$claim=$p['industrial_costs'][(string)$map->lot_id]??null;$origins=json_decode($map->origins,true);
|
||||
if(!$claim||$claim['material_origin']!==($origins['material']??null)||in_array($claim['material_origin'],$codes,true))throw new \DomainException('Material industrial sem exclusão individual do Stock valorizado.');
|
||||
$entry=$host->table('ic_inputs')->where($scope)->where('lot_id',$map->lot_id)->where('kind','material')->where('source_ref',$claim['material_origin'])->orderByDesc('version')->first();
|
||||
if(!$entry||!str_starts_with($entry->source_ref,'IND-TEST-MATERIAL-'))throw new \DomainException('Origem industrial fora do perímetro sintético seleccionado.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ final class CostLedgerController extends Controller
|
||||
{
|
||||
public function index(Request $r,GeneralLedger $ledger)
|
||||
{
|
||||
if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->focused($r,'cost');
|
||||
$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');
|
||||
|
||||
@@ -16,7 +16,7 @@ final class CostLedgerSource
|
||||
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;
|
||||
foreach(['gl_cost_sources','wo_orders','wo_entries','wo_decisions','dc_rates','dc_calculations','dc_decisions'] as $t)abort_unless(str_starts_with($t,'gl_')?SourceBook::has($t):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
|
||||
@@ -30,39 +30,39 @@ final class CostLedgerSource
|
||||
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.');}
|
||||
if(config('industrial_ledger.synthetic_enabled')===true){abort_unless(SourceBook::has('gl_industrial_sources'),503);if(SourceBook::table('gl_industrial_sources')->where('tenant_id',$m['tenant_id'])->where('company_id',$m['company_id'])->whereRaw("EXISTS(SELECT FROM jsonb_each_text(origins::jsonb) AS o WHERE o.value IN (?,?))",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));
|
||||
$s=$this->scope($u);$m=SourceBook::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++;}}
|
||||
foreach(SourceBook::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=SourceBook::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.');
|
||||
abort_unless(config('cost_ledger.correction_enabled')===true,403,'Correcção de custo não composta neste ensaio.');$s=$this->scope($u);abort_unless(SourceBook::has('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=SourceBook::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'];
|
||||
if(config('cost_ledger.correction_enabled')!==true||!SourceBook::has('gl_cost_correction_capability'))return false;
|
||||
$r=SourceBook::table('gl_correction_results')->where($s)->where('original_journal_id',$original->id)->first();if(!$r)return false;$j=SourceBook::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';
|
||||
$s=$this->scope($u);$q=SourceBook::table('gl_cost_sources')->where($s);$p=$q->orderBy('id')->paginate(25,['*'],'page',$page);$chosen=null;$source=null;$pending=null;
|
||||
if($order!==null){$m=SourceBook::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?SourceBook::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];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,14 +7,17 @@ final class GeneralLedgerController extends Controller
|
||||
{
|
||||
public function financialReceipt(Request $r,string $domain,string $key,GeneralLedger $ledger)
|
||||
{
|
||||
if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->receipt($r,$key,$domain);
|
||||
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)
|
||||
{
|
||||
if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->receipt($r,$key);
|
||||
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)
|
||||
{
|
||||
if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->report($r,$kind,app(ComposedLedger::class));
|
||||
$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);}
|
||||
@@ -30,16 +33,19 @@ final class GeneralLedgerController extends Controller
|
||||
}
|
||||
public function index(Request $r,GeneralLedger $ledger)
|
||||
{
|
||||
if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->page($r,app(ComposedLedger::class));
|
||||
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)
|
||||
{
|
||||
if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->page($r,app(ComposedLedger::class));
|
||||
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(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->command($r,$action,app(ComposedLedger::class));
|
||||
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());}
|
||||
@@ -47,17 +53,20 @@ final class GeneralLedgerController extends Controller
|
||||
}
|
||||
public function cycle(Request $r,GeneralLedger $ledger)
|
||||
{
|
||||
if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->page($r,app(ComposedLedger::class));
|
||||
$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)
|
||||
{
|
||||
if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->page($r,app(ComposedLedger::class));
|
||||
$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)
|
||||
{
|
||||
if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->flow($r);
|
||||
$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');
|
||||
|
||||
@@ -3,5 +3,6 @@ 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');}
|
||||
public function index(Request $r,GeneralLedger $ledger){if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->focused($r,'industrial');$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');}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ 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;
|
||||
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(str_starts_with($t,'gl_')?SourceBook::has($t):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{
|
||||
@@ -19,24 +19,24 @@ final class IndustrialLedgerSource
|
||||
$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.');
|
||||
if(SourceBook::has('gl_cost_sources')&&SourceBook::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 source(User $u,int $lot):array{$s=$this->scope($u);$m=SourceBook::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']]);
|
||||
abort_unless(config('industrial_ledger.correction_enabled')===true,403);$s=$this->scope($u);abort_unless(SourceBook::has('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=SourceBook::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'];
|
||||
if($j->source_revision===$source['recognition_revision'])return true;if(config('industrial_ledger.correction_enabled')!==true||!SourceBook::has('gl_industrial_correction_capability'))return false;$r=SourceBook::table('gl_correction_results')->where($s)->where('original_journal_id',$j->id)->first();if(!$r)return false;$replacement=SourceBook::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)];
|
||||
$s=$this->scope($u);$h=hash_init('sha256');$facts=0;$pending=0;foreach(SourceBook::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=SourceBook::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'];
|
||||
$s=$this->scope($u);$p=SourceBook::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=SourceBook::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=SourceBook::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]];
|
||||
$s=$this->scope($u);$p=SourceBook::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=SourceBook::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,20 @@
|
||||
<?php
|
||||
namespace App\Modules\Accounting;
|
||||
use Brick\Math\BigInteger;
|
||||
|
||||
/** Adds original report values only; never reconstructs journal balances. */
|
||||
final class InternalStatementTotals
|
||||
{
|
||||
public const CATEGORIES=['asset','liability','income','expense','unclassified'];
|
||||
private array $groups=[];
|
||||
public function add(array $row,string $category):void
|
||||
{
|
||||
if(!in_array($category,self::CATEGORIES,true))throw new \InvalidArgumentException('Rubrica inválida.');$currency=$row['currency'];foreach(self::CATEGORIES as$c)$this->groups[$currency][$c]??=['accounts'=>0,'opening_net_minor'=>'0','debit_minor'=>'0','credit_minor'=>'0','closing_net_minor'=>'0','inverted_accounts'=>0];$g=&$this->groups[$currency][$category];$g['accounts']++;
|
||||
foreach(['opening_net_minor','debit_minor','credit_minor','closing_net_minor']as$key)$g[$key]=(string)BigInteger::of($g[$key])->plus($row[$key]);
|
||||
if(($category==='asset'&&BigInteger::of($row['closing_net_minor'])->isNegative())||($category==='liability'&&BigInteger::of($row['closing_net_minor'])->isPositive()))$g['inverted_accounts']++;
|
||||
}
|
||||
public function result():array
|
||||
{
|
||||
$out=[];foreach($this->groups as$currency=>$groups){foreach($groups as$category=>&$g){$net=BigInteger::of($g['debit_minor'])->minus($g['credit_minor']);$g['period_net_minor']=(string)$net;$g['presentation_minor']=$g['accounts']===0?null:(string)(match($category){'liability'=>BigInteger::of($g['closing_net_minor'])->negated(),'income'=>$net->negated(),'expense'=>$net,default=>BigInteger::of($g['closing_net_minor'])});}unset($g);$known=BigInteger::of($groups['income']['presentation_minor']??'0')->minus($groups['expense']['presentation_minor']??'0');$out[$currency]=['groups'=>$groups,'known_result_subtotal_minor'=>(string)$known,'complete_result_minor'=>$groups['unclassified']['accounts']===0?(string)$known:null,'equity_minor'=>null,'complete_balance_sheet'=>false,'unclassified_accounts'=>$groups['unclassified']['accounts']];}return$out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
namespace App\Modules\Accounting;
|
||||
|
||||
use App\Shared\Context\CompanyContext;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\{Crypt,DB,Validator};
|
||||
use Tempo\Finance\Payables\Payables;
|
||||
use Tempo\Purchasing\Embedded\Services\RequisitionWorkflow;
|
||||
|
||||
final class InternalStatementsController
|
||||
{
|
||||
public const POLICY='SGF-INTERNAL-STATEMENTS-QA-v1';
|
||||
private function hash(array $v):string{return hash('sha256',Payables::canonical($v));}
|
||||
private function exact(array $v,array $rules):array{abort_if(array_diff(array_keys($v),array_keys($rules)),422);return Validator::make($v,$rules)->validate();}
|
||||
private function run(Request $r,string $action,\Closure $fn):mixed
|
||||
{
|
||||
abort_unless(config('internal_statements.enabled')===true,404);$host=DB::connection();$hostId=(int)$r->user()->id;$identity=$host->table('users')->where('id',$hostId)->first(['id','email','name']);$identityHash=$this->hash((array)$identity);$generation=$this->hash($r->session()->get('company_context',[]));
|
||||
try{return app(ComposedLedger::class)->run('view',function($engine,$actor,$binding,$origin,$scope)use($action,$fn,$host,$hostId,$identityHash,$generation){$meta=DB::table('fs_meta')->where('policy',self::POLICY)->first();abort_unless($meta&&DB::connection()->getDatabaseName()==='compras_receipts_test_'.$meta->composition&&hash_equals($meta->source_hash,(string)config('internal_statements.schema_sha256')),503,'Schema de demonstrações não conferido.');if($action!=='view')abort_unless($hostId===($action==='prepare'?15:16)&&$host->table('permission_grants')->where($origin['sgf_host_scope']+['user_id'=>$hostId,'permission'=>'general_ledger.statements.'.$action])->lockForUpdate()->first(),403);$person=DB::table('pa_access')->where($scope+['user_id'=>$actor->id,'action'=>'general_ledger.view'])->lockForUpdate()->value('person');abort_unless(is_string($person)&&$person!=='',403);$freshIdentity=$host->table('users')->where('id',$hostId)->lockForUpdate()->first(['id','email','name']);abort_unless($freshIdentity,403);$identityHash=$this->hash((array)$freshIdentity);return$fn($engine,$actor,$scope,$hostId,$person,$identityHash,$generation,$this->hash([$origin['binding_revision'],$origin['sgf_host_scope']]),$host,$origin);});}catch(\InvalidArgumentException$e){abort(422,$e->getMessage());}catch(\DomainException$e){abort(403,$e->getMessage());}
|
||||
}
|
||||
private function rows(array $s){return DB::table('fs_versions')->where($s);}
|
||||
private function row(?object $r):?array{if(!$r)return null;$v=(array)$r;$v['data']=json_decode($v['data'],true,64,JSON_THROW_ON_ERROR);return$v;}
|
||||
private function latest(array $s,string $kind,bool $approved=false):?array{$q=$this->rows($s)->where('kind',$kind);if($approved)$q->where('state','approved');return$this->row($q->orderByDesc('version')->first());}
|
||||
private function plan(array $s):array{$v=DB::table('gl_accounts')->where($s)->selectRaw('count(*) accounts,coalesce(max(id),0) last_id')->first();return(array)$v;}
|
||||
private function mapping(array $s,array $entries):array
|
||||
{
|
||||
$ids=array_column($entries,'account_id');$accounts=DB::table('gl_accounts')->where($s)->whereIn('id',$ids)->get(['id','code','label','currency'])->keyBy('id');abort_unless(count($ids)===$accounts->count(),403,'Conta fora do livro autorizado.');$out=[];foreach($entries as$e){$a=(array)$accounts[$e['account_id']];$out[]=['account_id'=>$e['account_id'],'category'=>$e['category'],'account'=>$a,'account_hash'=>$this->hash($a)];}usort($out,fn($a,$b)=>$a['account_id']<=>$b['account_id']);return$out;
|
||||
}
|
||||
private function validateMapping(array $s,array $mapping):void
|
||||
{
|
||||
$fresh=$this->mapping($s,array_map(fn($e)=>array_intersect_key($e,array_flip(['account_id','category'])),$mapping));abort_unless($this->hash($fresh)===$this->hash($mapping),409,'Conta ou correspondência alterada; exige revisão.');
|
||||
}
|
||||
private function input(array $v):array
|
||||
{
|
||||
if(isset($v['reason'])&&is_string($v['reason']))$v['reason']=trim($v['reason']);$d=$this->exact($v,['kind'=>'required|in:mapping,result','action'=>'required|in:prepare,review','version'=>'required|integer|min:0','reason'=>'required|string|min:10|max:2000','data'=>'present|array']);$d['version']=(int)$d['version'];
|
||||
if($d['action']==='review')$d['data']=$this->exact($d['data'],['decision'=>'required|in:approved,refused']);elseif($d['kind']==='mapping'){$d['data']=$this->exact($d['data'],['entries'=>'required|array|min:1|max:100','evidence'=>'required|string|min:10|max:2000']);$seen=[];foreach($d['data']['entries']as&$e){$e=$this->exact($e,['account_id'=>'required|integer|min:1','category'=>'required|in:asset,liability,income,expense,unclassified']);$e['account_id']=(int)$e['account_id'];abort_if(isset($seen[$e['account_id']]),422,'Conta repetida.');$seen[$e['account_id']]=true;}unset($e);}else$d['data']=$this->exact($d['data'],['mapping_id'=>'required|integer|min:1','from_on'=>'required|date_format:Y-m-d','to_on'=>'required|date_format:Y-m-d|after_or_equal:from_on','per_page'=>'required|integer|in:25,100','evidence'=>'required|string|min:10|max:2000']);return$d;
|
||||
}
|
||||
private function basis(array $s,string $kind,string $identity):array{return ['last'=>$this->latest($s,$kind),'mapping'=>$this->latest($s,'mapping',true),'mapping_latest'=>$this->latest($s,'mapping'),'plan'=>$this->plan($s),'identity'=>$identity];}
|
||||
private function capture($engine,array $s,array $mapping,array $d,?string $persistKey=null):array
|
||||
{
|
||||
$this->validateMapping($s,$mapping['data']['entries']);$map=collect($mapping['data']['entries'])->keyBy('account_id');$totals=new InternalStatementTotals();$digest=hash_init('sha256');$first=null;$query=array_intersect_key($d,array_flip(['from_on','to_on','per_page']));$plan=$this->plan($s);$count=0;
|
||||
for($page=1;;$page++){$report=$engine->trialBalance($query+['page'=>$page]);if(!$first)$first=$report;else abort_unless($this->hash($first['basis'])===$this->hash($report['basis'])&&$this->hash($first['totals'])===$this->hash($report['totals']),409,'Livro mudou entre páginas.');foreach($report['rows']as$row){$entry=$map->get($row['account_id']);$category=$entry['category']??'unclassified';$totals->add($row,$category);$line=$row+['category'=>$category];foreach(['opening_net_minor','debit_minor','credit_minor','closing_net_minor']as$key)$line[$key]=(string)$line[$key];hash_update($digest,Payables::canonical($line)."\n");if($persistKey)DB::table('fs_result_lines')->insert($s+['snapshot_key'=>$persistKey]+$line);$count++;}if($page>=$report['pagination']['last_page'])break;}
|
||||
$current=DB::table('gl_journals')->where($s)->where('journal_on','<=',$d['to_on'])->selectRaw('count(*) journals,coalesce(max(id),0) last_journal_id')->first();abort_unless((int)$current->journals===$first['basis']['journals']&&(int)$current->last_journal_id===$first['basis']['last_journal_id']&&$this->hash($plan)===$this->hash($this->plan($s))&&$count===$first['totals']['accounts'],409,'Fonte mudou durante a preparação.');
|
||||
$summary=['query'=>['from_on'=>$d['from_on'],'to_on'=>$d['to_on']],'mapping_id'=>$mapping['id'],'mapping_version'=>$mapping['version'],'basis'=>$first['basis'],'original_totals'=>array_map('strval',$first['totals']),'currencies'=>$totals->result(),'accounts'=>$count,'plan'=>$plan,'rows_sha256'=>hash_final($digest),'synthetic_only'=>true,'legal_model'=>false];return['summary'=>$summary,'source_basis'=>$this->hash($summary)];
|
||||
}
|
||||
private function csv(array $s,string $key,array $data):array
|
||||
{
|
||||
$stream=fopen('php://temp/maxmemory:1048576','w+');$h=hash_init('sha256');$write=function(array $row)use($stream,$h){$f=fopen('php://memory','w+');fputcsv($f,$row,';','"','',"\r\n");rewind($f);$bytes=stream_get_contents($f);fclose($f);fwrite($stream,$bytes);hash_update($h,$bytes);};
|
||||
$write(['DEMONSTRACOES INTERNAS PARCIAIS QA — SEM MODELO LEGAL']);$write(['Snapshot',$key,'Versao de resultado',$data['result_version'],'Observacao',$data['frozen_at']]);$write(['Datas',$data['summary']['query']['from_on'],$data['summary']['query']['to_on'],'Correspondencias',$data['summary']['mapping_version']]);$write(['Capital proprio','INDETERMINADO','Nao presumir zero ou completar equacao patrimonial']);$write(['Rubricas/pendencias',Payables::canonical($data['summary']['currencies'])]);$write(['Fundamento',"'".$data['evidence']]);$write(['Conta','Descricao','Moeda','Rubrica','Abertura liquida minor','Debito minor','Credito minor','Fecho liquido minor']);
|
||||
DB::table('fs_result_lines')->where($s+['snapshot_key'=>$key])->orderBy('code')->orderBy('account_id')->chunk(100,function($rows)use($write){foreach($rows as$r)$write(["'".$r->code,"'".$r->label,$r->currency,$r->category,$r->opening_net_minor,$r->debit_minor,$r->credit_minor,$r->closing_net_minor]);});rewind($stream);return['stream'=>$stream,'sha256'=>hash_final($h)];
|
||||
}
|
||||
private function execute($engine,$actor,array $s,int $hostId,string $person,string $identity,array $d,array $b,string $key,string $stamp,$host,array $origin):array
|
||||
{
|
||||
$last=$b['last'];abort_unless(($last['version']??0)===$d['version'],409,'Versão alterada; confira novamente.');$version=$d['version']+1;$prepared=$hostId;$native=$actor->id;$preparedPerson=$person;$preparedIdentity=$identity;
|
||||
if($d['action']==='prepare'){
|
||||
if($d['kind']==='mapping'){$entries=$this->mapping($s,$d['data']['entries']);$data=['entries'=>$entries,'evidence'=>$d['data']['evidence']];$source=$this->hash(['entries'=>$entries,'plan'=>$b['plan']]);}
|
||||
else{$m=$b['mapping'];abort_unless($m&&$m['id']===(int)$d['data']['mapping_id'],409,'Escolha explicitamente as correspondências revistas actuais.');$captured=$this->capture($engine,$s,$m,$d['data'],$key);$data=['snapshot_key'=>$key,'result_version'=>$version,'frozen_at'=>$stamp,'evidence'=>$d['data']['evidence'],'summary'=>$captured['summary']];$csv=$this->csv($s,$key,$data);$data['csv_sha256']=$csv['sha256'];fclose($csv['stream']);$source=$captured['source_basis'];DB::table('fs_results')->insert($s+['snapshot_key'=>$key,'data'=>Payables::canonical($data),'csv_sha256'=>$data['csv_sha256'],'source_basis'=>$source,'created_at'=>$stamp]);}
|
||||
$state='prepared';
|
||||
}else{
|
||||
abort_unless($last&&$last['state']==='prepared'&&$last['prepared_host_id']!==$hostId&&$last['prepared_native_id']!==$actor->id&&$last['prepared_person']!==$person,403,'Preparação actual e pessoa distinta obrigatórias.');$prepared=$last['prepared_host_id'];$native=$last['prepared_native_id'];$preparedPerson=$last['prepared_person'];$preparedIdentity=$last['preparer_identity'];$u=$host->table('users')->where('id',$prepared)->lockForUpdate()->first(['id','email','name']);abort_unless($u&&hash_equals($preparedIdentity,$this->hash((array)$u))&&$host->table('company_memberships')->where(['tenant_id'=>$origin['sgf_host_scope']['tenant_id'],'company_id'=>$origin['sgf_host_scope']['company_id'],'user_id'=>$prepared])->lockForUpdate()->first(),409,'Identidade/vínculo do preparador mudou.');abort_unless($host->table('permission_grants')->where($origin['sgf_host_scope']+['user_id'=>$prepared,'permission'=>'general_ledger.statements.prepare'])->lockForUpdate()->first(),403);$freshPerson=DB::table('pa_access')->where($s+['user_id'=>$native,'action'=>'general_ledger.view'])->lockForUpdate()->value('person');abort_unless($freshPerson===$preparedPerson,409,'Pessoa do preparador mudou.');$data=$last['data'];
|
||||
if($d['kind']==='mapping'){$this->validateMapping($s,$data['entries']);$source=$this->hash(['entries'=>$data['entries'],'plan'=>$b['plan']]);}else{$m=$b['mapping'];abort_unless($m&&$m['id']===$data['summary']['mapping_id'],409,'Correspondências mudaram desde a preparação.');$source=$this->capture($engine,$s,$m,$data['summary']['query']+['per_page'=>100])['source_basis'];$csv=$this->csv($s,$data['snapshot_key'],$data);abort_unless(hash_equals($data['csv_sha256'],$csv['sha256']),409,'Snapshot congelado incompatível.');fclose($csv['stream']);}abort_unless(hash_equals($last['source_basis'],$source),409,'Contas, livro ou dependências mudaram desde a preparação.');$state=$d['data']['decision'];
|
||||
}
|
||||
$impact=['before'=>['version'=>$d['version'],'state'=>$last['state']??null],'after'=>['version'=>$version,'state'=>$state],'kind'=>$d['kind'],'data'=>$data,'new_journals'=>0,'accounts_changed'=>false,'legal_model'=>false];$id=DB::table('fs_versions')->insertGetId($s+['kind'=>$d['kind'],'version'=>$version,'previous_id'=>$last['id']??null,'action'=>$d['action'],'state'=>$state,'prepared_host_id'=>$prepared,'prepared_native_id'=>$native,'prepared_person'=>$preparedPerson,'preparer_identity'=>$preparedIdentity,'host_actor_id'=>$hostId,'actor_id'=>$actor->id,'data'=>Payables::canonical($data),'source_basis'=>$source,'reason'=>$d['reason'],'created_at'=>now()->utc()]);return['id'=>$id,'kind'=>$d['kind'],'version'=>$version,'state'=>$state,'impact'=>$impact];
|
||||
}
|
||||
public function preview(Request $r)
|
||||
{
|
||||
$d=$this->input($r->all());$key=strtolower((string)$r->header('Idempotency-Key'));$this->exact(['key'=>$key],['key'=>'required|uuid']);return$this->run($r,$d['action'],function($e,$a,$s,$h,$p,$identity,$g,$binding,$host,$origin)use($d,$key){$b=$this->basis($s,$d['kind'],$identity);$stamp=now()->utc()->toIso8601String();$db=DB::connection();$level=$db->transactionLevel();$db->beginTransaction();try{$out=$this->execute($e,$a,$s,$h,$p,$identity,$d,$b,$key,$stamp,$host,$origin);}finally{while($db->transactionLevel()>$level)$db->rollBack();}$cut=['input'=>$d,'actor'=>$h,'person'=>$p,'generation'=>$g,'binding'=>$binding,'key'=>$key,'stamp'=>$stamp,'observed'=>time(),'basis'=>$this->hash($b),'impact'=>$out['impact']];return response()->json(['preview'=>Crypt::encryptString(Payables::canonical($cut)),'impact'=>$out['impact']])->header('Cache-Control','no-store');});
|
||||
}
|
||||
public function confirm(Request $r)
|
||||
{
|
||||
$v=$this->exact($r->all(),['preview'=>'required|string|max:131072']);try{$c=json_decode(Crypt::decryptString($v['preview']),true,64,JSON_THROW_ON_ERROR);}catch(\Throwable){abort(409,'Prévia inválida.');}abort_unless(is_array($c)&&is_array($c['input']??null),409);$d=$this->input($c['input']);return$this->run($r,$d['action'],function($e,$a,$s,$h,$p,$identity,$g,$binding,$host,$origin)use($c,$d){abort_unless($c['actor']===$h&&$c['person']===$p&&$c['generation']===$g&&$c['binding']===$binding&&$c['observed']>=time()-600&&$c['observed']<=time(),409,'Pessoa/contexto/prévia alterados.');$command=$s+['host_actor_id'=>$h,'command_key'=>$c['key']];$old=DB::table('fs_commands')->where($command)->first();if($old){abort_unless(hash_equals($old->request_hash,$this->hash($d))&&hash_equals($old->binding_hash,$binding),409,'Chave usada com outros dados.');return response()->json(json_decode($old->result,true)+['replayed'=>true])->header('Cache-Control','no-store');}$b=$this->basis($s,$d['kind'],$identity);abort_unless(hash_equals($c['basis'],$this->hash($b)),409,'Versão, identidade ou correspondências mudaram.');$out=$this->execute($e,$a,$s,$h,$p,$identity,$d,$b,$c['key'],$c['stamp'],$host,$origin);abort_unless($this->hash($out['impact'])===$this->hash($c['impact']),409,'Impacto mudou.');app(RequisitionWorkflow::class)->audit($a,'sgf.statements.command',null,['version'=>$d['version']],['host_actor_id'=>$h,'operation_key'=>$c['key'],'reason'=>$d['reason'],'after'=>$out]);DB::table('fs_commands')->insert($command+['actor_id'=>$a->id,'request_hash'=>$this->hash($d),'binding_hash'=>$binding,'input'=>Payables::canonical($d),'result'=>Payables::canonical($out),'created_at'=>now()->utc()]);return response()->json($out+['replayed'=>false],201)->header('Cache-Control','no-store');});
|
||||
}
|
||||
public function receipt(Request $r,string $key)
|
||||
{
|
||||
abort_if($r->query()!==[],422);$this->exact(['key'=>$key],['key'=>'required|uuid']);return$this->run($r,'view',function($e,$a,$s,$h,$p,$identity,$g,$binding)use($key){$old=DB::table('fs_commands')->where($s+['host_actor_id'=>$h,'command_key'=>$key])->first();abort_unless($old,404);abort_unless(hash_equals($old->binding_hash,$binding),409);return response()->json(['result'=>json_decode($old->result,true),'created_at'=>$old->created_at,'reason'=>json_decode($old->input,true)['reason'],'operation_executed'=>false,'historical_receipt_only'=>true])->header('Cache-Control','no-store');});
|
||||
}
|
||||
public function index(Request $r)
|
||||
{
|
||||
$d=$this->exact($r->query(),['view'=>'sometimes|in:history,accounts,result','kind'=>'sometimes|in:mapping,result','version_id'=>'required_if:view,result|prohibited_unless:view,result|integer|min:1','search'=>'sometimes|nullable|string|max:100','page'=>'sometimes|integer|min:1|max:100000','per_page'=>'sometimes|integer|in:25,100']);return$this->run($r,'view',function($e,$a,$s,$h,$p,$identity,$g,$binding,$host,$origin)use($d){$view=$d['view']??'history';$size=(int)($d['per_page']??25);$page=(int)($d['page']??1);$lastMapping=$this->latest($s,'mapping');$mapping=$this->latest($s,'mapping',true);$lastResult=$this->latest($s,'result');$approvedResult=$this->latest($s,'result',true);$snapshot=null;$matches=null;
|
||||
if($view==='accounts'){$q=DB::table('gl_accounts')->where($s);if(($d['search']??'')!==''){$needle='%'.str_replace(['!','%','_'],['!!','!%','!_'],$d['search']).'%';$q->where(fn($q)=>$q->whereRaw("code ILIKE ? ESCAPE '!'",[$needle])->orWhereRaw("label ILIKE ? ESCAPE '!'",[$needle]));}$rows=$q->orderBy('code')->orderBy('id')->paginate($size,['id','code','label','currency'],'page',$page);}
|
||||
elseif($view==='result'){$v=$this->row($this->rows($s)->where(['id'=>$d['version_id'],'kind'=>'result','state'=>'approved'])->first());abort_unless($v,403,'Resultado revisto fora do contexto.');$snapshot=$v['data'];$q=DB::table('fs_result_lines')->where($s+['snapshot_key'=>$snapshot['snapshot_key']]);$rows=$q->orderBy('code')->orderBy('account_id')->paginate($size,['*'],'page',$page);$current=$mapping&&$mapping['id']===$snapshot['summary']['mapping_id'];if($current){try{$now=$this->capture($e,$s,$mapping,$snapshot['summary']['query']+['per_page'=>100]);$current=hash_equals($v['source_basis'],$now['source_basis']);}catch(\Symfony\Component\HttpKernel\Exception\HttpExceptionInterface$ex){if($ex->getStatusCode()!==409)throw$ex;$current=false;}}$matches=$current;}
|
||||
else{$q=$this->rows($s);if(isset($d['kind']))$q->where('kind',$d['kind']);$rows=$q->orderByDesc('id')->paginate($size,['*'],'page',$page);$rows->setCollection($rows->getCollection()->map(fn($v)=>$this->row($v)));}
|
||||
$can=fn($action,$expected)=>$h===$expected&&$host->table('permission_grants')->where($origin['sgf_host_scope']+['user_id'=>$h,'permission'=>'general_ledger.statements.'.$action])->exists();return response()->json(['policy'=>self::POLICY,'view'=>$view,'records'=>$rows,'mapping_latest'=>$lastMapping,'mapping_approved'=>$mapping,'result_latest'=>$lastResult,'result_approved'=>$approvedResult,'snapshot'=>$snapshot,'current_source_matches'=>$matches,'capabilities'=>['prepare'=>$can('prepare',15),'review'=>$can('review',16)],'notice'=>'Demonstrações internas parciais QA; classificação pendente visível, capital não presumido. Não é modelo legal.'])->header('Cache-Control','no-store');});
|
||||
}
|
||||
public function export(Request $r,int $id)
|
||||
{
|
||||
abort_if($r->query()!==[],422);return$this->run($r,'view',function($e,$a,$s)use($id){$v=$this->row($this->rows($s)->where(['id'=>$id,'kind'=>'result','state'=>'approved'])->first());abort_unless($v,403,'Resultado não revisto ou fora do âmbito.');$data=$v['data'];$saved=DB::table('fs_results')->where($s+['snapshot_key'=>$data['snapshot_key']])->first();abort_unless($saved&&hash_equals($saved->csv_sha256,$data['csv_sha256']),409);$csv=$this->csv($s,$data['snapshot_key'],$data);if(!hash_equals($data['csv_sha256'],$csv['sha256'])){fclose($csv['stream']);abort(409,'Artefacto alterado.');}$stream=$csv['stream'];return response()->stream(function()use($stream){try{fpassthru($stream);}finally{fclose($stream);}},200,['Content-Type'=>'text/csv; charset=UTF-8','Content-Disposition'=>'attachment; filename="sgf-demonstracoes-internas-QA.csv"','X-Content-SHA256'=>$csv['sha256'],'Cache-Control'=>'no-store, private']);});
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ final class LedgerCompositionController extends Controller
|
||||
{
|
||||
public function index(Request $r,LedgerComposition $workspace)
|
||||
{
|
||||
if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->page($r,app(ComposedLedger::class));
|
||||
$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');
|
||||
|
||||
@@ -11,6 +11,8 @@ final class SalesLedgerController extends Controller
|
||||
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');}
|
||||
public function page(Request $r,GeneralLedger $ledger){if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->focused($r,'sales');return response()->view('accounting.sales-ledger',['data'=>$this->data($r,$ledger)])->header('Cache-Control','no-store');}
|
||||
public function index(Request $r,GeneralLedger $ledger){if(config('sgf_single_installation.ledger_enabled')===true)return app(ComposedLedgerController::class)->focused($r,'sales');return response()->json($this->data($r,$ledger))->header('Cache-Control','no-store');}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ 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(config('sales_ledger.synthetic_enabled')===true,403);ServiceReceivables::guard();foreach(['si_invoices','sr_records','sr_effects','gl_sales_capability'] as $table)abort_unless(str_starts_with($table,'gl_')?SourceBook::has($table):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;
|
||||
}
|
||||
@@ -37,27 +37,38 @@ final class SalesLedgerSource
|
||||
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.')};
|
||||
$expected=match($kind){'receivable.allocated'=>'allocate','receivable.reversed'=>'reverse_allocation','receivable.reduced'=>'reduction','receivable.reduction_reversed'=>'reverse_reduction',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);
|
||||
if($kind==='receivable.reduction_reversed'){
|
||||
$target=$this->effectQuery($scope)->where(['e.id'=>$e->target_effect_id,'e.kind'=>'reduction','e.obligation_id'=>$ob->id])->first();$r=DB::table('sr_records')->where($scope)->where(['id'=>$e->record_id,'kind'=>'correction'])->first();$cancel=DB::table('sd_cancellations')->where($scope)->where(['effect_id'=>$e->id,'state'=>'cancelled'])->first();
|
||||
if(!$target||!$r||!$cancel||$r->actor_id===$e->actor_id||$target->amount!==$e->amount||!SourceBook::table('gl_journals')->where($scope)->where('snapshot->source->effect_type','receivable.reduced')->where('snapshot->source->source_id',(int)$target->id)->exists())throw new \DomainException('Reversão sem crédito original contabilizado e anulação distinta.');
|
||||
return array_replace($base,['effect_type'=>$kind,'source_id'=>$id,'amount_minor'=>$this->minor($e->amount),'tax_minor'=>0,'recognition_revision'=>$this->hash(['invoice'=>$base['recognition_revision'],'target'=>(array)$target,'effect'=>(array)$e,'record'=>(array)$r,'cancellation'=>(array)$cancel]),'financial_effect'=>(array)$e]);
|
||||
}
|
||||
if($kind==='receivable.reduced'){
|
||||
$r=DB::table('sr_records')->where($scope)->where(['id'=>$e->record_id,'kind'=>'correction','invoice_id'=>$ob->invoice_id,'obligation_id'=>$ob->id])->first();
|
||||
$doc=DB::getSchemaBuilder()->hasTable('sd_outputs')?DB::table('sd_outputs')->where($scope)->where(['effect_id'=>$e->id,'invoice_id'=>$ob->invoice_id,'kind'=>'credit_note'])->first():null;
|
||||
if(!$r||!$doc||$r->actor_id===$e->actor_id||$r->amount!==$e->amount||!hash_equals($doc->pdf_sha256,hash('sha256',base64_decode($doc->pdf_base64,true)))||!SourceBook::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('Crédito sem documento, decisão distinta ou factura original contabilizada.');
|
||||
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,'record'=>(array)$r,'credit_document'=>(array)$doc]),'financial_effect'=>(array)$e,'credit_document_id'=>$doc->id,'operational_nominal_reduction'=>true]);
|
||||
}
|
||||
$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(!SourceBook::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.');
|
||||
if(!$target||$target->amount!==$e->amount||!SourceBook::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('si_invoices')->where($scope)->orderBy('id')->cursor() as $i){$facts++;hash_update($h,$i->snapshot);hash_update($h,$i->pdf_sha256);if(!SourceBook::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++;}
|
||||
if(in_array($e->kind,['allocate','reverse_allocation','reduction','reverse_reduction'],true)){if(!SourceBook::table('gl_journals')->where($scope)->where('snapshot->source->effect_type',match($e->kind){'allocate'=>'receivable.allocated','reduction'=>'receivable.reduced','reverse_reduction'=>'receivable.reduction_reversed',default=>'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)];
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
namespace App\Modules\Accounting;
|
||||
|
||||
use App\Shared\Installation\CompositionRuntime;
|
||||
use App\Shared\Context\CompanyContext;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tempo\Finance\GeneralLedger\LedgerSchema;
|
||||
|
||||
/** Read routing only. Domain facts stay in the host; ledger metadata stays in its original book. */
|
||||
final class SourceBook
|
||||
{
|
||||
private static function connection()
|
||||
{
|
||||
if(!(app()->environment('budget-testing')&&config('sgf_single_installation.enabled')===true&&config('sgf_single_installation.ledger_enabled')===true))return DB::connection();
|
||||
CompositionRuntime::assert();$host=CompositionRuntime::physical();$ctx=app(CompanyContext::class);$scope=$ctx->identifiers();$native=DB::connection('receipt_native');LedgerSchema::assertSynthetic($native);
|
||||
$binding=$native->table('gl_sgf_composition')->where('tenant_id',$scope['tenant_id'])->first();
|
||||
abort_unless($binding&&$binding->host_database===$host['database']&&(int)$binding->company_id===$scope['company_id']&&(int)$binding->unit_id===$ctx->unitId(),403);
|
||||
return $native;
|
||||
}
|
||||
public static function table(string $table){if(!preg_match('/^gl_[a-z_]+$/D',$table))throw new \LogicException('Ledger metadata only');return self::connection()->table($table);}
|
||||
public static function has(string $table):bool{if(!preg_match('/^gl_[a-z_]+$/D',$table))throw new \LogicException('Ledger metadata only');return self::connection()->getSchemaBuilder()->hasTable($table);}
|
||||
}
|
||||
Reference in New Issue
Block a user