-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMudrik_Full_SourceCode.txt
More file actions
11108 lines (10745 loc) · 394 KB
/
Copy pathMudrik_Full_SourceCode.txt
File metadata and controls
11108 lines (10745 loc) · 394 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
/*******************************************************
* 📄 FILE: ./middleware.ts
*******************************************************/
import { createServerClient, type CookieOptions } from "@supabase/ssr";
import type { User } from "@supabase/supabase-js";
import { NextResponse, type NextRequest } from "next/server";
export async function middleware(request: NextRequest) {
let response = NextResponse.next({ request: { headers: request.headers } });
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
let user: User | null = null;
if (url && key) {
const supabase = createServerClient(url, key, {
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(cookiesToSet: { name: string; value: string; options: CookieOptions }[]) {
cookiesToSet.forEach(({ name, value, options }) => {
response.cookies.set(name, value, options);
});
},
},
});
const {
data: { user: sessionUser },
} = await supabase.auth.getUser();
user = sessionUser;
} else {
console.warn(
"[mudrik] Middleware: NEXT_PUBLIC_SUPABASE_URL أو NEXT_PUBLIC_SUPABASE_ANON_KEY غير معرّفين؛ تُعامل الطلبات كغير مصادق عليها."
);
}
const path = request.nextUrl.pathname;
if (!user && path.startsWith("/api")) {
return NextResponse.json({ error: "غير مصرح" }, { status: 401 });
}
if (!user && path !== "/login" && path !== "/") {
const redirect = NextResponse.redirect(new URL("/login", request.url));
return redirect;
}
if (user && path === "/login") {
return NextResponse.redirect(new URL("/vault", request.url));
}
return response;
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"],
};
/*******************************************************
* 📄 FILE: ./app/settings/page.tsx
*******************************************************/
/**
* @project MUDRIK - AI Tender Consultant
* @author Al-Baraa | البراء
* @created March 2026
* @status Stable Version 1.0
* @copyright (c) 2026 All Rights Reserved
* @legal_notice This source code and all its algorithms are the sole property of Al-Baraa.
* Any unauthorized copying, modification, or distribution is strictly prohibited.
* مشروع مُدْرِك - مستشار المنافسات الذكي
* حقوق الملكية محفوظة (ج) ٢٠٢٦ - المؤلف: البراء
*/
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { AppShell } from "@/components/app-shell";
import { createClient } from "@/lib/supabase/client";
import { Key, Cpu, Box, Save, CheckCircle2, AlertCircle, Loader2, Plug, Sparkles } from "lucide-react";
import { MudrikLogo } from "@/components/mudrik-logo";
export default function SettingsPage() {
const supabase = useMemo(() => createClient(), []);
const [aiProvider, setAiProvider] = useState<"gemini" | "openai">("gemini");
const [openaiApiKey, setOpenaiApiKey] = useState("");
const [geminiApiKey, setGeminiApiKey] = useState("");
const [embeddingModel, setEmbeddingModel] = useState("text-embedding-3-small");
const [chatModel, setChatModel] = useState("gpt-4o-mini");
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [notice, setNotice] = useState<{ message: string; type: "error" | "success" } | null>(null);
const load = useCallback(async () => {
setLoading(true);
const { data: userData } = await supabase.auth.getUser();
const uid = userData.user?.id;
if (!uid) {
setLoading(false);
return;
}
const { data } = await supabase.from("user_settings").select("*").eq("user_id", uid).maybeSingle();
if (data) {
setAiProvider(data.ai_provider === "openai" ? "openai" : "gemini");
setOpenaiApiKey(data.model_api_key ?? "");
setGeminiApiKey(data.gemini_api_key ?? "");
setEmbeddingModel(data.embedding_model ?? "text-embedding-3-small");
setChatModel(data.chat_model ?? "gpt-4o-mini");
}
setLoading(false);
}, [supabase]);
useEffect(() => {
void load();
}, [load]);
async function onSave(e: React.FormEvent) {
e.preventDefault();
setSaving(true);
setNotice(null);
const { data: userData } = await supabase.auth.getUser();
const uid = userData.user?.id;
if (!uid) {
setSaving(false);
setNotice({ message: "انتهت الجلسة.", type: "error" });
return;
}
const { error } = await supabase.from("user_settings").upsert(
{
user_id: uid,
ai_provider: aiProvider,
model_api_key: openaiApiKey.trim() || null,
gemini_api_key: geminiApiKey.trim() || null,
embedding_model: embeddingModel.trim(),
chat_model: chatModel.trim(),
updated_at: new Date().toISOString(),
},
{ onConflict: "user_id" }
);
setSaving(false);
if (error) {
setNotice({ message: error.message, type: "error" });
return;
}
setNotice({ message: "تم حفظ الإعدادات بنجاح.", type: "success" });
}
return (
<AppShell title="إعدادات المنصة">
<div className="grid grid-cols-1 gap-10 lg:grid-cols-12">
<div className="lg:col-span-7">
<div className="bg-white rounded-[2rem] border border-slate-200 p-8 md:p-10 shadow-sm">
<div className="flex items-center gap-3 mb-8 pb-6 border-b border-slate-100">
<div className="bg-slate-100 p-3 rounded-2xl">
<MudrikLogo size={24} className="text-midnight" />
</div>
<div>
<h2 className="text-xl font-bold text-midnight">تكوين النماذج</h2>
<p className="text-sm text-mist">تحكم في محركات الذكاء الاصطناعي المستخدمة</p>
</div>
</div>
{loading ? (
<div className="flex flex-col items-center justify-center py-20 gap-4">
<Loader2 size={32} className="animate-spin text-midnight/20" />
<p className="text-sm font-medium text-mist">جارٍ تحميل الإعدادات…</p>
</div>
) : (
<form onSubmit={onSave} className="space-y-8">
<div className="space-y-3">
<label
htmlFor="provider"
className="flex items-center gap-2 text-sm font-bold text-charcoal"
>
<Plug size={16} className="text-mist" />
مزود الذكاء الاصطناعي (AI Provider)
</label>
<select
id="provider"
value={aiProvider}
onChange={(e) => setAiProvider(e.target.value === "openai" ? "openai" : "gemini")}
className="w-full rounded-2xl border border-slate-200 bg-slate-50/50 px-5 py-4 text-sm text-charcoal outline-none focus:border-midnight/40 focus:bg-white focus:ring-4 focus:ring-midnight/5 transition-all appearance-none"
>
<option value="gemini">جوجل جيمني (مجاني/Gemini)</option>
<option value="openai">أوبن إيه آي (OpenAI)</option>
</select>
</div>
<div className="space-y-3">
{aiProvider === "openai" ? (
<>
<label
htmlFor="openaiKey"
className="flex items-center gap-2 text-sm font-bold text-charcoal"
>
<Key size={16} className="text-mist" />
مفتاح OpenAI
</label>
<input
id="openaiKey"
name="openaiKey"
type="password"
autoComplete="off"
value={openaiApiKey}
onChange={(e) => setOpenaiApiKey(e.target.value)}
className="w-full rounded-2xl border border-slate-200 bg-slate-50/50 px-5 py-4 text-sm text-charcoal outline-none focus:border-midnight/40 focus:bg-white focus:ring-4 focus:ring-midnight/5 transition-all"
placeholder="sk-••••••••••••••••••••••••"
/>
<p className="text-xs leading-relaxed text-mist px-1">
يُستخدم هذا المفتاح للتضمين والبحث (RAG) والتوليد عند اختيار OpenAI.
</p>
</>
) : (
<>
<label
htmlFor="geminiKey"
className="flex items-center gap-2 text-sm font-bold text-charcoal"
>
<Sparkles size={16} className="text-mist" />
مفتاح Gemini
</label>
<input
id="geminiKey"
name="geminiKey"
type="password"
autoComplete="off"
value={geminiApiKey}
onChange={(e) => setGeminiApiKey(e.target.value)}
className="w-full rounded-2xl border border-slate-200 bg-slate-50/50 px-5 py-4 text-sm text-charcoal outline-none focus:border-midnight/40 focus:bg-white focus:ring-4 focus:ring-midnight/5 transition-all"
placeholder="AIzaSy•••••••••••••••••••••••"
/>
<p className="text-xs leading-relaxed text-mist px-1">
يُستخدم هذا المفتاح للتوليد عبر Gemini عند اختيار مزود Gemini.
</p>
</>
)}
</div>
{aiProvider === "openai" ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-3">
<label htmlFor="emb" className="flex items-center gap-2 text-sm font-bold text-charcoal">
<Box size={16} className="text-mist" />
نموذج التضمين
</label>
<select
id="emb"
value={embeddingModel}
onChange={(e) => setEmbeddingModel(e.target.value)}
className="w-full rounded-2xl border border-slate-200 bg-slate-50/50 px-5 py-4 text-sm text-charcoal outline-none focus:border-midnight/40 focus:bg-white focus:ring-4 focus:ring-midnight/5 transition-all appearance-none"
>
<option value="text-embedding-3-small">text-embedding-3-small (أسرع)</option>
<option value="text-embedding-3-large">text-embedding-3-large (أدق)</option>
<option value="text-embedding-ada-002">text-embedding-ada-002 (كلاسيكي)</option>
</select>
</div>
<div className="space-y-3">
<label htmlFor="chat" className="flex items-center gap-2 text-sm font-bold text-charcoal">
<Cpu size={16} className="text-mist" />
نموذج التوليد
</label>
<select
id="chat"
value={chatModel}
onChange={(e) => setChatModel(e.target.value)}
className="w-full rounded-2xl border border-slate-200 bg-slate-50/50 px-5 py-4 text-sm text-charcoal outline-none focus:border-midnight/40 focus:bg-white focus:ring-4 focus:ring-midnight/5 transition-all appearance-none"
>
<option value="gpt-4o-mini">gpt-4o-mini (اقتصادي)</option>
<option value="gpt-4o">gpt-4o (قوي جداً)</option>
<option value="o1-preview">o1-preview (تفكير عميق)</option>
</select>
</div>
</div>
) : null}
{notice && (
<div className={`flex items-center gap-3 rounded-2xl px-5 py-4 text-sm font-medium animate-in fade-in slide-in-from-top-2 ${
notice.type === "error" ? "bg-red-50 text-red-700 border border-red-100" : "bg-emerald-50 text-emerald-700 border border-emerald-100"
}`}>
{notice.type === "error" ? <AlertCircle size={18} /> : <CheckCircle2 size={18} />}
{notice.message}
</div>
)}
<button
type="submit"
disabled={saving}
className="flex items-center gap-2 rounded-full bg-midnight px-10 py-4 text-sm font-bold text-white shadow-lg shadow-midnight/20 transition-all hover:bg-slate-800 hover:shadow-xl hover:-translate-y-0.5 active:translate-y-0 disabled:opacity-50 disabled:translate-y-0"
>
{saving ? (
<Loader2 size={18} className="animate-spin" />
) : (
<Save size={18} />
)}
حفظ التغييرات
</button>
</form>
)}
</div>
</div>
<div className="lg:col-span-5 space-y-6">
<div className="bg-slate-50 rounded-[2rem] border border-slate-200 p-8">
<h3 className="text-lg font-bold text-midnight mb-4">لماذا BYOK؟</h3>
<p className="text-sm leading-relaxed text-mist">
نحن نتبع سياسة "أحضر مفتاحك الخاص" (Bring Your Own Key) لضمان أقصى درجات الخصوصية والتحكم في التكاليف.
بياناتك لا تُستخدم لتدريب النماذج العامة، وأنت تدفع فقط مقابل استهلاكك الفعلي لشركة OpenAI.
</p>
</div>
<div className="bg-midnight rounded-[2rem] p-8 text-white">
<h3 className="text-lg font-bold mb-4">نصيحة تقنية</h3>
<p className="text-sm leading-relaxed text-white/70">
للحصول على أفضل توازن بين السرعة والجودة في معالجة المناقصات العربية، نوصي باستخدام:
</p>
<div className="mt-6 space-y-3">
<div className="flex items-center justify-between text-xs border-b border-white/10 pb-2">
<span className="text-white/40">للتضمين:</span>
<span className="font-mono text-amber-400">text-embedding-3-small</span>
</div>
<div className="flex items-center justify-between text-xs border-b border-white/10 pb-2">
<span className="text-white/40">للتوليد:</span>
<span className="font-mono text-amber-400">gpt-4o-mini</span>
</div>
</div>
</div>
</div>
</div>
</AppShell>
);
}
/*******************************************************
* 📄 FILE: ./app/layout.tsx
*******************************************************/
/**
* @project MUDRIK - AI Tender Consultant
* @author Al-Baraa | البراء
* @created March 2026
* @status Stable Version 1.0
* @copyright (c) 2026 All Rights Reserved
* @legal_notice This source code and all its algorithms are the sole property of Al-Baraa.
* Any unauthorized copying, modification, or distribution is strictly prohibited.
* مشروع مُدْرِك - مستشار المنافسات الذكي
* حقوق الملكية محفوظة (ج) ٢٠٢٦ - المؤلف: البراء
*/
import type { Metadata } from "next";
import { IBM_Plex_Sans_Arabic } from "next/font/google";
import "./globals.css";
const ibmPlexSansArabic = IBM_Plex_Sans_Arabic({
subsets: ["arabic", "latin"],
weight: ["400", "500", "600", "700"],
variable: "--font-ibm-plex-sans-arabic",
display: "swap",
});
export const metadata: Metadata = {
title: "مُدْرِك | المنصة الذكية لتحليل وإعداد عروض المناقصات والمزايدات",
description:
"أتمتة دورة حياة تحليل كراسات الشروط بدقة عالية، مع مطابقة المتطلبات مع الخبرات السابقة وتوليد مسودات العروض المتوافقة.",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html dir="rtl" lang="ar" className={ibmPlexSansArabic.variable}>
<body className={`min-h-screen font-sans ${ibmPlexSansArabic.className}`}>{children}</body>
</html>
);
}
/*******************************************************
* 📄 FILE: ./app/api/auth/signout/route.ts
*******************************************************/
/**
* @project MUDRIK - AI Tender Consultant
* @author Al-Baraa | البراء
* @created March 2026
* @status Stable Version 1.0
* @copyright (c) 2026 All Rights Reserved
* @legal_notice This source code and all its algorithms are the sole property of Al-Baraa.
* Any unauthorized copying, modification, or distribution is strictly prohibited.
* مشروع مُدْرِك - مستشار المنافسات الذكي
* حقوق الملكية محفوظة (ج) ٢٠٢٦ - المؤلف: البراء
*/
import { NextResponse } from "next/server";
import { createServerSupabaseClient } from "@/lib/supabase/server";
export async function POST(request: Request) {
try {
const supabase = await createServerSupabaseClient();
await supabase.auth.signOut();
return NextResponse.redirect(new URL("/login", request.url), 302);
} catch (e) {
console.error("CRITICAL ERROR IN /api/auth/signout:", e);
return NextResponse.redirect(new URL("/login", request.url), 302);
}
}
/*******************************************************
* 📄 FILE: ./app/api/proposal/build/route.ts
*******************************************************/
/**
* @project MUDRIK - AI Tender Consultant
* @author Al-Baraa | البراء
* @created March 2026
* @status Stable Version 1.0
* @copyright (c) 2026 All Rights Reserved
* @legal_notice This source code and all its algorithms are the sole property of Al-Baraa.
* Any unauthorized copying, modification, or distribution is strictly prohibited.
* مشروع مُدْرِك - مستشار المنافسات الذكي
* حقوق الملكية محفوظة (ج) ٢٠٢٦ - المؤلف: البراء
*/
import { NextResponse } from "next/server";
import { normalizeProposalJson, proposalToMatrixText } from "@/lib/proposal-schema";
import { renderProposalDocx } from "@/lib/proposal-docx";
import { createServerSupabaseClient } from "@/lib/supabase/server";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
try {
const supabase = await createServerSupabaseClient();
const {
data: { user },
error: userErr,
} = await supabase.auth.getUser();
if (userErr || !user) {
return NextResponse.json({ error: "غير مصرح" }, { status: 401 });
}
const body = (await request.json()) as { proposal?: unknown };
if (!body.proposal) {
return NextResponse.json({ error: "حقل proposal مطلوب." }, { status: 400 });
}
let proposal;
try {
proposal = normalizeProposalJson(body.proposal);
} catch (e) {
const msg = e instanceof Error ? e.message : "هيكل غير صالح";
return NextResponse.json({ error: msg }, { status: 400 });
}
const buffer = renderProposalDocx({
title_ar: proposal.title_ar,
executive_summary: proposal.executive_summary,
technical_approach: proposal.technical_approach,
timeline: proposal.timeline,
pricing_notes: proposal.pricing_notes,
compliance_matrix_ar: proposalToMatrixText(proposal),
});
const filename = `mudrik-proposal-${Date.now()}.docx`;
return new NextResponse(new Uint8Array(buffer), {
status: 200,
headers: {
"Content-Type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"Content-Disposition": `attachment; filename="${encodeURIComponent(filename)}"`,
"Cache-Control": "no-store",
},
});
} catch (e) {
console.error("CRITICAL ERROR IN /api/proposal/build:", e);
const msg = e instanceof Error ? e.message : "خطأ غير متوقع";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
/*******************************************************
* 📄 FILE: ./app/api/engine/generate/route.ts
*******************************************************/
/**
* @project MUDRIK - AI Tender Consultant
* @author Al-Baraa | البراء
* @created March 2026
* @status Stable Version 1.0
* @copyright (c) 2026 All Rights Reserved
* @legal_notice This source code and all its algorithms are the sole property of Al-Baraa.
* Any unauthorized copying, modification, or distribution is strictly prohibited.
* مشروع مُدْرِك - مستشار المنافسات الذكي
* حقوق الملكية محفوظة (ج) ٢٠٢٦ - المؤلف: البراء
*/
import { GoogleGenerativeAI } from "@google/generative-ai";
import { NextResponse } from "next/server";
import { EMBEDDING_VECTOR_DIMENSIONS } from "@/lib/embedding-config";
import { buildEnterpriseSmartDraftPrompt } from "@/lib/rag-prompt";
import { createServerSupabaseClient } from "@/lib/supabase/server";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export const maxDuration = 60;
const GEMINI_EMBEDDING_MODEL = "gemini-embedding-001";
const RFP_CAP = 24000;
/** شخصية كاتب عطاءات أول: لغة تنفيذية رسمية، دمج سياقين، ومنع أي صياغة افتراضية أو رموز ماركداون. */
const GENERATE_SYSTEM_PROMPT_AR = `أنت كاتب عطاءات فني أول للمناقصات الحكومية السعودية، وتكتب الصياغة النهائية الجاهزة للتقديم نيابة عن شركتنا.
الهوية والأسلوب:
- اكتب بلسان المتكلم الجمع: نحن، شركتنا، فريقنا.
- استخدم لغة مهنية حازمة وموثوقة بصياغات من قبيل: نلتزم بـ، نؤكد على، بما يتماشى مع الأنظمة، وفق المتطلبات التعاقدية والتنظيمية.
- لا تكتب كأنك مساعد يشرح أو يوجه، بل كجهة متقدمة بعرض رسمي نهائي.
- امنع أي عبارات مثل: بناء على ملف الشركة، كما طُلب، أو بحسب التعليمات.
تكامل السياق:
- حلل المقاطع المسترجعة وحدد ما يعود إلى كراسة الشروط: نطاق، مواصفات، منهجية مطلوبة، اشتراطات امتثال.
- حلل المقاطع المسترجعة وحدد ما يعود إلى هوية الشركة: مشاريع سابقة، قدرات، شهادات، خبرات قطاعية.
- إذا ظهر في السياق ما يشير إلى MASTER_PROFILE أو Company Profile فاعتبره مرجع الهوية الرسمي لشركتنا، وادمجه مباشرة داخل النص بضمير نحن دون الإشارة إلى مصدره.
- ادمج القدرات والخبرات ضمن كل محور فني وتشغيلي بشكل طبيعي ومقنع.
دقة المحتوى:
- لا تستخدم أي حقول بديلة أو أقواس توجيهية أو نصوص مكانية.
- عند نقص تفاصيل محددة، اكتب صياغة احترافية عامة قوية تعكس ممارسات شركة رائدة دون اختلاق أسماء مشاريع أو أرقام غير مذكورة في السياق.
- أي أسماء أو أرقام أو شهادات أو وقائع محددة يجب أن تكون مستندة إلى السياق المتاح فقط.
هيكل الاستجابة الإلزامي:
1) نطاق العمل.
2) المنهجية الفنية والتنفيذ.
3) الامتثال النظامي والتعاقدي.
4) الخبرات والقدرات المؤسسية.
متطلبات الإخراج:
- أخرج نصا عربيا رسميا نظيفا وجاهزا للإدراج المباشر في مستند العرض الفني.
- لا تستخدم رموز ماركداون أو نجوم أو عناوين بعلامات خاصة أو تعداد بعلامات غير نصية.`;
function cleanGeneratedDraft(raw: string): string {
let t = raw.replace(/\r\n/g, "\n").trim();
t = t.replace(/\n{3,}/g, "\n\n");
t = t.replace(/[ \t]+$/gm, "");
t = t.replace(/[*#]/g, "");
return t;
}
export async function POST(request: Request) {
const apiKey = process.env.GEMINI_API_KEY?.trim();
if (!apiKey) {
return NextResponse.json(
{ error: "CRITICAL: GEMINI_API_KEY is missing from .env" },
{ status: 500 }
);
}
try {
const supabase = await createServerSupabaseClient();
const {
data: { user },
error: userErr,
} = await supabase.auth.getUser();
if (userErr || !user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const body = (await request.json()) as { rfpText?: string; documentId?: string };
let rfpText = typeof body.rfpText === "string" ? body.rfpText.trim() : "";
if (!rfpText && body.documentId) {
const { data: doc } = await supabase
.from("vault_documents")
.select("content")
.eq("id", body.documentId)
.eq("user_id", user.id)
.maybeSingle();
rfpText = typeof doc?.content === "string" ? doc.content.trim() : "";
}
if (!rfpText) {
return NextResponse.json({ error: "rfpText is required (or valid documentId with content)." }, { status: 400 });
}
const excerpt = rfpText.length > RFP_CAP ? rfpText.slice(0, RFP_CAP) : rfpText;
const genAI = new GoogleGenerativeAI(apiKey);
const embedModel = genAI.getGenerativeModel({ model: GEMINI_EMBEDDING_MODEL });
const embedRes = await embedModel.embedContent(excerpt.slice(0, 8000));
const queryEmbedding = embedRes.embedding?.values ?? [];
if (queryEmbedding.length !== EMBEDDING_VECTOR_DIMENSIONS) {
throw new Error(
`Embedding dimension mismatch: got ${queryEmbedding.length}, expected ${EMBEDDING_VECTOR_DIMENSIONS}`
);
}
const { data: matches, error: rpcErr } = await supabase.rpc("match_document_chunks", {
query_embedding: queryEmbedding,
match_count: 14,
min_similarity: 0.18,
});
if (rpcErr) {
console.error("[RAW GENERATION ERROR]:", rpcErr);
return NextResponse.json({ error: rpcErr.message }, { status: 500 });
}
const rows = Array.isArray(matches) ? matches : [];
const contextBlocks = rows
.map((r: { content?: string }) => String(r?.content ?? "").trim())
.filter(Boolean);
const ragContextOneString =
contextBlocks.length > 0
? contextBlocks.map((c, i) => `[${i + 1}] ${c}`).join("\n\n---\n\n")
: "";
const userPrompt = buildEnterpriseSmartDraftPrompt(
excerpt,
ragContextOneString ? [ragContextOneString] : []
);
const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });
const fullPrompt = `${GENERATE_SYSTEM_PROMPT_AR}\n\n${userPrompt}`;
const result = await model.generateContent(fullPrompt);
const draft = cleanGeneratedDraft(result.response.text());
return new Response(draft, {
status: 200,
headers: {
"Content-Type": "text/plain; charset=utf-8",
"X-Context-Chunks-Used": String(contextBlocks.length),
"Cache-Control": "no-store",
},
});
} catch (error) {
console.error("[RAW GENERATION ERROR]:", error);
const message = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: message }, { status: 500 });
}
}
/*******************************************************
* 📄 FILE: ./app/api/engine/analyze/route.ts
*******************************************************/
/**
* @project MUDRIK - AI Tender Consultant
* @author Al-Baraa | البراء
* @created March 2026
* @status Stable Version 1.0
* @copyright (c) 2026 All Rights Reserved
* @legal_notice This source code and all its algorithms are the sole property of Al-Baraa.
* Any unauthorized copying, modification, or distribution is strictly prohibited.
* مشروع مُدْرِك - مستشار المنافسات الذكي
* حقوق الملكية محفوظة (ج) ٢٠٢٦ - المؤلف: البراء
*/
import { NextResponse } from "next/server";
import { extractTextFromBuffer } from "@/lib/document-parser";
import { createServerSupabaseClient } from "@/lib/supabase/server";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
try {
const supabase = await createServerSupabaseClient();
const {
data: { user },
error: userErr,
} = await supabase.auth.getUser();
if (userErr || !user) {
return NextResponse.json({ error: "غير مصرح" }, { status: 401 });
}
const contentType = request.headers.get("content-type") ?? "";
if (!contentType.includes("multipart/form-data")) {
return NextResponse.json({ error: "يتطلب إرسال multipart/form-data مع الحقل rfp" }, { status: 400 });
}
const form = await request.formData();
const file = form.get("rfp");
if (!(file instanceof File)) {
return NextResponse.json({ error: "الملف مطلوب في الحقل rfp" }, { status: 400 });
}
const acceptedTypes = ["application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"];
if (file.type && !acceptedTypes.includes(file.type)) {
return NextResponse.json({ error: "يُقبل ملفات PDF أو DOCX فقط." }, { status: 400 });
}
const buffer = Buffer.from(await file.arrayBuffer());
let text: string;
try {
text = await extractTextFromBuffer(buffer, file.type || "application/pdf");
} catch (e) {
console.error("CRITICAL ERROR IN /api/engine/analyze (extract):", e);
const msg = e instanceof Error ? e.message : "فشل التحليل";
return NextResponse.json({ error: msg }, { status: 422 });
}
const excerpt = text.trim();
if (!excerpt) {
return NextResponse.json({ error: "لم يُستخرج نص من الملف." }, { status: 422 });
}
return NextResponse.json({
ok: true,
filename: file.name,
charCount: excerpt.length,
text: excerpt,
});
} catch (e) {
console.error("CRITICAL ERROR IN /api/engine/analyze:", e);
const msg = e instanceof Error ? e.message : "خطأ غير متوقع";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
/*******************************************************
* 📄 FILE: ./app/api/vault/ingest/route.ts
*******************************************************/
/**
* @project MUDRIK - AI Tender Consultant
* @author Al-Baraa | البراء
* @created March 2026
* @status Stable Version 1.0
* @copyright (c) 2026 All Rights Reserved
* @legal_notice This source code and all its algorithms are the sole property of Al-Baraa.
* Any unauthorized copying, modification, or distribution is strictly prohibited.
* مشروع مُدْرِك - مستشار المنافسات الذكي
* حقوق الملكية محفوظة (ج) ٢٠٢٦ - المؤلف: البراء
*/
import { NextResponse } from "next/server";
import { chunkTextByTokens } from "@/lib/chunking";
import { extractTextFromBuffer } from "@/lib/document-parser";
import { embedTexts } from "@/lib/model-gateway";
import { fetchUserModelSettings } from "@/lib/user-settings";
import { createServerSupabaseClient } from "@/lib/supabase/server";
import { assertEmbeddingVector } from "@/lib/embedding-config";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export const maxDuration = 60;
const EMBED_BATCH = 16;
const INSERT_BATCH = 40;
function formatVectorLiteral(values: number[]): string {
assertEmbeddingVector(values, "قبل الإدراج في قاعدة البيانات.");
return `[${values.join(",")}]`;
}
function safeFilename(name: unknown): string {
const s = typeof name === "string" ? name.trim() : "";
return s.length > 0 ? s : "document";
}
export async function POST(request: Request) {
try {
const supabase = await createServerSupabaseClient();
const {
data: { user },
error: userErr,
} = await supabase.auth.getUser();
if (userErr || !user) {
return NextResponse.json({ error: "غير مصرح" }, { status: 401 });
}
const body = (await request.json()) as { documentId?: string };
const documentId = body.documentId;
if (!documentId) {
return NextResponse.json({ error: "معرّف المستند مطلوب." }, { status: 400 });
}
const { data: docRow, error: docErr } = await supabase
.from("vault_documents")
.select("id, storage_path, user_id, filename, mime")
.eq("id", documentId)
.eq("user_id", user.id)
.single();
if (docErr || !docRow) {
return NextResponse.json({ error: "المستند غير موجود." }, { status: 404 });
}
const row = docRow as {
storage_path: string;
filename?: string | null;
mime?: string | null;
};
const storagePath = String(row.storage_path ?? "").trim();
if (!storagePath) {
await supabase
.from("vault_documents")
.update({ status: "failed", error_message: "مسار التخزين غير صالح" })
.eq("id", documentId);
return NextResponse.json({ error: "بيانات المستند غير مكتملة." }, { status: 400 });
}
await supabase
.from("vault_documents")
.update({ status: "processing", error_message: null })
.eq("id", documentId);
const settings = await fetchUserModelSettings(supabase, user.id);
const { data: fileData, error: dlErr } = await supabase.storage.from("vault").download(storagePath);
if (dlErr || !fileData) {
const errMsg = dlErr?.message ?? "تعذر التحميل";
await supabase
.from("vault_documents")
.update({ status: "failed", error_message: errMsg })
.eq("id", documentId);
return NextResponse.json({ error: "تعذر تحميل الملف من التخزين." }, { status: 500 });
}
const buffer = Buffer.from(await fileData.arrayBuffer());
const mime =
typeof row.mime === "string" && row.mime.trim()
? row.mime.trim()
: "application/pdf";
let text: string;
try {
text = await extractTextFromBuffer(buffer, mime);
} catch (e) {
const msg = e instanceof Error ? e.message : "فشل استخراج النص";
await supabase.from("vault_documents").update({ status: "failed", error_message: msg }).eq("id", documentId);
return NextResponse.json({ error: msg }, { status: 422 });
}
const trimmed = text.replace(/\u0000/g, "").trim();
if (!trimmed) {
await supabase
.from("vault_documents")
.update({ status: "failed", error_message: "لا يوجد نص قابل للاستخراج" })
.eq("id", documentId);
return NextResponse.json({ error: "لم يُستخرج أي نص من الملف." }, { status: 422 });
}
const contentUpdate: Record<string, unknown> = {
status: "processing",
error_message: null,
content: trimmed,
size_bytes: Number.isFinite(buffer.byteLength) ? buffer.byteLength : 0,
filename: safeFilename(row.filename),
};
const { error: contentErr } = await supabase.from("vault_documents").update(contentUpdate).eq("id", documentId);
if (contentErr) {
const { error: contentErr2 } = await supabase
.from("vault_documents")
.update({
status: "processing",
error_message: null,
size_bytes: contentUpdate.size_bytes,
filename: contentUpdate.filename,
})
.eq("id", documentId);
if (contentErr2) {
console.error("CRITICAL ERROR IN /api/vault/ingest (vault update):", contentErr, contentErr2);
return NextResponse.json({ error: contentErr2.message }, { status: 500 });
}
}
await supabase.from("document_chunks").delete().eq("document_id", documentId);
const chunks = chunkTextByTokens(trimmed, 512, 48).filter((c) => c.content.trim().length > 0);
if (chunks.length === 0) {
await supabase
.from("vault_documents")
.update({ status: "failed", error_message: "لا توجد مقاطع نصية صالحة للفهرسة" })
.eq("id", documentId);
return NextResponse.json({ error: "لم يُنتج التقسيم أي مقاطع." }, { status: 422 });
}
const vectors: number[][] = [];
for (let i = 0; i < chunks.length; i += EMBED_BATCH) {
const slice = chunks.slice(i, i + EMBED_BATCH);
const batchEmbeddings = await embedTexts(
settings,
slice.map((c) => c.content)
);
vectors.push(...batchEmbeddings);
}
if (vectors.length !== chunks.length) {
const msg = "عدد المتجهات لا يطابق عدد المقاطع.";
await supabase.from("vault_documents").update({ status: "failed", error_message: msg }).eq("id", documentId);
return NextResponse.json({ error: msg }, { status: 500 });
}
const rows = chunks.map((c, idx) => {
const content = c.content.trim() || "\u200c";
const emb = formatVectorLiteral(vectors[idx] ?? []);
return {
document_id: documentId,
user_id: user.id,
chunk_index: c.chunkIndex,
content,
token_estimate: c.tokenEstimate,
embedding: emb,
};
});
for (let i = 0; i < rows.length; i += INSERT_BATCH) {
const batch = rows.slice(i, i + INSERT_BATCH);
const { error: insErr } = await supabase.from("document_chunks").insert(batch);
if (insErr) {
console.error("CRITICAL ERROR IN /api/vault/ingest (chunk insert):", insErr);
await supabase
.from("vault_documents")
.update({ status: "failed", error_message: insErr.message })
.eq("id", documentId);
return NextResponse.json({ error: insErr.message }, { status: 500 });
}
}
await supabase
.from("vault_documents")
.update({ status: "ready", error_message: null })
.eq("id", documentId);
return NextResponse.json({
ok: true,
documentId,
chunks: chunks.length,
filename: safeFilename(row.filename),
});
} catch (e) {
console.error("CRITICAL ERROR IN /api/vault/ingest:", e);
const msg = e instanceof Error ? e.message : "خطأ غير متوقع";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
/*******************************************************
* 📄 FILE: ./app/page.tsx
*******************************************************/
/**
* @project MUDRIK - AI Tender Consultant
* @author Al-Baraa | البراء
* @created March 2026
* @status Stable Version 1.0
* @copyright (c) 2026 All Rights Reserved
* @legal_notice This source code and all its algorithms are the sole property of Al-Baraa.
* Any unauthorized copying, modification, or distribution is strictly prohibited.
* مشروع مُدْرِك - مستشار المنافسات الذكي
* حقوق الملكية محفوظة (ج) ٢٠٢٦ - المؤلف: البراء
*/
import Link from "next/link";
import { redirect } from "next/navigation";
import { createServerSupabaseClient } from "@/lib/supabase/server";
import { MudrikLogo } from "@/components/mudrik-logo";
export default async function HomePage() {
const supabase = await createServerSupabaseClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (user) {
redirect("/vault");
}
return (
<div className="flex min-h-screen flex-col bg-white">
<header className="border-b border-slate-100 bg-white/80 backdrop-blur-md sticky top-0 z-50">
<div className="mx-auto flex max-w-5xl items-center justify-between px-6 py-6">
<div className="flex items-center gap-2 text-xl font-bold text-midnight tracking-tight">
<div className="bg-midnight text-white p-1.5 rounded-lg">
<MudrikLogo size={20} />
</div>
<span>مُدْرِك</span>
</div>
<Link
href="/login"
className="rounded-full bg-midnight px-6 py-2.5 text-sm font-bold text-white transition hover:bg-slate-800 shadow-lg shadow-midnight/10"
>
دخول المنصة
</Link>