-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMudrik_Final_SourceCode_For_SAIP.txt
More file actions
12059 lines (11567 loc) · 424 KB
/
Copy pathMudrik_Final_SourceCode_For_SAIP.txt
File metadata and controls
12059 lines (11567 loc) · 424 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
# Mudrik Platform — Complete Source Disclosure Bundle
**Generated (UTC):** 2026-04-01T12:23:30.308Z
**Purpose:** Submission support document listing the project structure and full contents of application source and configuration files.
**Excluded from this bundle (by design):**
- **Required exclusions:** `node_modules/`, `.git/`, and any `.env` / `.env.*` files (secrets)
- **Non-source / cache:** `.next/`, `.turbo/`, `.vercel/`, `.cursor/`, and root-only `build/` / `dist/` (not `app/api/.../build/` route folders)
- **Junk:** `.DS_Store`, `Thumbs.db`
**Included:** `app/`, `components/`, `lib/`, `utils/` (if present), `tests/`, `supabase/`, `scripts/`, plus root configuration files listed in the script.
---
## 1. Project directory tree
```text
mudrik مدرك/
├── app/
│ ├── api/
│ │ ├── auth/
│ │ │ └── signout/
│ │ │ └── route.ts
│ │ ├── engine/
│ │ │ ├── analyze/
│ │ │ │ └── route.ts
│ │ │ └── generate/
│ │ │ └── route.ts
│ │ ├── proposal/
│ │ │ └── build/
│ │ │ └── route.ts
│ │ └── vault/
│ │ └── ingest/
│ │ └── route.ts
│ ├── company-profile/
│ │ └── page.tsx
│ ├── engine/
│ │ └── page.tsx
│ ├── login/
│ │ └── page.tsx
│ ├── settings/
│ │ └── page.tsx
│ ├── vault/
│ │ └── page.tsx
│ ├── globals.css
│ ├── layout.tsx
│ └── page.tsx
├── components/
│ ├── app-shell.tsx
│ └── mudrik-logo.tsx
├── lib/
│ ├── supabase/
│ │ ├── public/
│ │ │ └── شعار مدرك.png
│ │ ├── client.ts
│ │ └── server.ts
│ ├── chunking.ts
│ ├── document-parser.ts
│ ├── embedding-config.ts
│ ├── format.ts
│ ├── model-gateway.ts
│ ├── pdf.ts
│ ├── proposal-docx.ts
│ ├── proposal-schema.ts
│ ├── rag-prompt.ts
│ └── user-settings.ts
├── scripts/
│ └── export-saip-source-bundle.mjs
├── supabase/
│ ├── migrations/
│ │ ├── 001_mudrik_schema.sql
│ │ ├── 002_storage_vault.sql
│ │ └── 004_user_settings_gemini.sql
│ └── fix_infrastructure.sql
├── tests/
│ └── model-gateway.test.ts
├── .eslintrc.json
├── .gitignore
├── middleware.ts
├── Mudrik_Final_SourceCode_For_SAIP.txt
├── Mudrik_Full_SourceCode.txt
├── mudrik@1.0.0
├── next
├── next-env.d.ts
├── next.config.mjs
├── package-lock.json
├── package.json
├── postcss.config.mjs
├── tailwind.config.ts
├── tsconfig.json
└── vitest.config.ts
```
---
## 2. File contents
Each subsection is one file. Paths are relative to the project root.
### File: `.eslintrc.json`
```json
{
"extends": "next/core-web-vitals"
}
```
### File: `app/api/auth/signout/route.ts`
```typescript
/**
* @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/engine/analyze/route.ts`
```typescript
/**
* @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/engine/generate/route.ts`
```typescript
/**
* @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/proposal/build/route.ts`
```typescript
/**
* @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/vault/ingest/route.ts`
```typescript
/**
* @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/company-profile/page.tsx`
```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 { useEffect, useMemo, useState } from "react";
import { AppShell } from "@/components/app-shell";
import { Building2, BriefcaseBusiness, ShieldCheck, Save, Sparkles, CheckCircle2, AlertCircle } from "lucide-react";
type Notice = { message: string; type: "success" | "error" };
type ProfileModel = {
companyOverview: string;
services: string;
pastProjects: string;
certificates: string;
};
const STORAGE_KEY = "mudrik_company_profile_v1";
function analyzeProfile(model: ProfileModel) {
const merged = `${model.companyOverview}\n${model.services}\n${model.pastProjects}\n${model.certificates}`.trim();
const words = merged ? merged.split(/\s+/).length : 0;
const servicesCount = model.services
.split(/\n|،|,/)
.map((x) => x.trim())
.filter(Boolean).length;
const projectsCount = model.pastProjects
.split(/\n|؛|,/)
.map((x) => x.trim())
.filter(Boolean).length;
const certificatesCount = model.certificates
.split(/\n|،|,/)
.map((x) => x.trim())
.filter(Boolean).length;
return { words, servicesCount, projectsCount, certificatesCount };
}
export default function CompanyProfilePage() {
const [model, setModel] = useState<ProfileModel>({
companyOverview: "",
services: "",
pastProjects: "",
certificates: "",
});
const [notice, setNotice] = useState<Notice | null>(null);
useEffect(() => {
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return;
const parsed = JSON.parse(raw) as Partial<ProfileModel>;
setModel({
companyOverview: typeof parsed.companyOverview === "string" ? parsed.companyOverview : "",
services: typeof parsed.services === "string" ? parsed.services : "",
pastProjects: typeof parsed.pastProjects === "string" ? parsed.pastProjects : "",
certificates: typeof parsed.certificates === "string" ? parsed.certificates : "",
});
} catch {
// Ignore malformed local state and continue with blank form.
}
}, []);
const analysis = useMemo(() => analyzeProfile(model), [model]);
function onSave() {
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(model));
setNotice({ message: "تم حفظ ملف الشركة محلياً بنجاح.", type: "success" });
} catch {
setNotice({ message: "تعذر حفظ البيانات محلياً على المتصفح.", type: "error" });
}
}
return (
<AppShell title="ملف تعريف الشركة">
<div className="grid grid-cols-1 gap-8 lg:grid-cols-12">
<div className="space-y-8 lg:col-span-8">
<div className="rounded-[2rem] border border-slate-200 bg-white p-8 shadow-sm">
<p className="mb-6 text-sm leading-relaxed text-mist">
هذا النموذج مخصص لتجهيز سياق الشركة بصورة احترافية لتغذية مسودات العروض الفنية. أدخل البيانات بصياغة واضحة
ومباشرة، ثم احفظها بشكل دوري.
</p>
<div className="space-y-6">
<div className="space-y-2">
<label htmlFor="companyOverview" className="flex items-center gap-2 text-sm font-bold text-charcoal">
<Building2 size={16} className="text-mist" />
نبذة الشركة
</label>
<textarea
id="companyOverview"
rows={5}
value={model.companyOverview}
onChange={(e) => setModel((prev) => ({ ...prev, companyOverview: e.target.value }))}
className="w-full resize-none rounded-2xl border border-slate-200 bg-slate-50/50 px-4 py-3 text-sm leading-relaxed text-charcoal outline-none transition-all focus:border-midnight/40 focus:bg-white focus:ring-4 focus:ring-midnight/5"
placeholder="قدّم تعريفاً موجزاً عن الشركة، قطاعات العمل، ونطاق التغطية الجغرافية."
/>
</div>
<div className="space-y-2">
<label htmlFor="services" className="flex items-center gap-2 text-sm font-bold text-charcoal">
<BriefcaseBusiness size={16} className="text-mist" />
الخدمات الرئيسية
</label>
<textarea
id="services"
rows={5}
value={model.services}
onChange={(e) => setModel((prev) => ({ ...prev, services: e.target.value }))}
className="w-full resize-none rounded-2xl border border-slate-200 bg-slate-50/50 px-4 py-3 text-sm leading-relaxed text-charcoal outline-none transition-all focus:border-midnight/40 focus:bg-white focus:ring-4 focus:ring-midnight/5"
placeholder="مثال: حلول أمنية متقدمة، أنظمة مراقبة، إدارة مرافق، تشغيل وصيانة..."
/>
</div>
<div className="space-y-2">
<label htmlFor="projects" className="flex items-center gap-2 text-sm font-bold text-charcoal">
<Sparkles size={16} className="text-mist" />
المشاريع السابقة
</label>
<textarea
id="projects"
rows={6}
value={model.pastProjects}
onChange={(e) => setModel((prev) => ({ ...prev, pastProjects: e.target.value }))}
className="w-full resize-none rounded-2xl border border-slate-200 bg-slate-50/50 px-4 py-3 text-sm leading-relaxed text-charcoal outline-none transition-all focus:border-midnight/40 focus:bg-white focus:ring-4 focus:ring-midnight/5"
placeholder="اكتب كل مشروع في سطر مستقل مع الجهة والنتيجة الرئيسية."
/>
</div>
<div className="space-y-2">
<label htmlFor="certificates" className="flex items-center gap-2 text-sm font-bold text-charcoal">
<ShieldCheck size={16} className="text-mist" />
الشهادات والاعتمادات
</label>
<textarea
id="certificates"
rows={4}
value={model.certificates}
onChange={(e) => setModel((prev) => ({ ...prev, certificates: e.target.value }))}
className="w-full resize-none rounded-2xl border border-slate-200 bg-slate-50/50 px-4 py-3 text-sm leading-relaxed text-charcoal outline-none transition-all focus:border-midnight/40 focus:bg-white focus:ring-4 focus:ring-midnight/5"
placeholder="ISO، شهادات جودة، تصنيفات، اعتمادات قطاعية."
/>
</div>
</div>
{notice && (
<div
className={`mt-6 flex items-center gap-2 rounded-2xl px-4 py-3 text-sm font-medium ${
notice.type === "success"
? "border border-emerald-100 bg-emerald-50 text-emerald-700"
: "border border-red-100 bg-red-50 text-red-700"
}`}
>
{notice.type === "success" ? <CheckCircle2 size={16} /> : <AlertCircle size={16} />}
{notice.message}
</div>
)}
<div className="mt-8 flex items-center justify-end">
<button
type="button"
onClick={onSave}
className="inline-flex items-center gap-2 rounded-full bg-midnight px-7 py-3 text-sm font-bold text-white shadow-lg shadow-midnight/20 transition-all hover:-translate-y-0.5 hover:bg-slate-800 active:translate-y-0"
>
<Save size={16} />
حفظ ملف الشركة
</button>
</div>
</div>
</div>
<div className="space-y-6 lg:col-span-4">
<div className="rounded-[2rem] border border-slate-200 bg-white p-7 shadow-sm">
<h3 className="mb-4 text-lg font-bold text-midnight">تحليل سريع للجاهزية</h3>
<div className="space-y-4 text-sm">
<div className="flex items-center justify-between rounded-xl bg-slate-50 px-3 py-2">
<span className="text-mist">إجمالي الكلمات</span>
<span className="font-bold text-midnight">{analysis.words}</span>
</div>
<div className="flex items-center justify-between rounded-xl bg-slate-50 px-3 py-2">
<span className="text-mist">عدد الخدمات</span>
<span className="font-bold text-midnight">{analysis.servicesCount}</span>
</div>
<div className="flex items-center justify-between rounded-xl bg-slate-50 px-3 py-2">
<span className="text-mist">عدد المشاريع</span>
<span className="font-bold text-midnight">{analysis.projectsCount}</span>
</div>
<div className="flex items-center justify-between rounded-xl bg-slate-50 px-3 py-2">
<span className="text-mist">عدد الشهادات</span>
<span className="font-bold text-midnight">{analysis.certificatesCount}</span>
</div>
</div>
</div>
</div>
</div>
</AppShell>
);
}
```
### File: `app/engine/page.tsx`
```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 { Fragment, useState, type ReactNode } from "react";
import { AppShell } from "@/components/app-shell";
import {
FileSearch,
Sparkles,
AlertCircle,
FileText,
Loader2,
Wand2,
Copy,
Check,
} from "lucide-react";
/** Renders **bold** as <strong>; strips remaining stray * pairs for a clean formal look. */
function renderDraftRichText(text: string): ReactNode {
const lines = text.split("\n");
return lines.map((line, lineIdx) => (
<Fragment key={lineIdx}>
{lineIdx > 0 ? <br /> : null}
{renderLineWithBold(line)}
</Fragment>
));
}
function renderLineWithBold(line: string): ReactNode {
const nodes: ReactNode[] = [];
const re = /\*\*([^*]+)\*\*/g;
let last = 0;
let m: RegExpExecArray | null;
let key = 0;
while ((m = re.exec(line)) !== null) {
if (m.index > last) {
nodes.push(
<Fragment key={`t-${key++}`}>{stripLoneAsteriskEmphasis(line.slice(last, m.index))}</Fragment>
);
}
nodes.push(
<strong key={`b-${key++}`} className="font-semibold text-white">
{m[1]}
</strong>
);
last = m.index + m[0].length;
}
if (last < line.length) {
nodes.push(
<Fragment key={`t-${key++}`}>{stripLoneAsteriskEmphasis(line.slice(last))}</Fragment>
);
}
return nodes.length > 0 ? nodes : stripLoneAsteriskEmphasis(line);
}
function stripLoneAsteriskEmphasis(segment: string): ReactNode {
const parts = segment.split(/(\*[^*\n]+\*)/g);
if (parts.length === 1) return segment.replace(/\*/g, "");
return parts.map((part, i) => {
const single = part.match(/^\*([^*\n]+)\*$/);
if (single) return single[1];
return part.replace(/\*/g, "");
});
}
/** Plain text for Word/paste: no markdown asterisks or heading hashes. */
function stripMarkdownForClipboard(text: string): string {
return text.replace(/[*#]/g, "");
}
export default function EnginePage() {
const [drag, setDrag] = useState(false);
const [busy, setBusy] = useState<"idle" | "analyze" | "generate" | "build">("idle");
const [rfpText, setRfpText] = useState("");
const [filename, setFilename] = useState<string | null>(null);
const [draft, setDraft] = useState<string | null>(null);
const [notice, setNotice] = useState<{ message: string; type: "error" | "info" } | null>(null);
const [chunks, setChunks] = useState<number | null>(null);
const [copied, setCopied] = useState(false);
async function copyDraftToClipboard() {
if (!draft?.trim()) return;
try {
await navigator.clipboard.writeText(stripMarkdownForClipboard(draft));
setCopied(true);
window.setTimeout(() => setCopied(false), 2200);
} catch {
setNotice({ message: "تعذر النسخ. تحقق من أذونات المتصفح.", type: "error" });
}
}
async function analyzeFile(file: File) {
setNotice(null);
const acceptedTypes = ["application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"];
if (!acceptedTypes.includes(file.type)) {