convertir-formato-asistencia 1.2.3 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/copilot-instructions.md +50 -0
- package/README.md +28 -3
- package/index.js +50 -11
- package/index.test.js +92 -5
- package/package.json +12 -3
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# Copilot instructions for Convertir Formato de Asistencia
|
|
2
|
+
|
|
3
|
+
## Build, test, and validation
|
|
4
|
+
|
|
5
|
+
- Package manager: this repo declares `pnpm` in `package.json` (`packageManager: "pnpm@10.26.2"`). Prefer `pnpm` for install/test commands.
|
|
6
|
+
- Install dependencies:
|
|
7
|
+
- `pnpm install`
|
|
8
|
+
- Run the full test suite:
|
|
9
|
+
- `pnpm test`
|
|
10
|
+
- Equivalent direct runner: `pnpm vitest run`
|
|
11
|
+
- Run a single test file:
|
|
12
|
+
- `pnpm vitest run index.test.js`
|
|
13
|
+
- Node version expectation: project docs and CI target Node 20+; GitHub Actions runs on Node 20.x and 22.x.
|
|
14
|
+
- There is no dedicated lint script in `package.json`; validation is currently via Vitest tests.
|
|
15
|
+
|
|
16
|
+
## High-level architecture
|
|
17
|
+
|
|
18
|
+
- This repository is a small Node.js CLI utility that converts attendance Excel files into a cleaner Excel report.
|
|
19
|
+
- The main implementation lives in `index.js` and exports `generarReporte`, which is the core conversion pipeline used by the CLI and by programmatic callers.
|
|
20
|
+
- Flow of the conversion:
|
|
21
|
+
1. Validate input/output paths and ensure the source file exists.
|
|
22
|
+
2. Read the first worksheet from the Excel file using `xlsx`.
|
|
23
|
+
3. Convert Excel rows into JSON records.
|
|
24
|
+
4. Normalize the input columns and group records by user/date.
|
|
25
|
+
5. Build a calendar across the date range, then determine per-user attendance for each day.
|
|
26
|
+
6. Split results by department and create one worksheet per department with `ExcelJS`.
|
|
27
|
+
7. Write the final `.xlsx` output file.
|
|
28
|
+
- The CLI entrypoint also provides `--help` and `--version` behavior in the same file, and the binary name is `cofa` via `package.json` `bin`.
|
|
29
|
+
- Tests live in `index.test.js` and validate behavior through mocked `xlsx` and `exceljs` dependencies; the suite is designed around the current conversion logic rather than browser/UI assumptions.
|
|
30
|
+
|
|
31
|
+
## Key conventions in this repo
|
|
32
|
+
|
|
33
|
+
- The project is written in JavaScript with ESM (`"type": "module"`).
|
|
34
|
+
- Naming conventions are mostly Spanish and domain-specific, for example: `generarReporte`, `generarCalendario`, `obtenerTrabajadores`, `generarMapaAsistencia`.
|
|
35
|
+
- The workbook output uses department-based worksheets, not a single flat sheet. Each worksheet is created from `departamentos` discovered in the input data.
|
|
36
|
+
- Default input column names are Spanish and expected to match the attendance export format described in `README.md`:
|
|
37
|
+
- `ID de usuario`
|
|
38
|
+
- `Nombre`
|
|
39
|
+
- `Departamento`
|
|
40
|
+
- `Fecha/Hora`
|
|
41
|
+
- Default output column names are also defined in code and can be overridden via the optional `usuarioConfig` argument.
|
|
42
|
+
- File/date handling is important: records are grouped by `user + formatted date`, and time extraction uses the first/last timestamp of the day as entry/exit.
|
|
43
|
+
- The project treats weekend dates as a special state (`TRABAJÓ FIN DE SEMANA` or `FIN DE SEMANA`) and missing entries as `FALTÓ`.
|
|
44
|
+
- This repo is CLI/data-processing oriented, so changes usually touch `index.js` and the related test file rather than larger application frameworks or build tooling.
|
|
45
|
+
|
|
46
|
+
## Repository-specific notes
|
|
47
|
+
|
|
48
|
+
- `README.md` is the authoritative user-facing description of the tool and its CLI contract.
|
|
49
|
+
- CI workflow is defined at `.github/workflows/ci.yml`; it installs dependencies via pnpm and runs the test suite against Node 20.x and 22.x.
|
|
50
|
+
- There are no extra AI or agent instruction files in the repository root, so this file should be treated as the main repository-local guidance for Copilot sessions.
|
package/README.md
CHANGED
|
@@ -64,13 +64,13 @@ Instalación
|
|
|
64
64
|
Puedes importar y utilizar la función `generarReporte` directamente en tus proyectos Node.js.
|
|
65
65
|
|
|
66
66
|
```javascript
|
|
67
|
-
import { generarReporte } from "
|
|
67
|
+
import { generarReporte } from "convertir-formato-asistencia";
|
|
68
68
|
|
|
69
69
|
async function ejecutarReporte() {
|
|
70
70
|
const rutaEntrada = "./asistencia.xls";
|
|
71
71
|
const rutaSalida = "./reporte_personalizado.xlsx";
|
|
72
72
|
|
|
73
|
-
// Configuración opcional para personalizar
|
|
73
|
+
// Configuración opcional para personalizar columnas, encabezados y mensajes
|
|
74
74
|
const usuarioConfig = {
|
|
75
75
|
entrada: {
|
|
76
76
|
id: "Número de Empleado",
|
|
@@ -83,6 +83,11 @@ async function ejecutarReporte() {
|
|
|
83
83
|
salida: "Hora de Salida",
|
|
84
84
|
// Puedes añadir más nombres de columnas de salida aquí
|
|
85
85
|
},
|
|
86
|
+
mensajes: {
|
|
87
|
+
presente: "Asistió",
|
|
88
|
+
falto: "Sin asistencia",
|
|
89
|
+
finDeSemana: "Fin de semana",
|
|
90
|
+
},
|
|
86
91
|
};
|
|
87
92
|
|
|
88
93
|
try {
|
|
@@ -125,7 +130,27 @@ Este objeto se utiliza para definir los nombres de los encabezados de las column
|
|
|
125
130
|
- `departamento`: 'Departamento'
|
|
126
131
|
- `estado`: 'Estado'
|
|
127
132
|
|
|
128
|
-
|
|
133
|
+
#### `usuarioConfig.mensajes`
|
|
134
|
+
|
|
135
|
+
Este objeto permite personalizar los textos que aparecen en la columna `estado` cuando un trabajador está presente, falta o el día corresponde a fin de semana.
|
|
136
|
+
|
|
137
|
+
**Valores predeterminados para `mensajes`:**
|
|
138
|
+
|
|
139
|
+
- `presente`: 'PRESENTE'
|
|
140
|
+
- `falto`: 'SIN ASISTENCIA'
|
|
141
|
+
- `finDeSemana`: 'FIN DE SEMANA'
|
|
142
|
+
|
|
143
|
+
Ejemplo:
|
|
144
|
+
|
|
145
|
+
```javascript
|
|
146
|
+
const usuarioConfig = {
|
|
147
|
+
mensajes: {
|
|
148
|
+
presente: "Asistió",
|
|
149
|
+
falto: "Sin asistencia",
|
|
150
|
+
finDeSemana: "Fin de semana",
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
```
|
|
129
154
|
|
|
130
155
|
Notas y consejos
|
|
131
156
|
|
package/index.js
CHANGED
|
@@ -82,18 +82,23 @@ async function generarReporte(rutaEntrada, rutaSalida, usuarioConfig = {}) {
|
|
|
82
82
|
salida: 'Salida',
|
|
83
83
|
departamento: 'Departamento',
|
|
84
84
|
estado: "Estado"
|
|
85
|
+
},
|
|
86
|
+
mensajes: {
|
|
87
|
+
presente: 'PRESENTE',
|
|
88
|
+
falto: 'SIN ASISTENCIA',
|
|
89
|
+
finDeSemana: 'FIN DE SEMANA'
|
|
85
90
|
}
|
|
86
91
|
};
|
|
87
92
|
|
|
88
93
|
const config = {
|
|
89
94
|
entrada: { ...defaultConfig.entrada, ...usuarioConfig.entrada },
|
|
90
|
-
salida: { ...defaultConfig.salida, ...usuarioConfig.salida }
|
|
95
|
+
salida: { ...defaultConfig.salida, ...usuarioConfig.salida },
|
|
96
|
+
mensajes: { ...defaultConfig.mensajes, ...usuarioConfig.mensajes }
|
|
91
97
|
};
|
|
92
98
|
// Validar que se pasaron los argumentos necesarios
|
|
93
99
|
if (!rutaEntrada || !rutaSalida) {
|
|
94
|
-
console.error("❌ ERROR: Faltan argumentos.");
|
|
95
|
-
console.log("
|
|
96
|
-
console.log('Ejemplo: node index.js ./asistencia.xls ./reporte_abril.xlsx');
|
|
100
|
+
console.error("❌ ERROR: Faltan argumentos de entrada y/o salida.");
|
|
101
|
+
console.log("Para ver el uso correcto, ejecuta: cofa --help");
|
|
97
102
|
return;
|
|
98
103
|
}
|
|
99
104
|
|
|
@@ -174,19 +179,19 @@ async function generarReporte(rutaEntrada, rutaSalida, usuarioConfig = {}) {
|
|
|
174
179
|
rowData = {
|
|
175
180
|
id: trabajador.id, nombre: trabajador.nombre, fecha: dia,
|
|
176
181
|
entrada: hEntrada, salida: hSalida, depto: trabajador.depto,
|
|
177
|
-
estado: esFinde ?
|
|
182
|
+
estado: esFinde ? config.mensajes.finDeSemana : config.mensajes.presente
|
|
178
183
|
};
|
|
179
184
|
} else {
|
|
180
185
|
rowData = {
|
|
181
186
|
id: trabajador.id, nombre: trabajador.nombre, fecha: dia,
|
|
182
187
|
entrada: '--:--', salida: '--:--', depto: trabajador.depto,
|
|
183
|
-
estado: esFinde ?
|
|
188
|
+
estado: esFinde ? config.mensajes.finDeSemana : config.mensajes.falto
|
|
184
189
|
};
|
|
185
190
|
}
|
|
186
191
|
|
|
187
192
|
const row = worksheet.addRow(rowData);
|
|
188
193
|
// Color rojo si faltó
|
|
189
|
-
if (rowData.estado ===
|
|
194
|
+
if (rowData.estado === config.mensajes.falto) {
|
|
190
195
|
row.getCell('estado').font = { color: { argb: 'FFFF0000' }, bold: true };
|
|
191
196
|
}
|
|
192
197
|
});
|
|
@@ -205,16 +210,50 @@ async function generarReporte(rutaEntrada, rutaSalida, usuarioConfig = {}) {
|
|
|
205
210
|
}
|
|
206
211
|
}
|
|
207
212
|
|
|
213
|
+
function mostrarAyuda() {
|
|
214
|
+
console.log("\nUso: cofa <ruta_entrada> <ruta_salida>\n");
|
|
215
|
+
console.log("Descripción: Herramienta para convertir registros de asistencia de archivos XLS/XLSX a un reporte de Excel legible, agrupando por usuario y marcando ausencias.\n");
|
|
216
|
+
console.log("Argumentos:\n");
|
|
217
|
+
console.log(" <ruta_entrada> Ruta al archivo de asistencia de entrada (XLS/XLSX).");
|
|
218
|
+
console.log(" <ruta_salida> Ruta donde se guardará el reporte de Excel generado (XLSX).");
|
|
219
|
+
console.log("\nOpciones:\n");
|
|
220
|
+
console.log(" --help, -h Muestra esta información de ayuda.");
|
|
221
|
+
console.log(" --version, -v Muestra la versión de la aplicación.");
|
|
222
|
+
console.log("\nEjemplo:\n");
|
|
223
|
+
console.log(" cofa ./asistencia.xls ./reporte_abril.xlsx\n");
|
|
224
|
+
process.exit(0);
|
|
225
|
+
}
|
|
226
|
+
|
|
208
227
|
// convertir import.meta.url a path de archivo
|
|
209
228
|
const __filename = fileURLToPath(import.meta.url);
|
|
210
229
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
230
|
+
const invoked = path.basename(process.argv[1] || '');
|
|
231
|
+
const scriptName = path.basename(__filename);
|
|
232
|
+
|
|
233
|
+
if (invoked === scriptName || invoked === 'cofa') {
|
|
234
|
+
const args = process.argv.slice(2);
|
|
235
|
+
|
|
236
|
+
const packageJsonPath = path.join(path.dirname(__filename), "package.json");
|
|
237
|
+
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
|
|
238
|
+
const appVersion = packageJson.version;
|
|
239
|
+
|
|
240
|
+
if (args.includes("--version") || args.includes("-v")) {
|
|
241
|
+
console.log(`cofa v${appVersion}`);
|
|
242
|
+
process.exit(0);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
246
|
+
mostrarAyuda();
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const rutaEntrada = args[0];
|
|
250
|
+
const rutaSalida = args[1];
|
|
214
251
|
|
|
215
252
|
(async () => {
|
|
216
253
|
await generarReporte(rutaEntrada, rutaSalida);
|
|
217
254
|
})();
|
|
218
255
|
}
|
|
219
256
|
|
|
220
|
-
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
export { generarReporte };
|
package/index.test.js
CHANGED
|
@@ -46,7 +46,12 @@ vi.mock('exceljs', () => {
|
|
|
46
46
|
font: {},
|
|
47
47
|
fill: {},
|
|
48
48
|
})),
|
|
49
|
-
addRow: vi.fn()
|
|
49
|
+
addRow: vi.fn((rowData) => ({
|
|
50
|
+
getCell: vi.fn((cell) => ({
|
|
51
|
+
font: {},
|
|
52
|
+
})),
|
|
53
|
+
...rowData,
|
|
54
|
+
})),
|
|
50
55
|
};
|
|
51
56
|
|
|
52
57
|
const mockWorkbookInstance = {
|
|
@@ -86,8 +91,8 @@ describe('generarReporte', () => {
|
|
|
86
91
|
|
|
87
92
|
await generarReporte(undefined, 'ruta/salida.xlsx');
|
|
88
93
|
|
|
89
|
-
expect(consoleErrorSpy).toHaveBeenCalledWith("❌ ERROR: Faltan argumentos.");
|
|
90
|
-
expect(consoleLogSpy).toHaveBeenCalledWith("
|
|
94
|
+
expect(consoleErrorSpy).toHaveBeenCalledWith("❌ ERROR: Faltan argumentos de entrada y/o salida.");
|
|
95
|
+
expect(consoleLogSpy).toHaveBeenCalledWith("Para ver el uso correcto, ejecuta: cofa --help");
|
|
91
96
|
consoleErrorSpy.mockRestore();
|
|
92
97
|
consoleLogSpy.mockRestore();
|
|
93
98
|
});
|
|
@@ -98,8 +103,8 @@ describe('generarReporte', () => {
|
|
|
98
103
|
|
|
99
104
|
await generarReporte('ruta/entrada.xls', undefined);
|
|
100
105
|
|
|
101
|
-
expect(consoleErrorSpy).toHaveBeenCalledWith("❌ ERROR: Faltan argumentos.");
|
|
102
|
-
expect(consoleLogSpy).toHaveBeenCalledWith("
|
|
106
|
+
expect(consoleErrorSpy).toHaveBeenCalledWith("❌ ERROR: Faltan argumentos de entrada y/o salida.");
|
|
107
|
+
expect(consoleLogSpy).toHaveBeenCalledWith("Para ver el uso correcto, ejecuta: cofa --help");
|
|
103
108
|
consoleErrorSpy.mockRestore();
|
|
104
109
|
consoleLogSpy.mockRestore();
|
|
105
110
|
});
|
|
@@ -198,4 +203,86 @@ describe('generarReporte', () => {
|
|
|
198
203
|
|
|
199
204
|
consoleLogSpy.mockRestore();
|
|
200
205
|
});
|
|
206
|
+
|
|
207
|
+
it('debería usar mensajes personalizados para presente, falta y fin de semana', async () => {
|
|
208
|
+
const mockData = [
|
|
209
|
+
// 2026-04-01 (miércoles) con asistencia
|
|
210
|
+
{ 'ID de usuario': 1, 'Nombre': 'Jose', 'Fecha/Hora': new Date('2026-04-01T08:00:00.000Z'), 'Departamento': 'IT' },
|
|
211
|
+
// 2026-04-04 (sábado) con asistencia
|
|
212
|
+
{ 'ID de usuario': 1, 'Nombre': 'Jose', 'Fecha/Hora': new Date('2026-04-04T08:00:00.000Z'), 'Departamento': 'IT' },
|
|
213
|
+
// 2026-04-08 (miércoles) con asistencia
|
|
214
|
+
{ 'ID de usuario': 1, 'Nombre': 'Jose', 'Fecha/Hora': new Date('2026-04-08T08:00:00.000Z'), 'Departamento': 'IT' },
|
|
215
|
+
];
|
|
216
|
+
const usuarioConfig = {
|
|
217
|
+
mensajes: {
|
|
218
|
+
presente: 'ASISTIÓ',
|
|
219
|
+
falto: 'NO ASISTIÓ',
|
|
220
|
+
finDeSemana: 'WEEKEND'
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => { });
|
|
224
|
+
|
|
225
|
+
fs.existsSync.mockReturnValue(true);
|
|
226
|
+
xlsx.readFile.mockReturnValue({ SheetNames: ['Sheet1'], Sheets: { Sheet1: {} } });
|
|
227
|
+
xlsx.utils.sheet_to_json.mockReturnValue(mockData);
|
|
228
|
+
|
|
229
|
+
await generarReporte('ruta/entrada.xls', 'ruta/salida.xlsx', usuarioConfig);
|
|
230
|
+
|
|
231
|
+
expect(fs.existsSync).toHaveBeenCalledWith('ruta/entrada.xls');
|
|
232
|
+
const mockWorkbookInstance = ExcelJS.Workbook.mock.results[0].value;
|
|
233
|
+
|
|
234
|
+
const addRowCalls = mockWorkbookInstance.addWorksheet.mock.results[0].value.addRow.mock.calls;
|
|
235
|
+
|
|
236
|
+
expect(addRowCalls.some(call => call[0].estado === 'ASISTIÓ')).toBe(true);
|
|
237
|
+
expect(addRowCalls.some(call => call[0].estado === 'WEEKEND')).toBe(true);
|
|
238
|
+
expect(addRowCalls.some(call => call[0].estado === 'NO ASISTIÓ')).toBe(true);
|
|
239
|
+
|
|
240
|
+
expect(mockWorkbookInstance.xlsx.writeFile).toHaveBeenCalledWith('ruta/salida.xlsx');
|
|
241
|
+
expect(consoleLogSpy).toHaveBeenCalledWith("✨ ¡PROCESO COMPLETADO! El archivo se generó correctamente.");
|
|
242
|
+
|
|
243
|
+
consoleLogSpy.mockRestore();
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
it('debería usar mensajes personalizados para falta y fin de semana', async () => {
|
|
247
|
+
const mockData = [
|
|
248
|
+
// 2026-04-01 (miércoles) con asistencia
|
|
249
|
+
{ 'ID de usuario': 1, 'Nombre': 'Jose', 'Fecha/Hora': new Date('2026-04-01T08:00:00.000Z'), 'Departamento': 'IT' },
|
|
250
|
+
// 2026-04-04 (sábado) con asistencia
|
|
251
|
+
{ 'ID de usuario': 1, 'Nombre': 'Jose', 'Fecha/Hora': new Date('2026-04-04T08:00:00.000Z'), 'Departamento': 'IT' },
|
|
252
|
+
// 2026-04-08 (miércoles) con asistencia
|
|
253
|
+
{ 'ID de usuario': 1, 'Nombre': 'Jose', 'Fecha/Hora': new Date('2026-04-08T08:00:00.000Z'), 'Departamento': 'IT' },
|
|
254
|
+
// 2026-04-10 (viernes) con asistencia
|
|
255
|
+
{ 'ID de usuario': 1, 'Nombre': 'Jose', 'Fecha/Hora': new Date('2026-04-10T08:00:00.000Z'), 'Departamento': 'IT' },
|
|
256
|
+
];
|
|
257
|
+
const usuarioConfig = {
|
|
258
|
+
mensajes: {
|
|
259
|
+
falto: 'NO ASISTIÓ',
|
|
260
|
+
finDeSemana: 'WEEKEND'
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => { });
|
|
264
|
+
|
|
265
|
+
fs.existsSync.mockReturnValue(true);
|
|
266
|
+
xlsx.readFile.mockReturnValue({ SheetNames: ['Sheet1'], Sheets: { Sheet1: {} } });
|
|
267
|
+
xlsx.utils.sheet_to_json.mockReturnValue(mockData);
|
|
268
|
+
|
|
269
|
+
await generarReporte('ruta/entrada.xls', 'ruta/salida.xlsx', usuarioConfig);
|
|
270
|
+
|
|
271
|
+
expect(fs.existsSync).toHaveBeenCalledWith('ruta/entrada.xls');
|
|
272
|
+
const mockWorkbookInstance = ExcelJS.Workbook.mock.results[0].value;
|
|
273
|
+
|
|
274
|
+
// Verificar que addRow fue llamado con datos que contienen los mensajes personalizados
|
|
275
|
+
const addRowCalls = mockWorkbookInstance.addWorksheet.mock.results[0].value.addRow.mock.calls;
|
|
276
|
+
|
|
277
|
+
// Buscar filas con ausencia
|
|
278
|
+
// Días laborales sin asistencia (02, 03, 06, 07, 09) = 'NO ASISTIÓ'
|
|
279
|
+
// Fines de semana sin asistencia (05, 11, 12) = 'WEEKEND'
|
|
280
|
+
expect(addRowCalls.some(call => call[0].estado === 'NO ASISTIÓ')).toBe(true);
|
|
281
|
+
expect(addRowCalls.some(call => call[0].estado === 'WEEKEND')).toBe(true);
|
|
282
|
+
|
|
283
|
+
expect(mockWorkbookInstance.xlsx.writeFile).toHaveBeenCalledWith('ruta/salida.xlsx');
|
|
284
|
+
expect(consoleLogSpy).toHaveBeenCalledWith("✨ ¡PROCESO COMPLETADO! El archivo se generó correctamente.");
|
|
285
|
+
|
|
286
|
+
consoleLogSpy.mockRestore();
|
|
287
|
+
});
|
|
201
288
|
});
|
package/package.json
CHANGED
|
@@ -1,13 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "convertir-formato-asistencia",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "",
|
|
3
|
+
"version": "1.4.0",
|
|
4
|
+
"description": "Herramienta Node.js para convertir registros de asistencia (XLS/XLSX) a un reporte de Excel legible, agrupando por usuario y marcando ausencias.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|
|
8
8
|
"cofa": "./index.js"
|
|
9
9
|
},
|
|
10
|
-
"keywords": [
|
|
10
|
+
"keywords": [
|
|
11
|
+
"asistencia",
|
|
12
|
+
"excel",
|
|
13
|
+
"xls",
|
|
14
|
+
"xlsx",
|
|
15
|
+
"reporte",
|
|
16
|
+
"conversión",
|
|
17
|
+
"nodejs",
|
|
18
|
+
"herramienta"
|
|
19
|
+
],
|
|
11
20
|
"author": "",
|
|
12
21
|
"license": "MIT",
|
|
13
22
|
"dependencies": {
|