commit16
This commit is contained in:
@@ -187,8 +187,12 @@ class VirtualDesk
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
$base = $this->decode($case->payload);
|
||||
$payload = ['title' => $case->title, 'description' => $base['investment']['objective'] ?? '', 'regime' => 'unknown'];
|
||||
if (config('investor-path.enabled') && $case->simulation_id && (int) $case->user_id === $actor->id) {
|
||||
$serviceFields = json_decode($service->definition, true)['fields'];
|
||||
$payload = Arr::only(['title' => $case->title, 'description' => $base['investment']['objective'] ?? ''], array_keys($serviceFields));
|
||||
if (isset($serviceFields['regime']['options']['unknown'])) {
|
||||
$payload['regime'] = 'unknown';
|
||||
}
|
||||
if (isset($serviceFields['description']) && config('investor-path.enabled') && $case->simulation_id && (int) $case->user_id === $actor->id) {
|
||||
$draftRequest = Request::create('/');
|
||||
$draftRequest->setUserResolver(fn () => $actor);
|
||||
$draft = app(SimulationFormDrafts::class)->find($case->simulation_id, $draftRequest);
|
||||
@@ -197,7 +201,7 @@ class VirtualDesk
|
||||
$this->event($case, $actor, 'request_prefill_prepared', ['draft_id' => $draft->id, 'draft_version' => $draft->version_no, 'snapshot_sha256' => $draft->snapshot_sha256, 'fields' => ['title', 'description']]);
|
||||
}
|
||||
$context = app(InvestorContext::class)->state($case);
|
||||
if (count($context['opportunity_choices'] ?? []) > 1 && ! $opportunity) {
|
||||
if (isset($serviceFields['description']) && count($context['opportunity_choices'] ?? []) > 1 && ! $opportunity) {
|
||||
$payload['description'] = '';
|
||||
}
|
||||
$mapped = app(InvestorContext::class)->prefill($context, $opportunity)['desk'];
|
||||
@@ -205,9 +209,9 @@ class VirtualDesk
|
||||
$payload['context_opportunity'] = $opportunity;
|
||||
}
|
||||
$payload = app(InvestmentConsumerScope::class)->bind($actor, $caseId, $payload);
|
||||
$serviceFields = json_decode($service->definition, true)['fields'];
|
||||
foreach (['territory_id' => 'territory_id', 'location_source' => 'location_source', 'title' => 'title', 'description' => 'description', 'sector' => 'sector', 'province_id' => 'province_id', 'district_id' => 'district_id', 'admin_post_id' => 'admin_post_id', 'locality_id' => 'locality_id'] as $field => $source) {
|
||||
if (isset($serviceFields[$field],$mapped[$source]) && (empty($payload[$field]) || in_array($field, ['title', 'description'], true) && $context['revision'] > 0)) {
|
||||
if (isset($serviceFields[$field],$mapped[$source]) && (empty($payload[$field]) || in_array($field, ['title', 'description'], true) && $context['revision'] > 0)
|
||||
&& Validator::make(['value' => $mapped[$source]], ['value' => $this->fieldRules($serviceFields[$field], false)])->passes()) {
|
||||
$payload[$field] = $mapped[$source];
|
||||
}
|
||||
}
|
||||
@@ -272,25 +276,22 @@ class VirtualDesk
|
||||
'payload.country' => ['nullable', 'string', 'max:100', app(CountryCatalogue::class)->legacyCountryRule()],
|
||||
'payload.declared_origin_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()]];
|
||||
foreach ($definition['fields'] as $key => $field) {
|
||||
$active = ! isset($field['when']) || ($payload[$field['when']['field']] ?? null) === $field['when']['equals'];
|
||||
$active = $this->fieldApplies((string) $key, $definition['fields'], $payload);
|
||||
$required = $submitting && ($field['required'] ?? false) && $active;
|
||||
$rule = [$required ? 'required' : 'nullable'];
|
||||
$rule = [...$rule, ...match ($field['type']) {
|
||||
'number' => ['numeric', 'decimal:0,2', 'min:'.($field['min'] ?? 0), 'max:999999999999'], 'date' => ['date_format:Y-m-d'],
|
||||
'select' => [Rule::in(array_keys($field['options']))], 'territory' => ['uuid'],
|
||||
default => ['string', 'max:'.($field['type'] === 'textarea' ? 15000 : 1000)],
|
||||
}];
|
||||
$rules['payload.'.$key] = $rule;
|
||||
$rules['payload.'.$key] = $this->fieldRules($field, $required);
|
||||
}
|
||||
$validated = Validator::make(['payload' => $payload], $rules)->validate()['payload'];
|
||||
foreach ($definition['fields'] as $key => $field) {
|
||||
if ($field['type'] === 'select' && isset($validated[$key])) {
|
||||
$validated[$key] = (string) $validated[$key];
|
||||
}
|
||||
if ($field['type'] === 'territory' && ! empty($validated[$key])) {
|
||||
if (! app(InvestmentGeography::class)->publicReferences()->where('id', $validated[$key])->exists()) {
|
||||
throw ValidationException::withMessages(['payload.'.$key => 'Seleccione uma localização disponível no cadastro territorial.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($validated['territory_id'] ?? null) {
|
||||
if (($validated['territory_id'] ?? null) && $this->fieldApplies('territory_id', $definition['fields'], $validated)) {
|
||||
if ($submitting && trim($validated['location_source'] ?? '') === '') {
|
||||
throw ValidationException::withMessages(['payload.location_source' => 'Indique a fonte da localização.']);
|
||||
}
|
||||
@@ -299,11 +300,56 @@ class VirtualDesk
|
||||
return $validated;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $field
|
||||
* @return list<mixed> */
|
||||
private function fieldRules(array $field, bool $required): array
|
||||
{
|
||||
return [$required ? 'required' : 'nullable', ...match ($field['type']) {
|
||||
'number' => ['numeric', 'decimal:0,2', 'min:'.($field['min'] ?? 0), 'max:999999999999'], 'date' => ['date_format:Y-m-d'],
|
||||
'select' => [Rule::in(array_keys($field['options']))], 'territory' => ['uuid'],
|
||||
'email' => ['string', 'email', 'max:1000'], 'url' => ['string', 'url:http,https', 'max:1000'],
|
||||
default => ['string', 'max:'.($field['type'] === 'textarea' ? 15000 : 1000)],
|
||||
}];
|
||||
}
|
||||
|
||||
/** @param array<string,array<string,mixed>> $fields
|
||||
* @param array<string,mixed> $payload
|
||||
* @param array<string,bool> $ancestors */
|
||||
private function fieldApplies(string $key, array $fields, array $payload, array $ancestors = []): bool
|
||||
{
|
||||
$field = $fields[$key] ?? null;
|
||||
if (! $field || isset($ancestors[$key])) {
|
||||
return false;
|
||||
}
|
||||
if (! isset($field['when'])) {
|
||||
return true;
|
||||
}
|
||||
$parent = $field['when']['field'];
|
||||
$answer = $payload[$parent] ?? null;
|
||||
if (! is_scalar($answer) || (string) $answer !== $field['when']['equals']) {
|
||||
return false;
|
||||
}
|
||||
$ancestors[$key] = true;
|
||||
|
||||
return $this->fieldApplies($parent, $fields, $payload, $ancestors);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload
|
||||
* @param array<string,mixed> $definition
|
||||
* @return array<string,array<string,mixed>> */
|
||||
public function applicableFields(array $payload, array $definition): array
|
||||
{
|
||||
return array_filter($definition['fields'], fn ($key) => $this->fieldApplies((string) $key, $definition['fields'], $payload), ARRAY_FILTER_USE_KEY);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload
|
||||
* @param array<string,mixed> $definition
|
||||
* @return list<array<string,mixed>> */
|
||||
public function findings(array $payload): array
|
||||
public function findings(array $payload, array $definition): array
|
||||
{
|
||||
$findings = [];
|
||||
$fields = $this->applicableFields($payload, $definition);
|
||||
$financeApplies = isset($fields['investment_amount'], $fields['own_finance'], $fields['other_finance']);
|
||||
$amounts = array_map(function ($key) use ($payload) {
|
||||
$value = (string) ($payload[$key] ?? '');
|
||||
if (! preg_match('/^\d{1,12}(?:\.\d{1,2})?$/', $value)) {
|
||||
@@ -313,13 +359,13 @@ class VirtualDesk
|
||||
|
||||
return (int) $whole * 100 + (int) str_pad($fraction, 2, '0');
|
||||
}, ['investment_amount', 'own_finance', 'other_finance']);
|
||||
if (! in_array(null, $amounts, true) && $amounts[0] !== $amounts[1] + $amounts[2]) {
|
||||
if ($financeApplies && ! in_array(null, $amounts, true) && $amounts[0] !== $amounts[1] + $amounts[2]) {
|
||||
$findings[] = ['code' => 'finance_difference', 'severity' => 'error', 'field' => 'investment_amount', 'explanation' => 'A soma do financiamento difere do valor do investimento.', 'recommendation' => 'Confirme valores e moeda.', 'method' => 'deterministic', 'confidence' => null];
|
||||
}
|
||||
if (in_array(null, $amounts, true)) {
|
||||
if ($financeApplies && in_array(null, $amounts, true)) {
|
||||
$findings[] = ['code' => 'finance_unknown', 'severity' => 'warning', 'field' => 'investment_amount', 'explanation' => 'A coerência do financiamento permanece indeterminada sem os três valores válidos na mesma moeda.', 'recommendation' => 'Complete as fontes de financiamento; valores ausentes não são zero.', 'method' => 'deterministic', 'confidence' => null];
|
||||
}
|
||||
if (! ($payload['territory_id'] ?? null)) {
|
||||
if (isset($fields['territory_id']) && ! ($payload['territory_id'] ?? null)) {
|
||||
$findings[] = ['code' => 'location_unknown', 'severity' => 'warning', 'field' => 'territory_id', 'explanation' => 'Localização ainda não documentada.', 'recommendation' => 'Complete quando houver fonte.', 'method' => 'deterministic', 'confidence' => null];
|
||||
}
|
||||
$findings[] = ['code' => 'official_form_pending', 'severity' => 'warning', 'field' => null, 'explanation' => 'Adaptação digital do plano; não foi identificada uma versão oficial homologada do formulário APIEX no acervo.', 'recommendation' => 'A preparação e análise interna continuam disponíveis; confirme a versão exigida pela entidade para o ato oficial.', 'method' => 'documentary', 'confidence' => null];
|
||||
@@ -364,7 +410,7 @@ class VirtualDesk
|
||||
}
|
||||
abort_if($submit && trim($data['reason'] ?? '') === '', 422, 'Justifique a correção.');
|
||||
}
|
||||
$findings = $this->findings($payload);
|
||||
$findings = $this->findings($payload, $this->definition($request));
|
||||
if ($submit && array_filter($findings, fn ($f) => $f['severity'] === 'error')) {
|
||||
throw ValidationException::withMessages(['payload.investment_amount' => $findings[0]['explanation']]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user