-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindexhttps.js
More file actions
433 lines (394 loc) · 13.4 KB
/
Copy pathindexhttps.js
File metadata and controls
433 lines (394 loc) · 13.4 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
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { initializeWebSocket, getWebSocketStats } = require('./websocket-server')
const httpServer = express();
const app = express();
const fs = require('fs');
const allowedOrigins = [
'https://idari.aho.com',
'https://optik.aho.com',
'https://mekanik.aho.com',
'https://bakim.aho.com',
'https://kalite.aho.com',
'https://10.0.0.35:4200',
'http://10.0.0.35:4200',
'http://localhost:4200',
'https://localhost:4200',
'https://127.0.0.1:4200',
'http://127.0.0.1:4200',
// Geliştirme için ek originler
'https://10.0.0.35:3000',
'http://10.0.0.35:3000'
];
const corsOptions = {
origin: '*', // Tüm origin'lere izin ver
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Requested-With'],
optionsSuccessStatus: 200,
maxAge: 86400
};
const port = 3001;
const https = require('https');
const options = {
// key: fs.readFileSync('./ssl/10.0.0.35+3-key.pem'),
// cert: fs.readFileSync('./ssl/10.0.0.35+3.pem')
};
const server = https.createServer(options, app);
const { reset } = require('nodemon');
const { machine } = require('os');
app.use(express.json());
// Middleware
app.use(cors(corsOptions));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
app.use((req, res, next) => {
const origin = req.headers.origin;
// Origin'e göre dinamik olarak izin ver
if (origin && allowedOrigins.includes(origin)) {
res.header('Access-Control-Allow-Origin', origin);
} else {
// Geliştirme ortamında tüm origin'lere izin ver (isteğe bağlı)
res.header('Access-Control-Allow-Origin', '*');
}
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
if (req.method === 'OPTIONS') {
return res.status(200).end();
}
next();
});
app.use(express.json());
initializeWebSocket(server);
const apiStatsMiddleware = require('./apiStatsMiddleware');
app.use(apiStatsMiddleware.middleware());
// Route importları
const bilgi_islem = require('./routes/bilgiIslemRoutes');
const dosyaOkuma = require('./dosyaOkuma');
const planlamaCalisma = require('./controllers/planliCalisanFonksiyon');
const planlamaRout = require('./planlama');
const bakimRout = require('./bakim');
const mekanikmRout = require('./mekanik');
const satinAlmaRout = require('./satinalma');
const girisKaliteRout = require('./girisKalite');
const optikUretim = require('./optikUretim');
const portal_anket = require('./routes/portalAnketRoutes');
const portal_km = require('./routes/portalKmRoutes');
const portal_duyru = require('./routes/portalDuyruRoutes');
const portal_egitim = require('./routes/portalEgitimRoutes');
const portal_zimmet = require('./routes/portalZimmetRoutes');
const portal_envanter = require('./routes/portalEnvanterRoutes');
const haberRoutes = require('./routes/portalHaberRoutes');
const cariYonetimRoutes = require('./routes/portalCariYonetimRoutes');
const userRoutes = require('./routes/portalUserRouters');
const uretimKalite = require('./routes/uretimKaliteRoutes.js');
const maliyetRoutes = require('./routes/maliyetRoutes.js');
const maliyetRoutests = require('./routes/maliyetRoutests.js');
const satinAlmaSiparisRoutests = require('./routes/portalSatinAlmaRoutes.js');
const portalMakinaRoutes = require('./routes/portalMakinaRoutes.js');
const portalIsmulakatRoutes = require('./routes/portalIsmulakatRouter.js');
const productRoutes = require('./routes/machinePlan/productRoutes');
const operationRoutes = require('./routes/machinePlan/operationRoutes');
const machineRoutes = require('./routes/machinePlan/machineRoutes');
const orderRoutes = require('./routes/machinePlan/orderRoutes');
const productRoutingRoutes = require('./routes/machinePlan/productRoutingRoutes');
const scheduleRoutes = require('./routes/machinePlan/scheduleRoutes');
const machineCapabilityRoutes = require('./routes/machinePlan/machineCapabilityRoutes');
const dashboardRoutes = require('./routes/machinePlan/dashboardRoutes');
const gelirGiderRoutes = require('./routes/portalGelirGiderRoutes');
// Task reminder servisi
const TaskReminderService = require('./controllers/task-reminder');
// Task controller
const portal_task = require('./controllers/portalTaskController');
app.use('/portal_task', portal_task);
// Route tanımlamaları
app.use('/api/products', productRoutes);
app.use('/api/operations', operationRoutes);
app.use('/api/machines', machineRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/product-routings', productRoutingRoutes);
app.use('/api/schedules', scheduleRoutes);
app.use('/api/machine-capabilities', machineCapabilityRoutes);
app.use('/api/dashboard', dashboardRoutes);
app.use('/portal_egitim', portal_egitim);
app.use('/', planlamaCalisma);
app.use('/', bilgi_islem);
app.use('/portal_anket', portal_anket);
app.use('/portal_duyuru', portal_duyru);
app.use('/portal_km', portal_km);
app.use('/haber', haberRoutes);
app.use('/portal_zimmet', portal_zimmet);
app.use('/portal_envanter', portal_envanter);
app.use('/portal_gelir_gider', gelirGiderRoutes);
app.use('/portal_cariYonetim', cariYonetimRoutes);
app.use('/portal_user', userRoutes);
app.use('/uretimKalite', uretimKalite);
app.use('/dosya_okuma', dosyaOkuma);
app.use('/maliyet', maliyetRoutes);
app.use('/maliyets', maliyetRoutests);
app.use('/portal_satinalma', satinAlmaSiparisRoutests);
app.use('/portal_ik_mulakat', portalIsmulakatRoutes);
app.use('/portal_makina', portalMakinaRoutes);
app.use('/', optikUretim);
app.use('/', mekanikmRout);
app.use('/', planlamaRout);
app.use('/', bakimRout);
app.use('/', satinAlmaRout);
app.use('/', girisKaliteRout);
// İlk çalıştırmayı anında yapmak için:
// WebSocket istatistikleri endpoint'i
app.get('/websocket/stats', (req, res) => {
const stats = getWebSocketStats();
res.json({
status: 'OK',
websocket: {
enabled: true,
stats: stats || { totalConnections: 0, connectedUsers: [] }
}
});
});
// Health check endpoint
app.get('/health', (req, res) => {
const wsStats = getWebSocketStats();
res.json({
status: 'OK',
timestamp: new Date().toISOString(),
service: 'Aselsan Backend API',
websocket: {
enabled: true,
connections: wsStats ? wsStats.totalConnections : 0,
connectedUsers: wsStats ? wsStats.connectedUsers : [],
serverTime: new Date().toISOString()
},
features: {
taskReminders: true,
birthdayReminders: true,
organizationalAlerts: true,
websocket: true
}
});
});
// Task reminder status endpoint
app.get('/task-reminder/status', (req, res) => {
if (taskReminderService) {
const status = taskReminderService.getStatus();
res.json({
...status,
birthdayFeature: true,
features: ['task_reminders', 'birthday_reminders', 'organizational_alerts']
});
} else {
res.status(500).json({ error: 'Task reminder service not initialized' });
}
});
// Manuel reminder check endpoint
app.post('/task-reminder/check-now', async (req, res) => {
try {
if (taskReminderService) {
await taskReminderService.checkTaskDeadlines();
res.json({
message: 'Manual reminder check completed',
status: taskReminderService.getStatus(),
features: {
taskReminders: true,
birthdayReminders: true
}
});
} else {
res.status(500).json({ error: 'Task reminder service not initialized' });
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Birthday endpoints
app.get('/birthday-reminder/status', (req, res) => {
if (taskReminderService) {
try {
const status = taskReminderService.getBirthdayStatus();
res.json({
...status,
service: 'Birthday Reminder Service',
organizationalStructure: true,
hierarchyBased: true
});
} catch (error) {
res.status(500).json({
error: 'Birthday service not available',
details: error.message
});
}
} else {
res.status(500).json({ error: 'Task reminder service not initialized' });
}
});
app.post('/birthday-reminder/check-now', async (req, res) => {
try {
if (taskReminderService) {
const result = await taskReminderService.checkBirthdayReminders();
res.json({
message: 'Manual birthday check completed',
result: result,
status: taskReminderService.getStatus(),
timestamp: new Date().toISOString()
});
} else {
res.status(500).json({ error: 'Task reminder service not initialized' });
}
} catch (error) {
res.status(500).json({
error: 'Birthday check failed',
details: error.message
});
}
});
app.get('/birthday-reminder/stats', async (req, res) => {
try {
if (taskReminderService) {
const stats = await taskReminderService.getBirthdayStats();
res.json(stats);
} else {
res.status(500).json({ error: 'Task reminder service not initialized' });
}
} catch (error) {
res.status(500).json({
error: 'Failed to get birthday stats',
details: error.message
});
}
});
// Yaklaşan doğum günleri listesi
app.get('/birthday-reminder/upcoming', async (req, res) => {
try {
if (taskReminderService) {
const upcoming = await taskReminderService.getUpcomingBirthdaysForAPI();
res.json({
count: upcoming.length,
upcoming: upcoming,
period: 'next_7_days'
});
} else {
res.status(500).json({ error: 'Task reminder service not initialized' });
}
} catch (error) {
res.status(500).json({
error: 'Failed to get upcoming birthdays',
details: error.message
});
}
});
// Bugün doğum günü olanlar
app.get('/birthday-reminder/today', async (req, res) => {
try {
if (taskReminderService) {
const todayBirthdays = await taskReminderService.getTodaysBirthdays();
res.json({
count: todayBirthdays.length,
birthdays: todayBirthdays,
date: new Date().toISOString().split('T')[0]
});
} else {
res.status(500).json({ error: 'Task reminder service not initialized' });
}
} catch (error) {
res.status(500).json({
error: 'Failed to get today\'s birthdays',
details: error.message
});
}
});
// WebSocket test endpoint
app.get('/websocket-test', (req, res) => {
const token = req.query.token || 'test';
const testUrl = `ws://10.0.0.35:3000/ws?token=${token}`;
res.json({
test: 'WebSocket Connection Test',
url: testUrl,
instructions: 'Open browser console and run:',
javascript: `const ws = new WebSocket("${testUrl}"); ws.onopen = () => console.log("✅ Connected"); ws.onmessage = (e) => console.log("📨:", e.data);`
});
});
// Notification service status
app.get('/notification-service/status', (req, res) => {
res.json({
status: 'OK',
service: 'Notification Service',
features: {
taskNotifications: true,
birthdayNotifications: true,
realTimeUpdates: true,
unreadCount: true
},
endpoints: {
getNotifications: '/portal_task/notifications',
getUnreadCount: '/portal_task/notifications/unread-count',
markAsRead: '/portal_task/notifications/:id/read',
markAllRead: '/portal_task/notifications/mark-all-read'
}
});
});
// WebSocket durumu
app.get('/ws-status', (req, res) => {
const stats = getWebSocketStats();
res.json({
server_time: new Date().toISOString(),
ws_enabled: true,
stats: stats || { totalConnections: 0, connectedUsers: [] }
});
});
// Task reminder servisini başlat
let taskReminderService;
const startReminderService = () => {
try {
taskReminderService = new TaskReminderService();
taskReminderService.start();
console.log('✅ Task reminder service started successfully');
console.log('🎂 Birthday reminder system: ENABLED');
console.log('🏢 Organizational hierarchy: INTEGRATED');
} catch (error) {
console.error('❌ Failed to start task reminder service:', error);
}
};
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM received, shutting down gracefully');
if (taskReminderService) {
taskReminderService.stop();
console.log('🎂 Birthday reminder service stopped');
}
process.exit(0);
});
process.on('SIGINT', () => {
console.log('SIGINT received, shutting down gracefully');
if (taskReminderService) {
taskReminderService.stop();
console.log('🎂 Birthday reminder service stopped');
}
process.exit(0);
});
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
if (taskReminderService) {
taskReminderService.stop();
console.log('🎂 Birthday reminder service stopped due to error');
}
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
if (taskReminderService) {
taskReminderService.stop();
console.log('🎂 Birthday reminder service stopped due to unhandled rejection');
}
process.exit(1);
});
server.listen(port, '10.0.0.35', () => {
startReminderService();
console.log('HTTPS server running on port 3000');
});
module.exports = { app, server };
// app.listen(3001, '10.0.0.35', () => {
// });