veltrixcode commited on
Commit
c5fa0f1
·
verified ·
1 Parent(s): f4e0b33

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +150 -34
server.js CHANGED
@@ -16,6 +16,19 @@ app.use(express.json());
16
  app.use(express.static('public'));
17
  app.use('/uploads', express.static('uploads'));
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  // Database Connection Pool
20
  const db = mysql.createPool({
21
  host: 'gateway01.eu-central-1.prod.aws.tidbcloud.com',
@@ -32,7 +45,8 @@ const db = mysql.createPool({
32
  });
33
 
34
  function initDb() {
35
- // Change profile_image_url to TEXT to avoid truncation
 
36
  const createCardholdersTable = `
37
  CREATE TABLE IF NOT EXISTS cardholders (
38
  id INT AUTO_INCREMENT PRIMARY KEY,
@@ -68,28 +82,28 @@ function initDb() {
68
  `;
69
 
70
  db.query(createCardholdersTable, (err) => {
71
- if (err) console.error('Error creating cardholders table:', err);
72
- else console.log('Cardholders table ready');
73
  });
74
 
75
  db.query(createAreasTable, (err) => {
76
- if (err) console.error('Error creating areas table:', err);
77
- else console.log('Areas table ready');
78
  });
79
 
80
  db.query(createPaymentsTable, (err) => {
81
- if (err) console.error('Error creating payments table:', err);
82
- else console.log('Payments table ready');
83
  });
84
  }
85
 
86
  // Check connection
87
  db.getConnection((err, connection) => {
88
  if (err) {
89
- console.error('Error connecting to database:', err);
90
  return;
91
  }
92
- console.log('Connected to TiDB MySQL database via Pool');
93
  connection.release();
94
  initDb();
95
  });
@@ -98,29 +112,35 @@ db.getConnection((err, connection) => {
98
 
99
  // Create Cardholder
100
  app.post('/api/cardholders', (req, res) => {
101
- console.log('Received POST /api/cardholders data:', req.body); // Debug log
102
  const { name, phone, aadhar, nominee, samriddhi, account, installments, area, profile_image_url } = req.body;
103
 
104
  // Validate required fields
105
  if (!name) {
 
106
  return res.status(400).json({ error: 'Name is required' });
107
  }
108
 
109
  const sql = `INSERT INTO cardholders (name, phone, aadhar_card, nominee_card, samriddhi_card, account_no, installments_paid, area, profile_image_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
110
- const values = [name, phone, aadhar, nominee, samriddhi, account, installments, area, profile_image_url];
 
 
 
111
 
112
  db.query(sql, values, (err, result) => {
113
  if (err) {
114
- console.error('Error inserting data:', err); // Log full error
115
  res.status(500).json({ error: 'Database error: ' + err.message });
116
  } else {
 
117
  res.status(201).json({ message: 'Cardholder added successfully', id: result.insertId });
118
  }
119
  });
120
  });
121
 
122
- // Get All Cardholders (optionally filtered by area)
123
  app.get('/api/cardholders', (req, res) => {
 
124
  const { area } = req.query;
125
  let sql = 'SELECT * FROM cardholders';
126
  let params = [];
@@ -128,15 +148,18 @@ app.get('/api/cardholders', (req, res) => {
128
  if (area) {
129
  sql += ' WHERE area = ?';
130
  params.push(area);
 
131
  }
132
 
133
  sql += ' ORDER BY created_at DESC';
 
134
 
135
  db.query(sql, params, (err, results) => {
136
  if (err) {
137
- console.error('Error fetching data:', err);
138
  res.status(500).json({ error: 'Database error' });
139
  } else {
 
140
  res.json(results);
141
  }
142
  });
@@ -144,8 +167,10 @@ app.get('/api/cardholders', (req, res) => {
144
 
145
  // Update Cardholder
146
  app.put('/api/cardholders/:id', (req, res) => {
 
147
  const { id } = req.params;
148
- // Map incoming keys to what we expect (handle both form inputs and raw DB objects)
 
149
  const name = req.body.name;
150
  const phone = req.body.phone;
151
  const area = req.body.area;
@@ -159,12 +184,16 @@ app.put('/api/cardholders/:id', (req, res) => {
159
 
160
  const sql = `UPDATE cardholders SET name=?, phone=?, aadhar_card=?, nominee_card=?, samriddhi_card=?, account_no=?, installments_paid=?, area=?, profile_image_url=? WHERE id=?`;
161
  const values = [name, phone, aadhar, nominee, samriddhi, account, installments, area, profile_image_url, id];
 
 
 
162
 
163
  db.query(sql, values, (err, result) => {
164
  if (err) {
165
- console.error('Error updating user:', err);
166
  res.status(500).json({ error: 'Database error: ' + err.message });
167
  } else {
 
168
  res.json({ message: 'User updated successfully' });
169
  }
170
  });
@@ -172,13 +201,19 @@ app.put('/api/cardholders/:id', (req, res) => {
172
 
173
  // Delete Cardholder
174
  app.delete('/api/cardholders/:id', (req, res) => {
 
175
  const { id } = req.params;
 
 
176
  const sql = 'DELETE FROM cardholders WHERE id = ?';
 
 
177
  db.query(sql, [id], (err, result) => {
178
  if (err) {
179
- console.error('Error deleting user:', err);
180
  res.status(500).json({ error: 'Database error' });
181
  } else {
 
182
  res.json({ message: 'User deleted successfully' });
183
  }
184
  });
@@ -188,12 +223,16 @@ app.delete('/api/cardholders/:id', (req, res) => {
188
 
189
  // Get Areas
190
  app.get('/api/areas', (req, res) => {
 
191
  const sql = 'SELECT * FROM areas ORDER BY name ASC';
 
 
192
  db.query(sql, (err, results) => {
193
  if (err) {
194
- console.error('Error fetching areas:', err);
195
  res.status(500).json({ error: 'Database error' });
196
  } else {
 
197
  res.json(results.map(row => row.name));
198
  }
199
  });
@@ -201,19 +240,28 @@ app.get('/api/areas', (req, res) => {
201
 
202
  // Add Area
203
  app.post('/api/areas', (req, res) => {
 
204
  const { name } = req.body;
205
- if (!name) return res.status(400).json({ error: 'Area name is required' });
 
 
 
 
206
 
207
  const sql = 'INSERT INTO areas (name) VALUES (?)';
 
 
 
208
  db.query(sql, [name], (err, result) => {
209
  if (err) {
210
- // Check for duplicate entry
211
  if (err.code === 'ER_DUP_ENTRY') {
 
212
  return res.status(409).json({ error: 'Area already exists' });
213
  }
214
- console.error('Error adding area:', err);
215
  res.status(500).json({ error: 'Database error' });
216
  } else {
 
217
  res.status(201).json({ message: 'Area added', id: result.insertId });
218
  }
219
  });
@@ -222,40 +270,77 @@ app.post('/api/areas', (req, res) => {
222
  // --- Payments ---
223
 
224
  app.post('/api/payments', (req, res) => {
 
 
 
225
  const { cardholderId, amount, date } = req.body;
226
 
227
- if (!cardholderId || !amount || !date) {
228
- return res.status(400).json({ error: 'Missing fields' });
 
 
 
 
 
 
229
  }
 
 
 
 
 
 
230
 
231
  const insertPayment = 'INSERT INTO payments (cardholder_id, amount, payment_date) VALUES (?, ?, ?)';
232
  const updateCardholder = 'UPDATE cardholders SET installments_paid = installments_paid + 1 WHERE id = ?';
233
 
 
 
234
  db.beginTransaction(err => {
235
- if (err) return res.status(500).json({ error: 'Transaction error' });
 
 
 
 
 
 
 
236
 
237
  db.query(insertPayment, [cardholderId, amount, date], (err, result) => {
238
  if (err) {
 
239
  return db.rollback(() => {
240
- console.error('Error recording payment:', err);
241
- res.status(500).json({ error: 'Database error' });
242
  });
243
  }
244
 
 
 
 
 
 
245
  db.query(updateCardholder, [cardholderId], (err, result) => {
246
  if (err) {
 
247
  return db.rollback(() => {
248
- console.error('Error updating installment count:', err);
249
- res.status(500).json({ error: 'Database error' });
250
  });
251
  }
252
 
 
 
 
253
  db.commit(err => {
254
  if (err) {
 
255
  return db.rollback(() => {
256
- res.status(500).json({ error: 'Commit error' });
 
257
  });
258
  }
 
259
  res.status(201).json({ message: 'Payment recorded and installment added' });
260
  });
261
  });
@@ -265,14 +350,19 @@ app.post('/api/payments', (req, res) => {
265
 
266
  // Get Payments for Cardholder
267
  app.get('/api/payments/:cardholderId', (req, res) => {
 
268
  const { cardholderId } = req.params;
 
 
269
  const sql = 'SELECT * FROM payments WHERE cardholder_id = ? ORDER BY payment_date DESC, created_at DESC';
 
270
 
271
  db.query(sql, [cardholderId], (err, results) => {
272
  if (err) {
273
- console.error('Error fetching payments:', err);
274
  res.status(500).json({ error: 'Database error' });
275
  } else {
 
276
  res.json(results);
277
  }
278
  });
@@ -281,35 +371,61 @@ app.get('/api/payments/:cardholderId', (req, res) => {
281
  // --- System Reset ---
282
 
283
  app.post('/api/admin/flush', (req, res) => {
 
 
284
  const dropPayments = 'DROP TABLE IF EXISTS payments';
285
  const dropCardholders = 'DROP TABLE IF EXISTS cardholders';
286
  const dropAreas = 'DROP TABLE IF EXISTS areas';
287
 
 
288
  db.query(dropPayments, (err) => {
289
- if (err) console.error('Error dropping payments:', err);
 
290
 
 
291
  db.query(dropCardholders, (err) => {
292
  if (err) {
293
- console.error('Error dropping cardholders:', err);
294
  return res.status(500).json({ error: 'Failed to drop cardholders table' });
295
  }
 
 
 
296
  db.query(dropAreas, (err) => {
297
  if (err) {
298
- console.error('Error dropping areas:', err);
299
  return res.status(500).json({ error: 'Failed to drop areas table' });
300
  }
 
301
 
302
- // Re-init DB
303
  initDb();
 
304
  res.json({ message: 'System flushed and reset successfully' });
305
  });
306
  });
307
  });
308
  });
309
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  // Start server on 0.0.0.0 to allow external connections
311
  app.listen(port, host, () => {
 
 
 
312
  console.log(`Server running at http://${host}:${port}`);
313
  console.log(`Accessible locally at http://localhost:${port}`);
314
  console.log(`Accessible on network at http://<your-ip>:${port}`);
 
315
  });
 
16
  app.use(express.static('public'));
17
  app.use('/uploads', express.static('uploads'));
18
 
19
+ // Request logging middleware
20
+ app.use((req, res, next) => {
21
+ console.log(`\n[${new Date().toISOString()}] ${req.method} ${req.url}`);
22
+ console.log('Headers:', JSON.stringify(req.headers, null, 2));
23
+ if (req.body && Object.keys(req.body).length > 0) {
24
+ console.log('Body:', JSON.stringify(req.body, null, 2));
25
+ }
26
+ if (req.query && Object.keys(req.query).length > 0) {
27
+ console.log('Query:', JSON.stringify(req.query, null, 2));
28
+ }
29
+ next();
30
+ });
31
+
32
  // Database Connection Pool
33
  const db = mysql.createPool({
34
  host: 'gateway01.eu-central-1.prod.aws.tidbcloud.com',
 
45
  });
46
 
47
  function initDb() {
48
+ console.log('\n[DB Init] Starting database initialization...');
49
+
50
  const createCardholdersTable = `
51
  CREATE TABLE IF NOT EXISTS cardholders (
52
  id INT AUTO_INCREMENT PRIMARY KEY,
 
82
  `;
83
 
84
  db.query(createCardholdersTable, (err) => {
85
+ if (err) console.error('[DB Init] Error creating cardholders table:', err);
86
+ else console.log('[DB Init] Cardholders table ready');
87
  });
88
 
89
  db.query(createAreasTable, (err) => {
90
+ if (err) console.error('[DB Init] Error creating areas table:', err);
91
+ else console.log('[DB Init] Areas table ready');
92
  });
93
 
94
  db.query(createPaymentsTable, (err) => {
95
+ if (err) console.error('[DB Init] Error creating payments table:', err);
96
+ else console.log('[DB Init] Payments table ready');
97
  });
98
  }
99
 
100
  // Check connection
101
  db.getConnection((err, connection) => {
102
  if (err) {
103
+ console.error('[DB Connection] Error connecting to database:', err);
104
  return;
105
  }
106
+ console.log('[DB Connection] Connected to TiDB MySQL database via Pool');
107
  connection.release();
108
  initDb();
109
  });
 
112
 
113
  // Create Cardholder
114
  app.post('/api/cardholders', (req, res) => {
115
+ console.log('\n[POST /api/cardholders] Processing request...');
116
  const { name, phone, aadhar, nominee, samriddhi, account, installments, area, profile_image_url } = req.body;
117
 
118
  // Validate required fields
119
  if (!name) {
120
+ console.log('[POST /api/cardholders] Validation failed: Name is required');
121
  return res.status(400).json({ error: 'Name is required' });
122
  }
123
 
124
  const sql = `INSERT INTO cardholders (name, phone, aadhar_card, nominee_card, samriddhi_card, account_no, installments_paid, area, profile_image_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
125
+ const values = [name, phone, aadhar, nominee, samriddhi, account, installments || 0, area, profile_image_url];
126
+
127
+ console.log('[POST /api/cardholders] Executing SQL:', sql);
128
+ console.log('[POST /api/cardholders] Values:', values);
129
 
130
  db.query(sql, values, (err, result) => {
131
  if (err) {
132
+ console.error('[POST /api/cardholders] Database error:', err);
133
  res.status(500).json({ error: 'Database error: ' + err.message });
134
  } else {
135
+ console.log('[POST /api/cardholders] Success! Inserted ID:', result.insertId);
136
  res.status(201).json({ message: 'Cardholder added successfully', id: result.insertId });
137
  }
138
  });
139
  });
140
 
141
+ // Get All Cardholders
142
  app.get('/api/cardholders', (req, res) => {
143
+ console.log('\n[GET /api/cardholders] Processing request...');
144
  const { area } = req.query;
145
  let sql = 'SELECT * FROM cardholders';
146
  let params = [];
 
148
  if (area) {
149
  sql += ' WHERE area = ?';
150
  params.push(area);
151
+ console.log('[GET /api/cardholders] Filtering by area:', area);
152
  }
153
 
154
  sql += ' ORDER BY created_at DESC';
155
+ console.log('[GET /api/cardholders] Executing SQL:', sql);
156
 
157
  db.query(sql, params, (err, results) => {
158
  if (err) {
159
+ console.error('[GET /api/cardholders] Database error:', err);
160
  res.status(500).json({ error: 'Database error' });
161
  } else {
162
+ console.log('[GET /api/cardholders] Success! Returned', results.length, 'records');
163
  res.json(results);
164
  }
165
  });
 
167
 
168
  // Update Cardholder
169
  app.put('/api/cardholders/:id', (req, res) => {
170
+ console.log('\n[PUT /api/cardholders/:id] Processing request...');
171
  const { id } = req.params;
172
+ console.log('[PUT /api/cardholders/:id] Cardholder ID:', id);
173
+
174
  const name = req.body.name;
175
  const phone = req.body.phone;
176
  const area = req.body.area;
 
184
 
185
  const sql = `UPDATE cardholders SET name=?, phone=?, aadhar_card=?, nominee_card=?, samriddhi_card=?, account_no=?, installments_paid=?, area=?, profile_image_url=? WHERE id=?`;
186
  const values = [name, phone, aadhar, nominee, samriddhi, account, installments, area, profile_image_url, id];
187
+
188
+ console.log('[PUT /api/cardholders/:id] Executing SQL:', sql);
189
+ console.log('[PUT /api/cardholders/:id] Values:', values);
190
 
191
  db.query(sql, values, (err, result) => {
192
  if (err) {
193
+ console.error('[PUT /api/cardholders/:id] Database error:', err);
194
  res.status(500).json({ error: 'Database error: ' + err.message });
195
  } else {
196
+ console.log('[PUT /api/cardholders/:id] Success! Affected rows:', result.affectedRows);
197
  res.json({ message: 'User updated successfully' });
198
  }
199
  });
 
201
 
202
  // Delete Cardholder
203
  app.delete('/api/cardholders/:id', (req, res) => {
204
+ console.log('\n[DELETE /api/cardholders/:id] Processing request...');
205
  const { id } = req.params;
206
+ console.log('[DELETE /api/cardholders/:id] Cardholder ID:', id);
207
+
208
  const sql = 'DELETE FROM cardholders WHERE id = ?';
209
+ console.log('[DELETE /api/cardholders/:id] Executing SQL:', sql);
210
+
211
  db.query(sql, [id], (err, result) => {
212
  if (err) {
213
+ console.error('[DELETE /api/cardholders/:id] Database error:', err);
214
  res.status(500).json({ error: 'Database error' });
215
  } else {
216
+ console.log('[DELETE /api/cardholders/:id] Success! Affected rows:', result.affectedRows);
217
  res.json({ message: 'User deleted successfully' });
218
  }
219
  });
 
223
 
224
  // Get Areas
225
  app.get('/api/areas', (req, res) => {
226
+ console.log('\n[GET /api/areas] Processing request...');
227
  const sql = 'SELECT * FROM areas ORDER BY name ASC';
228
+ console.log('[GET /api/areas] Executing SQL:', sql);
229
+
230
  db.query(sql, (err, results) => {
231
  if (err) {
232
+ console.error('[GET /api/areas] Database error:', err);
233
  res.status(500).json({ error: 'Database error' });
234
  } else {
235
+ console.log('[GET /api/areas] Success! Returned', results.length, 'areas');
236
  res.json(results.map(row => row.name));
237
  }
238
  });
 
240
 
241
  // Add Area
242
  app.post('/api/areas', (req, res) => {
243
+ console.log('\n[POST /api/areas] Processing request...');
244
  const { name } = req.body;
245
+
246
+ if (!name) {
247
+ console.log('[POST /api/areas] Validation failed: Area name is required');
248
+ return res.status(400).json({ error: 'Area name is required' });
249
+ }
250
 
251
  const sql = 'INSERT INTO areas (name) VALUES (?)';
252
+ console.log('[POST /api/areas] Executing SQL:', sql);
253
+ console.log('[POST /api/areas] Area name:', name);
254
+
255
  db.query(sql, [name], (err, result) => {
256
  if (err) {
 
257
  if (err.code === 'ER_DUP_ENTRY') {
258
+ console.log('[POST /api/areas] Duplicate entry:', name);
259
  return res.status(409).json({ error: 'Area already exists' });
260
  }
261
+ console.error('[POST /api/areas] Database error:', err);
262
  res.status(500).json({ error: 'Database error' });
263
  } else {
264
+ console.log('[POST /api/areas] Success! Inserted ID:', result.insertId);
265
  res.status(201).json({ message: 'Area added', id: result.insertId });
266
  }
267
  });
 
270
  // --- Payments ---
271
 
272
  app.post('/api/payments', (req, res) => {
273
+ console.log('\n[POST /api/payments] Processing request...');
274
+ console.log('[POST /api/payments] Request body:', JSON.stringify(req.body, null, 2));
275
+
276
  const { cardholderId, amount, date } = req.body;
277
 
278
+ // Detailed validation logging
279
+ if (!cardholderId) {
280
+ console.log('[POST /api/payments] Validation failed: cardholderId is missing');
281
+ return res.status(400).json({ error: 'Missing cardholderId field' });
282
+ }
283
+ if (!amount) {
284
+ console.log('[POST /api/payments] Validation failed: amount is missing');
285
+ return res.status(400).json({ error: 'Missing amount field' });
286
  }
287
+ if (!date) {
288
+ console.log('[POST /api/payments] Validation failed: date is missing');
289
+ return res.status(400).json({ error: 'Missing date field' });
290
+ }
291
+
292
+ console.log('[POST /api/payments] Validated data:', { cardholderId, amount, date });
293
 
294
  const insertPayment = 'INSERT INTO payments (cardholder_id, amount, payment_date) VALUES (?, ?, ?)';
295
  const updateCardholder = 'UPDATE cardholders SET installments_paid = installments_paid + 1 WHERE id = ?';
296
 
297
+ console.log('[POST /api/payments] Starting transaction...');
298
+
299
  db.beginTransaction(err => {
300
+ if (err) {
301
+ console.error('[POST /api/payments] Transaction begin error:', err);
302
+ return res.status(500).json({ error: 'Transaction error: ' + err.message });
303
+ }
304
+
305
+ console.log('[POST /api/payments] Inserting payment record...');
306
+ console.log('[POST /api/payments] SQL:', insertPayment);
307
+ console.log('[POST /api/payments] Values:', [cardholderId, amount, date]);
308
 
309
  db.query(insertPayment, [cardholderId, amount, date], (err, result) => {
310
  if (err) {
311
+ console.error('[POST /api/payments] Error inserting payment:', err);
312
  return db.rollback(() => {
313
+ console.log('[POST /api/payments] Transaction rolled back');
314
+ res.status(500).json({ error: 'Database error inserting payment: ' + err.message });
315
  });
316
  }
317
 
318
+ console.log('[POST /api/payments] Payment inserted successfully. ID:', result.insertId);
319
+ console.log('[POST /api/payments] Updating cardholder installment count...');
320
+ console.log('[POST /api/payments] SQL:', updateCardholder);
321
+ console.log('[POST /api/payments] Cardholder ID:', cardholderId);
322
+
323
  db.query(updateCardholder, [cardholderId], (err, result) => {
324
  if (err) {
325
+ console.error('[POST /api/payments] Error updating installment count:', err);
326
  return db.rollback(() => {
327
+ console.log('[POST /api/payments] Transaction rolled back');
328
+ res.status(500).json({ error: 'Database error updating installments: ' + err.message });
329
  });
330
  }
331
 
332
+ console.log('[POST /api/payments] Installment count updated. Affected rows:', result.affectedRows);
333
+ console.log('[POST /api/payments] Committing transaction...');
334
+
335
  db.commit(err => {
336
  if (err) {
337
+ console.error('[POST /api/payments] Commit error:', err);
338
  return db.rollback(() => {
339
+ console.log('[POST /api/payments] Transaction rolled back');
340
+ res.status(500).json({ error: 'Commit error: ' + err.message });
341
  });
342
  }
343
+ console.log('[POST /api/payments] Transaction committed successfully!');
344
  res.status(201).json({ message: 'Payment recorded and installment added' });
345
  });
346
  });
 
350
 
351
  // Get Payments for Cardholder
352
  app.get('/api/payments/:cardholderId', (req, res) => {
353
+ console.log('\n[GET /api/payments/:cardholderId] Processing request...');
354
  const { cardholderId } = req.params;
355
+ console.log('[GET /api/payments/:cardholderId] Cardholder ID:', cardholderId);
356
+
357
  const sql = 'SELECT * FROM payments WHERE cardholder_id = ? ORDER BY payment_date DESC, created_at DESC';
358
+ console.log('[GET /api/payments/:cardholderId] Executing SQL:', sql);
359
 
360
  db.query(sql, [cardholderId], (err, results) => {
361
  if (err) {
362
+ console.error('[GET /api/payments/:cardholderId] Database error:', err);
363
  res.status(500).json({ error: 'Database error' });
364
  } else {
365
+ console.log('[GET /api/payments/:cardholderId] Success! Returned', results.length, 'payments');
366
  res.json(results);
367
  }
368
  });
 
371
  // --- System Reset ---
372
 
373
  app.post('/api/admin/flush', (req, res) => {
374
+ console.log('\n[POST /api/admin/flush] ⚠️ WARNING: System flush requested!');
375
+
376
  const dropPayments = 'DROP TABLE IF EXISTS payments';
377
  const dropCardholders = 'DROP TABLE IF EXISTS cardholders';
378
  const dropAreas = 'DROP TABLE IF EXISTS areas';
379
 
380
+ console.log('[POST /api/admin/flush] Dropping payments table...');
381
  db.query(dropPayments, (err) => {
382
+ if (err) console.error('[POST /api/admin/flush] Error dropping payments:', err);
383
+ else console.log('[POST /api/admin/flush] Payments table dropped');
384
 
385
+ console.log('[POST /api/admin/flush] Dropping cardholders table...');
386
  db.query(dropCardholders, (err) => {
387
  if (err) {
388
+ console.error('[POST /api/admin/flush] Error dropping cardholders:', err);
389
  return res.status(500).json({ error: 'Failed to drop cardholders table' });
390
  }
391
+ console.log('[POST /api/admin/flush] Cardholders table dropped');
392
+
393
+ console.log('[POST /api/admin/flush] Dropping areas table...');
394
  db.query(dropAreas, (err) => {
395
  if (err) {
396
+ console.error('[POST /api/admin/flush] Error dropping areas:', err);
397
  return res.status(500).json({ error: 'Failed to drop areas table' });
398
  }
399
+ console.log('[POST /api/admin/flush] Areas table dropped');
400
 
401
+ console.log('[POST /api/admin/flush] Reinitializing database...');
402
  initDb();
403
+ console.log('[POST /api/admin/flush] ✅ System flush completed successfully');
404
  res.json({ message: 'System flushed and reset successfully' });
405
  });
406
  });
407
  });
408
  });
409
 
410
+ // 404 handler
411
+ app.use((req, res) => {
412
+ console.log(`\n[404] Route not found: ${req.method} ${req.url}`);
413
+ res.status(404).json({ error: 'Route not found' });
414
+ });
415
+
416
+ // Error handler
417
+ app.use((err, req, res, next) => {
418
+ console.error('\n[Error Handler] Unhandled error:', err);
419
+ res.status(500).json({ error: 'Internal server error: ' + err.message });
420
+ });
421
+
422
  // Start server on 0.0.0.0 to allow external connections
423
  app.listen(port, host, () => {
424
+ console.log('\n========================================');
425
+ console.log('🚀 Server Started Successfully!');
426
+ console.log('========================================');
427
  console.log(`Server running at http://${host}:${port}`);
428
  console.log(`Accessible locally at http://localhost:${port}`);
429
  console.log(`Accessible on network at http://<your-ip>:${port}`);
430
+ console.log('========================================\n');
431
  });