panels-origin/api/storage.ts
Cursor Agent caf40e29fb
feat: facturas, ajustes de nómina, finiquitos, dispersión e IMSS
Reutiliza el catálogo de proveedores y agrega carga de facturas, conceptos de la semana, préstamos editables, finiquitos, dispersión, historial de personal, reportes y jornal de cotización.

Co-authored-by: alberto.martinez <alberto.martinez@mrdev.mx>
2026-09-24 16:40:08 +00:00

202 lines
6.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);
}
export async function deleteObject(key: string): Promise<void> {
if (s3Configured()) {
await getClient().send(
new DeleteObjectCommand({ Bucket: config.s3Bucket, Key: key }),
);
return;
}
const path = join(DATA_DIR, "local-objects", key);
try {
const { unlink } = await import("node:fs/promises");
await unlink(path);
} catch (e) {
if ((e as NodeJS.ErrnoException)?.code !== "ENOENT") throw e;
}
}
// --- 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 dispersionDocKey(dispersionId: number, storageName: string): string {
return `dispersions/${dispersionId}/${storageName}`;
}
export function projectLogoKey(projectId: number, side: "left" | "right", ext: string): string {
return `logos/${projectId}-${side}.${ext}`;
}