✦

جامعة الكوفة

كلية الإدارة والاقتصاد

شعبة شؤون الطلبة والتسجيل
نظام إعداد وطباعة الكتب الرسمية

جارٍ تشغيل النظام...

💻 وضع أوفلاين محلي
جامعة الكوفة
كلية الإدارة والاقتصاد
شعبة شؤون الطلبة والتسجيل
نظام إعداد وطباعة الكتب الرسمية

تسجيل الدخول

أدخل بيانات حسابك للوصول إلى النظام

حساب واحد يعمل Online وOffline. في أول مرة اربط هذا اللابتوب برمز من المدير، ثم استخدم نفس اسم المستخدم وكلمة المرور.
تصميم وتطوير النظامالأستاذ يوسف صالح يوسف الحلوجامعة الكوفة — كلية الإدارة والاقتصاد

تنبيه انتهاء الجلسة

لم يتم تسجيل أي نشاط منذ مدة. سيتم تسجيل خروجك تلقائيًا لحماية النظام.

05:00

إعداد كتاب صحة الصدور

اختر نوع الكتاب، أكمل البيانات، راجع المعاينة، ثم اطبع أو احفظ وأرشف.

اليوم
الشهر
السنة
اليوم
الشهر
السنة
يرجى إكمال الحقول المحددة باللون الأحمر قبل الطباعة.
إعدادات القالب والطباعة
Ministry of Higher Education
and Scientific Research
UNIVERSITY OF
KUFA
Faculty of Administration &
Economics
جمهورية العراق
وزارة التعليم العالي
والبحث العلمي
جامعة الكوفة
كلية الإدارة والاقتصاد
العدد  :                 / د.م
التاريخ :        /      / ٢٠٢٦
علامة مائية
إلى/ مديرية التعليم المهني في المحافظة
م/ صحة صدور
تحية طيبة ....

.. مع التقدير ..
ا.د. حيدر جواد المرشدي
معاون العميد للشؤون العلمية والدراسات العليا
٢٠٢٦//
نسخة منه إلى //
*مكتب السيد م. العميد للتفضل بالاطلاع .. مع التقدير.
*شؤون الطلب المسائي مع الأوليات.
*يوسف صالح يوسف*
W W W .uokufa.edu.iq
University of Kufa , Kufa , P.O.Box (21), Najaf Governorate , Iraq
E-mail:mang@uokufa.edu.iq
E-mail:info@uokufa.edu.iq
T : +964(0)33 340952   F: +964(0)33 340951
جامعة الكوفة - الكوفة - ص.ب. (٢١) - محافظة النجف الأشرف - جمهورية العراق

إدارة التواقيع

يمكن إضافة المسؤولين وتعديل أسمائهم ومناصبهم وإخفاؤهم وتحديد التوقيع الافتراضي.

لوحة الإحصائيات

إجمالي الكتب٠
كتب اليوم٠
كتب الشهر٠
المطبوعة٠
المسلّمة٠

حسب نوع الكتاب

حسب القسم

إنجاز الموظفين

آخر نشاطات الموظفين

🔄 مركز المزامنة — v12.3.15

🌐 الإدارة المركزية — الحساب الموحد Online / Offline

تدير من هنا الحسابات والأجهزة والمزامنة. رابط /exec يعمل في الخلفية ولا يحتاج الموظف لفتحه.

الحسابات المركزية

الأجهزة المرتبطة

👥 إدارة الحسابات المركزية والصلاحيات

إضافة وتعديل وتعطيل الحسابات من مكان واحد. في نسخة Offline يلزم الإنترنت لإدارة الحسابات المركزية.

التقارير الإدارية

التاريخنوع الكتابالطالبالقسمالحالةالموظف
حدد المدة ثم أنشئ التقرير.

إعدادات الطابعات

احفظ إزاحات مستقلة لكل طابعة، ثم اخترها من نموذج الكتاب.

إدارة أنواع الكتب ونصوصها

يمكن تعديل العنوان والنص، أو إضافة كتاب جديد. استخدم المتغيرات مثل: {الاسم}، {القسم}، {المرحلة}، {الدراسة}، {السنة}، {الجهة}.

📚 نماذج الكتب الجاهزة

مكتبة ملفات جاهزة للعمل. يمكن للمدير رفع PDF أو Word أو صورة من اللابتوب، وتُحفظ الملفات تلقائيًا في Google Drive. جميع المستخدمين يستطيعون فتح النماذج، والحذف للمدير فقط.

📋 سجل نشاط المستخدمين

سجل تدقيق للعمليات المهمة في النظام. متاح لمدير النظام فقط.

👨‍🎓 ملف الطالب الموحد

⚠️ إدارة التعارضات

لا يتم استبدال أي نسخة تلقائيًا. اختر النسخة التي تريد اعتمادها لكل سجل.

🩺 مركز صحة النظام

🤖 المساعد الإداري الذكي

يمكنك إنشاء صياغة للكتاب الحالي، أو سؤال المساعد عن أي كتاب أو طلب رسمي إلى العميد أو معاون العميد أو جهة أخرى.

⚙️ إعدادات الذكاء الاصطناعي

هذه الإعدادات متاحة لمدير النظام فقط. مفتاح Gemini يُحفظ في Script Properties ولا يظهر داخل HTML.

جارٍ فحص الاتصال...

يستخدم النظام نموذج Flash سريعًا، وعند ازدحامه يجرب نموذجًا احتياطيًا تلقائيًا.

