-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
325 lines (279 loc) · 10.8 KB
/
server.js
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
require('dotenv').config();
const express = require('express');
const { Pool } = require('pg');
const bodyParser = require('body-parser');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const mime = require('mime-types');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const authenticateJWT = require('./authMiddleware');
const app = express();
const port = process.env.PORT || 3000;
const upload = multer({ dest: 'uploads/' });
console.log('JWT_SECRET:', process.env.JWT_SECRET ? 'is set' : 'is not set');
// CORS configuration
const corsOptions = {
origin: 'http://localhost:3001',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
optionsSuccessStatus: 204
};
// Apply CORS middleware
app.use(cors(corsOptions));
// Handle preflight requests
app.options('*', cors(corsOptions));
// Middleware to set CORS headers for all responses
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
res.header('Access-Control-Allow-Origin', 'http://localhost:3001');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
app.use(bodyParser.json());
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// Ensure uploads directory exists
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
// Database setup
const pool = new Pool({
connectionString: process.env.DATABASE_URL_POOLED,
ssl: {
rejectUnauthorized: false
},
connectionTimeoutMillis: 5000,
idleTimeoutMillis: 10000,
});
pool.on('connect', () => {
console.log('Connected to the database');
});
pool.on('error', (err) => {
console.error('Unexpected error on idle client', err);
process.exit(-1);
});
// Health check route
app.get('/health', (req, res) => {
res.status(200).send('OK');
});
// Login route for JWT token generation
app.post('/login', async (req, res) => {
const { email, password } = req.body;
// Hardcoded user for testing purposes
const testEmail = 'benjaminkakaimasai001@gmail.com';
const testPassword = 'co37x74bobG';
const hashedPassword = bcrypt.hashSync(testPassword, 10);
const user = { email: testEmail, password: hashedPassword };
if (email === user.email && bcrypt.compareSync(password, user.password)) {
const token = jwt.sign({ email: user.email }, process.env.JWT_SECRET, { expiresIn: '1h' });
// Add this line to log the generated token
console.log('Generated Token:', token);
res.json({ token });
} else {
res.status(401).send('Invalid credentials');
}
});
// Token refresh route
app.post('/refresh-token', authenticateJWT, (req, res) => {
const { email } = req.user;
const newToken = jwt.sign({ email }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token: newToken });
});
app.get('/', (req, res) => {
res.status(200).send('Welcome to the client management app');
});
// Client routes
app.post('/clients', authenticateJWT, async (req, res) => {
const { project, bedrooms, budget, schedule, email, fullname, phone, quality, conversation_status, paymentDetails } = req.body;
try {
await pool.query('BEGIN');
const clientResult = await pool.query(
'INSERT INTO clients (project, bedrooms, budget, schedule, email, fullname, phone, quality, conversation_status) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *',
[project, bedrooms, budget, schedule, email, fullname, phone, quality, conversation_status]
);
const newClient = clientResult.rows[0];
if (paymentDetails) {
await pool.query(
'INSERT INTO payment_details (client_id, amount_paid, payment_duration, total_amount, balance, payment_date) VALUES ($1, $2, $3, $4, $5, $6)',
[newClient.id, paymentDetails.amountPaid, paymentDetails.paymentDuration, paymentDetails.totalAmount, paymentDetails.balance, new Date()]
);
}
await pool.query('COMMIT');
res.status(201).json(newClient);
} catch (err) {
await pool.query('ROLLBACK');
console.error('Error executing query', err.stack);
res.status(500).send('Server error');
}
});
// New status update route
app.post('/clients/:id/status', authenticateJWT, async (req, res) => {
const clientId = req.params.id;
const { status } = req.body;
try {
const result = await pool.query(
'UPDATE clients SET conversation_status = $1 WHERE id = $2 RETURNING *',
[status, clientId]
);
if (result.rows.length === 0) {
return res.status(404).send('Client not found');
}
res.json(result.rows[0]);
} catch (err) {
console.error('Error updating client status:', err.stack);
res.status(500).send('Server error');
}
});
app.post('/clients/:id/documents', authenticateJWT, upload.array('documents'), async (req, res) => {
const clientId = req.params.id;
const files = req.files;
try {
for (const file of files) {
const documentPath = file.path;
await pool.query(
'INSERT INTO client_documents (client_id, document_name, document_path) VALUES ($1, $2, $3)',
[clientId, file.originalname, documentPath]
);
console.log(`Document saved: ${documentPath}`);
}
res.status(200).send('Documents uploaded successfully');
} catch (err) {
console.error('Error uploading documents', err.stack);
res.status(500).send('Server error');
}
});
app.get('/clients/:id/documents', authenticateJWT, async (req, res) => {
const clientId = req.params.id;
try {
const result = await pool.query(
'SELECT * FROM client_documents WHERE client_id = $1',
[clientId]
);
res.json(result.rows);
} catch (err) {
console.error('Error fetching documents', err.stack);
res.status(500).send('Server error');
}
});
app.get('/documents/:id', authenticateJWT, async (req, res) => {
const documentId = req.params.id;
try {
const result = await pool.query('SELECT * FROM client_documents WHERE id = $1', [documentId]);
if (result.rows.length === 0) {
return res.status(404).send('Document not found');
}
const documentPath = result.rows[0].document_path;
const documentName = result.rows[0].document_name;
console.log(`Attempting to send file: ${documentPath}`);
if (fs.existsSync(documentPath)) {
const mimeType = mime.lookup(documentPath) || 'application/octet-stream';
res.setHeader('Content-Type', mimeType);
res.setHeader('Content-Disposition', `inline; filename="${path.basename(documentPath)}"`);
fs.createReadStream(documentPath).pipe(res);
} else {
console.error(`File not found: ${documentPath}`);
res.status(404).send('File not found');
}
} catch (err) {
console.error('Error retrieving document', err.stack);
res.status(500).send('Server error');
}
});
app.delete('/documents/:id', authenticateJWT, async (req, res) => {
const documentId = req.params.id;
try {
const result = await pool.query('DELETE FROM client_documents WHERE id = $1 RETURNING *', [documentId]);
if (result.rows.length === 0) {
return res.status(404).send('Document not found');
}
fs.unlink(result.rows[0].document_path, (err) => {
if (err) {
console.error('Error deleting file:', err);
}
});
res.status(200).json(result.rows[0]);
} catch (err) {
console.error('Error deleting document', err.stack);
res.status(500).send('Server error');
}
});
app.get('/clients', authenticateJWT, async (req, res) => {
try {
const result = await pool.query(`
SELECT c.*, pd.amount_paid, pd.payment_duration, pd.total_amount, pd.balance, pd.payment_date
FROM clients c
LEFT JOIN payment_details pd ON c.id = pd.client_id
`);
res.json(result.rows);
} catch (err) {
console.error('Error executing query', err.stack);
res.status(500).send('Server error');
}
});
app.get('/clients/finalized', authenticateJWT, async (req, res) => {
try {
const result = await pool.query("SELECT * FROM clients WHERE conversation_status = 'Finalized Deal'");
res.json(result.rows);
} catch (err) {
console.error('Error executing query', err.stack);
res.status(500).send('Server error');
}
});
app.get('/clients/high-quality', authenticateJWT, async (req, res) => {
try {
const result = await pool.query("SELECT * FROM clients WHERE quality = 'high'");
res.json(result.rows);
} catch (err) {
console.error('Error executing query', err.stack);
res.status(500).send('Server error');
}
});
app.get('/clients/pending', authenticateJWT, async (req, res) => {
try {
const result = await pool.query("SELECT * FROM clients WHERE conversation_status = 'Pending'");
res.json(result.rows);
} catch (err) {
console.error('Error executing query', err.stack);
res.status(500).send('Server error');
}
});
app.get('/clients/:id', authenticateJWT, async (req, res) => {
const clientId = req.params.id;
try {
const result = await pool.query('SELECT * FROM clients WHERE id = $1', [clientId]);
if (result.rows.length === 0) {
return res.status(404).send('Client not found');
}
res.json(result.rows[0]);
} catch (err) {
console.error('Error fetching client', err.stack);
res.status(500).send('Server error');
}
});
app.delete('/clients/:id', authenticateJWT, async (req, res) => {
const clientId = req.params.id;
try {
const result = await pool.query('DELETE FROM clients WHERE id = $1 RETURNING *', [clientId]);
if (result.rows.length === 0) {
return res.status(404).send('Client not found');
}
res.status(200).json(result.rows[0]);
} catch (err) {
console.error('Error deleting client', err.stack);
res.status(500).send('Server error');
}
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Unhandled error:', err.stack);
res.status(500).send('Server error');
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});