fix: corretto veramente ldap e d altro
This commit is contained in:
+101
-7
@@ -1,7 +1,7 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const pool = require('../db');
|
||||
const { logAttivita } = require('../activityDb');
|
||||
const { db, logAttivita } = require('../activityDb');
|
||||
|
||||
// Helper: resolve agent name from DB (best-effort, non-blocking)
|
||||
async function resolveAgentName(agentId) {
|
||||
@@ -36,7 +36,7 @@ async function otrsRequest(method, path, bodyData = {}) {
|
||||
};
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 6000);
|
||||
const timeoutId = setTimeout(() => controller.abort(), 15000);
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
@@ -51,11 +51,15 @@ async function otrsRequest(method, path, bodyData = {}) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`OTRS REST API error (${response.status}): ${errorText}`);
|
||||
}
|
||||
return await response.json();
|
||||
const result = await response.json();
|
||||
if (result && result.Error) {
|
||||
throw new Error(`OTRS API Error: ${result.Error.ErrorMessage} (${result.Error.ErrorCode})`);
|
||||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
clearTimeout(timeoutId);
|
||||
if (err.name === 'AbortError') {
|
||||
throw new Error('OTRS REST API request timed out (6s limit exceeded)');
|
||||
throw new Error('OTRS REST API request timed out (15s limit exceeded)');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
@@ -258,6 +262,62 @@ router.get('/:id', async (req, res) => {
|
||||
return res.status(404).json({ error: 'Ticket not found' });
|
||||
}
|
||||
|
||||
const ticket = ticketResult.rows[0];
|
||||
if (ticket.customer_user_id && !ticket.customer_first && process.env.OTRS_API_URL && process.env.OTRS_API_USER) {
|
||||
try {
|
||||
// 1. Try to read from local SQLite cache in internal.db
|
||||
let cachedUser = null;
|
||||
try {
|
||||
cachedUser = db.prepare('SELECT email, first_name, last_name, phone FROM customer_user_cache WHERE login = ?').get(ticket.customer_user_id);
|
||||
} catch (dbErr) {
|
||||
console.warn('[LDAP Cache Detail] SQLite cache read failed:', dbErr.message);
|
||||
}
|
||||
|
||||
if (cachedUser) {
|
||||
ticket.customer_first = cachedUser.first_name || '';
|
||||
ticket.customer_last = cachedUser.last_name || '';
|
||||
ticket.customer_email = cachedUser.email || '';
|
||||
ticket.customer_phone = cachedUser.phone || '';
|
||||
} else {
|
||||
// 2. Fallback to live API fetch
|
||||
const getResult = await otrsRequest('POST', '/CustomerUserGet', { UserLogin: ticket.customer_user_id });
|
||||
const getData = (getResult && getResult.Data) || getResult;
|
||||
if (getData && getData.CustomerUser) {
|
||||
const u = getData.CustomerUser;
|
||||
ticket.customer_first = u.UserFirstname || '';
|
||||
ticket.customer_last = u.UserLastname || '';
|
||||
ticket.customer_email = u.UserEmail || '';
|
||||
ticket.customer_phone = u.UserPhone || '';
|
||||
|
||||
// 3. Store in SQLite cache for subsequent detail queries
|
||||
try {
|
||||
db.prepare(`
|
||||
INSERT INTO customer_user_cache (login, email, first_name, last_name, customer_id, phone)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(login) DO UPDATE SET
|
||||
email=excluded.email,
|
||||
first_name=excluded.first_name,
|
||||
last_name=excluded.last_name,
|
||||
customer_id=excluded.customer_id,
|
||||
phone=excluded.phone
|
||||
`).run(
|
||||
u.UserLogin,
|
||||
u.UserEmail || '',
|
||||
u.UserFirstname || '',
|
||||
u.UserLastname || '',
|
||||
u.UserCustomerID || '',
|
||||
u.UserPhone || ''
|
||||
);
|
||||
} catch (cacheErr) {
|
||||
console.warn('[LDAP Cache Detail] Failed to write fetched user to SQLite cache:', cacheErr.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (apiErr) {
|
||||
console.warn(`Failed to fetch LDAP customer details for detail view:`, apiErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch articles
|
||||
const articlesResult = await pool.query(
|
||||
`SELECT
|
||||
@@ -613,7 +673,7 @@ router.patch('/:id', async (req, res) => {
|
||||
}
|
||||
|
||||
// 1. Try to update via REST API if configured
|
||||
if (process.env.OTRS_API_URL && process.env.OTRS_API_USER) {
|
||||
if (process.env.OTRS_API_URL && process.env.OTRS_API_USER && process.env.FORCE_DB_UPDATE !== 'true') {
|
||||
try {
|
||||
const ticketFields = {};
|
||||
if (updates.ticket_state_id !== undefined) ticketFields.StateID = updates.ticket_state_id;
|
||||
@@ -664,6 +724,23 @@ router.patch('/:id', async (req, res) => {
|
||||
};
|
||||
}
|
||||
const result = await otrsRequest('PATCH', `/Ticket/${id}`, reqBody);
|
||||
|
||||
// Option 1: Log the time directly to the DB if the API succeeded but OTRS didn't save it
|
||||
if (!isNaN(timeUnit) && timeUnit > 0 && result && result.ArticleID) {
|
||||
try {
|
||||
await pool.query(
|
||||
`INSERT INTO time_accounting (
|
||||
ticket_id, article_id, time_unit,
|
||||
create_time, create_by, change_time, change_by
|
||||
) VALUES ($1, $2, $3, NOW(), $4, NOW(), $4)`,
|
||||
[id, result.ArticleID, timeUnit, operatorId]
|
||||
);
|
||||
console.log(`[Time Accounting] Successfully logged ${timeUnit} minutes for ticket ${id} via DB insert.`);
|
||||
} catch (timeDbErr) {
|
||||
console.error('[Time Accounting] Failed to log time unit in database:', timeDbErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
const isClosing = updates.ticket_state_id && current.ticket_state_id !== updates.ticket_state_id;
|
||||
resolveAgentName(operatorId).then(agente_nome => {
|
||||
logAttivita({
|
||||
@@ -942,7 +1019,7 @@ router.post('/:id/articles', async (req, res) => {
|
||||
const contentType = isHtml ? 'text/html; charset=utf-8' : 'text/plain; charset=utf-8';
|
||||
|
||||
// 1. Try to add note via REST API if configured
|
||||
if (process.env.OTRS_API_URL && process.env.OTRS_API_USER) {
|
||||
if (process.env.OTRS_API_URL && process.env.OTRS_API_USER && process.env.FORCE_DB_UPDATE !== 'true') {
|
||||
try {
|
||||
const payload = {
|
||||
Article: {
|
||||
@@ -969,6 +1046,23 @@ router.post('/:id/articles', async (req, res) => {
|
||||
}
|
||||
|
||||
const result = await otrsRequest('PATCH', `/Ticket/${id}`, payload);
|
||||
|
||||
// Option 1: Log the time directly to the DB if the API succeeded but OTRS didn't save it
|
||||
if (time_unit && result && result.ArticleID) {
|
||||
try {
|
||||
await pool.query(
|
||||
`INSERT INTO time_accounting (
|
||||
ticket_id, article_id, time_unit,
|
||||
create_time, create_by, change_time, change_by
|
||||
) VALUES ($1, $2, $3, NOW(), $4, NOW(), $4)`,
|
||||
[id, result.ArticleID, parseFloat(time_unit), operatorId]
|
||||
);
|
||||
console.log(`[Time Accounting] Successfully logged ${time_unit} minutes for ticket ${id} via DB insert.`);
|
||||
} catch (timeDbErr) {
|
||||
console.error('[Time Accounting] Failed to log time unit in database:', timeDbErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
resolveAgentName(operatorId).then(agente_nome => {
|
||||
logAttivita({
|
||||
agente_id: operatorId,
|
||||
@@ -1179,7 +1273,7 @@ router.patch('/batch/update', async (req, res) => {
|
||||
}
|
||||
|
||||
// 1. Try to update via REST API if configured
|
||||
if (process.env.OTRS_API_URL && process.env.OTRS_API_USER) {
|
||||
if (process.env.OTRS_API_URL && process.env.OTRS_API_USER && process.env.FORCE_DB_UPDATE !== 'true') {
|
||||
try {
|
||||
const ticketFields = {};
|
||||
if (updates.ticket_state_id !== undefined) ticketFields.StateID = updates.ticket_state_id;
|
||||
|
||||
Reference in New Issue
Block a user