`);win.document.close();selectedArchiveIds.clear();loadArchive()}).withFailureHandler(error=>{win.close();authFailure(error)}).batchMarkPrinted(ids,sessionToken)} function showHistory(index){const row=archiveRows[index];if(!row)return;const lines=(row.history||[]).map(x=>'• '+x.action+' — '+x.time+(x.detail?' — '+x.detail:'')).join('\n');alert('تفاصيل كتاب: '+row.studentName+'\nرقم الأرشيف: '+row.archiveId+'\nتاريخ الإنشاء: '+(row.savedAt||'—')+'\nآخر تعديل: '+(row.updatedAt||'—')+'\nآخر طباعة: '+(row.printedAt||'—')+'\nتاريخ التسليم: '+(row.deliveredAt||'—')+'\nتاريخ الحذف: '+(row.deletedAt||'—')+'\n\nسجل العمليات:\n'+(lines||'لا توجد عمليات مسجلة.'))} function exportArchiveCsv(){ el('archiveStatus').textContent='جارٍ تجهيز ملف Excel...';google.script.run.withSuccessHandler(data=>{ const term=val('archiveSearch').toLowerCase(),type=val('archiveType'),status=val('archiveBookStatus'),from=val('archiveFrom'),to=val('archiveTo'); const rows=(data||[]).filter(row=>{const stateOk=archiveView==='trash'?row.recordState==='deleted':row.recordState!=='deleted';const day=String(row.savedAt||'').slice(0,10).replace(/\//g,'-');const hay=[row.archiveId,row.studentName,row.department,row.destination,row.governorate,row.docNo,row.letterTypeName].join(' ').toLowerCase();return stateOk&&(!type||row.letterType===type)&&(!status||row.bookStatus===status)&&(!term||hay.includes(term))&&(!from||day>=from)&&(!to||day<=to)}); if(!rows.length){el('archiveStatus').textContent='لا توجد نتائج لتصديرها.';return} const quote=value=>'"'+String(value==null?'':value).replace(/"/g,'""')+'"',header=['رقم الأرشيف','تاريخ الإنشاء','آخر تعديل','نوع الكتاب','اسم الطالب','الجهة','القسم','المرحلة','الدراسة','عدد الوثيقة','تاريخ المراجعة','تاريخ الطباعة','تاريخ التسليم','التوقيع']; const lines=[header,...rows.map(row=>[row.archiveId,row.savedAt,row.updatedAt,row.letterTypeName||letterNames[row.letterType],row.studentName,row.destination||row.governorate,row.department,row.stage,row.study,row.docNo,row.reviewDate,row.printedAt,row.deliveredAt,(signatures.find(x=>x.id===row.signatory)||{}).name||row.signatory])]; downloadBlob('\ufeff'+lines.map(line=>line.map(quote).join(',')).join('\r\n'),'أرشيف_الكتب_الرسمية.csv','text/csv;charset=utf-8');el('archiveStatus').textContent='تم تصدير جميع النتائج.'; }).withFailureHandler(error=>{el('archiveStatus').textContent='تعذر التصدير: '+(error.message||error)}).exportArchiveData(sessionToken); } function downloadBlob(content,name,type){const blob=new Blob([content],{type:type}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)} function fillArchiveForm(row){ if(![...el('letterType').options].some(x=>x.value===row.letterType))el('letterType').insertAdjacentHTML('beforeend',``); el('letterType').value=row.letterType||'vocational'; el('studentName').value=row.studentName||'';el('gender').value=row.gender||'male'; const known=[...el('governorate').options].some(option=>option.value===row.governorate&&option.value!=='غير ذلك'); el('governorate').value=!row.governorate?'':known?row.governorate:'غير ذلك';el('customGovernorate').value=known?'':row.governorate||''; el('destination').value=row.destination||'';if(row.extraData){const x=row.extraData;el('hostRecipient1').value=x.recipient1||'إلى السيد عميد كلية الإدارة والاقتصاد المحترم';el('hostRecipient2').value=x.recipient2||'إلى السيد معاون العميد المحترم';el('hostRecipient3').value=x.recipient3||'إلى السيد رئيس القسم المحترم';el('hostFromStudy').value=x.fromStudy||'المسائية';el('hostToStudy').value=x.toStudy||'الصباحية';el('hostAcademicYear').value=x.academicYear||'2026-2027';el('hostReason').value=x.reason||'لأسباب صحية';el('hostAttachmentType').value=x.attachmentType||'تقرير طبي';el('hostFeePercent').value=x.feePercent||'25%';el('hostMedicalNo').value=x.medicalNo||'';el('hostMedicalDate').value=x.medicalDate||'';if(el('hostRequestDate'))el('hostRequestDate').value=x.requestDate||'';}el('treatmentDestination').value=['مستشفى الحكيم العام','مستشفى الصدر العام','مستشفى الفرات الاوسط التعليمي','مستشفى النجف التعليمي'].includes(row.destination)?row.destination:(row.destination?'أخرى':'');el('customTreatmentDestination').value=(el('treatmentDestination').value==='أخرى'?(row.destination||''):'');el('customTreatmentDestination').style.display=el('treatmentDestination').value==='أخرى'?'block':'none';el('reviewDay').value=row.reviewDay||''; const reviewParts=String(row.reviewDate||'').split('/'); const oldYearFirst=(reviewParts[0]||'').length===4; el('reviewDateDay').value=oldYearFirst?(reviewParts[2]||''):(reviewParts[0]||'');el('reviewDateMonth').value=reviewParts[1]||'';el('reviewDateYear').value=oldYearFirst?(reviewParts[0]||''):(reviewParts[2]||''); el('docNo').value=row.docNo||'';el('docDay').value=row.docDay||'';el('docMonth').value=row.docMonth||'';el('docYear').value=row.docYear||''; el('department').value=row.department||'';el('stage').value=row.stage||'';el('study').value=row.study||'الصباحية';el('signatory').value=row.signatory||getDefaultSignatureId();el('bookStatus').value=row.bookStatus||'مؤرشف';el('organizerName').value=row.organizerName||''; } function editArchive(index){const row=archiveRows[index];if(!row)return;fillArchiveForm(row);editingArchiveId=row.archiveId;el('archiveSaveBtn').textContent='تحديث السجل المؤرشف';closeArchive();el('form').classList.remove('was-validated');update();window.scrollTo({top:0,behavior:'smooth'})} function cloneArchive(index){const row=archiveRows[index];if(!row)return;fillArchiveForm(row);editingArchiveId='';el('studentName').value='';el('bookStatus').value='مؤرشف';el('archiveSaveBtn').textContent='حفظ وأرشفة';closeArchive();update();el('studentName').focus();window.scrollTo({top:0,behavior:'smooth'})} function printArchived(index){const row=archiveRows[index];if(!row)return;fillArchiveForm(row);editingArchiveId=row.archiveId;update();google.script.run.withSuccessHandler(()=>{closeArchive();setTimeout(()=>window.print(),150)}).withFailureHandler(authFailure).markArchiveAction(row.archiveId,'printed',sessionToken)} async function kaeBuildFullBackup(){ if(!window.KAE_IS_LOCAL)throw new Error('النسخة الاحتياطية الكاملة متاحة في نسخة Offline.'); if(!currentUser||currentUser.role!=='admin')throw new Error('هذه العملية متاحة لمدير النظام فقط.'); const st=await window.KAE_LOCAL_API.load(); return {type:'KAE_FULL_BACKUP',formatVersion:2,appVersion:'11.2.0',exportedAt:new Date().toISOString(),deviceName:(localStorage.getItem('kaeDeviceName')||''),summary:{archive:(st.archive||[]).length,users:(st.users||[]).length,activity:(st.activity||[]).length,signatures:(st.signatures||[]).length},data:{users:st.users||[],archive:st.archive||[],activity:st.activity||[],signatures:st.signatures||[],settings:st.settings||null}}; } async function kaeDownloadFullBackup(prefix){ const data=await kaeBuildFullBackup(),stamp=new Date().toISOString().replace(/[:.]/g,'-').slice(0,19); downloadBlob(JSON.stringify(data,null,2),(prefix||'KAE_نسخة_احتياطية_كاملة')+'_'+stamp+'.json','application/json;charset=utf-8'); return data; } function downloadBackup(){ if(!window.KAE_IS_LOCAL){el('archiveStatus').textContent='جارٍ إعداد النسخة الاحتياطية...';google.script.run.withSuccessHandler(data=>{downloadBlob(JSON.stringify(data,null,2),'نسخة_احتياطية_لأرشيف_الكتب.json','application/json;charset=utf-8');el('archiveStatus').textContent='تم تنزيل النسخة الاحتياطية.'}).withFailureHandler(authFailure).getArchiveBackup(sessionToken);return} el('archiveStatus').textContent='جارٍ إعداد نسخة كاملة من البيانات المحلية...'; kaeDownloadFullBackup().then(data=>{el('archiveStatus').textContent='تم تنزيل النسخة الكاملة — '+arabicDigits(data.summary.archive)+' كتاب، '+arabicDigits(data.summary.users)+' حساب.'}).catch(authFailure) } function restoreBackupFile(input){ const file=input.files&&input.files[0];if(!file)return; if(!window.KAE_IS_LOCAL){if(!confirm('سيتم دمج السجلات غير الموجودة من النسخة الاحتياطية. المتابعة؟')){input.value='';return}const reader=new FileReader();reader.onload=()=>{try{const data=JSON.parse(reader.result);google.script.run.withSuccessHandler(result=>{alert('تمت الاستعادة.\nالسجلات المضافة: '+arabicDigits(result.imported)+'\nالمتجاوزة لوجودها مسبقًا: '+arabicDigits(result.skipped));input.value='';loadSignatures();loadArchive()}).withFailureHandler(error=>{authFailure(error);input.value=''}).restoreArchiveBackup(data,sessionToken)}catch(error){alert('ملف النسخة الاحتياطية غير صالح.');input.value=''}};reader.readAsText(file,'UTF-8');return} if(!currentUser||currentUser.role!=='admin'){alert('الاستعادة متاحة لمدير النظام فقط.');input.value='';return} const reader=new FileReader();reader.onload=async()=>{try{ const b=JSON.parse(reader.result);if(!b||b.type!=='KAE_FULL_BACKUP'||!b.data||!Array.isArray(b.data.archive)||!Array.isArray(b.data.users))throw new Error('هذا ليس ملف نسخة احتياطية كاملة صالحًا.'); const info='النسخة: '+(b.exportedAt||'غير معروف')+'\nالكتب: '+arabicDigits((b.data.archive||[]).length)+'\nالحسابات: '+arabicDigits((b.data.users||[]).length)+'\n\nسيتم أخذ نسخة تلقائية من الوضع الحالي أولًا، ثم استبدال البيانات المحلية. المتابعة؟'; if(!confirm(info)){input.value='';return} el('archiveStatus').textContent='جارٍ إنشاء نسخة أمان قبل الاستعادة...';await kaeDownloadFullBackup('KAE_قبل_الاستعادة'); const old=await window.KAE_LOCAL_API.load();const next={users:b.data.users||[],archive:b.data.archive||[],activity:b.data.activity||[],signatures:b.data.signatures||[],settings:b.data.settings||old.settings,sessions:old.sessions||{}}; await window.KAE_LOCAL_API.save(next);input.value='';alert('تمت الاستعادة بنجاح.\nتم الحفاظ على جلسة الدخول الحالية وإعدادات ربط الجهاز.');location.reload(); }catch(error){input.value='';alert('تعذر استعادة النسخة: '+(error.message||error));el('archiveStatus').textContent='فشلت الاستعادة.'}};reader.readAsText(file,'UTF-8') } function getDefaultSignatureId(){return (signatures.find(x=>x.active&&x.isDefault)||signatures.find(x=>x.active)||{}).id||'associate'} function loadSignatures(){const fallback=[{id:'associate',name:'ا.د. حيدر جواد المرشدي',role:'معاون العميد للشؤون العلمية والدراسات العليا',active:true,isDefault:true},{id:'dean',name:'أ.د. حيدر جاسم الجبوري',role:'العـمـيـــــــــد',active:true,isDefault:false}];if(!sessionToken){signatures=fallback;applySignatures();return}google.script.run.withSuccessHandler(items=>{signatures=items&&items.length?items:fallback;applySignatures()}).withFailureHandler(authFailure).getSignatures(sessionToken)} function applySignatures(){const select=el('signatory'),previous=select.value;select.innerHTML=signatures.filter(x=>x.active).map(x=>``).join('');select.value=[...select.options].some(x=>x.value===previous)?previous:getDefaultSignatureId();update()} function openSignatures(){renderSignatureEditors();el('signatureModal').classList.add('open')} function closeSignatures(){el('signatureModal').classList.remove('open')} function renderSignatureEditors(){el('signatureEditors').innerHTML=signatures.map((item,index)=>`
`).join('')} function addSignatureEditor(){if(el('signatureEditors').children.length)signatures=collectSignatureEditors();signatures.push({id:'signature-'+Date.now(),name:'',role:'',active:true,isDefault:!signatures.length});renderSignatureEditors()} function removeSignatureEditor(index){signatures=collectSignatureEditors();if(signatures.length===1){alert('يجب إبقاء توقيع واحد على الأقل.');return}signatures.splice(index,1);renderSignatureEditors()} function collectSignatureEditors(){return [...document.querySelectorAll('.signature-editor')].map(box=>({id:box.dataset.id,name:box.querySelector('.sig-name').value.trim(),role:box.querySelector('.sig-role').value.trim(),active:box.querySelector('.sig-active').checked,isDefault:box.querySelector('.sig-default').checked}))} function saveSignatureSettings(){const items=collectSignatureEditors();el('signatureStatus').textContent='جارٍ الحفظ...';google.script.run.withSuccessHandler(saved=>{signatures=saved;applySignatures();el('signatureStatus').textContent='تم حفظ إعدادات التواقيع.'}).withFailureHandler(authFailure).saveSignatures(items,sessionToken)} function closeModal(id){el(id).classList.remove('open')} let v12AutosaveTimer=null; function v12Today(){const d=new Date();return d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+String(d.getDate()).padStart(2,'0')} function v12Esc(s){return escapeHtml(String(s==null?'':s))} async function openStudentsHub(){el('studentsHubModal').classList.add('open');await loadStudentsHub()} const DEFAULT_STUDENT_REQUIREMENTS=[ {key:'document',name:'الوثيقة الإعدادية'}, {key:'verification',name:'صحة صدور الوثيقة'}, {key:'guarantee',name:'الكفالة القانونية'}, {key:'nationalId',name:'البطاقة الوطنية'}, {key:'residence',name:'بطاقة السكن'}, {key:'photos',name:'صور شخصية'}, {key:'registration',name:'استمارة التسجيل'}, {key:'medical',name:'الفحص الطبي'}, {key:'undertakings',name:'التعهدات'} ]; function normalizeStudentRequirements(r){ const saved=Array.isArray(r&&r.requirements)?r.requirements:[]; const map=new Map(saved.map(x=>[x.key||x.name,x])); const base=DEFAULT_STUDENT_REQUIREMENTS.map(x=>Object.assign({status:'مكتملة',note:'',followDate:''},x,map.get(x.key)||{})); saved.filter(x=>!DEFAULT_STUDENT_REQUIREMENTS.some(d=>(x.key&&d.key===x.key)||d.name===x.name)).forEach(x=>base.push(Object.assign({status:'مكتملة',note:'',followDate:''},x))); return base; } function studentReqStats(r){ const a=normalizeStudentRequirements(r), active=a.filter(x=>x.status!=='لا تنطبق'), missing=active.filter(x=>x.status==='ناقصة'), follow=active.filter(x=>x.status==='قيد المتابعة'||x.status==='لم ترد'||x.status==='مطلوب إرسال'); return {all:a,missing,follow,complete:missing.length===0&&follow.length===0}; } function reqBadge(r){ const st=studentReqStats(r); if(st.missing.length)return '🔴 نواقص '+arabicDigits(st.missing.length)+''; if(st.follow.length)return '🟠 متابعة '+arabicDigits(st.follow.length)+''; return '🟢 مكتمل'; } function renderStudentRequirements(reqs){ const box=el('stuRequirements');if(!box)return;box.innerHTML=''; (reqs||[]).forEach(x=>addStudentRequirement(x)); updateStudentReqSummary(); } function addStudentRequirement(x){ const box=el('stuRequirements');if(!box)return; x=x||{key:'custom_'+Date.now(),name:'',status:'ناقصة',note:'',followDate:''}; const row=document.createElement('div');row.className='stu-req-row';row.dataset.key=x.key||('custom_'+Date.now()); row.innerHTML=''; row.querySelector('.sr-status').value=x.status||'مكتملة'; row.querySelectorAll('input,select').forEach(e=>e.addEventListener('input',updateStudentReqSummary)); box.appendChild(row); } function collectStudentRequirements(){ return [...document.querySelectorAll('#stuRequirements .stu-req-row')].map(row=>({key:row.dataset.key||('custom_'+Date.now()),name:row.querySelector('.sr-name').value.trim(),status:row.querySelector('.sr-status').value,note:row.querySelector('.sr-note').value.trim(),followDate:row.querySelector('.sr-date').value})).filter(x=>x.name); } function updateStudentReqSummary(){ const a=collectStudentRequirements(),missing=a.filter(x=>x.status==='ناقصة'||x.status==='تحتاج تجديد'),follow=a.filter(x=>['قيد المتابعة','لم ترد','مطلوب إرسال'].includes(x.status)),e=el('stuReqSummary');if(!e)return; if(missing.length){e.textContent='🔴 لديه نواقص: '+arabicDigits(missing.length);e.className='stu-req-summary req-bad'} else if(follow.length){e.textContent='🟠 قيد المتابعة: '+arabicDigits(follow.length);e.className='stu-req-summary req-wait'} else{e.textContent='🟢 الملف مكتمل';e.className='stu-req-summary req-ok'} } function newStudentForm(){el('stuId').value='';el('stuName').value='';el('stuUniversityId').value='';renderStudentRequirements(normalizeStudentRequirements({}));el('studentEditor').hidden=false;el('stuName').focus()} async function loadStudentsHub(){ const q=val('studentHubSearch'),filter=el('studentReqFilter')?el('studentReqFilter').value:''; google.script.run.withSuccessHandler(rows=>{ if(filter)rows=rows.filter(r=>{const st=studentReqStats(r);if(filter==='complete')return st.complete;if(filter==='missing')return st.missing.length;if(filter==='followup')return st.follow.length;const x=st.all.find(a=>a.key===filter);return x&&x.status!=='مكتملة'&&x.status!=='لا تنطبق'}); el('studentsHubStatus').textContent='عدد النتائج: '+arabicDigits(rows.length); el('studentsHubList').innerHTML=rows.length?''+rows.map(r=>{const st=studentReqStats(r),detail=[...st.missing,...st.follow].slice(0,3).map(x=>x.name+' — '+x.status).join('
');return ''}).join('')+'
الطالبالرقمالقسمالمرحلةالدراسةالحالةالأوليات
'+v12Esc(r.name)+'
'+v12Esc(r.studentId)+'
'+v12Esc(r.universityId||'—')+''+v12Esc(r.department||'—')+''+v12Esc(r.stage||'—')+''+v12Esc(r.study||'—')+''+v12Esc(r.state||'مستمر')+''+reqBadge(r)+(detail?'
'+detail+'
':'')+'
':'
لا توجد ملفات طلبة بعد.
' }).withFailureHandler(authFailure).listStudents(q,sessionToken) } function editStudentRecord(j){const r=JSON.parse(j);el('stuId').value=r.studentId||'';el('stuName').value=r.name||'';el('stuUniversityId').value=r.universityId||'';['Department','Stage','Study','State'].forEach(k=>{const e=el('stu'+k),key=k.toLowerCase();if(e&&r[key])e.value=r[key]});renderStudentRequirements(normalizeStudentRequirements(r));el('studentEditor').hidden=false} function saveStudentRecord(){const d={studentId:val('stuId'),name:val('stuName').trim(),universityId:val('stuUniversityId').trim(),department:val('stuDepartment'),stage:val('stuStage'),study:val('stuStudy'),state:val('stuState'),requirements:collectStudentRequirements()};if(!d.name){alert('أدخل اسم الطالب.');return}google.script.run.withSuccessHandler(()=>{el('studentEditor').hidden=true;loadStudentsHub()}).withFailureHandler(authFailure).saveStudent(d,sessionToken)} function studentRequirementsWarning(r){ const st=studentReqStats(r),a=[...st.missing,...st.follow];if(!a.length)return; const msg=a.slice(0,5).map(x=>'• '+x.name+' — '+x.status+(x.note?' ('+x.note+')':'')).join('\\n'); setTimeout(()=>alert('⚠️ تنبيه: ملف الطالب يحتوي على أوليات تحتاج متابعة:\\n'+msg+'\\n\\nيمكنك إنشاء الكتاب بشكل طبيعي؛ هذا التنبيه لا يمنع العمل.'),80); } function useStudentRecord(j){const r=JSON.parse(j);closeModal('studentsHubModal');el('studentName').value=r.name||'';if(r.department)el('department').value=r.department;if(r.stage)el('stage').value=r.stage;if(r.study)el('study').value=r.study;update();studentRequirementsWarning(r);el('studentName').focus()} async function importStudentsFromArchive(){if(!window.KAE_IS_LOCAL){alert('هذه الأداة متاحة في نسخة Offline.');return}const s=await window.KAE_LOCAL_API.load();s.students=s.students||[];const key=x=>String(x||'').replace(/\s+/g,' ').trim();const known=new Set(s.students.map(x=>key(x.name)+'|'+key(x.department)));let n=0;(s.archive||[]).filter(r=>!r.deleted&&!r._purged&&r.studentName).forEach(r=>{const k=key(r.studentName)+'|'+key(r.department);if(!known.has(k)){s.students.push({studentId:'STU-'+Date.now()+'-'+Math.random().toString(36).slice(2,7).toUpperCase(),name:r.studentName,department:r.department||'',stage:r.stage||'',study:r.study||'',state:'مستمر',createdAt:new Date().toLocaleString('ar-IQ'),createdBy:'استيراد من الأرشيف',_syncPending:true,_clientModifiedMs:Date.now()});known.add(k);n++}});await window.KAE_LOCAL_API.save(s);el('studentsHubStatus').textContent='تم إنشاء '+arabicDigits(n)+' ملف طالب من الأرشيف.';loadStudentsHub()} async function openWorkflowHub(){el('workflowHubModal').classList.add('open');await renderWorkflowHub()} async function renderWorkflowHub(){if(!window.KAE_IS_LOCAL){el('workflowBoard').innerHTML='
متاح في نسخة Offline.
';return}const s=await window.KAE_LOCAL_API.load(),rows=(s.archive||[]).filter(r=>!r.deleted&&!r._purged);const sts=['مسودة','قيد التدقيق','جاهز للطباعة','بانتظار التوقيع','جاهز للتسليم','تم التسليم'];el('workflowBoard').innerHTML=sts.map(st=>{const a=rows.filter(r=>(r.bookStatus||'مؤرشف')===st);return '
'+st+' ('+arabicDigits(a.length)+')'+a.slice(0,30).map(r=>'
'+v12Esc(r.studentName||'—')+'
'+v12Esc(r.letterTypeName||r.letterType||'')+'
'+v12Esc(r.archiveId)+'
').join('')+'
'}).join('')} function v12SetStatus(id,status){if(!status)return;google.script.run.withSuccessHandler(()=>renderWorkflowHub()).withFailureHandler(authFailure).setArchiveStatus(id,status,sessionToken)} async function openDailyWork(){el('dailyWorkModal').classList.add('open');if(!window.KAE_IS_LOCAL)return;const s=await window.KAE_LOCAL_API.load(),rows=(s.archive||[]).filter(r=>!r.deleted&&!r._purged),today=new Date().toLocaleDateString('ar-IQ'),mine=rows.filter(r=>String(r.savedAt||'').includes(today)||String(r.updatedAt||'').includes(today)),pending=rows.filter(r=>r._syncPending),delivery=rows.filter(r=>r.bookStatus==='جاهز للتسليم'),sign=rows.filter(r=>r.bookStatus==='بانتظار التوقيع');el('dailyWorkBody').innerHTML='
عمليات اليوم'+arabicDigits(mine.length)+'
بانتظار التوقيع'+arabicDigits(sign.length)+'
جاهزة للتسليم'+arabicDigits(delivery.length)+'
بانتظار المزامنة'+arabicDigits(pending.length)+'

المستخدم: '+v12Esc(currentUser&¤tUser.name||'—')+' — الجهاز: '+v12Esc(localStorage.getItem('kaeDeviceName')||'—')+'

'} async function openConflictManager(){el('conflictManagerModal').classList.add('open');await renderConflictManager()} async function renderConflictManager(){if(!window.KAE_IS_LOCAL)return;const s=await window.KAE_LOCAL_API.load(),rows=(s.archive||[]).filter(r=>r._syncConflict);el('conflictManagerBody').innerHTML=rows.length?rows.map(r=>'
'+v12Esc(r.studentName||r.archiveId)+'
'+v12Esc(r.archiveId)+'

النسخة المحلية: '+v12Esc(r.updatedBy||r.createdBy||'—')+' — '+v12Esc(r.updatedAt||r.savedAt||'')+'

النسخة المركزية محفوظة داخل سجل التعارض.

').join(''):'
✅ لا توجد تعارضات حاليًا.
'} function resolveV12Conflict(id,mode){if(!confirm(mode==='server'?'سيتم استبدال النسخة المحلية بالنسخة المركزية. متابعة؟':'سيتم اعتماد النسخة المحلية وإعادة إرسالها. متابعة؟'))return;google.script.run.withSuccessHandler(()=>{renderConflictManager();refreshSyncCenter()}).withFailureHandler(authFailure).resolveLocalConflict(id,mode,sessionToken)} async function openSystemHealth(){el('systemHealthModal').classList.add('open');google.script.run.withSuccessHandler(h=>{const online=navigator.onLine,linked=!!localStorage.getItem('kaeDeviceToken'),last=localStorage.getItem('kaeLastArchiveSync')||'لم تتم';el('systemHealthBody').innerHTML='
الإصدار: v12.3.0
الإنترنت: '+(online?'🟢 متصل':'🟠 Offline')+'
ربط الجهاز: '+(linked?'🟢 مربوط':'غير مربوط')+'
الأرشيف: '+arabicDigits(h.archive)+' | الطلبة: '+arabicDigits(h.students)+' | السلة: '+arabicDigits(h.trash)+'
بانتظار المزامنة: '+arabicDigits(h.pending)+' | التعارضات: '+arabicDigits(h.conflicts)+'
الحسابات: '+arabicDigits(h.users)+' | سجل النشاط: '+arabicDigits(h.activity)+'
آخر مزامنة: '+v12Esc(last)+'
'}).withFailureHandler(authFailure).systemHealth(sessionToken)} async function downloadFullLocalBackupV12(){if(!window.KAE_IS_LOCAL)return;const s=await window.KAE_LOCAL_API.load(),blob=new Blob([JSON.stringify({type:'KAE_FULL_BACKUP_V12',version:'12.0.0',exportedAt:new Date().toISOString(),state:s},null,2)],{type:'application/json;charset=utf-8'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='KAE_FULL_BACKUP_'+v12Today()+'.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),1000)} async function copyV12Diagnostic(){const s=window.KAE_IS_LOCAL?await window.KAE_LOCAL_API.load():{};const report=['KAE v12 Diagnostic','Device: '+(localStorage.getItem('kaeDeviceName')||''),'Online: '+navigator.onLine,'Archive: '+((s.archive||[]).length),'Students: '+((s.students||[]).length),'Pending: '+((s.archive||[]).filter(x=>x._syncPending).length),'Conflicts: '+((s.archive||[]).filter(x=>x._syncConflict).length),'Last sync: '+(localStorage.getItem('kaeLastArchiveSync')||'')].join('\n');try{await navigator.clipboard.writeText(report);alert('تم نسخ تقرير التشخيص.')}catch(e){prompt('انسخ التقرير:',report)}} function v12DraftSnapshot(){return {studentName:val('studentName'),letterType:val('letterType'),department:val('department'),stage:val('stage'),study:val('study'),destination:val('destination'),bookStatus:val('bookStatus'),savedAt:Date.now()}} function startV12Autosave(){clearInterval(v12AutosaveTimer);v12AutosaveTimer=setInterval(()=>{try{if(sessionToken&&val('studentName'))localStorage.setItem('kaeFormDraftV12',JSON.stringify(v12DraftSnapshot()))}catch(e){}},5000)} function restoreV12DraftIfAny(){try{localStorage.removeItem(storageKey)}catch(e){}} function renderBars(target,data){const entries=Object.entries(data||{}).sort((a,b)=>b[1]-a[1]),max=Math.max(1,...entries.map(x=>x[1]));el(target).innerHTML=entries.length?entries.map(([name,count])=>`
${escapeHtml(name||'غير محدد')}
${arabicDigits(count)}
`).join(''):'

لا توجد بيانات.

'} function renderDashboard(data){el('dashTotal').textContent=arabicDigits(data.total);el('dashToday').textContent=arabicDigits(data.today);el('dashMonth').textContent=arabicDigits(data.month);el('dashPrinted').textContent=arabicDigits(data.printed);el('dashDelivered').textContent=arabicDigits(data.delivered);el('dashDrafts').textContent=arabicDigits(data.drafts);renderBars('typeChart',data.byType);renderBars('departmentChart',data.byDepartment);renderBars('employeeChart',data.byEmployee);el('recentActivity').innerHTML=(data.recentActivity||[]).map(x=>`
${escapeHtml(x.action)}${escapeHtml(x.employee)} — ${escapeHtml(x.time)}
${escapeHtml(x.detail)}
`).join('')||'

لا توجد نشاطات حديثة.

'} function applyRoleViewForUser(u){if(!u)return;el('currentUserName').textContent=u.name;el('currentUserRole').textContent=roleLabel(u.role);document.querySelectorAll('.admin-only').forEach(x=>x.style.display=u.role==='admin'?'':'none');const viewer=u.role==='viewer';document.querySelectorAll('.print,.pdf,.archive-save,.new-letter,#draftSaveBtn').forEach(x=>x.style.display=viewer?'none':'');el('batchBar').style.display=viewer?'none':'flex';if(el('manualSyncBtn'))el('manualSyncBtn').style.display=window.KAE_IS_LOCAL?'':'none';if(el('syncCenterBtn'))el('syncCenterBtn').style.display=window.KAE_IS_LOCAL?'':'none'} function openUsers(){ el('usersModal').classList.add('open');el('usersStatus').textContent='جارٍ تحميل الحسابات المركزية...'; if(window.KAE_IS_LOCAL&¤tUser&¤tUser.role==='admin'){ const url=(localStorage.getItem('kaeOnlineSyncUrl')||'').trim(),tok=(localStorage.getItem('kaeDeviceToken')||'').trim(); if(!url||!tok){el('usersStatus').textContent='هذا الجهاز غير مربوط بالنظام المركزي. اربطه بحساب المدير أولًا.';return} if(!navigator.onLine){el('usersStatus').textContent='إدارة الحسابات المركزية تحتاج إنترنت. العمل والأرشيف المحلي يستمران Offline.';return} kaeJsonpApi(url,unifiedApiParams({api:'adminDashboard'}),20000).then(r=>{if(!r||r.ok!==true)throw new Error(r&&r.error?r.error:'تعذر تحميل الحسابات');usersState=r.users||[];renderUsers();el('usersStatus').textContent='الحسابات المعروضة مركزية. أي إضافة أو تعديل يُحفظ مباشرة في Online.'}).catch(e=>{el('usersStatus').textContent='تعذر تحميل الحسابات المركزية: '+(e.message||e)});return; } google.script.run.withSuccessHandler(items=>{usersState=items;renderUsers();el('usersStatus').textContent=''}).withFailureHandler(authFailure).listUsers(sessionToken) } function renderUsers(){el('usersList').innerHTML=usersState.map((u,i)=>`
آخر دخول: ${escapeHtml(u.lastLogin||'لم يدخل بعد')}
${u.id?``:''}
`).join('')} function addUserEditor(){usersState.push({id:'',name:'',username:'',role:'employee',active:true});renderUsers()} function userEditorData(index){const box=el('usersList').children[index],base=usersState[index];return{id:base.id,name:box.querySelector('.usr-name').value.trim(),username:box.querySelector('.usr-username').value.trim(),role:box.querySelector('.usr-role').value,password:box.querySelector('.usr-password').value,active:base.active!==false}} async function saveUserEditor(index){ const d=userEditorData(index); if(window.KAE_IS_LOCAL&¤tUser&¤tUser.role==='admin'){ if(!navigator.onLine){el('usersStatus').textContent='لا يمكن إنشاء أو تعديل حساب مركزي بدون إنترنت. أعد المحاولة عند توفر الاتصال.';return} if(!d.name||d.username.length<3){el('usersStatus').textContent='أدخل اسم الموظف واسم مستخدم من 3 أحرف على الأقل.';return} if(!d.id&&d.password.length<8){el('usersStatus').textContent='كلمة مرور الموظف الجديد لا تقل عن 8 أحرف.';return} el('usersStatus').textContent='جارٍ الحفظ في النظام المركزي...'; try{ let salt='',passwordHash=''; if(d.password){salt='S-'+Date.now()+'-'+Math.random().toString(36).slice(2);passwordHash=await window.KAE_LOCAL_API.hashPassword(salt+d.password)} const url=(localStorage.getItem('kaeOnlineSyncUrl')||'').trim(); const r=await kaeJsonpApi(url,unifiedApiParams({api:'adminSaveUser',userId:d.id||'',name:d.name,username:d.username,role:d.role,active:d.active!==false?'1':'0',salt:salt,passwordHash:passwordHash}),20000); if(!r||r.ok!==true)throw new Error(r&&r.error?r.error:'تعذر حفظ الحساب'); el('usersStatus').textContent='✅ تم حفظ الحساب مركزيًا. سيظهر الآن في الإدارة المركزية ويمكن إنشاء رمز ربط له.'; await openUsers(); if(el('unifiedAdminModal')&&el('unifiedAdminModal').classList.contains('open'))unifiedLoadDashboard(); }catch(e){el('usersStatus').textContent='تعذر حفظ الحساب المركزي: '+(e.message||e)} return; } google.script.run.withSuccessHandler(()=>openUsers()).withFailureHandler(authFailure).saveUser(d,sessionToken) } async function toggleUserEditor(index){ const u=usersState[index]; if(window.KAE_IS_LOCAL&¤tUser&¤tUser.role==='admin'){ if(!navigator.onLine){el('usersStatus').textContent='تغيير حالة الحساب المركزي يحتاج إنترنت.';return} try{const url=(localStorage.getItem('kaeOnlineSyncUrl')||'').trim();const r=await kaeJsonpApi(url,unifiedApiParams({api:'adminToggleUser',userId:u.id,active:u.active===false?'1':'0'}),20000);if(!r||r.ok!==true)throw new Error(r&&r.error?r.error:'تعذر تغيير الحالة');openUsers();}catch(e){el('usersStatus').textContent=e.message||e}return; } google.script.run.withSuccessHandler(()=>openUsers()).withFailureHandler(authFailure).toggleUser(u.id,u.active===false,sessionToken) } function openReports(){el('reportsModal').classList.add('open');el('reportType').innerHTML=''+((systemSettings.bookTypes||[]).filter(x=>x.enabled!==false).map(x=>``).join(''));if(el('reportDepartment').options.length===1)[...el('department').options].filter(x=>x.value).forEach(x=>el('reportDepartment').insertAdjacentHTML('beforeend',``))} function reportFilters(){return{from:val('reportFrom'),to:val('reportTo'),letterType:val('reportType'),department:val('reportDepartment'),status:val('reportStatus')}} function loadReport(){el('reportSummary').textContent='جارٍ إعداد التقرير...';google.script.run.withSuccessHandler(rows=>{reportRows=rows||[];el('reportSummary').textContent='عدد الكتب: '+arabicDigits(reportRows.length);el('reportBody').innerHTML=reportRows.length?reportRows.map(x=>`${escapeHtml(x.savedAt)}${escapeHtml(x.letterTypeName)}${escapeHtml(x.studentName)}${escapeHtml(x.department)}${escapeHtml(x.bookStatus)}${escapeHtml(x.createdBy||'—')}`).join(''):'لا توجد نتائج.'}).withFailureHandler(authFailure).getReport(reportFilters(),sessionToken)} function exportReportExcel(){if(!reportRows.length){alert('أنشئ التقرير أولًا.');return}const q=v=>'"'+String(v||'').replace(/"/g,'""')+'"',lines=[['التاريخ','نوع الكتاب','اسم الطالب','القسم','الحالة','الموظف'],...reportRows.map(x=>[x.savedAt,x.letterTypeName,x.studentName,x.department,x.bookStatus,x.createdBy])];downloadBlob('\ufeff'+lines.map(r=>r.map(q).join(',')).join('\r\n'),'تقرير_الكتب.csv','text/csv;charset=utf-8')} function printReport(){if(!reportRows.length){alert('أنشئ التقرير أولًا.');return}const win=window.open('','_blank');if(!win){alert('اسمح بالنوافذ المنبثقة لطباعة التقرير.');return}const rows=reportRows.map(x=>`${escapeHtml(x.savedAt)}${escapeHtml(x.letterTypeName)}${escapeHtml(x.studentName)}${escapeHtml(x.department)}${escapeHtml(x.bookStatus)}`).join('');win.document.write(`تقرير الكتب

تقرير الكتب الرسمية

عدد الكتب: ${arabicDigits(reportRows.length)}

${rows}
التاريخالنوعالطالبالقسمالحالة