mirror of
https://origin.cursor.com/mrdevmx/panels.git
synced 2026-10-09 14:53:18 +00:00
<!-- CURSOR_AGENT_PR_BODY_BEGIN --> ## Validación de endpoints y SPs Se probaron todos los endpoints nuevos (gastos, almacén, control presupuestal, IAM) y sus RPCs asociados. ### Bugs corregidos en migraciones/SQL 1. **IAM grants en schema core** — `iam-004e` intentaba `GRANT` sobre `core` con rol `iam_owner` (sin permiso). Los grants cruzados se movieron a `core-027-iam-rpc-cross-grants.sql`. 2. **`_cost_settings` ambiguo** — columnas `budget_warn_pct` etc. colisionaban con `RETURNS TABLE` en PL/pgSQL, rompiendo `fn_expense_create` y control presupuestal. Corregido en `core-028-fix-cost-settings-ambiguous.sql`. ### Tests añadidos - `api/cost_modules_test.ts` — CRUD RPC gastos, flujo almacén completo, control presupuestal, IAM permisos - `scripts/crud-smoke-test.sh` — smoke HTTP de todos los endpoints nuevos ### Resultados - `deno test cost_modules_test.ts` — 5/5 OK - `./scripts/crud-smoke-test.sh` — todos los checks OK (gastos CRUD, IVA, cost-settings, almacén, transferencias, cost-control, IAM) <!-- CURSOR_AGENT_PR_BODY_END --> <div><a href="https://cursor.com/agents/bc-eeec3b5c-f789-43e8-a353-0755e4706377?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/background-agent?bcId=bc-eeec3b5c-f789-43e8-a353-0755e4706377&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img alt="Open in Cursor" width="131" height="28" src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a> </div>
183 lines
6 KiB
TypeScript
183 lines
6 KiB
TypeScript
import {
|
|
S3Client,
|
|
PutObjectCommand,
|
|
GetObjectCommand,
|
|
ListObjectsV2Command,
|
|
DeleteObjectCommand,
|
|
} from "npm:@aws-sdk/client-s3@3";
|
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
import { dirname, join } from "node:path";
|
|
import { config, DATA_DIR } from "./config.ts";
|
|
|
|
/**
|
|
* Almacenamiento de archivos (Fase 4c): expedientes cifrados, PDFs de
|
|
* gafetes, logos. Antes vivían en el volumen local (panel-data) -- un
|
|
* volumen local no se comparte entre réplicas ni microservicios, así que
|
|
* es el mismo cuello de botella que motivó salir de SQLite, solo que en
|
|
* otra capa. El contenido YA viene cifrado con AES-GCM (docs_crypto.ts)
|
|
* antes de llegar aquí -- el bucket nunca ve texto plano.
|
|
*
|
|
* Backend real: S3-compatible (Cloudflare R2). Si no hay credenciales S3
|
|
* (dev local), cae a disco bajo DATA_DIR. En staging/producción el volumen
|
|
* local no escala: hay que configurar S3_*.
|
|
*/
|
|
|
|
let client: S3Client | null = null;
|
|
|
|
export function s3Configured(): boolean {
|
|
return !!(config.s3Endpoint && config.s3Bucket && config.s3AccessKeyId && config.s3SecretAccessKey);
|
|
}
|
|
|
|
export type StoragePing = {
|
|
configured: boolean;
|
|
ok: boolean;
|
|
backend: "s3" | "local";
|
|
error?: string;
|
|
};
|
|
|
|
function s3Err(e: unknown): string {
|
|
if (e && typeof e === "object") {
|
|
const o = e as {
|
|
name?: string;
|
|
message?: string;
|
|
Code?: string;
|
|
$metadata?: { httpStatusCode?: number };
|
|
};
|
|
return [o.name, o.Code, o.$metadata?.httpStatusCode, o.message].filter(Boolean).join(": ");
|
|
}
|
|
return String(e);
|
|
}
|
|
|
|
/**
|
|
* R2: HeadBucket suele dar 403 con token de Account API acotado al bucket.
|
|
* ListObjectsV2 (o un put/get sonda) es lo que realmente usamos en runtime.
|
|
*/
|
|
export async function pingStorage(): Promise<StoragePing> {
|
|
if (!s3Configured()) {
|
|
try {
|
|
await mkdir(join(DATA_DIR, "local-objects"), { recursive: true });
|
|
return { configured: false, ok: true, backend: "local" };
|
|
} catch (e) {
|
|
return { configured: false, ok: false, backend: "local", error: s3Err(e) };
|
|
}
|
|
}
|
|
try {
|
|
await getClient().send(
|
|
new ListObjectsV2Command({ Bucket: config.s3Bucket, MaxKeys: 1 }),
|
|
);
|
|
return { configured: true, ok: true, backend: "s3" };
|
|
} catch (listErr) {
|
|
try {
|
|
await probeStorageReadWrite();
|
|
return { configured: true, ok: true, backend: "s3" };
|
|
} catch (writeErr) {
|
|
const error = `list=${s3Err(listErr)}; write=${s3Err(writeErr)}`;
|
|
console.error(
|
|
"[storage] ping failed",
|
|
error,
|
|
"endpoint=",
|
|
config.s3Endpoint,
|
|
"bucket=",
|
|
config.s3Bucket,
|
|
"region=",
|
|
config.s3Region,
|
|
);
|
|
return { configured: true, ok: false, backend: "s3", error };
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Put + get + delete de un objeto sonda. No dejar basura en el bucket. */
|
|
export async function probeStorageReadWrite(): Promise<void> {
|
|
const key = `_panels/connectivity-probe-${crypto.randomUUID()}`;
|
|
const payload = new TextEncoder().encode("panels-connectivity-probe");
|
|
await putObject(key, payload);
|
|
const got = await getObject(key);
|
|
if (new TextDecoder().decode(got) !== "panels-connectivity-probe") {
|
|
throw new Error("El objeto sonda no coincide con lo escrito");
|
|
}
|
|
if (s3Configured()) {
|
|
await getClient().send(new DeleteObjectCommand({ Bucket: config.s3Bucket, Key: key }));
|
|
}
|
|
}
|
|
|
|
function getClient(): S3Client {
|
|
if (!client) {
|
|
client = new S3Client({
|
|
endpoint: config.s3Endpoint,
|
|
region: config.s3Region || "auto",
|
|
forcePathStyle: true,
|
|
// R2 no implementa los checksums CRC32 que el SDK v3 manda por defecto.
|
|
requestChecksumCalculation: "WHEN_REQUIRED",
|
|
responseChecksumValidation: "WHEN_REQUIRED",
|
|
credentials: {
|
|
accessKeyId: config.s3AccessKeyId,
|
|
secretAccessKey: config.s3SecretAccessKey,
|
|
},
|
|
});
|
|
}
|
|
return client;
|
|
}
|
|
|
|
async function streamToUint8Array(body: unknown): Promise<Uint8Array> {
|
|
const chunks: Uint8Array[] = [];
|
|
// deno-lint-ignore no-explicit-any
|
|
for await (const chunk of body as any) {
|
|
chunks.push(chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk));
|
|
}
|
|
const total = chunks.reduce((n, c) => n + c.length, 0);
|
|
const out = new Uint8Array(total);
|
|
let offset = 0;
|
|
for (const c of chunks) {
|
|
out.set(c, offset);
|
|
offset += c.length;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export async function putObject(key: string, bytes: Uint8Array): Promise<void> {
|
|
if (s3Configured()) {
|
|
await getClient().send(
|
|
new PutObjectCommand({ Bucket: config.s3Bucket, Key: key, Body: bytes }),
|
|
);
|
|
return;
|
|
}
|
|
const path = join(DATA_DIR, "local-objects", key);
|
|
await mkdir(dirname(path), { recursive: true });
|
|
await writeFile(path, bytes);
|
|
}
|
|
|
|
export async function getObject(key: string): Promise<Uint8Array> {
|
|
if (s3Configured()) {
|
|
const res = await getClient().send(
|
|
new GetObjectCommand({ Bucket: config.s3Bucket, Key: key }),
|
|
);
|
|
return await streamToUint8Array(res.Body);
|
|
}
|
|
const path = join(DATA_DIR, "local-objects", key);
|
|
return await readFile(path);
|
|
}
|
|
|
|
// --- Convenciones de key por dominio (equivalentes a los antiguos
|
|
// workerDir/projectDir/companyDir + Deno.readFile/writeFile) ---
|
|
export function workerDocKey(workerId: number, storageName: string): string {
|
|
return `expedientes/${workerId}/${storageName}`;
|
|
}
|
|
export function projectDocKey(projectId: number, storageName: string): string {
|
|
return `proyectos/${projectId}/${storageName}`;
|
|
}
|
|
export function companyDocKey(companyId: number, storageName: string): string {
|
|
return `empresas/${companyId}/${storageName}`;
|
|
}
|
|
export function badgeJobPdfKey(jobId: number): string {
|
|
return `pdfs/gafetes-${jobId}.pdf`;
|
|
}
|
|
export function loanReceiptPdfKey(loanId: number, weekId: number): string {
|
|
return `pdfs/prestamo-${loanId}-semana-${weekId}.pdf`;
|
|
}
|
|
export function expenseDocKey(expenseId: number, storageName: string): string {
|
|
return `expenses/${expenseId}/${storageName}`;
|
|
}
|
|
export function projectLogoKey(projectId: number, side: "left" | "right", ext: string): string {
|
|
return `logos/${projectId}-${side}.${ext}`;
|
|
}
|