-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
373 lines (321 loc) · 16.7 KB
/
Copy pathserver.js
File metadata and controls
373 lines (321 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
const express = require('express');
const path = require('path');
const fs = require('fs/promises');
const fsSync = require('fs');
const fetch = require('node-fetch');
// --- Helpers de Utilidad ---
async function fetchWithTimeout(url, options = {}, timeout = 18000) { // Aumentado para prompts complejos
const controller = new AbortController();
options.signal = controller.signal;
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, options);
clearTimeout(timeoutId);
return response;
} catch (error) {
clearTimeout(timeoutId);
if (error.name === 'AbortError') {
throw new Error(`Request timed out after ${timeout / 1000} seconds`);
}
throw error;
}
}
function cleanModelJsonString(raw) {
if (!raw || typeof raw !== 'string') return raw;
let s = raw.replace(/^\uFEFF/, '').trim();
s = s.replace(/^```(?:json)?\n?/, '');
s = s.replace(/\n?```$/, '');
return s.trim();
}
function tryParseModelJson(raw) {
const cleaned = cleanModelJsonString(raw);
try {
return JSON.parse(cleaned);
} catch (e) {
console.error("Fallo al parsear JSON, intentando limpiar:", cleaned);
throw new Error('No se pudo parsear JSON del modelo: ' + e.message);
}
}
async function getApiKey() {
const apiKey = process.env.GEMINI_API_KEY;
if (apiKey) return apiKey;
const keyPath = path.join(__dirname, 'credencialgemini');
if (fsSync.existsSync(keyPath)) {
const txt = await fs.readFile(keyPath, 'utf-8');
const m = txt.match(/AIza[A-Za-z0-9_-]{35}/);
if (m) return m[0];
}
throw new Error('API Key de Gemini no encontrada.');
}
// --- NUEVA ARQUITECTURA DE LLAMADAS A LA IA ---
async function loadContext(filePath) {
try {
return await fs.readFile(path.join(__dirname, 'conocimientos', filePath), 'utf-8');
} catch (error) {
console.warn(`Advertencia: No se pudo cargar el contexto: ${filePath}`);
return '';
}
}
// Extrae las notas legales de la sección y capítulo específico
function extractLegalNotes(fullText, sectionRomano, chapterNumber) {
let extracted = "";
// Buscar Sección
if (sectionRomano) {
const sectionRegex = new RegExp(`SECCIÓN ${sectionRomano}:[\\s\\S]*?(?=SECCIÓN |$)`, 'i');
const sectionMatch = fullText.match(sectionRegex);
if (sectionMatch) {
const chapterStart = sectionMatch[0].search(/CAPÍTULO \d+:/i);
if (chapterStart !== -1) {
extracted += sectionMatch[0].substring(0, chapterStart).trim() + "\n\n";
} else {
extracted += sectionMatch[0].trim() + "\n\n";
}
}
}
// Buscar Capítulo
if (chapterNumber) {
const chapterRegex = new RegExp(`CAPÍTULO ${chapterNumber}:[\\s\\S]*?(?=CAPÍTULO \\d+:|SECCIÓN |$)`, 'i');
const chapterMatch = fullText.match(chapterRegex);
if (chapterMatch) {
extracted += chapterMatch[0].trim();
}
}
return extracted || "Notas legales no encontradas para esta sección/capítulo en el resumen.";
}
async function callGemini(prompt, apiKey) {
const modelName = 'gemini-2.5-flash-lite'; // MODELO CORREGIDO Y FIJADO
const geminiUrl = `https://generativelanguage.googleapis.com/v1/models/${modelName}:generateContent?key=${apiKey}`; // API v1 CORREGIDA
const response = await fetchWithTimeout(geminiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
temperature: 0.1,
maxOutputTokens: 8192,
// response_mime_type: "application/json", // Eliminado para compatibilidad con v1
}
})
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`Error en la API de Gemini ${response.status}: ${errorBody}`);
}
const rawData = await response.json();
const candidateText = rawData?.candidates?.[0]?.content?.parts?.[0]?.text;
if (!candidateText) {
console.error("Respuesta de Gemini sin contenido:", JSON.stringify(rawData));
throw new Error('La API de Gemini no devolvió contenido válido.');
}
return tryParseModelJson(candidateText);
}
// 1. Clasificación
async function callClassification(apiKey, description, notes, clarificationAnswers = "") {
const promptTemplate = await fs.readFile(path.join(__dirname, 'prompts', 'prompt_clasificacion.txt'), 'utf-8');
const rgiContext = await loadContext('razonamiento_rgi_avanzado.txt');
const grutecaContext = await loadContext('criterios_gruteca_caaarem.txt');
const nicaContext = await loadContext('doctrina_dga_nicaragua.txt');
const prompt = promptTemplate
.replace('{RGI_CONTEXT}', rgiContext)
.replace('{GRUTECA_CONTEXT}', grutecaContext)
.replace('{NICA_CONTEXT}', nicaContext)
.replace('{DESCRIPTION}', description)
.replace('{NOTES}', notes)
.replace('{CLARIFICATION_ANSWERS}', clarificationAnswers);
return callGemini(prompt, apiKey);
}
// 2. Base Legal
async function callLegalBasis(apiKey, codigo) {
const promptTemplate = await fs.readFile(path.join(__dirname, 'prompts', 'prompt_base_legal.txt'), 'utf-8');
const legalContext = `${await loadContext('jurisprudencia_tata_dga.txt')}\n\n${await loadContext('contexto_legal_sac.txt')}`;
const notesTypeContext = await loadContext('tipos-de-notas.json');
const prompt = promptTemplate
.replace('{LEGAL_CONTEXT}', legalContext)
.replace('{NOTES_TYPE_CONTEXT}', notesTypeContext)
.replace('{CODIGO}', codigo);
return callGemini(prompt, apiKey);
}
// 3. Regulaciones
async function callRegulatoryAnalysis(apiKey, description) {
const promptTemplate = await fs.readFile(path.join(__dirname, 'prompts', 'prompt_regulaciones.txt'), 'utf-8');
const regulatoryContext = await loadContext('analisis_riesgo_tecnico_comercial.txt');
const prompt = promptTemplate.replace('{REGULATORY_CONTEXT}', regulatoryContext).replace('{DESCRIPTION}', description);
return callGemini(prompt, apiKey);
}
// 4. Riesgo de Mercancía
async function callCustomsRiskAnalysis(apiKey, description) {
const promptTemplate = await fs.readFile(path.join(__dirname, 'prompts', 'prompt_riesgo_mercancia.txt'), 'utf-8');
const riskContext = await loadContext('gestion_riesgos_aduaneros_ni.txt');
const prompt = promptTemplate.replace('{RISK_CONTEXT}', riskContext).replace('{DESCRIPTION}', description);
return callGemini(prompt, apiKey);
}
// 5. Optimización Arancelaria
async function callTariffOptimization(apiKey, codigo, origen, perfilImportador) {
const promptTemplate = await fs.readFile(path.join(__dirname, 'prompts', 'prompt_optimizacion_arancelaria.txt'), 'utf-8');
const tariffContext = await loadContext('regimenes_preferenciales_ni.txt');
const prompt = promptTemplate.replace('{TARIFF_CONTEXT}', tariffContext).replace('{CODIGO}', codigo).replace('{ORIGEN}', origen).replace('{PERFIL_IMPORTADOR}', perfilImportador);
return callGemini(prompt, apiKey);
}
// --- Orquestador y Formateador ---
async function generateReportFlow(description, notes, origen, perfilImportador, clarificationAnswers = "") {
const apiKey = await getApiKey();
const fullReport = {};
console.log("Iniciando Paso 1: Clasificación" + (clarificationAnswers ? " (con aclaraciones)..." : "..."));
fullReport.classification = await callClassification(apiKey, description, notes, clarificationAnswers);
// Retorno anticipado si la IA necesita aclaración del usuario
if (fullReport.classification?.necesitaAclaracion) {
console.log("La IA requiere aclaración del usuario. Retornando preguntas.");
return fullReport;
}
const codigo = fullReport.classification?.clasificacionPropuesta?.codigo;
if (!codigo) {
console.warn("No se obtuvo un código arancelario válido. Análisis cancelado.");
throw new Error('No se pudo obtener el código arancelario final.');
}
console.log(`Paso 1 completado. Código propuesto: ${codigo}. Iniciando análisis paralelos...`);
const [legal, regulatory, risk, tariff] = await Promise.all([
callLegalBasis(apiKey, codigo).catch(e => ({ error: e.message })),
callRegulatoryAnalysis(apiKey, description).catch(e => ({ error: e.message })),
callCustomsRiskAnalysis(apiKey, description).catch(e => ({ error: e.message })),
callTariffOptimization(apiKey, codigo, origen, perfilImportador).catch(e => ({ error: e.message }))
]);
console.log("Pasos 2-5 completados.");
fullReport.legal = legal;
fullReport.regulatory = regulatory;
fullReport.risk = risk;
fullReport.tariff = tariff;
return fullReport;
}
function reportToUI(report) {
const parts = [];
const addSection = (title, content) => parts.push(`\n### ${title}\n${content}`);
if (report.classification?.clasificacionPropuesta) {
const { codigo, descripcion } = report.classification.clasificacionPropuesta;
const { scoreFiabilidad, argumentoMerciologico } = report.classification;
addSection('1. Análisis de Clasificación Arancelaria',
`**Código Propuesto:** ${codigo || 'N/A'}\n` +
`**Descripción:** ${descripcion || 'N/A'}\n` +
`**Fiabilidad:** ${scoreFiabilidad ? Math.round(scoreFiabilidad * 100) + '%' : 'N/A'}\n` +
`**Argumento Merciológico:**\n${argumentoMerciologico || 'N/A'}`
);
}
if (report.legal && !report.legal.error) {
const { applied_rules, notes_applied, jurisprudencia } = report.legal.fundamentoLegal;
let content = '';
if (applied_rules?.length > 0) content += '**Reglas Generales Aplicadas:**\n' + applied_rules.map(r => `- **${r.rule_id}:** ${r.descripcion}`).join('\n') + '\n';
if (notes_applied?.length > 0) content += '**Notas de Sección/Capítulo:**\n' + notes_applied.map(n => `- **${n.note_id} (${n.tipo || 'N/A'}):** ${n.descripcion}`).join('\n') + '\n';
if (jurisprudencia?.length > 0) content += '**Jurisprudencia Relevante (TATA):**\n' + jurisprudencia.map(j => `- **${j.case_id}:** ${j.summary}`).join('\n') + '\n';
if (content) addSection('2. Fundamento Legal y Jurisprudencia', content);
}
if (report.regulatory && !report.regulatory.error) {
const { institucionPrincipal, requisitos } = report.regulatory.analisisRegulatorio;
if (requisitos?.length > 0) {
let content = `**Institución Principal Sugerida:** ${institucionPrincipal || 'N/A'}\n**Requisitos y Permisos:**\n` + requisitos.map(r => `- **${r.nombre} (${r.institucion}):** ${r.detalle}`).join('\n');
addSection('3. Análisis Regulatorio (Permisos y Barreras)', content);
}
}
if (report.risk && !report.risk.error) {
const { analisisRiesgoMercancia } = report.risk;
if (analisisRiesgoMercancia?.length > 0) {
let content = analisisRiesgoMercancia.map(r => `**${r.riesgoIdentificado}:** ${r.justificacion}\n *Recomendación:* ${r.recomendacion}`).join('\n\n');
addSection('4. Análisis de Riesgo Inherente a la Mercancía', content);
}
}
if (report.tariff && !report.tariff.error) {
const { regimenSugerido, cumpleOrigenPotencial, justificacionOrigen, comparativaArancelaria, recomendacionEstrategica } = report.tariff.analisisOptimizacion;
if (regimenSugerido) {
let content = `**Régimen Sugerido:** ${regimenSugerido}\n` +
`**Cumple Origen Potencial:** ${cumpleOrigenPotencial}\n` +
`*Justificación:* ${justificacionOrigen}\n\n` +
`**Comparativa:**\n- Arancel Normal (NMF): ${comparativaArancelaria.arancelNMF}\n- Arancel Preferencial: ${comparativaArancelaria.arancelPreferencial}\n` +
`**Ahorro Potencial:** ${comparativaArancelaria.ahorroPotencial}\n\n` +
`**Recomendación Estratégica:** ${recomendacionEstrategica}`;
addSection('5. Análisis de Optimización Arancelaria', content);
}
}
// Sección final de resumen
if (parts.length > 0) {
const summary = `El análisis sugiere la clasificación en el código ${report.classification?.clasificacionPropuesta?.codigo || '[no determinado]'}. Se identificaron ${report.regulatory?.analisisRegulatorio?.requisitos?.length || 0} requisitos regulatorios y ${report.risk?.analisisRiesgoMercancia?.length || 0} riesgos inherentes. Se recomienda ${report.tariff?.analisisOptimizacion?.recomendacionEstrategica || 'revisar la documentación para asegurar el cumplimiento'}.`;
addSection('### Dictamen Técnico Preliminar (No Vinculante)', summary);
}
return { ui_text: parts.join('\n') };
}
// --- Servidor Express y Endpoints ---
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'templates', 'index.html'));
});
app.post('/api/find-sac-chapter', async (req, res) => {
try {
const { description } = req.body;
if (!description) return res.status(400).json({ error: 'La descripción no puede estar vacía.' });
const apiKey = await getApiKey();
const indiceText = await loadContext('secciones-capitulos.json');
const legalNotesText = await loadContext('resumen_notas_legales_sac.txt');
const grutecaContext = await loadContext('criterios_gruteca_caaarem.txt');
const nicaContext = await loadContext('doctrina_dga_nicaragua.txt');
const promptTemplate = await fs.readFile(path.join(__dirname, 'prompts', 'prompt_ubicacion.txt'), 'utf-8');
const prompt = promptTemplate
.replace('{LEGAL_NOTES_CONTEXT}', legalNotesText)
.replace('{INDICE_CONTEXT}', indiceText)
.replace('{GRUTECA_CONTEXT}', grutecaContext)
.replace('{NICA_CONTEXT}', nicaContext)
.replace('{DESCRIPTION}', description);
const aiResult = await callGemini(prompt, apiKey);
const chapterNumber = aiResult.chapter_number;
if (!chapterNumber) return res.status(404).json({ error: 'El modelo no pudo determinar un capítulo.' });
const sectionsData = JSON.parse(indiceText);
let foundSection = null, foundChapter = null;
let romanSection = aiResult.seccion_number || "";
for (const section of sectionsData) {
const chapter = section.chapters.find(c => c.number == chapterNumber);
if (chapter) {
foundSection = section;
foundChapter = chapter;
if (!romanSection) {
// Tratar de extraer el número romano del texto de la sección: "SECCIÓN II: PRODUCTOS..."
const match = section.name.match(/SECCIÓN\s+([IXV]+)\b/i);
if (match) romanSection = match[1];
}
break;
}
}
if (!foundChapter) return res.status(404).json({ error: `Capítulo ${chapterNumber} no encontrado.` });
const extractedNotes = extractLegalNotes(legalNotesText, romanSection, chapterNumber);
res.status(200).json({
section: foundSection.name.split(':')[0],
chapter: foundChapter.name,
chapter_number: foundChapter.number,
rationale: aiResult.rationale,
extractedNotes: extractedNotes,
notasSugeridas: aiResult.notasSugeridas
});
} catch (error) {
console.error('Error en /api/find-sac-chapter:', error.stack || error);
res.status(500).json({ error: 'Error interno en el servidor.', message: error.message });
}
});
app.post('/api/generate-report', async (req, res) => {
try {
const { description, notes, origen, perfilImportador, clarificationAnswers } = req.body;
if (!description) return res.status(400).json({ error: 'La descripción es obligatoria.' });
const finalReport = await generateReportFlow(description, notes, origen || 'No especificado', perfilImportador || 'General', clarificationAnswers || "");
// Enviar el objeto de informe completo y estructurado
res.status(200).json({
ok: true,
report: finalReport
});
} catch (error) {
console.error('Error fatal en /api/generate-report:', error.stack || error);
res.status(500).json({ ok: false, error: 'Error interno al generar el informe.', message: error.message });
}
});
module.exports = app;
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Servidor Merx corriendo en http://localhost:${PORT}`);
});
}