-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
594 lines (514 loc) · 19.2 KB
/
Copy pathindex.js
File metadata and controls
594 lines (514 loc) · 19.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
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const cors = require('cors');
const axios = require('axios');
const path = require('path');
const productRoutes = require('./routes/productRoutes');
const userRoutes = require('./routes/userRoutes');
const userProfileRoutes = require('./routes/userProfileRoutes');
const adminRoutes = require('./routes/adminRoutes');
const adminDashboardRoutes = require('./routes/adminDashboardRoutes');
const adminProductRoutes = require('./routes/adminProductRoutes');
const paymentRoutes = require('./routes/paymentRoutes');
const myProductRoutes = require('./routes/myProductRoutes');
const notificationRoutes = require('./routes/notificationRoutes');
const adminNotificationRoutes = require('./routes/adminNotificationRoutes');
const Transaction = require('./models/Transaction');
const Order = require('./models/Order');
const { protect } = require('./middleware/authMiddleware');
dotenv.config();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const PORT = process.env.PORT || 5000;
// CORS Configuration
const allowedOrigins = [
process.env.FRONTEND_URL_PRODUCTION,
process.env.FRONTEND_URL_LOCAL,
];
const corsOptions = {
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error(`CORS policy error: ${origin} is not allowed.`));
}
},
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 3600, // Add this option to specify the maximum age of the CORS configuration
};
app.use(cors(corsOptions));
// MongoDB Connection
mongoose
.connect(process.env.MONGO_URI)
.then(() => console.log('MongoDB connected'))
.catch((err) => console.error('Database connection error:', err));
// Serve static files
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// Base API Endpoint
app.get('/', (req, res) => res.send('API is running...'));
// Admin Routes
app.use('/api/adminDashboard', adminDashboardRoutes);
app.use('/api/adminProduct', adminProductRoutes);
app.use('/api/admin', adminRoutes);
// User Routes
app.use('/api/products', productRoutes);
app.use('/api/userProfile', userProfileRoutes);
app.use('/api/users', userRoutes);
app.use('/api/payment', paymentRoutes);
app.use('/api/myProducts', myProductRoutes);
app.use('/api/notify', notificationRoutes);
app.use('/api/notifyAdmin', adminNotificationRoutes);
// Get available couriers based on type
app.get("/api/couriers", async (req, res) => {
const { type } = req.query;
if (!type) {
return res.status(400).json({ error: "Type query parameter is required." });
}
try {
const response = await axios.get(`${process.env.GOSHIIP_BASE_URL}/shipments/courier-partners/`, {
headers: { Authorization: `Bearer ${process.env.GOSHIIP_API_KEY}` },
params: { type },
});
res.status(200).json(response.data);
} catch (error) {
console.error("Error fetching couriers:", error.response?.data || error.message);
res.status(error.response?.status || 500).json({
error: "Failed to fetch couriers.",
details: error.response?.data || error.message,
});
}
});
// Define constant parcels data
const CONSTANT_PARCELS = {
weight: 5,
length: 10,
width: 10,
height: 5,
};
// Get single rate for a specific courier
app.post("/api/rates", async (req, res) => {
const { carrierName, type, toAddress, fromAddress, parcels, items } = req.body;
console.log(req.body)
if (!carrierName || !type || !toAddress || !fromAddress || !parcels || !items) {
return res.status(400).json({ error: "Missing required fields." });
}
if (!toAddress.name || toAddress.name.trim() === "") {
return res.status(400).json({ error: "Name is required." });
}
if (!toAddress.phone || !/^0\d{10}$/.test(toAddress.phone)) {
return res.status(400).json({ error: "Invalid phone number. Please enter 11 digits starting with 0." });
}
if (!toAddress.email || !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(toAddress.email)) {
return res.status(400).json({ error: "Invalid email address" });
}
if (!toAddress.address || toAddress.address.trim() === "") {
return res.status(400).json({ error: "Address is required" });
}
try {
const response = await axios.post(
`${process.env.GOSHIIP_BASE_URL}/tariffs/getpricesingle/${carrierName}`,
{
type,
toAddress,
fromAddress,
parcels: CONSTANT_PARCELS,
items,
},
{
headers: {
Authorization: `Bearer ${process.env.GOSHIIP_API_KEY}`,
"Content-Type": "application/json",
},
}
);
res.status(200).json(response.data);
console.log(response.data);
}
catch (error) {
console.error("Error fetching couriers:", error);
if (error.response?.status === 400) {
// Handle validation errors
console.error("Validation error:", error.response?.data);
res.status(400).json({
error: "Validation error",
details: error.response?.data,
});
} else if (error.response?.status === 401) {
// Handle authentication errors
console.error("Authentication error:", error.response?.data);
res.status(401).json({
error: "Authentication error",
details: error.response?.data,
});
} else if (error.response?.status === 429) {
// Handle rate limit errors
console.error("Rate limit exceeded:", error.response?.data);
res.status(429).json({
error: "Rate limit exceeded",
details: error.response?.data,
});
} else if (error.response?.data?.rates?.status === false) {
// Handle Goshiip API error cases
const errorMessage = error.response?.data?.rates?.message;
if (errorMessage.includes("Undefined array key \"distance\"")) {
res.status(400).json({
error: "Invalid address",
details: "Please enter a valid address.",
});
} else if (errorMessage.includes("Truq cannot service this shipment because of the weight.")) {
res.status(400).json({
error: "Invalid shipment weight",
details: "Truq cannot service this shipment because of the weight.",
});
} else {
res.status(400).json({
error: "Goshiip API error",
details: errorMessage,
});
}
} else {
// Handle generic errors
console.error("Error fetching couriers:", error);
res.status(error.response?.status || 500).json({
error: "Failed to fetch couriers.",
details: error.response?.data || error.message,
});
}
}
});
// Verification payment route
app.get('/api/verify-transaction/:reference', async (req, res) => {
const { reference } = req.params;
try {
console.log(`Starting transaction verification for reference: ${reference}`);
// Verify the Paystack transaction
const response = await axios.get(`https://api.paystack.co/transaction/verify/${reference}`, {
headers: {
Authorization: `Bearer ${process.env.PAYSTACK_SECRET_KEY}`,
},
});
console.log('Transaction verification response:', response.data);
// Ensure the transaction was successful
if (response.data.data.status === 'success') {
const transactionData = response.data.data;
console.log('Transaction data:', transactionData);
const { redis_key, rate_id, order_id } = transactionData.metadata;
// Create and save the transaction
const newTransaction = new Transaction({
transactionId: transactionData.id,
reference: transactionData.reference,
amount: transactionData.amount,
orderId: order_id,
currency: transactionData.currency,
status: transactionData.status,
customerEmail: transactionData.customer.email,
paymentMethod: transactionData.channel,
paidAt: transactionData.paid_at,
gatewayResponse: transactionData.gateway_response,
});
try {
await newTransaction.save();
// Update the Order with the transactionId
await Order.findOneAndUpdate({ _id: order_id }, { $set: { transactionReference: transactionData.reference } }, { new: true });
console.log('Order updated with transactionId');
} catch (error) {
console.error('Error saving transaction and updating order with transactionId:', error);
}
// Prepare the booking payload
const bookingPayload = {
redis_key,
rate_id,
user_id: process.env.GOSHIP_USER_ID,
platform: 'web2',
delivery_note: 'Your delivery is on the way',
};
console.log('Booking payload:', bookingPayload);
let bookingResponse = null;
try {
// Make the booking API request
console.log('Sending booking request...');
bookingResponse = await axios.post(
`${process.env.GOSHIIP_BASE_URL}/bookshipment`,
bookingPayload,
{
headers: {
Authorization: `Bearer ${process.env.GOSHIIP_API_KEY}`,
},
}
);
console.log('Booking response:', bookingResponse.data);
// Check if booking was successful
if (bookingResponse.data.status) {
const shipmentId = bookingResponse.data.data.shipmentId; // Get the shipment ID
const shipmentReference = bookingResponse.data.data.reference;
console.log(`Booking successful. Shipment ID: ${shipmentReference}`);
try {
// Update the Order with the shipmentId
await Order.findOneAndUpdate({ _id: order_id }, { $set: { shipmentReference } }, { new: true });
console.log('Order updated with shipmentReference');
} catch (error) {
console.error('Error updating order with shipmentReference:', error);
}
try {
// Trigger the Assign API with shipment_id in the body
console.log(`Triggering Assign API for shipment ID: ${shipmentId}`);
const assignPayload = {
shipment_id: shipmentId,
};
const assignResponse = await axios.post(
`${process.env.GOSHIIP_BASE_URL}/shipment/assign`,
assignPayload,
{
headers: {
Authorization: `Bearer ${process.env.GOSHIIP_API_KEY}`,
},
}
);
console.log('Assign response:', assignResponse.data);
// Handle assign response
if (assignResponse.status === 200) {
console.log('Shipment assignment successful.');
res.status(200).json({
message: 'Payment verified, shipment booked, and assignment successful.',
transactionDetails: {
amount: transactionData.amount,
status: transactionData.status,
paymentMethod: transactionData.channel,
currency: transactionData.currency,
paidAt: transactionData.paid_at,
shipmentId, // Return shipmentId instead of shipmentReference
},
bookingStatus: bookingResponse.data.message,
assignStatus: assignResponse.data.message,
});
} else {
console.log('Assignment failed:', assignResponse.data.message);
res.status(assignResponse.status).json({
message: 'Shipment booked but assignment failed.',
assignStatus: assignResponse.data.message,
});
}
} catch (error) {
console.error('Error assigning shipment:', error.response ? error.response.data : error.message);
res.status(500).json({
message: 'Shipment booked, but failed to trigger assignment.',
error: error.message,
});
}
} else {
console.log('Booking failed:', bookingResponse.data.message);
res.status(400).json({
message: 'Booking failed.',
bookingStatus: bookingResponse.data.message,
});
}
} catch (error) {
console.error('Error booking shipment:', error.response ? error.response.data : error.message);
res.status(500).json({
message: 'Error occurred during booking process.',
error: error.message,
});
}
} else {
console.log('Transaction verification failed:', response.data.data.status);
res.status(400).json({ error: 'Transaction verification failed.' });
}
} catch (err) {
console.error('Error verifying transaction:', err.message);
res.status(500).json({ error: 'Error verifying the transaction.', details: err.message });
}
});
// Get Transaction by reference
app.get('/api/transaction/verify/:reference', async (req, res) => {
const { reference } = req.params;
// Validate the reference parameter
if (!reference || reference.trim() === '') {
return res.status(400).json({ error: 'Reference is required' });
}
try {
// Retrieve the transaction
const transaction = await Transaction.findOne({ reference });
if (transaction) {
// Format the transaction data
const formattedTransaction = {
transactionId: transaction.transactionId,
reference: transaction.reference,
amount: transaction.amount,
currency: transaction.currency,
status: transaction.status,
customerEmail: transaction.customerEmail,
paymentMethod: transaction.paymentMethod,
paidAt: transaction.paidAt,
};
res.status(200).json({ data: formattedTransaction });
} else {
res.status(404).json({ message: 'Transaction not found' });
}
} catch (error) {
console.error('Error verifying transaction:', error.message);
res.status(500).json({ error: 'Error verifying transaction' });
}
});
// Get all Transactions
app.get('/api/transactions', protect, async (req, res) => {
try {
// Replace with the logged-in user's email or ID
const customerEmail = req.user.email;
const transactions = await Transaction.find({ customerEmail }).sort({ paidAt: -1 });
if (!transactions.length) {
return res.status(404).json({ message: 'No transactions found for this user' });
}
res.status(200).json({ message: 'Transactions retrieved successfully', data: transactions });
} catch (error) {
console.error('Error fetching transactions:', error.message);
res.status(500).json({ message: 'Internal server error', error: error.message });
}
});
// Track Shipment Endpoint
app.get('/api/track-shipment/:reference', async (req, res) => {
const { reference } = req.params;
console.log(reference)
if (!reference) {
return res.status(400).json({
status: false,
message: 'Shipment reference is required.',
});
}
try {
// Call the GoShiip API to track shipment
const response = await axios.get(`${process.env.GOSHIIP_BASE_URL}/shipment/track/${reference}`, {
headers: {
'Authorization': `Bearer ${process.env.GOSHIIP_API_KEY}`,
},
});
if (response.data.status) {
// Format and send the shipment tracking data
res.status(200).json({
status: true,
message: response.data.message,
data: response.data.data,
});
console.log('Shipment tracking data:', response.data.data);
} else {
// Handle API response errors
res.status(404).json({
status: false,
message: response.data.message || 'Shipment not found.',
});
}
} catch (error) {
// Log and handle errors
console.error('Error tracking shipment:', error.response?.data || error.message);
res.status(500).json({
status: false,
message: 'Internal server error.',
error: error.response?.data || error.message,
});
}
});
// Get all shipments
app.get("/api/shipments", async (req, res) => {
const { status } = req.query; // Optional status filter (e.g., "pending", "in progress", etc.)
const apiUrl = `https://delivery-staging.apiideraos.com/api/v2/token/user/allorders${status ? `?status=${status}` : ""
}`;
const headers = {
Authorization: `Bearer ${process.env.GOSHIIP_API_KEY}`, // Replace "Secret Key" with your actual API key
};
try {
const response = await axios.get(apiUrl, { headers });
if (response.status === 200) {
res.status(200).json({
message: "Shipments fetched successfully",
data: response.data.data,
});
} else {
res.status(response.status).json({
message: data.message || "Failed to fetch shipments",
status: response.data.status,
});
}
} catch (error) {
console.error("Error fetching shipments:", error);
res.status(500).json({
message: "Internal Server Error",
error: error.message,
});
}
});
// Cancel a shipment
app.get("/api/shipments/cancel/:reference", async (req, res) => {
const { reference } = req.params; // Shipment reference from the request parameters
const apiUrl = `https://delivery-staging.apiideraos.com/api/v2/token/shipment/cancel/${reference}`;
const headers = {
Authorization: `Bearer ${process.env.GOSHIIP_API_KEY}`, // Replace with your actual API key
};
try {
const response = await axios.get(apiUrl, { headers });
if (response.status === 200) {
res.status(200).json({
message: "Shipment cancellation request sent successfully",
data: response.data.data,
status: response.data.status,
});
} else {
res.status(response.status).json({
message: response.data.message || "Failed to cancel shipment",
status: response.data.status,
});
}
} catch (error) {
console.error("Error canceling shipment:", error);
res.status(500).json({
message: "Internal Server Error",
error: error.message,
});
}
});
app.get('/api/orders/user/:userId', async (req, res) => {
try {
const userId = req.params.userId;
const orders = await Order.find({ userId })
.populate({ path: 'productId', model: 'Product' })
.populate({ path: 'sellerId', model: 'User', select: 'username email phoneNumber' })
.sort({ createdAt: -1 });
res.json({ orders });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Error retrieving orders' });
}
});
// Start Server
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
module.exports = app;
// Track Shipment Endpoint
// app.get('/api/track-shipment/:reference', async (req, res) => {
// const { reference } = req.params;
// try {
// const response = await axios.get(`${process.env.GOSHIIP_BASE_URL}/shipment/track/${reference}`, {
// headers: {
// 'Authorization': `Bearer ${process.env.GOSHIIP_API_KEY}`,
// }
// });
// if (response.data.status) {
// res.json({
// status: true,
// data: response.data.data
// });
// } else {
// res.json({
// status: false,
// message: 'Could not fetch tracking data'
// });
// }
// } catch (error) {
// console.error(error);
// res.status(500).json({
// status: false,
// message: 'Internal server error'
// });
// }
// });