-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathworkEntries.js
More file actions
310 lines (260 loc) · 9.06 KB
/
Copy pathworkEntries.js
File metadata and controls
310 lines (260 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
const express = require('express');
const { getDatabase } = require('../database/init');
const { authenticateUser } = require('../middleware/auth');
const { workEntrySchema, updateWorkEntrySchema } = require('../validation/schemas');
const router = express.Router();
// Dates are persisted as ISO calendar days (YYYY-MM-DD) so that exports and
// clients receive a date rather than a timestamp.
function toDateOnly(value) {
if (value instanceof Date) {
return value.toISOString().split('T')[0];
}
return String(value).split('T')[0];
}
// All routes require authentication
router.use(authenticateUser);
// Get all work entries for authenticated user (with optional client filter)
router.get('/', (req, res) => {
const { clientId } = req.query;
const db = getDatabase();
let query = `
SELECT we.id, we.client_id, we.hours, we.description, we.date,
we.created_at, we.updated_at, c.name as client_name
FROM work_entries we
JOIN clients c ON we.client_id = c.id
WHERE we.user_email = ?
`;
const params = [req.userEmail];
if (clientId) {
const clientIdNum = parseInt(clientId);
if (isNaN(clientIdNum)) {
return res.status(400).json({ error: 'Invalid client ID' });
}
query += ' AND we.client_id = ?';
params.push(clientIdNum);
}
query += ' ORDER BY we.date DESC, we.created_at DESC';
db.all(query, params, (err, rows) => {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
res.json({ workEntries: rows });
});
});
// Get specific work entry
router.get('/:id', (req, res) => {
const workEntryId = parseInt(req.params.id);
if (isNaN(workEntryId)) {
return res.status(400).json({ error: 'Invalid work entry ID' });
}
const db = getDatabase();
db.get(
`SELECT we.id, we.client_id, we.hours, we.description, we.date,
we.created_at, we.updated_at, c.name as client_name
FROM work_entries we
JOIN clients c ON we.client_id = c.id
WHERE we.id = ? AND we.user_email = ?`,
[workEntryId, req.userEmail],
(err, row) => {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
if (!row) {
return res.status(404).json({ error: 'Work entry not found' });
}
res.json({ workEntry: row });
}
);
});
// Create new work entry
router.post('/', (req, res, next) => {
try {
const { error, value } = workEntrySchema.validate(req.body);
if (error) {
return next(error);
}
const { clientId, hours, description, date } = value;
const db = getDatabase();
// Verify client exists and belongs to user
db.get(
'SELECT id FROM clients WHERE id = ? AND user_email = ?',
[clientId, req.userEmail],
(err, row) => {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
if (!row) {
return res.status(400).json({ error: 'Client not found or does not belong to user' });
}
// Create work entry
db.run(
'INSERT INTO work_entries (client_id, user_email, hours, description, date) VALUES (?, ?, ?, ?, ?)',
[clientId, req.userEmail, hours, description || null, toDateOnly(date)],
function(err) {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ error: 'Failed to create work entry' });
}
// Return the created work entry with client name
db.get(
`SELECT we.id, we.client_id, we.hours, we.description, we.date,
we.created_at, we.updated_at, c.name as client_name
FROM work_entries we
JOIN clients c ON we.client_id = c.id
WHERE we.id = ?`,
[this.lastID],
(err, row) => {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ error: 'Work entry created but failed to retrieve' });
}
res.status(201).json({
message: 'Work entry created successfully',
workEntry: row
});
}
);
}
);
}
);
} catch (error) {
next(error);
}
});
// Update work entry
router.put('/:id', (req, res, next) => {
try {
const workEntryId = parseInt(req.params.id);
if (isNaN(workEntryId)) {
return res.status(400).json({ error: 'Invalid work entry ID' });
}
const { error, value } = updateWorkEntrySchema.validate(req.body);
if (error) {
return next(error);
}
const db = getDatabase();
// Check if work entry exists and belongs to user
db.get(
'SELECT id FROM work_entries WHERE id = ? AND user_email = ?',
[workEntryId, req.userEmail],
(err, row) => {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
if (!row) {
return res.status(404).json({ error: 'Work entry not found' });
}
// If clientId is being updated, verify it belongs to user
if (value.clientId) {
db.get(
'SELECT id FROM clients WHERE id = ? AND user_email = ?',
[value.clientId, req.userEmail],
(err, clientRow) => {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
if (!clientRow) {
return res.status(400).json({ error: 'Client not found or does not belong to user' });
}
performUpdate();
}
);
} else {
performUpdate();
}
function performUpdate() {
// Build update query dynamically
const updates = [];
const values = [];
if (value.clientId !== undefined) {
updates.push('client_id = ?');
values.push(value.clientId);
}
if (value.hours !== undefined) {
updates.push('hours = ?');
values.push(value.hours);
}
if (value.description !== undefined) {
updates.push('description = ?');
values.push(value.description || null);
}
if (value.date !== undefined) {
updates.push('date = ?');
values.push(toDateOnly(value.date));
}
updates.push('updated_at = CURRENT_TIMESTAMP');
values.push(workEntryId, req.userEmail);
const query = `UPDATE work_entries SET ${updates.join(', ')} WHERE id = ? AND user_email = ?`;
db.run(query, values, function(err) {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ error: 'Failed to update work entry' });
}
// Return updated work entry with client name
db.get(
`SELECT we.id, we.client_id, we.hours, we.description, we.date,
we.created_at, we.updated_at, c.name as client_name
FROM work_entries we
JOIN clients c ON we.client_id = c.id
WHERE we.id = ?`,
[workEntryId],
(err, row) => {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ error: 'Work entry updated but failed to retrieve' });
}
res.json({
message: 'Work entry updated successfully',
workEntry: row
});
}
);
});
}
}
);
} catch (error) {
next(error);
}
});
// Delete work entry
router.delete('/:id', (req, res) => {
const workEntryId = parseInt(req.params.id);
if (isNaN(workEntryId)) {
return res.status(400).json({ error: 'Invalid work entry ID' });
}
const db = getDatabase();
// Check if work entry exists and belongs to user
db.get(
'SELECT id FROM work_entries WHERE id = ? AND user_email = ?',
[workEntryId, req.userEmail],
(err, row) => {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ error: 'Internal server error' });
}
if (!row) {
return res.status(404).json({ error: 'Work entry not found' });
}
// Delete work entry
db.run(
'DELETE FROM work_entries WHERE id = ? AND user_email = ?',
[workEntryId, req.userEmail],
function(err) {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ error: 'Failed to delete work entry' });
}
res.json({ message: 'Work entry deleted successfully' });
}
);
}
);
});
module.exports = router;