-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1228 lines (1084 loc) · 34.2 KB
/
server.js
File metadata and controls
1228 lines (1084 loc) · 34.2 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const path = require('path');
const { Pool } = require('pg');
const multer = require('multer');
const fs = require('fs'); // Apenas uma declaração de 'fs' é necessária
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// Configure multer for file uploads
const upload = multer({
dest: 'uploads/',
limits: {
fileSize: 5 * 1024 * 1024 // 5MB limit
}
});
// =================== CORREÇÃO DO BANCO DE DADOS ===================
// Lógica para ler a senha do secret do Docker ou do .env
const password = process.env.DB_PASSWORD_FILE
? fs.readFileSync(process.env.DB_PASSWORD_FILE, 'utf8').trim()
: process.env.DB_PASSWORD;
// Configuração do Pool usando variáveis de ambiente individuais
const pool = new Pool({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USERNAME,
password: password, // Usamos a senha lida do secret ou do .env
database: process.env.DB_DATABASE,
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
// =================== FIM DA CORREÇÃO ===================
// Database connection with retry
async function connectWithRetry() {
let retries = 5;
while (retries) {
try {
const client = await pool.connect();
console.log('✅ Connected to PostgreSQL database');
client.release();
break;
} catch (err) {
console.log(`❌ Database connection failed. Retries left: ${retries - 1}`);
retries -= 1;
if (retries === 0) {
console.error('❌ Could not connect to database:', err.stack);
process.exit(1);
}
await new Promise(res => setTimeout(res, 5000));
}
}
}
// Enhanced security middleware
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://cdnjs.cloudflare.com"],
fontSrc: ["'self'", "https://fonts.gstatic.com", "https://cdnjs.cloudflare.com"],
scriptSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'"],
frameSrc: ["'none'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
workerSrc: ["'none'"],
},
},
crossOriginEmbedderPolicy: false,
crossOriginResourcePolicy: { policy: "cross-origin" }
}));
app.use(cors({
origin: process.env.ALLOWED_ORIGINS?.split(',') || [
'http://localhost:3000',
'https://sms.druzzo.com.br',
'http://localhost:8080'
],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
}));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Serve static files with proper headers
app.use(express.static(path.join(__dirname), {
setHeaders: (res, path) => {
if (path.endsWith('.css')) {
res.setHeader('Content-Type', 'text/css');
} else if (path.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript');
}
}
}));
app.use('/css', express.static(path.join(__dirname, 'css')));
app.use('/js', express.static(path.join(__dirname, 'js')));
app.use('/public', express.static(path.join(__dirname, 'public')));
// Enhanced request logging middleware
app.use((req, res, next) => {
const timestamp = new Date().toISOString();
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.ip;
console.log(`${timestamp} - ${req.method} ${req.path} - IP: ${ip} - User-Agent: ${req.get('User-Agent')?.substring(0, 50)}...`);
next();
});
// Rate limiting middleware (simple implementation)
const requestCounts = new Map();
const RATE_LIMIT_WINDOW = 60000; // 1 minute
const RATE_LIMIT_MAX = 100; // requests per window
app.use((req, res, next) => {
const ip = req.ip;
const now = Date.now();
if (!requestCounts.has(ip)) {
requestCounts.set(ip, { count: 1, resetTime: now + RATE_LIMIT_WINDOW });
} else {
const clientData = requestCounts.get(ip);
if (now > clientData.resetTime) {
clientData.count = 1;
clientData.resetTime = now + RATE_LIMIT_WINDOW;
} else {
clientData.count++;
if (clientData.count > RATE_LIMIT_MAX) {
return res.status(429).json({
error: 'Too many requests',
message: 'Rate limit exceeded. Please try again later.'
});
}
}
}
next();
});
// Enhanced health check endpoint
app.get('/health', async (req, res) => {
try {
const dbResult = await pool.query('SELECT NOW(), version()');
const memUsage = process.memoryUsage();
res.status(200).json({
status: 'healthy',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
environment: process.env.NODE_ENV || 'development',
version: '2.0.0',
database: {
status: 'connected',
timestamp: dbResult.rows[0].now,
version: dbResult.rows[0].version.split(' ')[0]
},
memory: {
used: Math.round(memUsage.heapUsed / 1024 / 1024) + ' MB',
total: Math.round(memUsage.heapTotal / 1024 / 1024) + ' MB',
external: Math.round(memUsage.external / 1024 / 1024) + ' MB',
rss: Math.round(memUsage.rss / 1024 / 1024) + ' MB'
},
system: {
platform: process.platform,
nodeVersion: process.version,
pid: process.pid
}
});
} catch (error) {
console.error('Health check failed:', error);
res.status(503).json({
status: 'unhealthy',
timestamp: new Date().toISOString(),
error: 'Database connection failed',
uptime: process.uptime(),
details: process.env.NODE_ENV === 'development' ? error.message : 'Service unavailable'
});
}
});
// Serve main HTML file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// API information endpoint
app.get('/api', (req, res) => {
res.json({
name: 'SMS App DS API',
version: '2.0.0',
description: 'Sistema de Comandos SMS para Rastreadores',
endpoints: {
models: {
'GET /api/models': 'Listar modelos de equipamentos',
'POST /api/models': 'Adicionar novo modelo',
'PUT /api/models/:id': 'Atualizar modelo',
'DELETE /api/models/:id': 'Deletar modelo'
},
commands: {
'GET /api/models/:modelId/commands': 'Listar comandos por modelo',
'POST /api/commands': 'Adicionar novo comando',
'PUT /api/commands/:id': 'Atualizar comando',
'DELETE /api/commands/:id': 'Deletar comando'
},
sms: {
'POST /api/sms/send': 'Enviar comando SMS',
'GET /api/sms/history': 'Histórico de envios',
'GET /api/sms/stats': 'Estatísticas de envios'
},
reports: {
'GET /api/reports/pdf': 'Gerar relatório PDF',
'GET /api/reports/csv': 'Exportar dados CSV'
}
},
documentation: 'https://github.com/DevHMedeiros/sms-app-ds',
support: 'admin@druzzo.com.br'
});
});
// ==================== DEVICE MODELS ROUTES ====================
// Get all device models
app.get('/api/models', async (req, res) => {
try {
const result = await pool.query(`
SELECT
m.*,
COUNT(c.id) as command_count
FROM device_models m
LEFT JOIN commands c ON m.id = c.model_id
GROUP BY m.id
ORDER BY m.name
`);
res.json({
success: true,
data: result.rows,
count: result.rows.length
});
} catch (error) {
console.error('Error fetching models:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch models',
message: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error'
});
}
});
// Add new device model
app.post('/api/models', async (req, res) => {
try {
const { name, description } = req.body;
if (!name || name.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Model name is required'
});
}
const result = await pool.query(
'INSERT INTO device_models (name, description, created_at) VALUES ($1, $2, NOW()) RETURNING *',
[name.trim(), description || null]
);
res.status(201).json({
success: true,
message: 'Model added successfully',
data: result.rows[0]
});
} catch (error) {
console.error('Error adding model:', error);
if (error.code === '23505') { // Unique violation
res.status(409).json({
success: false,
error: 'Model name already exists'
});
} else {
res.status(500).json({
success: false,
error: 'Failed to add model',
message: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error'
});
}
}
});
// Update device model
app.put('/api/models/:id', async (req, res) => {
try {
const { id } = req.params;
const { name, description } = req.body;
if (!name || name.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Model name is required'
});
}
const result = await pool.query(
'UPDATE device_models SET name = $1, description = $2, updated_at = NOW() WHERE id = $3 RETURNING *',
[name.trim(), description || null, id]
);
if (result.rows.length === 0) {
return res.status(404).json({
success: false,
error: 'Model not found'
});
}
res.json({
success: true,
message: 'Model updated successfully',
data: result.rows[0]
});
} catch (error) {
console.error('Error updating model:', error);
if (error.code === '23505') {
res.status(409).json({
success: false,
error: 'Model name already exists'
});
} else {
res.status(500).json({
success: false,
error: 'Failed to update model'
});
}
}
});
// Delete device model
app.delete('/api/models/:id', async (req, res) => {
try {
const { id } = req.params;
// Check if model has commands
const commandCheck = await pool.query('SELECT COUNT(*) FROM commands WHERE model_id = $1', [id]);
const commandCount = parseInt(commandCheck.rows[0].count);
if (commandCount > 0) {
return res.status(409).json({
success: false,
error: `Cannot delete model. It has ${commandCount} associated commands.`,
suggestion: 'Delete all commands first or use force delete.'
});
}
const result = await pool.query('DELETE FROM device_models WHERE id = $1 RETURNING *', [id]);
if (result.rows.length === 0) {
return res.status(404).json({
success: false,
error: 'Model not found'
});
}
res.json({
success: true,
message: 'Model deleted successfully',
data: result.rows[0]
});
} catch (error) {
console.error('Error deleting model:', error);
res.status(500).json({
success: false,
error: 'Failed to delete model'
});
}
});
// ==================== COMMANDS ROUTES ====================
// Get commands for a specific model
app.get('/api/models/:modelId/commands', async (req, res) => {
try {
const { modelId } = req.params;
const result = await pool.query(`
SELECT
c.*,
m.name as model_name
FROM commands c
JOIN device_models m ON c.model_id = m.id
WHERE c.model_id = $1
ORDER BY c.command_text
`, [modelId]);
res.json({
success: true,
data: result.rows,
count: result.rows.length,
modelId: parseInt(modelId)
});
} catch (error) {
console.error('Error fetching commands:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch commands'
});
}
});
// Get all commands
app.get('/api/commands', async (req, res) => {
try {
const result = await pool.query(`
SELECT
c.*,
m.name as model_name
FROM commands c
JOIN device_models m ON c.model_id = m.id
ORDER BY m.name, c.command_text
`);
res.json({
success: true,
data: result.rows,
count: result.rows.length
});
} catch (error) {
console.error('Error fetching commands:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch commands'
});
}
});
// Add new command
app.post('/api/commands', async (req, res) => {
try {
const { modelId, commandText, description } = req.body;
if (!modelId || !commandText || commandText.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Model ID and command text are required'
});
}
// Check if model exists
const modelCheck = await pool.query('SELECT id FROM device_models WHERE id = $1', [modelId]);
if (modelCheck.rows.length === 0) {
return res.status(404).json({
success: false,
error: 'Model not found'
});
}
const result = await pool.query(
'INSERT INTO commands (model_id, command_text, description, created_at) VALUES ($1, $2, $3, NOW()) RETURNING *',
[modelId, commandText.trim(), description || null]
);
res.status(201).json({
success: true,
message: 'Command added successfully',
data: result.rows[0]
});
} catch (error) {
console.error('Error adding command:', error);
if (error.code === '23505') {
res.status(409).json({
success: false,
error: 'Command already exists for this model'
});
} else {
res.status(500).json({
success: false,
error: 'Failed to add command'
});
}
}
});
// Update command
app.put('/api/commands/:id', async (req, res) => {
try {
const { id } = req.params;
const { commandText, description } = req.body;
if (!commandText || commandText.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Command text is required'
});
}
const result = await pool.query(
'UPDATE commands SET command_text = $1, description = $2, updated_at = NOW() WHERE id = $3 RETURNING *',
[commandText.trim(), description || null, id]
);
if (result.rows.length === 0) {
return res.status(404).json({
success: false,
error: 'Command not found'
});
}
res.json({
success: true,
message: 'Command updated successfully',
data: result.rows[0]
});
} catch (error) {
console.error('Error updating command:', error);
res.status(500).json({
success: false,
error: 'Failed to update command'
});
}
});
// Delete command
app.delete('/api/commands/:id', async (req, res) => {
try {
const { id } = req.params;
const result = await pool.query('DELETE FROM commands WHERE id = $1 RETURNING *', [id]);
if (result.rows.length === 0) {
return res.status(404).json({
success: false,
error: 'Command not found'
});
}
res.json({
success: true,
message: 'Command deleted successfully',
data: result.rows[0]
});
} catch (error) {
console.error('Error deleting command:', error);
res.status(500).json({
success: false,
error: 'Failed to delete command'
});
}
});
// ==================== SMS ROUTES ====================
// Send SMS command
app.post('/api/sms/send', async (req, res) => {
try {
const { phoneNumbers, modelId, commandText, notes } = req.body;
if (!phoneNumbers || !Array.isArray(phoneNumbers) || phoneNumbers.length === 0) {
return res.status(400).json({
success: false,
error: 'Phone numbers array is required'
});
}
if (!modelId || !commandText || commandText.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Model ID and command text are required'
});
}
// Validate phone numbers
const phoneRegex = /^[\d\+\-\(\)\s]{10,20}$/;
const invalidPhones = phoneNumbers.filter(phone => !phoneRegex.test(phone.trim()));
if (invalidPhones.length > 0) {
return res.status(400).json({
success: false,
error: 'Invalid phone numbers detected',
invalidPhones
});
}
// Check if model exists
const modelCheck = await pool.query('SELECT name FROM device_models WHERE id = $1', [modelId]);
if (modelCheck.rows.length === 0) {
return res.status(404).json({
success: false,
error: 'Model not found'
});
}
const modelName = modelCheck.rows[0].name;
const results = [];
const errors = [];
// Process each phone number
for (const phone of phoneNumbers) {
try {
const cleanPhone = phone.trim();
// Here you would integrate with your SMS service
// For now, we'll simulate SMS sending and log to database
const smsResult = await sendSMSCommand(cleanPhone, commandText, modelName);
const result = await pool.query(`
INSERT INTO sms_history
(phone_number, model_id, command_text, status, sent_at, details, notes, response_data)
VALUES ($1, $2, $3, $4, NOW(), $5, $6, $7)
RETURNING *
`, [
cleanPhone,
modelId,
commandText.trim(),
smsResult.success ? 'sent' : 'failed',
smsResult.details || null,
notes || null,
JSON.stringify(smsResult)
]);
results.push({
phone: cleanPhone,
status: smsResult.success ? 'sent' : 'failed',
id: result.rows[0].id,
details: smsResult.details
});
} catch (error) {
console.error(`Error sending SMS to ${phone}:`, error);
errors.push({
phone: phone.trim(),
error: error.message
});
}
}
const successCount = results.filter(r => r.status === 'sent').length;
const failCount = results.filter(r => r.status === 'failed').length + errors.length;
res.json({
success: successCount > 0,
message: `SMS processing completed. Sent: ${successCount}, Failed: ${failCount}`,
summary: {
total: phoneNumbers.length,
sent: successCount,
failed: failCount
},
results,
errors: errors.length > 0 ? errors : undefined
});
} catch (error) {
console.error('Error in SMS send endpoint:', error);
res.status(500).json({
success: false,
error: 'Failed to send SMS',
message: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error'
});
}
});
// Mock SMS sending function (replace with real SMS service)
async function sendSMSCommand(phoneNumber, command, modelName) {
try {
// Simulate SMS sending delay
await new Promise(resolve => setTimeout(resolve, 100));
// Simulate success/failure (90% success rate)
const success = Math.random() > 0.1;
if (success) {
return {
success: true,
details: `Command "${command}" sent successfully to ${modelName} device`,
messageId: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
cost: 0.05 // Simulated cost
};
} else {
return {
success: false,
details: 'SMS delivery failed - network error',
errorCode: 'NETWORK_ERROR'
};
}
} catch (error) {
return {
success: false,
details: error.message,
errorCode: 'UNKNOWN_ERROR'
};
}
}
// Get SMS history with advanced filtering
app.get('/api/sms/history', async (req, res) => {
try {
const {
page = 1,
limit = 50,
status,
modelId,
phoneNumber,
dateFrom,
dateTo,
search
} = req.query;
const offset = (page - 1) * limit;
let whereClause = '';
const params = [];
let paramCount = 0;
// Build dynamic WHERE clause
const conditions = [];
if (status) {
paramCount++;
conditions.push(`h.status = $${paramCount}`);
params.push(status);
}
if (modelId) {
paramCount++;
conditions.push(`h.model_id = $${paramCount}`);
params.push(modelId);
}
if (phoneNumber) {
paramCount++;
conditions.push(`h.phone_number ILIKE $${paramCount}`);
params.push(`%${phoneNumber}%`);
}
if (dateFrom) {
paramCount++;
conditions.push(`h.sent_at >= $${paramCount}`);
params.push(dateFrom);
}
if (dateTo) {
paramCount++;
conditions.push(`h.sent_at <= $${paramCount}`);
params.push(dateTo);
}
if (search) {
paramCount++;
conditions.push(`(h.command_text ILIKE $${paramCount} OR h.notes ILIKE $${paramCount} OR m.name ILIKE $${paramCount})`);
params.push(`%${search}%`);
}
if (conditions.length > 0) {
whereClause = 'WHERE ' + conditions.join(' AND ');
}
// Add pagination parameters
params.push(limit, offset);
const limitParam = paramCount + 1;
const offsetParam = paramCount + 2;
const query = `
SELECT
h.*,
m.name as model_name,
CASE
WHEN h.status = 'sent' THEN '✅'
WHEN h.status = 'failed' THEN '❌'
WHEN h.status = 'pending' THEN '⏳'
ELSE '❓'
END as status_icon
FROM sms_history h
LEFT JOIN device_models m ON h.model_id = m.id
${whereClause}
ORDER BY h.sent_at DESC
LIMIT $${limitParam} OFFSET $${offsetParam}
`;
const result = await pool.query(query, params);
// Get total count for pagination
const countQuery = `
SELECT COUNT(*)
FROM sms_history h
LEFT JOIN device_models m ON h.model_id = m.id
${whereClause}
`;
const countResult = await pool.query(countQuery, params.slice(0, paramCount));
const total = parseInt(countResult.rows[0].count);
res.json({
success: true,
data: result.rows,
pagination: {
page: parseInt(page),
limit: parseInt(limit),
total,
pages: Math.ceil(total / limit),
hasNext: (page * limit) < total,
hasPrev: page > 1
},
filters: {
status,
modelId,
phoneNumber,
dateFrom,
dateTo,
search
}
});
} catch (error) {
console.error('Error fetching SMS history:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch SMS history'
});
}
});
// Get SMS statistics
app.get('/api/sms/stats', async (req, res) => {
try {
const { period = '30' } = req.query; // days
const stats = await pool.query(`
SELECT
COUNT(*) as total_messages,
COUNT(CASE WHEN status = 'sent' THEN 1 END) as sent_count,
COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_count,
COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
COUNT(DISTINCT phone_number) as unique_numbers,
COUNT(DISTINCT model_id) as models_used,
DATE_TRUNC('day', sent_at) as date
FROM sms_history
WHERE sent_at >= NOW() - INTERVAL '${parseInt(period)} days'
GROUP BY DATE_TRUNC('day', sent_at)
ORDER BY date DESC
`);
const totals = await pool.query(`
SELECT
COUNT(*) as total_messages,
COUNT(CASE WHEN status = 'sent' THEN 1 END) as sent_count,
COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_count,
COUNT(DISTINCT phone_number) as unique_numbers,
ROUND(AVG(CASE WHEN status = 'sent' THEN 1.0 ELSE 0.0 END) * 100, 2) as success_rate
FROM sms_history
WHERE sent_at >= NOW() - INTERVAL '${parseInt(period)} days'
`);
const topModels = await pool.query(`
SELECT
m.name,
COUNT(*) as usage_count,
COUNT(CASE WHEN h.status = 'sent' THEN 1 END) as success_count
FROM sms_history h
JOIN device_models m ON h.model_id = m.id
WHERE h.sent_at >= NOW() - INTERVAL '${parseInt(period)} days'
GROUP BY m.id, m.name
ORDER BY usage_count DESC
LIMIT 10
`);
res.json({
success: true,
period: `${period} days`,
summary: totals.rows[0],
daily: stats.rows,
topModels: topModels.rows
});
} catch (error) {
console.error('Error fetching SMS stats:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch SMS statistics'
});
}
});
// ==================== REPORTS ROUTES ====================
// Generate PDF report (placeholder - requires puppeteer or similar)
app.get('/api/reports/pdf', async (req, res) => {
try {
const { period = 'week' } = req.query;
// This would generate a PDF report
// For now, return a placeholder response
res.json({
success: true,
message: 'PDF report generation not implemented yet',
suggestion: 'Use CSV export for now',
period
});
} catch (error) {
console.error('Error generating PDF report:', error);
res.status(500).json({
success: false,
error: 'Failed to generate PDF report'
});
}
});
// Export CSV data
app.get('/api/reports/csv', async (req, res) => {
try {
const { period = '30' } = req.query;
const result = await pool.query(`
SELECT
h.phone_number,
m.name as model_name,
h.command_text,
h.status,
h.sent_at,
h.notes,
h.details
FROM sms_history h
LEFT JOIN device_models m ON h.model_id = m.id
WHERE h.sent_at >= NOW() - INTERVAL '${parseInt(period)} days'
ORDER BY h.sent_at DESC
`);
// Generate CSV content
const headers = ['Phone Number', 'Model', 'Command', 'Status', 'Sent At', 'Notes', 'Details'];
let csvContent = headers.join(',') + '\n';
result.rows.forEach(row => {
const csvRow = [
`"${row.phone_number}"`,
`"${row.model_name || ''}"`,
`"${row.command_text}"`,
`"${row.status}"`,
`"${row.sent_at}"`,
`"${row.notes || ''}"`,
`"${row.details || ''}"`
].join(',');
csvContent += csvRow + '\n';
});
res.setHeader('Content-Type', 'text/csv');
res.setHeader('Content-Disposition', `attachment; filename="sms_report_${period}days.csv"`);
res.send(csvContent);
} catch (error) {
console.error('Error generating CSV report:', error);
res.status(500).json({
success: false,
error: 'Failed to generate CSV report'
});
}
});
// ==================== LEGACY SMS ROUTES (for compatibility) ====================
// Legacy SMS routes for backward compatibility
app.get('/api/sms', async (req, res) => {
// Redirect to new history endpoint
req.url = '/api/sms/history';
return app._router.handle(req, res);
});
app.post('/api/sms', async (req, res) => {
try {
const { phone, message, sender } = req.body;
if (!phone || !message) {
return res.status(400).json({
success: false,
error: 'Phone and message are required'
});
}
const result = await pool.query(
'INSERT INTO sms_messages (phone, message, sender, created_at) VALUES ($1, $2, $3, NOW()) RETURNING *',
[phone, message, sender || 'system']
);
res.status(201).json({
success: true,
message: 'SMS sent successfully',
data: result.rows[0]
});
} catch (error) {
console.error('Error sending SMS:', error);
res.status(500).json({
success: false,
error: 'Failed to send SMS'
});
}
});
// ==================== DATABASE INITIALIZATION ====================
async function initializeDatabase() {