-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchanges.diff
More file actions
4294 lines (3960 loc) · 149 KB
/
changes.diff
File metadata and controls
4294 lines (3960 loc) · 149 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
```diff
diff --git a/app/api/admin/agents/[agentId]/route.ts b/app/api/admin/agents/[agentId]/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/admin/agents/[agentId]/route.ts
+++ b/app/api/admin/agents/[agentId]/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
+import { apiErrorResponse } from '@/lib/errorHandling';
// Helper function to validate admin session
async function validateAdmin(req: NextRequest) {
@@ -29,7 +30,7 @@
try {
const session = await validateAdmin(req);
if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
const agent = await prisma.agent.findUnique({
@@ -45,15 +46,15 @@
});
if (!agent) {
- return NextResponse.json({ error: "Agent not found" }, { status: 404 });
+ return apiErrorResponse("Agent not found", 404, "AGENT_NOT_FOUND");
}
return NextResponse.json(agent);
} catch (error) {
console.error("Error fetching agent:", error);
- return NextResponse.json(
- { error: "Failed to fetch agent" },
- { status: 500 }
+ return apiErrorResponse(
+ "Failed to fetch agent",
+ 500, "FETCH_AGENT_FAILED", error instanceof Error ? error.message : String(error)
);
}
}
@@ -64,14 +65,14 @@
try {
const session = await validateAdmin(req);
if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
const data = await req.json();
// Validate data
if (data.isAvailable !== undefined && typeof data.isAvailable !== 'boolean') {
- return NextResponse.json(
- { error: "Invalid isAvailable value" },
- { status: 400 }
+ return apiErrorResponse(
+ "Invalid isAvailable value",
+ 400, "INVALID_INPUT"
);
}
@@ -90,9 +91,9 @@
return NextResponse.json(updatedAgent);
} catch (error) {
console.error("Error updating agent:", error);
- return NextResponse.json(
- { error: "Failed to update agent" },
- { status: 500 }
+ return apiErrorResponse(
+ "Failed to update agent",
+ 500, "UPDATE_AGENT_FAILED", error instanceof Error ? error.message : String(error)
);
}
}
@@ -103,19 +104,19 @@
try {
const session = await validateAdmin(req);
if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
// Check if agent exists
const agent = await prisma.agent.findUnique({
where: { id: params.agentId },
});
if (!agent) {
- return NextResponse.json({ error: "Agent not found" }, { status: 404 });
+ return apiErrorResponse("Agent not found", 404, "AGENT_NOT_FOUND");
}
// Delete agent
await prisma.agent.delete({
where: { id: params.agentId },
});
return NextResponse.json({ message: "Agent deleted successfully" });
} catch (error) {
console.error("Error deleting agent:", error);
- return NextResponse.json(
- { error: "Failed to delete agent" },
- { status: 500 }
+ return apiErrorResponse(
+ "Failed to delete agent",
+ 500, "DELETE_AGENT_FAILED", error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/admin/agents/route.ts b/app/api/admin/agents/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/admin/agents/route.ts
+++ b/app/api/admin/agents/route.ts
@@ -3,6 +3,7 @@
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import nodemailer from 'nodemailer';
+import { apiErrorResponse } from '@/lib/errorHandling';
interface UserWithAgent {
id: string;
@@ -43,7 +44,7 @@
try {
const session = await validateAdmin(req);
console.log("session from get request in agents api handler: ", session)
- if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ if (!session) { // Ensure session is valid and user is admin
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
const agents = await prisma.agent.findMany({
@@ -59,9 +60,9 @@
return NextResponse.json(agents);
} catch (error) {
console.error("Error fetching agents:", error);
- return NextResponse.json(
- { error: "Failed to fetch agents" },
- { status: 500 }
+ return apiErrorResponse(
+ "Failed to fetch agents",
+ 500, "FETCH_AGENTS_FAILED", error instanceof Error ? error.message : String(error)
);
}
}
@@ -69,22 +70,22 @@
export async function POST(req: NextRequest) {
try {
const session = await validateAdmin(req);
- if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ if (!session) { // Ensure session is valid and user is admin
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
const { email, name, specialties } = await req.json();
// Input validation
if (!email || !specialties) {
- return NextResponse.json(
- { error: "Email and specialties are required" },
- { status: 400 }
+ return apiErrorResponse(
+ "Email and specialties are required",
+ 400, "MISSING_FIELDS"
);
}
if (!email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
- return NextResponse.json(
- { error: "Invalid email format" },
- { status: 400 }
+ return apiErrorResponse(
+ "Invalid email format",
+ 400, "INVALID_EMAIL_FORMAT"
);
}
@@ -97,9 +98,9 @@
// Check if user is already an agent
if (user?.Agent) {
- return NextResponse.json(
- { error: "User is already an agent" },
- { status: 400 }
+ return apiErrorResponse(
+ "User is already an agent",
+ 400, "USER_ALREADY_AGENT"
);
}
@@ -131,9 +132,9 @@
});
} catch (emailError) {
console.error("Error sending welcome email:", emailError);
- // Delete created user if email fails
+ // Delete created user if email fails to prevent orphaned user accounts
await prisma.user.delete({ where: { id: user?.id } });
- return NextResponse.json(
- { error: "Failed to send verification email" },
- { status: 500 }
+ return apiErrorResponse(
+ "Failed to send verification email",
+ 500, "EMAIL_SEND_FAILED", emailError instanceof Error ? emailError.message : String(emailError)
);
}
}
@@ -156,9 +157,9 @@
}
} catch (error) {
console.error("Error creating agent:", error);
- return NextResponse.json(
- { error: "Failed to create agent" },
- { status: 500 }
+ return apiErrorResponse(
+ "Failed to create agent",
+ 500, "CREATE_AGENT_FAILED", error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/admin/analytics/route.ts b/app/api/admin/analytics/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/admin/analytics/route.ts
+++ b/app/api/admin/analytics/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
+import { apiErrorResponse } from '@/lib/errorHandling';
// Helper function to validate admin session
async function validateAdmin(req: NextRequest) {
@@ -29,7 +30,7 @@
try {
const session = await validateAdmin(req);
if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
// Get time range from query params
@@ -67,9 +68,9 @@
agentPerformance
});
} catch (error) {
console.error("Error fetching analytics:", error);
- return NextResponse.json(
- { error: "Failed to fetch analytics data" },
- { status: 500 }
+ return apiErrorResponse(
+ "Failed to fetch analytics data",
+ 500, "ANALYTICS_FETCH_FAILED", error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/admin/chats/route.ts b/app/api/admin/chats/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/admin/chats/route.ts
+++ b/app/api/admin/chats/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
+import { apiErrorResponse } from '@/lib/errorHandling';
// Helper function to validate admin session
async function validateAdmin(req: NextRequest) {
@@ -29,7 +30,7 @@
try {
const session = await validateAdmin(req);
if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
const status = req.nextUrl.searchParams.get('status');
@@ -59,9 +60,9 @@
return NextResponse.json(chats);
} catch (error) {
console.error("Error fetching chats:", error);
- return NextResponse.json(
- { error: "Failed to fetch chats" },
- { status: 500 }
+ return apiErrorResponse(
+ "Failed to fetch chats",
+ 500, "FETCH_CHATS_FAILED", error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/admin/settings/route.ts b/app/api/admin/settings/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/admin/settings/route.ts
+++ b/app/api/admin/settings/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
+import { apiErrorResponse } from '@/lib/errorHandling';
// Helper function to validate admin session
async function validateAdmin(req: NextRequest) {
@@ -29,7 +30,7 @@
try {
const session = await validateAdmin(req);
if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
// Default settings
@@ -44,9 +45,9 @@
// For now, we'll just return the default settings
return NextResponse.json(defaultSettings);
} catch (error) {
- console.error("Error fetching settings:", error);
- return NextResponse.json(
- { error: "Failed to fetch settings" },
- { status: 500 }
+ console.error("Error fetching settings:", error); // Log the actual error for debugging
+ return apiErrorResponse(
+ "Failed to fetch settings",
+ 500, "FETCH_SETTINGS_FAILED", error instanceof Error ? error.message : String(error)
);
}
}
@@ -55,15 +56,15 @@
try {
const session = await validateAdmin(req);
if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
const settings = await req.json();
// Validate settings
if (typeof settings !== 'object') {
- return NextResponse.json(
- { error: "Invalid settings format" },
- { status: 400 }
+ return apiErrorResponse(
+ "Invalid settings format",
+ 400, "INVALID_INPUT"
);
}
@@ -74,9 +75,9 @@
settings
});
} catch (error) {
- console.error("Error updating settings:", error);
- return NextResponse.json(
- { error: "Failed to update settings" },
- { status: 500 }
+ console.error("Error updating settings:", error); // Log the actual error for debugging
+ return apiErrorResponse(
+ "Failed to update settings",
+ 500, "UPDATE_SETTINGS_FAILED", error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/admin/stats/route.ts b/app/api/admin/stats/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/admin/stats/route.ts
+++ b/app/api/admin/stats/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
+import { apiErrorResponse } from '@/lib/errorHandling';
// Helper function to validate admin session
async function validateAdmin(req: NextRequest) {
@@ -29,7 +30,7 @@
try {
const session = await validateAdmin(req);
if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
// Get total agents count
@@ -59,9 +60,9 @@
resolutionRate
});
} catch (error) {
- console.error("Error fetching admin stats:", error);
- return NextResponse.json(
- { error: "Failed to fetch admin statistics" },
- { status: 500 }
+ console.error("Error fetching admin stats:", error); // Log the actual error for debugging
+ return apiErrorResponse(
+ "Failed to fetch admin statistics",
+ 500, "FETCH_ADMIN_STATS_FAILED", error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/ads/[id]/analytics/route.ts b/app/api/ads/[id]/analytics/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/ads/[id]/analytics/route.ts
+++ b/app/api/ads/[id]/analytics/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
+import { apiErrorResponse } from '@/lib/errorHandling';
// Simple in-memory cache
const analyticsCache = new Map<string, { views: number; clicks: number; shares: number }>();
@@ -18,15 +19,15 @@
});
if (!ad) {
- return NextResponse.json(
- { error: 'Ad not found' },
- { status: 404 }
+ return apiErrorResponse(
+ 'Ad not found',
+ 404, 'AD_NOT_FOUND'
);
}
// Update cache
analyticsCache.set(id, ad);
-
return NextResponse.json(ad);
} catch (error) {
console.error('Error fetching analytics:', error);
- return NextResponse.json(
- { error: 'Failed to fetch analytics' },
- { status: 500 }
+ return apiErrorResponse(
+ 'Failed to fetch analytics',
+ 500, 'ANALYTICS_FETCH_FAILED', error instanceof Error ? error.message : String(error)
);
}
}
@@ -38,9 +39,9 @@
const { type } = await request.json();
if (!['views', 'clicks', 'shares'].includes(type)) {
- return NextResponse.json(
- { error: 'Invalid analytics type' },
- { status: 400 }
+ return apiErrorResponse(
+ 'Invalid analytics type',
+ 400, 'INVALID_ANALYTICS_TYPE'
);
}
@@ -52,9 +53,9 @@
return NextResponse.json(ad);
} catch (error) {
- console.error('Error updating analytics:', error);
- return NextResponse.json(
- { error: 'Failed to update analytics' },
- { status: 500 }
+ console.error('Error updating analytics:', error); // Log the actual error for debugging
+ return apiErrorResponse(
+ 'Failed to update analytics',
+ 500, 'ANALYTICS_UPDATE_FAILED', error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/ads/[id]/boost/route.ts b/app/api/ads/[id]/boost/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/ads/[id]/boost/route.ts
+++ b/app/api/ads/[id]/boost/route.ts
@@ -2,6 +2,7 @@
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
import { boostOptions } from '@/constants';
+import { apiErrorResponse } from '@/lib/errorHandling';
export async function POST(
request: NextRequest,
@@ -9,34 +10,34 @@
) {
try {
// Make sure id is valid
const { id } = params;
if (!id) {
- return NextResponse.json(
- { error: 'Invalid ad ID' },
- { status: 400 }
+ return apiErrorResponse(
+ 'Invalid ad ID',
+ 400, 'INVALID_AD_ID'
);
}
// Parse request body
let boostType: number, duration: number;
try {
const body = await request.json();
({ boostType, duration } = body);
if (!boostType || !duration) {
- return NextResponse.json(
- { error: 'Missing required fields: boostType and duration' },
- { status: 400 }
+ return apiErrorResponse(
+ 'Missing required fields: boostType and duration',
+ 400, 'MISSING_FIELDS'
);
}
// Validate boost type
const validBoostType = boostOptions.some(opt => opt.id === boostType);
if (!validBoostType) {
- return NextResponse.json(
- { error: 'Invalid boost type' },
- { status: 400 }
+ return apiErrorResponse(
+ 'Invalid boost type',
+ 400, 'INVALID_BOOST_TYPE'
);
}
// Validate duration
const validDuration = boostOptions.find(opt => opt.id === boostType)?.duration.includes(duration);
if (!validDuration) {
- return NextResponse.json(
- { error: 'Invalid duration for selected boost type' },
- { status: 400 }
+ return apiErrorResponse(
+ 'Invalid duration for selected boost type',
+ 400, 'INVALID_BOOST_DURATION'
);
}
} catch (e) {
- return NextResponse.json(
- { error: 'Invalid request body' },
- { status: 400 }
+ return apiErrorResponse(
+ 'Invalid request body',
+ 400, 'INVALID_REQUEST_BODY', e instanceof Error ? e.message : String(e)
);
}
// Get token from cookies
const token = request.cookies.get('next-auth.session-token')?.value;
if (!token) {
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ return apiErrorResponse('Unauthorized', 401, 'UNAUTHORIZED');
}
// Verify token and get userId
const decoded = jwt.verify(token, process.env.NEXTAUTH_SECRET!) as { id: string };
const userId = decoded.id;
@@ -50,15 +51,15 @@
include: { subscriptionPlan: true }
});
- // If no subscription, return available plans and redirect info
+ // If no active subscription, return available plans and redirect info
if (!user?.subscriptionPlan || user.subscriptionPlan.expiryDate < new Date()) {
const availablePlans = await prisma.subscriptionPlan.findMany({
select: {
id: true,
name: true,
price: true,
duration: true,
- benefits: true
+ benefits: true,
}
});
@@ -67,7 +68,7 @@
message: 'Active subscription required to boost ads',
adId: id,
subscriptionPlans: availablePlans,
- redirectUrl: '/dashboard/promotions'
+ redirectUrl: '/dashboard/promotions' // Suggest redirect to promotions page
}, { status: 403 });
}
@@ -81,20 +82,20 @@
});
if (!ad || ad.userId !== userId) {
- return NextResponse.json(
- { error: 'Ad not found or unauthorized' },
- { status: 404 }
+ return apiErrorResponse(
+ 'Ad not found or unauthorized',
+ 404, 'AD_NOT_FOUND_OR_UNAUTHORIZED'
);
}
// Check if ad is already boosted
if (ad.featured && ad.boostEndDate && new Date(ad.boostEndDate) > new Date()) {
- return NextResponse.json(
- { error: 'Ad is already boosted' },
- { status: 400 }
+ return apiErrorResponse(
+ 'Ad is already boosted',
+ 400, 'AD_ALREADY_BOOSTED'
);
}
-
+ // Check if ad is active
if (ad.status !== 'Active') {
return NextResponse.json(
{ error: 'Ad must be active before it can be boosted' },
@@ -123,9 +124,9 @@
}
});
} catch (error) {
- console.error('Error boosting ad:', error instanceof Error ? error.message : error);
- return NextResponse.json(
- { error: 'Failed to boost ad' },
- { status: 500 }
+ console.error('Error boosting ad:', error); // Log the actual error for debugging
+ return apiErrorResponse(
+ 'Failed to boost ad',
+ 500, 'BOOST_AD_FAILED', error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/ads/[id]/feature/route.ts b/app/api/ads/[id]/feature/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/ads/[id]/feature/route.ts
+++ b/app/api/ads/[id]/feature/route.ts
@@ -1,13 +1,14 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
+import { apiErrorResponse } from '@/lib/errorHandling';
export async function PATCH(
req: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const token = req.cookies.get('next-auth.session-token')?.value;
if (!token) {
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ return apiErrorResponse('Unauthorized', 401, 'UNAUTHORIZED');
}
const decoded = jwt.verify(token, process.env.NEXTAUTH_SECRET!) as { id: string };
@@ -19,8 +20,8 @@
});
if (!user?.subscriptionPlan || user.subscriptionPlan.expiryDate < new Date()) {
- return NextResponse.json(
- { error: 'Active subscription required to feature ads. Please upgrade your plan.' },
- { status: 403 }
+ return apiErrorResponse(
+ 'Active subscription required to feature ads. Please upgrade your plan.',
+ 403, 'SUBSCRIPTION_REQUIRED'
);
}
@@ -29,8 +30,8 @@
});
if (!ad || ad.userId !== userId) {
- return NextResponse.json(
- { error: 'Ad not found or unauthorized' },
- { status: 404 }
+ return apiErrorResponse(
+ 'Ad not found or unauthorized',
+ 404, 'AD_NOT_FOUND_OR_UNAUTHORIZED'
);
}
@@ -45,8 +46,9 @@
message: 'Ad featured successfully'
});
} catch (error) {
- console.error('Error featuring ad:', error);
- return NextResponse.json(
- { error: 'Failed to feature ad' },
- { status: 500 }
+ console.error('Error featuring ad:', error); // Log the actual error for debugging
+ return apiErrorResponse(
+ 'Failed to feature ad',
+ 500, 'FEATURE_AD_FAILED', error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/ads/[id]/status/route.ts b/app/api/ads/[id]/status/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/ads/[id]/status/route.ts
+++ b/app/api/ads/[id]/status/route.ts
@@ -2,6 +2,7 @@
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
import { headers } from 'next/headers';
+import { apiErrorResponse } from '@/lib/errorHandling';
// Define params interface
interface RouteParams {
@@ -17,15 +18,15 @@
const id = params?.id;
if (!id || typeof id !== 'string') {
- return NextResponse.json(
- { error: 'Invalid ad ID' },
- { status: 400 }
+ return apiErrorResponse(
+ 'Invalid ad ID',
+ 400, 'INVALID_AD_ID'
);
}
// Get token from cookies
const token = req.cookies.get('next-auth.session-token')?.value;
if (!token) {
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ return apiErrorResponse('Unauthorized', 401, 'UNAUTHORIZED');
}
// Rest of your code remains the same
@@ -34,8 +35,8 @@
const { status } = await req.json();
const validStatuses = ['Active', 'Pending', 'Inactive', 'Sold'];
if (!validStatuses.includes(status)) {
- return NextResponse.json(
- { error: 'Invalid status value' },
- { status: 400 }
+ return apiErrorResponse(
+ 'Invalid status value',
+ 400, 'INVALID_STATUS_VALUE'
);
}
if (!ad || ad.userId !== userId) {
- return NextResponse.json(
- { error: 'Ad not found or unauthorized' },
- { status: 404 }
+ return apiErrorResponse(
+ 'Ad not found or unauthorized',
+ 404, 'AD_NOT_FOUND_OR_UNAUTHORIZED'
);
}
return NextResponse.json({
ad: updatedAd,
message: `Ad status updated to ${status}`
});
} catch (error) {
- console.error('Error updating ad status:', error);
- return NextResponse.json(
- { error: 'Failed to update ad status' },
- { status: 500 }
+ console.error('Error updating ad status:', error); // Log the actual error for debugging
+ return apiErrorResponse(
+ 'Failed to update ad status',
+ 500, 'UPDATE_AD_STATUS_FAILED', error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/ads/boosted/route.ts b/app/api/ads/boosted/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/ads/boosted/route.ts
+++ b/app/api/ads/boosted/route.ts
@@ -1,13 +1,14 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
+import { apiErrorResponse } from '@/lib/errorHandling';
export async function GET(request: NextRequest) {
try {
// Get token from cookies
const token = request.cookies.get('next-auth.session-token')?.value;
if (!token) {
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ return apiErrorResponse('Unauthorized', 401, 'UNAUTHORIZED');
}
// Verify token and get userId
@@ -27,8 +28,9 @@
});
} catch (error) {
- console.error('Error fetching boosted ads:', error);
- return NextResponse.json(
- { error: 'Failed to fetch boosted ads' },
- { status: 500 }
+ console.error('Error fetching boosted ads:', error); // Log the actual error for debugging
+ return apiErrorResponse(
+ 'Failed to fetch boosted ads',
+ 500, 'FETCH_BOOSTED_ADS_FAILED', error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/ads/my-ads/route.ts b/app/api/ads/my-ads/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/ads/my-ads/route.ts
+++ b/app/api/ads/my-ads/route.ts
@@ -2,6 +2,7 @@
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
+import { apiErrorResponse } from '@/lib/errorHandling';
export const dynamic = 'force-dynamic';
export const revalidate = 30; // Revalidate every 30 seconds
@@ -9,9 +10,9 @@
try {
// Get token from cookies
const token = request.cookies.get('next-auth.session-token')?.value;
if (!token) {
- return NextResponse.json(
- { error: 'Unauthorized' },
- { status: 401 }
+ return apiErrorResponse(
+ 'Unauthorized',
+ 401, 'UNAUTHORIZED'
);
}
@@ -48,9 +49,9 @@
]);
if (!user) {
- return NextResponse.json(
- { error: 'User not found' },
- { status: 404 }
+ return apiErrorResponse(
+ 'User not found',
+ 404, 'USER_NOT_FOUND'
);
}
@@ -67,9 +68,9 @@
);
} catch (error) {
- console.error('Error in my-ads route:', error);
- return NextResponse.json(
- { error: 'Internal server error' },
- { status: 500 }
+ console.error('Error in my-ads route:', error); // Log the actual error for debugging
+ return apiErrorResponse(
+ 'Internal server error',
+ 500, 'FETCH_MY_ADS_FAILED', error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/agent/analytics/route.ts b/app/api/agent/analytics/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/agent/analytics/route.ts
+++ b/app/api/agent/analytics/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
+import { apiErrorResponse } from '@/lib/errorHandling';
// Helper function to validate agent session
async function validateAgent(req: NextRequest) {
@@ -29,7 +30,7 @@
try {
const session = await validateAgent(req);
if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
// Get time range from query params
@@ -67,9 +68,9 @@
responseTimeData
});
} catch (error) {
- console.error("Error fetching agent analytics:", error);
- return NextResponse.json(
- { error: "Failed to fetch analytics data" },
- { status: 500 }
+ console.error("Error fetching agent analytics:", error); // Log the actual error for debugging
+ return apiErrorResponse(
+ "Failed to fetch analytics data",
+ 500, "FETCH_AGENT_ANALYTICS_FAILED", error instanceof Error ? error.message : String(error)
);
}
}
diff --git a/app/api/agent/chats/[chatId]/accept/route.ts b/app/api/agent/chats/[chatId]/accept/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/agent/chats/[chatId]/accept/route.ts
+++ b/app/api/agent/chats/[chatId]/accept/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
+import { apiErrorResponse } from '@/lib/errorHandling';
export async function POST(
req: NextRequest,
@@ -8,19 +9,19 @@
) {
try {
// Get and validate token
const token = req.cookies.get('next-auth.session-token')?.value;
if (!token) {
- return NextResponse.json(
- { error: 'Unauthorized' },
- { status: 401 }
+ return apiErrorResponse(
+ 'Unauthorized',
+ 401, 'UNAUTHORIZED'
);
}
// Verify token and get userId
const session = jwt.verify(token, process.env.NEXTAUTH_SECRET!) as { id: string };
if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
const agent = await prisma.agent.findUnique({
@@ -28,7 +29,7 @@
});
if (!agent) {
- return NextResponse.json({ error: "Not an agent" }, { status: 403 });
+ return apiErrorResponse("Not an agent", 403, "NOT_AN_AGENT");
}
const chat = await prisma.supportChat.update({
@@ -55,6 +56,9 @@
return NextResponse.json(chat);
} catch (error) {
- console.error('Error accepting chat:', error);
- return NextResponse.json({ error: "Failed to accept chat" }, { status: 500 });
+ console.error('Error accepting chat:', error); // Log the actual error for debugging
+ return apiErrorResponse(
+ "Failed to accept chat",
+ 500, "ACCEPT_CHAT_FAILED", error instanceof Error ? error.message : String(error)
+ );
}
}
diff --git a/app/api/agent/chats/[chatId]/messages/route.ts b/app/api/agent/chats/[chatId]/messages/route.ts
index abcdef1..abcdef2 100644
--- a/app/api/agent/chats/[chatId]/messages/route.ts
+++ b/app/api/agent/chats/[chatId]/messages/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';
+import { apiErrorResponse } from '@/lib/errorHandling';
export async function POST(
req: NextRequest,
@@ -8,28 +9,28 @@
try {
// Get and validate token
const token = req.cookies.get('next-auth.session-token')?.value;
if (!token) {
- return NextResponse.json(
- { error: 'Unauthorized' },
- { status: 401 }
+ return apiErrorResponse(
+ 'Unauthorized',
+ 401, 'UNAUTHORIZED'
);
}
// Verify token and get userId
const session = jwt.verify(token, process.env.NEXTAUTH_SECRET!) as { id: string };
if (!session) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ return apiErrorResponse("Unauthorized", 401, "UNAUTHORIZED");
}
// Verify agent status
const agent = await prisma.agent.findUnique({
where: { userId: session.id }
});
if (!agent) {
- return NextResponse.json({ error: "Not an agent" }, { status: 403 });
+ return apiErrorResponse("Not an agent", 403, "NOT_AN_AGENT");
}
// Get message content from request
const { content } = await req.json();
if (!content) {
- return NextResponse.json({ error: "Message content is required" }, { status: 400 });
+ return apiErrorResponse("Message content is required", 400, "MESSAGE_CONTENT_REQUIRED");
}
// Verify chat exists and agent is assigned to it
@@ -40,7 +41,7 @@
});
if (!chat) {
- return NextResponse.json({ error: "Chat not found or not assigned to you" }, { status: 404 });
+ return apiErrorResponse("Chat not found or not assigned to you", 404, "CHAT_NOT_FOUND_OR_UNASSIGNED");
}
// Create message