@@ -148,24 +148,64 @@ class OpportunityCanonicalContract
|
||||
$data = $this->schemaData($payload, $schema['$defs']['opportunityCreate'], $schema['$defs']);
|
||||
$result = $validator->validate($data, json_decode(json_encode($schema, JSON_THROW_ON_ERROR)));
|
||||
if ($error = $result->error()) {
|
||||
$errors = [];
|
||||
foreach ((new ErrorFormatter)->format($error) as $path => $messages) {
|
||||
$errors['canonical'.str_replace('/', '.', $path)] = $messages;
|
||||
throw ValidationException::withMessages($this->schemaValidationErrors($error));
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string,list<string>> */
|
||||
private function schemaValidationErrors(ValidationError $error): array
|
||||
{
|
||||
$errors = [];
|
||||
$formatter = new ErrorFormatter;
|
||||
$collect = function (ValidationError $node) use (&$collect, &$errors, $formatter): void {
|
||||
if ($node->subErrors() !== []) {
|
||||
foreach ($node->subErrors() as $child) {
|
||||
$collect($child);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
$required = function (ValidationError $node) use (&$required, &$errors): void {
|
||||
if ($node->keyword() === 'required') {
|
||||
$prefix = 'canonical.'.implode('.', $node->data()->fullPath());
|
||||
foreach ($node->args()['missing'] ?? [] as $field) {
|
||||
$errors[rtrim($prefix, '.').'.'.$field] = ['Preencha este campo antes de submeter.'];
|
||||
$prefix = rtrim('canonical.'.implode('.', $node->data()->fullPath()), '.');
|
||||
$args = $node->args();
|
||||
if ($node->keyword() === 'required') {
|
||||
foreach ($args['missing'] ?? [] as $field) {
|
||||
$errors[$prefix.'.'.$field][] = 'Preencha este campo antes de submeter.';
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
if ($node->keyword() === 'additionalProperties') {
|
||||
$definition = $node->schema()->info()->data();
|
||||
$declared = is_object($definition) ? (array) ($definition->properties ?? []) : [];
|
||||
foreach ($args['properties'] ?? [] as $field) {
|
||||
// Opis can report declared properties as unchecked after a sibling field fails.
|
||||
// Keep real unknown-property errors without turning valid fields into errors.
|
||||
if (! array_key_exists($field, $declared)) {
|
||||
$errors[$prefix.'.'.$field][] = 'Campo não previsto no contrato desta categoria.';
|
||||
}
|
||||
}
|
||||
foreach ($node->subErrors() as $child) {
|
||||
$required($child);
|
||||
}
|
||||
};
|
||||
$required($error);
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
if ($node->keyword() === 'minLength') {
|
||||
$errors[$prefix][] = 'Preencha este campo com pelo menos '.$args['min'].' caracteres; tem '.$args['length'].'.';
|
||||
|
||||
return;
|
||||
}
|
||||
if ($node->keyword() === 'maxLength') {
|
||||
$errors[$prefix][] = 'Este campo admite até '.$args['max'].' caracteres; tem '.$args['length'].'.';
|
||||
|
||||
return;
|
||||
}
|
||||
foreach ($formatter->format($node) as $path => $messages) {
|
||||
$key = rtrim('canonical'.str_replace('/', '.', $path), '.');
|
||||
$errors[$key] = array_values(array_unique([...($errors[$key] ?? []), ...$messages]));
|
||||
}
|
||||
};
|
||||
$collect($error);
|
||||
|
||||
// Formatting must never make an invalid schema result acceptable.
|
||||
return $errors ?: ['canonical' => ['Não foi possível validar o contrato. Reveja os campos preenchidos.']];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $node
|
||||
@@ -246,6 +286,13 @@ class OpportunityCanonicalContract
|
||||
}
|
||||
} else {
|
||||
$location = $row->payload;
|
||||
// §10.2 area/unit consistency applies at submission. Resource drafts may
|
||||
// retain incomplete measurements; never invent a unit or convert values.
|
||||
$hasArea = isset($location['area_value']);
|
||||
$hasUnit = isset($location['area_unit']) && $location['area_unit'] !== '';
|
||||
$check(! $hasArea || $hasUnit, "locations.$index.area_unit", 'Indique a unidade da área antes de submeter; a preparação incompleta continua guardada nos recursos.');
|
||||
$check(! $hasUnit || $hasArea, "locations.$index.area_value", 'Indique o valor da área antes de submeter; a unidade não determina o valor.');
|
||||
$check(! $hasUnit || in_array($location['area_unit'], OpportunityResources::AREA_UNITS, true), "locations.$index.area_unit", 'Use uma unidade do catálogo existente: sqm, ha ou sqkm.');
|
||||
$check(! empty($location['district_id']) && ! empty($location['role']) && array_key_exists('is_primary', $location), "locations.$index", 'Localização requer distrito, papel e indicação de principal.');
|
||||
app(InvestmentGeography::class)->selection($location, true);
|
||||
$country = $location['country_code'] ?? null;
|
||||
@@ -492,10 +539,13 @@ class OpportunityCanonicalContract
|
||||
->orWhereExists(fn ($i) => $i->selectRaw('1')->from('investor_contacts as ic')->join('investors as inv', 'inv.id', '=', 'ic.investor_id')->whereColumn('ic.contact_id', 'contacts.id')->whereIn('inv.organization_id', $orgs)->whereNull('inv.deleted_at'));
|
||||
})->get(['id', 'full_name']);
|
||||
|
||||
$submissionProperties = $this->schema(false)['$defs']['opportunityCreate']['properties'];
|
||||
|
||||
return ['version' => self::VERSION, 'modularProfiles' => app(OpportunityModularProfiles::class)->enabled() ? OpportunityModularProfiles::PROFILES : [],
|
||||
'historyVersion' => app(OpportunityModularProfiles::class)->enabled() ? OpportunityModularProfiles::HISTORY_VERSION : null,
|
||||
'schema' => $this->schema(true)['$defs']['opportunityCreate'],
|
||||
'definitions' => $this->schema(true)['$defs'],
|
||||
'submissionTextLimits' => ['demand_statement' => array_intersect_key($submissionProperties['demand_statement'], array_flip(['minLength', 'maxLength']))],
|
||||
'activities' => DB::table('economic_activities')->where('status', 'published')->get(['id', 'parent_id', 'sector_id', 'label_pt_mz', 'catalog_version_id']),
|
||||
'contacts' => $contacts, 'contactInvestors' => $record?->organization_id ? DB::table('investors')->where('organization_id', $record->organization_id)->whereNull('deleted_at')->whereIn('status', ['prospect', 'active'])->get(['id', 'legal_name']) : [],
|
||||
'countries' => app(CountryCatalogue::class)->all(),
|
||||
|
||||
Reference in New Issue
Block a user