informe-comercial-alfa/app/lib/dataverse.js

101 lines
4.3 KiB
JavaScript
Raw Normal View History

const BASE = `${process.env.DATAVERSE_URL}/api/data/v9.2`;
const MAX_RETRIES = 3;
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// Reintenta 429 (throttling de Dataverse) respetando Retry-After — ver migration.md §8.
export async function dv(path, accessToken, attempt = 0) {
const r = await fetch(`${BASE}/${path}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json",
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
// FormattedValue: etiqueta legible de option sets. lookuplogicalname: qué entidad es un lookup
// polimórfico (ej. "Referente a" de una actividad puede ser cuenta U oportunidad) — sin esto
// no hay forma de saber a qué tabla apunta un _regardingobjectid_value.
Prefer: 'odata.include-annotations="OData.Community.Display.V1.FormattedValue,Microsoft.Dynamics.CRM.lookuplogicalname"',
},
// Caché de 4 min en vez de no-store — decisión revisada: la versión 100% en vivo (sin caché)
// tardaba 2-4s por página. Subido de 90s a 240s (2026-09-22, a pedido de Marco tras seguir
// viendo 4s): más frecuencia de reuso de caché, a cambio de hasta 4 min de atraso en vez de
// 1.5 — razonable para un informe que se consulta, no un panel en tiempo real. El alcance
// (owner) ya viaja en la URL vía $filter, así que cachear por URL no filtra datos entre
// usuarios con distinto alcance — la Capa 2 de autorización (ownerFilter) sigue siendo la que
// decide qué URL se pide, no el token. Ver migration.md §8, "plan B" ya documentado ahí.
next: { revalidate: 240 },
});
if (r.status === 401) throw new Error("TOKEN_EXPIRED");
if (r.status === 429 && attempt < MAX_RETRIES) {
const retryAfter = Number(r.headers.get("Retry-After")) || 2 ** attempt;
await sleep(retryAfter * 1000);
return dv(path, accessToken, attempt + 1);
}
if (!r.ok) throw new Error(`DATAVERSE_${r.status}: ${(await r.text()).slice(0, 300)}`);
return r.json();
}
// Lectura SIN caché (cache: "no-store"): para validar justo antes de escribir — el `dv()` de arriba
// puede traer datos de hasta 4 min atrás.
export async function dvFresh(path, accessToken) {
const r = await fetch(`${BASE}/${path}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json",
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
Prefer: 'odata.include-annotations="OData.Community.Display.V1.FormattedValue,Microsoft.Dynamics.CRM.lookuplogicalname"',
},
cache: "no-store",
});
if (r.status === 401) throw new Error("TOKEN_EXPIRED");
if (!r.ok) throw new Error(`DATAVERSE_${r.status}: ${(await r.text()).slice(0, 300)}`);
return r.json();
}
// Escritura (POST crea, PATCH actualiza) con los derechos del usuario conectado (token delegado).
// Devuelve el JSON creado (POST, `return=representation`) o null (PATCH, 204). Solo la usa el
// agendador (lib/agendadorServer.js).
export async function dvWrite(method, path, accessToken, body, extraHeaders = {}) {
const r = await fetch(`${BASE}/${path}`, {
method,
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json",
"Content-Type": "application/json",
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
...(method === "POST" ? { Prefer: "return=representation" } : {}),
// `If-Match` con el etag leído: si alguien cambió el registro mientras tanto, Dynamics responde 412.
...extraHeaders,
},
body: JSON.stringify(body),
cache: "no-store",
});
if (r.status === 401) throw new Error("TOKEN_EXPIRED");
if (!r.ok) {
let msg = "";
try { msg = (await r.json())?.error?.message || ""; } catch { /* sin cuerpo */ }
throw new Error(`DATAVERSE_${r.status}: ${msg.slice(0, 300)}`);
}
return r.status === 204 ? null : r.json();
}
// Etiqueta legible de un option set, entregada por el header Prefer de arriba.
export function fv(o, key) {
return o[`${key}@OData.Community.Display.V1.FormattedValue`] || null;
}
// A qué entidad apunta un lookup polimórfico — key con el mismo formato que fv(), ej.
// lookupType(o, "_regardingobjectid_value").
export function lookupType(o, key) {
return o[`${key}@Microsoft.Dynamics.CRM.lookuplogicalname`] || null;
}
export function odataString(s) {
return String(s).replace(/'/g, "''");
}