diff --git a/docs/refactoring-plan.md b/docs/refactoring-plan.md new file mode 100644 index 0000000..0da6cb2 --- /dev/null +++ b/docs/refactoring-plan.md @@ -0,0 +1,118 @@ +# Plan de Refactorización - Mejora de Mantenibilidad + +**Fecha:** 2024 +**Estado:** Propuesto +**Objetivo:** Mejorar la mantenibilidad del código eliminando duplicación y reduciendo la complejidad de archivos grandes. + +## Resumen Ejecutivo + +El proyecto ha crecido orgánicamente y presenta varios problemas de mantenibilidad: +- **19 duplicaciones** de la función `toIsoSql` +- **Múltiples duplicaciones** de `sha256Hex` en tests +- **Archivos excesivamente grandes**: `group-sync.ts` (1307 líneas), `server.ts` (665 líneas) +- **Código compartido duplicado** entre `src/` (bot) y `apps/web/` +- **Setup repetitivo** en tests (60+ archivos) + +Este plan aborda estos problemas en 4 fases priorizadas. + +--- + +## 🔴 Fase 1: Eliminación de Duplicación de Utilidades (1-2 horas) + +**Prioridad:** CRÍTICA +**Impacto:** Alto (reduce ~150 líneas duplicadas) +**Riesgo:** Bajo (cambio mecánico) + +### Objetivos +1. Centralizar función `toIsoSql` en un único lugar +2. Centralizar función `sha256Hex` para tests +3. Eliminar todas las duplicaciones mediante imports + +### Archivos a Crear + +#### `src/utils/date.ts` +- Exportar función `toIsoSql(d?: Date): string` +- Documentar formato de salida (ISO SQL: `YYYY-MM-DD HH:MM:SS.mmm`) + +#### `tests/helpers/crypto.ts` +- Exportar función `sha256Hex(input: string): Promise` +- Reutilizar en todos los tests web y unit + +### Archivos a Modificar + +**Archivos con `toIsoSql` duplicada (19 archivos):** +- `apps/web/src/hooks.server.ts` +- `apps/web/src/routes/api/tasks/[id]/claim/+server.ts` +- `apps/web/src/routes/api/tasks/[id]/uncomplete/+server.ts` +- `src/services/group-sync.ts` +- `tests/unit/services/cleanup-inactive.test.ts` +- `tests/unit/tasks/complete-reaction.test.ts` +- `tests/unit/services/metrics-health.test.ts` +- `tests/unit/services/response-queue.cleanup.test.ts` +- `tests/web/api.integrations.feeds.test.ts` +- `tests/web/api.me.preferences.test.ts` +- `tests/web/api.me.tasks.test.ts` +- `tests/web/api.tasks.complete.reaction.test.ts` +- `tests/web/app.integrations.page.test.ts` +- `tests/web/app.preferences.page.test.ts` +- Y otros según `grep -rn "function toIsoSql"` + +**Archivos con `sha256Hex` duplicada:** +- `tests/web/api.integrations.feeds.test.ts` +- `tests/web/api.me.preferences.test.ts` +- `tests/web/api.me.tasks.test.ts` +- `tests/web/app.integrations.page.test.ts` +- `tests/web/app.preferences.page.test.ts` +- Verificar que `src/utils/crypto.ts` y `apps/web/src/lib/server/crypto.ts` no estén duplicados + +### Pasos de Ejecución +1. Crear `src/utils/date.ts` con implementación de referencia +2. Crear `tests/helpers/crypto.ts` con implementación de referencia +3. Buscar y reemplazar imports en todos los archivos afectados +4. Eliminar definiciones locales de las funciones +5. Ejecutar suite completa de tests: `bun test` +6. Verificar que no hay regresiones + +### Criterios de Éxito +- ✅ Todos los tests pasan +- ✅ Solo existe 1 definición de `toIsoSql` en el código fuente +- ✅ Solo existe 1 definición de `sha256Hex` en tests +- ✅ Reducción de ~150 líneas de código + +--- + +## 🔴 Fase 2: División de `group-sync.ts` (3-4 horas) + +**Prioridad:** CRÍTICA +**Impacto:** Alto (mejora legibilidad y testabilidad) +**Riesgo:** Medio (requiere análisis cuidadoso) + +### Objetivos +1. Dividir archivo monolítico de 1307 líneas en módulos cohesivos +2. Separar responsabilidades claramente +3. Facilitar testing unitario de cada componente +4. Mantener API pública compatible + +### Análisis Previo Necesario + +**Archivos a consultar para entender el alcance:** +- `src/services/group-sync.ts` (archivo principal a dividir) +- `tests/unit/services/group-sync.test.ts` +- `tests/unit/services/group-sync.onboarding.test.ts` +- `tests/unit/services/group-sync.coverage.test.ts` +- `tests/unit/services/group-sync.gating.test.ts` +- `tests/unit/services/group-sync.label-update.test.ts` +- `tests/unit/services/group-sync.sync-members.test.ts` +- `tests/unit/services/group-sync.members.test.ts` +- `tests/unit/services/group-sync.fetch-members.test.ts` +- `tests/unit/services/group-sync.scheduler.test.ts` +- `tests/unit/services/group-sync.scheduler.gating.test.ts` + +**Identificar en el código:** +- Funciones públicas vs privadas +- Responsabilidades principales (sincronización, scheduling, gating, eventos) +- Dependencias entre funciones +- Estado compartido (si existe) + +### Estructura Propuesta +