refactor
This commit is contained in:
66
src/routes/export.js
Normal file
66
src/routes/export.js
Normal file
@@ -0,0 +1,66 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { calculateNetHours } = require('../utils/timeCalculator');
|
||||
|
||||
/**
|
||||
* Initialize export routes with database instance
|
||||
* @param {Database} db - SQLite database instance
|
||||
* @returns {Router} - Configured Express router
|
||||
*/
|
||||
function createExportRouter(db) {
|
||||
/**
|
||||
* GET /api/export?from=YYYY-MM-DD&to=YYYY-MM-DD
|
||||
* Export entries as CSV
|
||||
*/
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const { from, to } = req.query;
|
||||
|
||||
let query = 'SELECT * FROM entries';
|
||||
const params = [];
|
||||
|
||||
if (from && to) {
|
||||
query += ' WHERE date >= ? AND date <= ?';
|
||||
params.push(from, to);
|
||||
} else if (from) {
|
||||
query += ' WHERE date >= ?';
|
||||
params.push(from);
|
||||
} else if (to) {
|
||||
query += ' WHERE date <= ?';
|
||||
params.push(to);
|
||||
}
|
||||
|
||||
query += ' ORDER BY date ASC, start_time ASC';
|
||||
|
||||
const stmt = db.prepare(query);
|
||||
const entries = stmt.all(...params);
|
||||
|
||||
// Generate CSV with German formatting
|
||||
let csv = 'Datum,Startzeit,Endzeit,Pause in Minuten,Gesamtstunden\n';
|
||||
|
||||
entries.forEach(entry => {
|
||||
const calculated = calculateNetHours(entry.start_time, entry.end_time, entry.pause_minutes);
|
||||
|
||||
// Format date as DD.MM.YYYY
|
||||
const [year, month, day] = entry.date.split('-');
|
||||
const formattedDate = `${day}.${month}.${year}`;
|
||||
|
||||
// Use comma as decimal separator for hours
|
||||
const netHoursFormatted = calculated.netHours.toFixed(2).replace('.', ',');
|
||||
|
||||
csv += `${formattedDate},${entry.start_time},${entry.end_time},${entry.pause_minutes},${netHoursFormatted}\n`;
|
||||
});
|
||||
|
||||
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
|
||||
res.setHeader('Content-Disposition', 'attachment; filename="zeiterfassung.csv"');
|
||||
res.send(csv);
|
||||
} catch (error) {
|
||||
console.error('Error exporting entries:', error);
|
||||
res.status(500).json({ error: 'Failed to export entries' });
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
module.exports = createExportRouter;
|
||||
Reference in New Issue
Block a user