feat(proactive): integrate private supply observations and demonstrate Gurue comparison in QA
This commit is contained in:
@@ -128,7 +128,7 @@ class OpportunityManagement
|
||||
$this->check($record, $data['etag']);
|
||||
abort_if($record->trashed() || $record->status === 'archived', 409, 'Restaure antes de editar.');
|
||||
}
|
||||
if (array_key_exists('proactive', $data)) $data['proactive'] = app(ProactiveInvestment::class)->draft($data['proactive'], $record);
|
||||
if (array_key_exists('proactive', $data)) $data['proactive'] = app(ProactiveInvestment::class)->draft($data['proactive'], $record, $actor);
|
||||
$before = $record->getAttributes();
|
||||
$previousCanonical = $record->exists ? ($this->values($record)['canonical'] ?? []) : [];
|
||||
$changes = array_intersect_key($data, array_flip([...self::FIELDS, ...self::PRIVATE_DRAFT_FIELDS]));
|
||||
@@ -227,7 +227,7 @@ class OpportunityManagement
|
||||
$record = Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
abort_if($record->owner_user_id !== null, 403, 'A v1 exige pedido e decisão de arquivo; não concede exclusão ou restauro ao Promotor.');
|
||||
$this->check($record, $data['etag']);
|
||||
if (array_key_exists('proactive', $data)) $data['proactive'] = app(ProactiveInvestment::class)->draft($data['proactive'], $record);
|
||||
if (array_key_exists('proactive', $data)) $data['proactive'] = app(ProactiveInvestment::class)->draft($data['proactive'], $record, $actor);
|
||||
$before = $record->getAttributes();
|
||||
if ($data['action'] === 'restore') {
|
||||
abort_unless($record->trashed() || $record->status === 'archived', 409, 'Registo não está eliminado/arquivado.');
|
||||
|
||||
@@ -16,12 +16,14 @@ final class ProactiveInvestment
|
||||
public const NOTICE = 'A ausência de registo não comprova ausência de oferta. Proximidade não comprova contrato, participação, energia acessível, terra disponível ou benefício fiscal. Necessidade confirmada não comprova viabilidade comercial; hipótese de fornecimento não é encomenda.';
|
||||
public const GROUPS = ['exists' => 'O que existe', 'needs' => 'Necessidades identificadas', 'ideas' => 'Ideias de investimento'];
|
||||
|
||||
public function draft(array $input, ?Opportunity $record = null): array
|
||||
public function draft(array $input, ?Opportunity $record = null, ?\App\Models\User $actor = null): array
|
||||
{
|
||||
$d = Validator::make(['proactive' => $input], [
|
||||
'proactive' => 'required|array:version,kind,evidence,need,idea,relations', 'proactive.version' => 'required|integer|in:1',
|
||||
'proactive' => 'required|array:version,kind,evidence,need,idea,relations,supply_comparisons', 'proactive.version' => 'required|integer|in:1',
|
||||
'proactive.kind' => 'required|in:exists,needs,ideas', 'proactive.evidence' => 'present|array|max:60',
|
||||
'proactive.evidence.*' => 'array:id,category,purpose,statement,interpretation,source,locator,period,scope,coverage,verified_on,access,document_id',
|
||||
'proactive.evidence.*' => 'array:id,category,purpose,statement,interpretation,source,locator,period,scope,coverage,verified_on,access,document_id,observation_id',
|
||||
'proactive.evidence.*.observation_id'=>'sometimes|nullable|string|size:64',
|
||||
'proactive.supply_comparisons'=>'sometimes|array|max:40',
|
||||
'proactive.evidence.*.id' => 'required|uuid|distinct',
|
||||
'proactive.evidence.*.category' => 'required|in:activity,resource,infrastructure,supply,demand',
|
||||
'proactive.evidence.*.purpose' => 'required|in:local,methodology',
|
||||
@@ -47,6 +49,19 @@ final class ProactiveInvestment
|
||||
'proactive.relations.*.reference' => 'required|string|max:4000',
|
||||
'proactive.relations.*.evidence_ids' => 'present|array|max:60', 'proactive.relations.*.evidence_ids.*' => 'uuid|distinct',
|
||||
])->validate()['proactive'];
|
||||
$actor??=auth()->user();
|
||||
if (!empty($d['supply_comparisons'])) $d['supply_comparisons']=app(ProactiveSupply::class)->comparisons($actor,$d['supply_comparisons'],$record);
|
||||
foreach($d['evidence'] as &$proof){
|
||||
if(!empty($proof['observation_id'])){
|
||||
$canonical=app(ProactiveSupply::class)->evidence($actor,$proof['observation_id'],$record);
|
||||
if($proof['access']!=='internal') $this->fail('evidence','A observação da base interna não pode ser reclassificada como pública.');
|
||||
$proof=array_replace($proof,$canonical);
|
||||
}
|
||||
}
|
||||
unset($proof);
|
||||
foreach($d['supply_comparisons']??[] as $comparison){
|
||||
if(!in_array($comparison['observation_id'],array_column($d['evidence'],'observation_id'),true))$this->fail('supply_comparisons','A comparação deve conservar a evidência interna da observação seleccionada.');
|
||||
}
|
||||
$ids = array_column($d['evidence'], 'id');
|
||||
foreach ([$d['need'], ...$d['relations']] as $row) {
|
||||
if (array_diff($row['evidence_ids'], $ids)) $this->fail('evidence', 'Seleccione apenas evidências desta análise.');
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/** Internal observations, never a public business directory or proof of demand. */
|
||||
final class ProactiveSupply
|
||||
{
|
||||
public const LIMITATIONS = 'Informação administrativa histórica e incompleta. Actividade actual, capacidade, procura e compromissos por confirmar. Ausência de registos significa informação insuficiente, nunca ausência de oferta.';
|
||||
|
||||
public function authorize(User $actor, ?Opportunity $record = null): void
|
||||
{
|
||||
$access=app(PortalProfileAccess::class);
|
||||
$internal=collect(OpportunityManagement::CATEGORIES)->contains(fn($type)=>$access->internalAssignment($actor,$type)!==null);
|
||||
abort_unless($access->legacyWriteAllowed($actor)||$internal,403);
|
||||
if ($record?->exists) $access->authorize($actor,'view',$record);
|
||||
}
|
||||
|
||||
private function read(User $actor, callable $callback): mixed
|
||||
{
|
||||
return DB::transaction(function()use($actor,$callback){
|
||||
DB::select("select set_config('app.actor_user_id',?,true),set_config('app.proactive_supply_read','internal',true)",[(string)$actor->id]);
|
||||
return $callback();
|
||||
});
|
||||
}
|
||||
|
||||
public function search(User $actor,array $input,?Opportunity $record=null): array
|
||||
{
|
||||
$this->authorize($actor,$record);
|
||||
$v=Validator::make($input,[
|
||||
'territory_id'=>['required','uuid',Rule::exists('geo_locations','id')->whereNull('deleted_at')],
|
||||
'activity'=>'nullable|string|max:150','sector'=>'nullable|string|max:250','page'=>'nullable|integer|min:1|max:100000',
|
||||
])->validate();
|
||||
if(!Schema::hasTable('proactive_supply_observations'))return ['installed'=>false,'rows'=>[],'total'=>null,'limitations'=>self::LIMITATIONS,'status'=>'Base interna ainda não carregada neste ambiente.'];
|
||||
return $this->read($actor,function()use($v){
|
||||
$ids=[$v['territory_id']];
|
||||
// Canonical descendants, not a name-only cross-province match.
|
||||
$front=$ids;
|
||||
for($depth=0;$depth<5&&$front;$depth++){
|
||||
$front=DB::table('geo_locations')->whereIn('parent_id',$front)->whereNull('deleted_at')->pluck('id')->all();
|
||||
$ids=[...$ids,...$front];
|
||||
}
|
||||
$base=DB::table('proactive_supply_observations as o')->join('proactive_supply_sources as s','s.sha256','=','o.source_hash')->whereIn('o.territory_id',$ids);
|
||||
$sectors=(clone $base)->where('o.sector','<>','')->distinct()->orderBy('o.sector')->pluck('o.sector')->all();
|
||||
if(!empty($v['sector']))$base->where('o.sector',$v['sector']);
|
||||
if(!empty($v['activity']))$base->where(fn($q)=>$q->where('o.cae','ilike','%'.$v['activity'].'%')->orWhereRaw("translate(lower(o.activity),'áàâãéêíóôõúç','aaaaeeiooouc') LIKE ?",['%'.strtolower(\Illuminate\Support\Str::ascii($v['activity'])).'%']));
|
||||
$page=$v['page']??1;
|
||||
// Exact repeated observations are retained in storage, counted separately.
|
||||
$total=(clone $base)->whereNull('o.duplicate_of')->count();
|
||||
$duplicates=(clone $base)->whereNotNull('o.duplicate_of')->count();
|
||||
$rows=(clone $base)->whereNull('o.duplicate_of')->orderBy('o.name')->orderBy('o.id')->offset(($page-1)*25)->limit(25)->get(['o.id','o.entity_key','o.name','o.province','o.district','o.territory_id','o.territory_resolution','o.cae','o.activity','o.sector','o.source_date','o.sheet','o.row_number','o.source_hash','o.identity_conflict','s.name as source_name','s.period as source_period','s.imported_at']);
|
||||
$coverage=DB::table('proactive_supply_observations')->selectRaw("count(*) FILTER (WHERE territory_id IS NULL) AS unmapped, count(*) FILTER (WHERE territory_resolution='province_only_district_unknown') AS province_only")->first();
|
||||
return ['installed'=>true,'rows'=>$rows,'total'=>$total,'duplicate_sightings'=>$duplicates,'page'=>$page,'per_page'=>25,'sectors'=>$sectors,'territory_coverage'=>$coverage,'limitations'=>self::LIMITATIONS,'status'=>$total?'Registos documentais encontrados; não equivalem a empresas únicas ou oferta actual confirmada.':'Informação insuficiente nesta base e nestes filtros.'];
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve server-side source lineage; a caller cannot fabricate an internal observation. */
|
||||
public function comparisons(User $actor,array $input,?Opportunity $record): array
|
||||
{
|
||||
$this->authorize($actor,$record);
|
||||
$v=Validator::make(['rows'=>$input],[
|
||||
'rows'=>'array|max:40','rows.*'=>'array:observation_id,relationship,rationale,limitations',
|
||||
'rows.*.observation_id'=>'required|string|size:64|distinct',
|
||||
'rows.*.relationship'=>'required|in:competition,complementarity,partner,uncertain',
|
||||
'rows.*.rationale'=>'required|string|max:4000','rows.*.limitations'=>'required|string|max:4000',
|
||||
])->validate()['rows'];
|
||||
if(!$v)return [];
|
||||
abort_unless(Schema::hasTable('proactive_supply_observations'),422,'Base interna indisponível.');
|
||||
return $this->read($actor,function()use($v){
|
||||
foreach($v as $row){
|
||||
$o=DB::table('proactive_supply_observations')->where('id',$row['observation_id'])->first();
|
||||
if(!$o)throw \Illuminate\Validation\ValidationException::withMessages(['proactive.supply_comparisons'=>'Registo da oferta indisponível; preserve a referência anterior e confira o ambiente.']);
|
||||
}
|
||||
return $v;
|
||||
});
|
||||
}
|
||||
|
||||
public function evidence(User $actor,string $id,?Opportunity $record): array
|
||||
{
|
||||
$this->authorize($actor,$record);
|
||||
return $this->read($actor,function()use($id){
|
||||
$o=DB::table('proactive_supply_observations as o')->join('proactive_supply_sources as s','s.sha256','=','o.source_hash')->where('o.id',$id)->first(['o.*','s.name as source_name','s.period as source_period']);
|
||||
if(!$o)throw \Illuminate\Validation\ValidationException::withMessages(['proactive.evidence'=>'Observação interna indisponível neste ambiente.']);
|
||||
return ['observation_id'=>$o->id,'category'=>'supply','purpose'=>'local','access'=>'internal','document_id'=>null,
|
||||
'statement'=>'Registo administrativo: '.$o->name.'; CAE '.$o->cae.'; '.($o->activity?:'actividade por classificar').'; '.$o->district.', '.$o->province.'. Não confirma actividade actual.',
|
||||
'source'=>$o->source_name.'; SHA256 '.$o->source_hash,'locator'=>$o->sheet.'!linha '.$o->row_number,
|
||||
'period'=>$o->source_date.'; '.$o->source_period,'scope'=>$o->district.', '.$o->province,
|
||||
'coverage'=>self::LIMITATIONS.($o->identity_conflict?' Identificador partilhado por denominações divergentes: identidade por conferir.':''),
|
||||
];
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user