سامانه صدور فاکتور و حسابداری
feat/d4a-request-work-queue
audit-remediation-wave3-4-20261002
audit-remediation-wave3-verify-20261002
audit-remediation-wave4-20261002
audit-remediation-wave4b-20261002
audit-remediation-wave5a-identity-20261002
audit-remediation-wave5b-offboarding-20261002
audit-remediation-wave5c-authorization-20261002
audit-security-intent-review-20261002
audit/finora-financial-core-20261115
audit/finora-master-prompt-phase0-20261016
audit/finora-stage3-legacy-source-readonly-20261023
audit/full-controls-20261030
audit/owner-live-state-reconcile-20261012
audit/owner-review-20261007
audit/phase1-live-permissions-readonly-20261013
audit/reconcile-live-state-20261006
audit/reconcile-state-20261002
audit/wp0-hardening-baseline-20261102
branding-login-favicon-20261002
c8-workflow-task1
c8-workflow-task2
c8-workflow-task3
chore/wave0-pages-gate-closeout
claude-code-plugins-setup
design/finora-c01-authoritative-source-draft-20261124
docs-wave4b-verified-20261002
docs/active-company-invoice-release-evidence-20261014
docs/agent-operating-model-20261114
docs/chart-taxpayer-release-evidence-20261004
docs/cloud-only-agent-orchestration-20261115
docs/confirm-finora-product-charter-20261115
docs/continuation-20261030
docs/d4a-verified
docs/external-work-review-20261121
docs/finora-audit-continuity-20261014
docs/finora-backup-merge-evidence-20261014
docs/finora-ci-reconciliation-20261122
docs/finora-codex-master-prompt
docs/finora-eight-phase-plan-20261011
docs/finora-f002-live-buyer-filter-verified-20261015
docs/finora-license-race-release-evidence-20261014
docs/finora-license-rollout-acceptance-20261015
docs/finora-phase0-repeat-and-pages-nav-verified-20261015
docs/finora-phase0-repeat-evidence-20261015
docs/finora-selectors-release-and-fixture-qa-20261015
docs/finora-stagea-pr240-ci-triage-20261123
docs/finora-test-license-live-pass-20261015
docs/finora-v2-m01-coverage-20261124
docs/handoff-charter-v2-20261124
docs/invoice-product-search-release-20261011
docs/invoice-workspace-release-20261007
docs/phase-status-20261031
docs/phase0-acceptance-release-evidence-20261012
docs/phase0-admin-provision-release-evidence-20261012
docs/phase0-core-bundle-owner-login-open-20261013
docs/phase0-duplicate-js-release-20261016
docs/phase0-f001-auth-rest-shared-timeout-20261013
docs/phase0-f001-owner-login-observed-20261013
docs/phase0-f001-second-device-fail-40s-20261013
docs/phase0-f003-release-verification-20261011
docs/phase0-f004-print-release-evidence-20261012
docs/phase0-f004-watermark-release-evidence-20261012
docs/phase0-f005-large-selector-release-20261012
docs/phase0-f005-release-evidence-20261012
docs/phase0-f006-dark-release-evidence-20261012
docs/phase0-f008-final-pr-closure-evidence-20261012
docs/phase0-f008-reconcile-stale-prs-20261012
docs/phase0-f107-production-evidence-20261012
docs/phase0-kavenegar-otp-preflight-release-20261012
docs/phase0-login-release-evidence-20261012
docs/phase0-login-rest-bootstrap-stage-release-20261012
docs/phase0-owner-app-assets-bundle-release-20261013
docs/phase0-owner-login-csp-release-20261012
docs/phase0-reconcile-postmerge-evidence-20261012
docs/phase0-site-probe-release-evidence-20261012
docs/phase0-startup-release-evidence-20261012
docs/phase3-treasury-release-evidence-20261014
docs/pilot-posted-correction-release-evidence-20261014
docs/pilot-purchase-correction-release-evidence-20261014
docs/print-persian-release-verification-20261011
docs/qa-ci-triage-218-20261122
docs/real-account-qa-20261030
docs/release-state-20261007
docs/seamless-amendment-release-20261014
docs/seamless-document-correction-release-20261014
docs/settings-login-release-20261025
docs/stripe-qa-deployment-evidence-20261011
docs/ux-f2-release-evidence-20261011
docs/ux-f2-release-verification-20261011
docs/wave0-closeout
docs/wave2-closeout
exec-phase1-architecture
exec-phase1-implementation
exec-phase1-qa
exec-phase1-security-release
exec-phase1-ux
feat/accounting-document-draft-approval-20261011
feat/accounting-document-release-candidate-20261011
feat/active-company-strict-isolation-20261014
feat/admin-provisioning-reconciled-20261011
feat/admin-secure-user-provisioning-20261011
feat/admin-user-provisioning-merged-20261011
feat/d4a-request-work-queue
feat/document-lifecycle-atf-20261118
feat/document-lifecycle-temp-permanent-atef
feat/draft-first-attachment-lifecycle-216
feat/finora-offline-encrypted-backup-20261014
feat/finora-phase-a-navigation-20261023
feat/finora-stripe-sandbox-edge-gate
feat/immutable-attachment-temporary-vouchers
feat/iran-accounting-design-audit
feat/journal-document-lifecycle-20261118
feat/journal-rpc-repository-adapter-20261117
feat/office-c7-fulltext-ocr-provenance
feat/password-recovery-admin-reset-20261025
feat/pilot-expense-income-inplace-amendment-20261014
feat/pilot-journal-invoice-correction-20261014
feat/pilot-purchase-correction-20261014
feat/pilot-treasury-unallocated-correction-20261014
feat/retain-document-editor-after-save-20261014
feat/seamless-financial-document-correction-20261014
feat/slice-b-tenant-rbac
feat/stripe-sandbox-invoice-probe
feature/accounting-core-p0
feature/accounting-product-guidance
feature/admin-identity-phone-auth
feature/commercial-rnd
feature/finora-phase1a-supabase-cli-20261016
feature/finora-stage2-manual-canary-20261017
feature/finora-stage3-commercial-payload-20261023
feature/finora-stage3-enforce-invoice-rpc-20261023
feature/finora-stage3-enforce-purchase-red-20261023
feature/invoice-workspace-cleanup
feature/phase0-kavenegar-otp-preflight-20261012
feature/ux-commerce-settings-r2
fix-shell-scroll-live-cache-20261002
fix-shell-scrollbar-explicit-ownership-20261002
fix-shell-scrollbar-ownership-20261002
fix-shell-scrollbar-right-edge-20261002
fix/about-bug-report-20261114
fix/active-company-invoice-scope-20261014
fix/active-company-isolation-reconcile-20261014
fix/admin-central-password-reset-20261028
fix/auth-network-diagnostics
fix/chart-taxpayer-reference-20261003
fix/combobox-enter-reliability
fix/combobox-live-search
fix/combobox-production-cache
fix/combobox-release-asset-v2
fix/company-edit-action-20261028
fix/company-edit-pilot-delete-20261014
fix/company-form-action-state-20261014
fix/company-form-action-state-rebased-20261014
fix/contact-operational-balance-20261111
fix/dark-theme-contrast
fix/financial-lifecycle-recovery-20261124
fix/finora-accounting-test-organization-readiness-20261015
fix/finora-b01-safe-org-switch-20261124
fix/finora-b02-sync-recovery-20261124
fix/finora-b03-conflict-review-20261124
fix/finora-org-license-bootstrap-race-20261014
fix/finora-stage3-posted-source-immutable-20261023
fix/finora-v2-b03-r2-qa-20261124
fix/finora-v2-b03-r3-readonly-20261124
fix/g01-asof-financial-position-20261128
fix/invoice-product-search-rehydrate-20261011
fix/invoice-search-cache-bust
fix/issue229-linked-draft-status-20261122
fix/login-assets-retry-20261014
fix/login-inert-startup-20261110
fix/login-member-access-20261101
fix/login-resilience-20261017
fix/login-short-viewport-20261028
fix/login-startup-readiness-20261024
fix/navigation-utilities-placement-20261105
fix/office-c7-source-ref-binding
fix/office-c7-source-ref-binding-v2
fix/owner-login-network-20261026
fix/password-recovery-invalid-cancel-20261026
fix/payment-amount-format-20261111
fix/phase0-admin-provision-seat-bootstrap-20261012
fix/phase0-auth-bundled-assets-for-unstable-isp-20261013
fix/phase0-auth-handler-binding-stalled-session-20261012
fix/phase0-login-context-stage-visibility-20261012
fix/phase0-login-single-local-bundle-20261013
fix/phase0-login-site-probe-clarity-20261012
fix/phase0-login-ui-ready-20261012
fix/phase0-modal-dashboard-drill-20261011
fix/phase0-pages-blocking-core-bundles-20261013
fix/phase0-print-no-draft-watermark-20261012
fix/phase0-startup-parallel-asset-load-20261012
fix/phase3-behavioral-verification
fix/preserve-pending-edits-20261121
fix/print-persian-digit-consistency-20261011
fix/recovery-login-startup-20261027
fix/report-opening-balance-release-20261130
fix/settings-checkbox-persistence-20261024
fix/taxpayer-arithmetic-20261004
fix/ux-keyboard-search-f2-20261011
fix/wave2-request-input-integrity
hardening/c01-source-draft-20261129
hardening/global-draft-conversion-20261113
hardening/wp1-ledger-integrity-20261102
integration/finora-execution-20261124
integration/issue229-ui-qa-20261122
integration/wp1-ledger-core-20261115
integration/wp2-manual-journal-rpc-20261116
main
ops-heartbeat-v2-20261002
ops-progress-heartbeat-rule-20261002
ops/wave4-production-20261003
plan/financial-core-phase1-approval-20261016
qa/attachment-allocator-two-session-20261122
qa/draft-first-save-red-evidence-20261122
qa/finora-autopost-retry-identity-red-20261122
qa/finora-identity-rpc-security-tripwire-20261122
qa/finora-issue223-manual-kardex-browser-red-20261123
qa/finora-issue223-stock-real-jwt-20261123
qa/finora-issue238-inventory-count-browser-red-20261123
qa/finora-issue238-save-browser-red-20261122
qa/finora-login-cors-header-preflight-20261025
qa/finora-phase0-saved-session-repeat-20261015
qa/finora-phase5-posted-insert-jwt-red-20261123
qa/finora-stage3-ui-jwt-autopost-20261023
qa/finora-v2-g01-report-reconciliation-20261125
qa/free-supabase-local-wp2-20261116
qa/issue229-approval-boundary-jwt-20261122
qa/issue229-sale-save-linked-draft-red-20261122
qa/phase0-acceptance-start-20261012
qa/phase0-f005-account-project-contract-stress-20261012
qa/phase0-f005-selector-stress-20261012
qa/phase0-f006-dark-contrast-20261012
qa/post-wave4-verification-20261003
qa/posted-source-immutable-jwt-20261122
qa/pr219-wp1-disposable-dburl-proof-20261123
qa/purchase-source-jwt-20261122
qa/real-settings-acceptance-20261025
qa/recovery-mail-acceptance-20261026
qa/source-autopost-jwt-atomicity-20261122
qa/wave0-negative-gate-proof
qa/wp2-auth-tenant-e2e-20261117
qa/wp2-authorized-journal-write-20261122
qa/wp2-financial-paths-reconciliation-20261122
qa/wp3-financial-tenant-isolation-20261117
remediation/wave0-liveqa-wave1
remediation/wave2-request-integrity
staging/finora-stage22-free-20261022
state-scroll-verified-20261002
state-wave4b-production-20261002
state-wave5a-production-20261002
test/finora-accounting-boot-readiness-20261015
test/finora-f0-02-production-selectors-20261015
test/finora-pages-commerce-event-wiring-20261015
test/finora-pages-invoice-selectors-readonly-20261015
test/finora-stage3-jwt-source-post-20261023
test/phase0-invoice-fixture-bootstrap-20261016
test/phase0-invoice-persistence-20261011
test/phase0-pages-delayed-dispatcher-20261016
ux-scroll-ownership-20261002
work/finora-stage3-enforce-purchase-green-20261023
work/finora-stage3-enforce-sale-green-20261023
work/finora-stage3-payload-green-20261023
| 1 | /* Office Slice C1/C2 mature correspondence evidence + actionable referrals. */ |
| 2 | (function(){ |
| 3 | function oe(v){return typeof esc==='function'?esc(v):String(v??'')} |
| 4 | function faDate(v){if(!v)return '—';try{return new Date(v).toLocaleString('fa-IR')}catch(_){return String(v)}} |
| 5 | window.officeReadEvidenceFor=function(correspondenceId){return (datastore.correspondenceAudit||[]).filter(x=>x.event==='read'&&x.correspondenceId===correspondenceId)}; |
| 6 | window.officeMarkReadEvidence=async function(correspondenceId){ |
| 7 | if(!currentUser?.organizationId||!correspondenceId)return false; |
| 8 | const {error}=await sb.rpc('office_mark_correspondence_read',{p_organization_id:currentUser.organizationId,p_correspondence_id:correspondenceId}); |
| 9 | if(error){console.error('office read evidence failed',error);return false} |
| 10 | try{await pullAll()}catch(e){console.error('office read evidence refresh failed',e)} |
| 11 | return true; |
| 12 | }; |
| 13 | const baseOfficeOpenRecord=window.officeOpenRecord; |
| 14 | window.officeOpenRecord=async function(id){ |
| 15 | const x=(datastore.correspondence||[]).find(r=>r.id===id);if(!x)return; |
| 16 | if(x.status!=='draft'){ |
| 17 | const ok=await window.officeMarkReadEvidence(id); |
| 18 | if(!ok)return alert('ثبت مشاهده نامه در سرور انجام نشد؛ برای حفظ صحت سابقه، نمایش نامه متوقف شد.'); |
| 19 | } |
| 20 | return baseOfficeOpenRecord(id); |
| 21 | }; |
| 22 | |
| 23 | window.FINORA_REFERRAL_QUEUE=[]; |
| 24 | window.officeReferralWorkQueue=function(){return Array.isArray(window.FINORA_REFERRAL_QUEUE)?window.FINORA_REFERRAL_QUEUE:[]}; |
| 25 | window.officeLoadReferralQueue=async function(render=true){ |
| 26 | if(!currentUser?.organizationId)return []; |
| 27 | const {data,error}=await sb.rpc('office_referral_work_queue',{p_organization_id:currentUser.organizationId}); |
| 28 | if(error){console.error('office referral queue failed',error);if(render)alert('دریافت کارتابل ارجاعات ناموفق بود: '+error.message);return []} |
| 29 | window.FINORA_REFERRAL_QUEUE=Array.isArray(data)?data:[]; |
| 30 | if(render)renderReferralWork(); |
| 31 | return window.FINORA_REFERRAL_QUEUE; |
| 32 | }; |
| 33 | window.officeActOnReferral=async function(referralId,action){ |
| 34 | if(!currentUser?.organizationId||!referralId)return false; |
| 35 | const label=action==='acknowledged'?'تأیید دریافت':'تکمیل ارجاع'; |
| 36 | const note=prompt('یادداشت '+label+' (اختیاری):')||''; |
| 37 | const {error}=await sb.rpc('office_act_on_referral',{ |
| 38 | p_organization_id:currentUser.organizationId,p_referral_id:referralId,p_action:action,p_note:note |
| 39 | }); |
| 40 | if(error){console.error('office referral action failed',error);alert(label+' انجام نشد: '+error.message);return false} |
| 41 | await window.officeLoadReferralQueue(false); |
| 42 | renderReferralWork(); |
| 43 | alert(label+' با سابقه غیرقابلتغییر ثبت شد.'); |
| 44 | return true; |
| 45 | }; |
| 46 | function renderReferralWork(){ |
| 47 | const root=document.getElementById('view-office');if(!root)return; |
| 48 | const rows=window.officeReferralWorkQueue(); |
| 49 | const body=rows.length?rows.map(r=>{ |
| 50 | const mine=String(r.to_user_id||'')===String(currentUser?.id||''); |
| 51 | const status=r.state==='completed'?'تکمیلشده':r.state==='acknowledged'?'دریافتشده':'ارسالشده'; |
| 52 | const actions=mine&&r.state==='sent' |
| 53 | ?'<button class="btn btn-primary btn-inline" onclick="officeActOnReferral(\''+oe(r.referral_id)+'\',\'acknowledged\')">تأیید دریافت</button>' |
| 54 | :mine&&r.state==='acknowledged' |
| 55 | ?'<button class="btn btn-primary btn-inline" onclick="officeActOnReferral(\''+oe(r.referral_id)+'\',\'completed\')">تکمیل</button>' |
| 56 | :''; |
| 57 | return '<tr><td><strong>'+oe(r.register_number||'—')+'</strong></td><td>'+oe(r.subject||'—')+'</td><td>'+status+(r.overdue?' <strong>· معوق</strong>':'')+'</td><td>'+faDate(r.due_at)+'</td><td>'+oe(r.note||'—')+'</td><td><button class="btn btn-secondary btn-inline" onclick="officeOpenRecord(\''+oe(r.correspondence_id)+'\')">نامه</button> '+actions+'</td></tr>' |
| 58 | }).join(''):'<tr><td colspan="6" class="af-empty">ارجاع فعالی برای نمایش وجود ندارد.</td></tr>'; |
| 59 | root.innerHTML='<div class="af-head"><div><h1>ارجاعات و پیگیری</h1><p>کارتابل سرورمحور ارجاعات؛ وضعیت دریافت، تکمیل و مهلت پیگیری از سابقه غیرقابلتغییر محاسبه میشود.</p></div><div><button class="btn btn-secondary btn-inline" onclick="officeLoadReferralQueue(true)">بازخوانی</button></div></div><div class="card"><div class="table-responsive"><table><thead><tr><th>نامه</th><th>موضوع</th><th>وضعیت</th><th>مهلت</th><th>یادداشت</th><th>عملیات</th></tr></thead><tbody>'+body+'</tbody></table></div></div>'; |
| 60 | } |
| 61 | const c1OfficeRender=window.officeRender; |
| 62 | window.officeRender=function(task='inbox'){ |
| 63 | if(task==='work'){ |
| 64 | c1OfficeRender('inbox'); |
| 65 | renderReferralWork(); |
| 66 | window.officeLoadReferralQueue(true); |
| 67 | return; |
| 68 | } |
| 69 | return c1OfficeRender(task); |
| 70 | }; |
| 71 | |
| 72 | window.officeReferPrompt=async function(correspondenceId){ |
| 73 | if(typeof hasFinoraCapability==='function'&&!hasFinoraCapability('office_automation','refer'))return alert('برای ارجاع دسترسی سازمانی لازم را ندارید.'); |
| 74 | const {data:members,error}=await sb.from('organization_members').select('id,user_id,position_title,is_owner').eq('organization_id',currentUser.organizationId).eq('status','active'); |
| 75 | if(error)return alert(error.message); |
| 76 | const ids=(members||[]).map(x=>x.user_id),profiles=ids.length?(await sb.from('profiles').select('id,full_name,email').in('id',ids)).data||[]:[]; |
| 77 | const choices=(members||[]).filter(x=>x.user_id!==currentUser.id).map((m,i)=>({n:i+1,m,p:profiles.find(p=>p.id===m.user_id)})); |
| 78 | if(!choices.length)return alert('عضو دیگری برای ارجاع در این سازمان وجود ندارد.'); |
| 79 | const text=choices.map(x=>x.n+') '+(x.p?.full_name||x.p?.email||x.m.position_title||'کاربر')).join('\n'); |
| 80 | const pick=Number(prompt('ارجاع به کدام عضو؟\n'+text)),chosen=choices.find(x=>x.n===pick);if(!chosen)return; |
| 81 | const note=prompt('یادداشت ارجاع (اختیاری):')||''; |
| 82 | const dueRaw=String(prompt('مهلت ارجاع (اختیاری، نمونه 2026-10-01T12:00):')||'').trim(); |
| 83 | let dueAt=null; |
| 84 | if(dueRaw){const d=new Date(dueRaw);if(Number.isNaN(d.getTime()))return alert('فرمت مهلت معتبر نیست.');dueAt=d.toISOString()} |
| 85 | const {error:rpcError}=await sb.rpc('office_refer_correspondence_v2',{ |
| 86 | p_organization_id:currentUser.organizationId,p_correspondence_id:correspondenceId, |
| 87 | p_to_member_id:chosen.m.id,p_note:note,p_due_at:dueAt |
| 88 | }); |
| 89 | if(rpcError){ |
| 90 | console.error('office referral failed',rpcError); |
| 91 | if(/target member cannot read correspondence/i.test(rpcError.message||''))return alert('این کاربر طبق سطح دسترسی/دامنه/محرمانگی مجاز به خواندن این نامه نیست.'); |
| 92 | return alert('ارجاع انجام نشد: '+rpcError.message); |
| 93 | } |
| 94 | await pullAll();alert('ارجاع ثبت شد و در کارتابل پیگیری قابل مشاهده است.');officeRender('work'); |
| 95 | }; |
| 96 | |
| 97 | window.FINORA_ARCHIVE_INDEX=[]; |
| 98 | window.officeArchiveIndex=function(){return Array.isArray(window.FINORA_ARCHIVE_INDEX)?window.FINORA_ARCHIVE_INDEX:[]}; |
| 99 | function canOffice(c){return typeof hasFinoraCapability==='function'&&hasFinoraCapability('office_automation',c)} |
| 100 | function renderArchiveIndex(){ |
| 101 | const root=document.getElementById('view-office');if(!root)return; |
| 102 | const rows=window.officeArchiveIndex(); |
| 103 | const body=rows.length?rows.map(r=>{ |
| 104 | const tags=Array.isArray(r.tags)?r.tags.join('، '):''; |
| 105 | const sourceMap={metadata:'فراداده',body:'متن نامه',ocr:'متن OCR'}; |
| 106 | const source=sourceMap[r.match_source]||'فراداده'; |
| 107 | const provenance=r.ocr_evidence_id?('OCR: '+oe(r.ocr_provider||'نامشخص')+' · '+oe(r.ocr_language||'—')+(r.ocr_corrected?' · اصلاح انسانی':' · خروجی خام')):'—'; |
| 108 | const classify=(canOffice('archive')||canOffice('configure'))?'<button class="btn btn-secondary btn-inline" onclick="officeClassifyPrompt(\''+oe(r.correspondence_id)+'\')">طبقهبندی</button> ':''; |
| 109 | const ocr=(canOffice('archive')||canOffice('configure'))?'<button class="btn btn-secondary btn-inline" onclick="officeRecordOcrEvidence(\''+oe(r.correspondence_id)+'\')">ثبت متن OCR</button> '+(r.ocr_evidence_id?'<button class="btn btn-secondary btn-inline" onclick="officeCorrectOcrEvidence(\''+oe(r.ocr_evidence_id)+'\')">اصلاح OCR</button> ':''):''; |
| 110 | const link=(canOffice('edit')||canOffice('refer'))?'<button class="btn btn-secondary btn-inline" onclick="officeLinkPrompt(\''+oe(r.correspondence_id)+'\')">ارتباط</button>':''; |
| 111 | return '<tr><td><strong>'+oe(r.register_number||'—')+'</strong></td><td>'+oe(r.subject||'—')+'</td><td>'+oe(r.folder||'—')+'</td><td>'+oe(r.classification_code||'—')+'</td><td>'+oe(tags||'—')+'</td><td>'+source+'<div class="text-muted">'+provenance+'</div></td><td>'+Number(r.related_count||0).toLocaleString('fa-IR')+'</td><td><button class="btn btn-secondary btn-inline" onclick="officeOpenRecord(\''+oe(r.correspondence_id)+'\')">مشاهده</button> '+classify+ocr+link+'</td></tr>' |
| 112 | }).join(''):'<tr><td colspan="8" class="af-empty">مکاتبهای مطابق فیلتر آرشیو یافت نشد.</td></tr>'; |
| 113 | root.innerHTML='<div class="af-head"><div><h1>جستوجو و آرشیو مکاتبات</h1><p>جستوجوی Full-text سرورمحور روی فراداده، متن نامه و متن OCR ثبتشده. C7 خودش OCR انجام نمیدهد و دقت OCR فارسی هنوز با اسکن واقعی تأیید نشده است.</p></div></div><div class="card"><div class="form-row"><div class="form-group" style="grid-column:span 2"><label>جستوجو</label><input id="office-archive-q" class="form-control" placeholder="شماره، موضوع، متن نامه، متن OCR"></div><div class="form-group"><label>پوشه</label><input id="office-archive-folder" class="form-control"></div><div class="form-group"><label>کد طبقهبندی</label><input id="office-archive-code" class="form-control"></div></div><button class="btn btn-primary btn-inline" onclick="officeLoadArchiveIndex(true)">جستوجو</button></div><div class="card"><div class="table-responsive"><table><thead><tr><th>ثبت</th><th>موضوع</th><th>پوشه</th><th>کد</th><th>برچسبها</th><th>منبع تطبیق</th><th>ارتباطها</th><th>عملیات</th></tr></thead><tbody>'+body+'</tbody></table></div></div>'; |
| 114 | } |
| 115 | window.officeLoadArchiveIndex=async function(render=true){ |
| 116 | if(!currentUser?.organizationId)return []; |
| 117 | const q=document.getElementById('office-archive-q')?.value||null; |
| 118 | const folder=document.getElementById('office-archive-folder')?.value||null; |
| 119 | const code=document.getElementById('office-archive-code')?.value||null; |
| 120 | const {data,error}=await sb.rpc('office_archive_search_v2',{p_organization_id:currentUser.organizationId,p_query:q,p_folder:folder,p_classification_code:code,p_related_to:null,p_limit:100}); |
| 121 | if(error){console.error('office archive search failed',error);if(render)alert('جستوجوی آرشیو ناموفق بود: '+error.message);return []} |
| 122 | window.FINORA_ARCHIVE_INDEX=Array.isArray(data)?data:[]; |
| 123 | if(render)renderArchiveIndex(); |
| 124 | return window.FINORA_ARCHIVE_INDEX; |
| 125 | }; |
| 126 | window.officeRecordOcrEvidence=async function(correspondenceId){ |
| 127 | if(!(canOffice('archive')||canOffice('configure')))return alert('برای ثبت Evidence OCR دسترسی لازم را ندارید.'); |
| 128 | const attachments=(datastore.correspondenceAttachments||[]).filter(x=>x.correspondenceId===correspondenceId); |
| 129 | if(!attachments.length)return alert('برای ثبت OCR ابتدا باید یک پیوست/اسکن واقعی به همین نامه متصل باشد.'); |
| 130 | const choices=attachments.map((x,i)=>({n:i+1,x})); |
| 131 | const pick=Number(prompt('فایل منبع OCR را انتخاب کنید:\n'+choices.map(z=>z.n+') '+(z.x.fileName||z.x.id)).join('\n'))); |
| 132 | const chosen=choices.find(z=>z.n===pick);if(!chosen)return; |
| 133 | const sourceRef=chosen.x.id; |
| 134 | const provider=String(prompt('نام موتور/ارائهدهنده OCR:')||'').trim();if(!provider)return; |
| 135 | const language=String(prompt('زبان خروجی (مثلاً fa):')||'fa').trim(); |
| 136 | const confidenceRaw=String(prompt('Confidence بین 0 و 1 (اختیاری):')||'').trim(); |
| 137 | const confidence=confidenceRaw===''?null:Number(confidenceRaw);if(confidence!==null&&(!Number.isFinite(confidence)||confidence<0||confidence>1))return alert('Confidence باید بین صفر و یک باشد.'); |
| 138 | const text=String(prompt('متن خروجی OCR را وارد کنید:')||'');if(!text.trim())return; |
| 139 | const {error}=await sb.rpc('office_record_ocr_evidence',{p_organization_id:currentUser.organizationId,p_correspondence_id:correspondenceId,p_source_ref:sourceRef,p_provider:provider,p_language:language,p_confidence:confidence,p_text:text}); |
| 140 | if(error){console.error('office OCR evidence failed',error);return alert('ثبت Evidence OCR انجام نشد: '+error.message)} |
| 141 | await window.officeLoadArchiveIndex(true);alert('خروجی OCR به پیوست واقعی همین نامه متصل و با provenance ثبت شد. این قابلیت خودِ OCR را اجرا نمیکند.'); |
| 142 | }; |
| 143 | window.officeCorrectOcrEvidence=async function(ocrEvidenceId){ |
| 144 | if(!(canOffice('archive')||canOffice('configure')))return alert('برای اصلاح OCR دسترسی لازم را ندارید.'); |
| 145 | const corrected=String(prompt('متن اصلاحشده OCR:')||'');if(!corrected.trim())return; |
| 146 | const note=String(prompt('یادداشت اصلاح (اختیاری):')||''); |
| 147 | const {error}=await sb.rpc('office_correct_ocr_evidence',{p_organization_id:currentUser.organizationId,p_ocr_evidence_id:ocrEvidenceId,p_corrected_text:corrected,p_note:note}); |
| 148 | if(error){console.error('office OCR correction failed',error);return alert('اصلاح OCR ثبت نشد: '+error.message)} |
| 149 | await window.officeLoadArchiveIndex(true);alert('اصلاح انسانی بهصورت Evidence جدید ثبت شد؛ خروجی خام OCR حفظ شده است.'); |
| 150 | }; |
| 151 | window.officeClassifyPrompt=async function(correspondenceId){ |
| 152 | if(!(canOffice('archive')||canOffice('configure')))return alert('برای طبقهبندی آرشیو دسترسی لازم را ندارید.'); |
| 153 | const folder=String(prompt('پوشه آرشیو:')||'').trim(); |
| 154 | const code=String(prompt('کد طبقهبندی:')||'').trim(); |
| 155 | const tags=String(prompt('برچسبها با ویرگول جدا شوند:')||'').split(',').map(x=>x.trim()).filter(Boolean); |
| 156 | const {error}=await sb.rpc('office_classify_correspondence',{p_organization_id:currentUser.organizationId,p_correspondence_id:correspondenceId,p_folder:folder,p_classification_code:code,p_tags:tags}); |
| 157 | if(error){console.error('office classification failed',error);return alert('طبقهبندی انجام نشد: '+error.message)} |
| 158 | await window.officeLoadArchiveIndex(true);alert('طبقهبندی آرشیو با سابقه غیرقابلتغییر ثبت شد.'); |
| 159 | }; |
| 160 | window.officeLinkPrompt=async function(sourceId){ |
| 161 | if(!(canOffice('edit')||canOffice('refer')))return alert('برای ایجاد ارتباط نامه دسترسی لازم را ندارید.'); |
| 162 | const choices=(datastore.correspondence||[]).filter(x=>x.id!==sourceId).map((x,i)=>({n:i+1,x})); |
| 163 | if(!choices.length)return alert('نامه دیگری برای ایجاد ارتباط در دسترس نیست.'); |
| 164 | const text=choices.slice(0,50).map(z=>z.n+') '+(z.x.registerNumber||'—')+' · '+(z.x.subject||'بدون موضوع')).join('\n'); |
| 165 | const pick=Number(prompt('نامه مقصد را انتخاب کنید:\n'+text)),chosen=choices.find(z=>z.n===pick);if(!chosen)return; |
| 166 | const relPick=String(prompt('نوع ارتباط: 1 = پاسخ به، 2 = مرتبط')||'').trim(); |
| 167 | const relation=relPick==='1'?'reply_to':relPick==='2'?'related':null;if(!relation)return; |
| 168 | const {error}=await sb.rpc('office_link_correspondence',{p_organization_id:currentUser.organizationId,p_source_id:sourceId,p_target_id:chosen.x.id,p_relation_type:relation}); |
| 169 | if(error){console.error('office relation failed',error);return alert('ایجاد ارتباط انجام نشد: '+error.message)} |
| 170 | await window.officeLoadArchiveIndex(true);alert('ارتباط نامه با سابقه غیرقابلتغییر ثبت شد.'); |
| 171 | }; |
| 172 | const c2OfficeRender=window.officeRender; |
| 173 | window.officeRender=function(task='inbox'){ |
| 174 | if(task==='archive'){ |
| 175 | c2OfficeRender('inbox'); |
| 176 | renderArchiveIndex(); |
| 177 | window.officeLoadArchiveIndex(true); |
| 178 | return; |
| 179 | } |
| 180 | return c2OfficeRender(task); |
| 181 | }; |
| 182 | |
| 183 | window.FINORA_TEMPLATE_CATALOG=[]; |
| 184 | window.officeTemplateCatalog=function(){return Array.isArray(window.FINORA_TEMPLATE_CATALOG)?window.FINORA_TEMPLATE_CATALOG:[]}; |
| 185 | window.officeLoadTemplateCatalog=async function(render=true){ |
| 186 | if(!currentUser?.organizationId)return []; |
| 187 | const includeInactive=window.FINORA_OFFICE_TASK==='templates'&&(canOffice('configure')); |
| 188 | const {data,error}=await sb.rpc('office_template_catalog',{p_organization_id:currentUser.organizationId,p_include_inactive:includeInactive}); |
| 189 | if(error){console.error('office template catalog failed',error);if(render)alert('دریافت قالبهای نامه ناموفق بود: '+error.message);return []} |
| 190 | window.FINORA_TEMPLATE_CATALOG=Array.isArray(data)?data:[]; |
| 191 | if(render){ |
| 192 | if(window.FINORA_OFFICE_TASK==='templates')renderTemplateManager(); |
| 193 | else if(window.FINORA_OFFICE_TASK==='new')renderTemplateSelector(); |
| 194 | } |
| 195 | return window.FINORA_TEMPLATE_CATALOG; |
| 196 | }; |
| 197 | function renderTemplateManager(){ |
| 198 | const root=document.getElementById('view-office');if(!root)return; |
| 199 | const rows=window.officeTemplateCatalog(); |
| 200 | const canConfigure=canOffice('configure'); |
| 201 | const form=canConfigure?'<div class="card"><h3>نسخه جدید قالب</h3><div class="form-row"><div class="form-group"><label>کلید ثابت قالب</label><input id="office-template-edit-key" class="form-control" maxlength="64" placeholder="OFFICIAL_REPLY"></div><div class="form-group" style="grid-column:span 3"><label>عنوان قالب</label><input id="office-template-edit-name" class="form-control" maxlength="160"></div></div><div class="form-group"><label>الگوی موضوع</label><input id="office-template-edit-subject" class="form-control" maxlength="500"></div><div class="form-group"><label>متن قالب</label><textarea id="office-template-edit-body" class="form-control" rows="10"></textarea></div><label><input id="office-template-edit-active" type="checkbox" checked> نسخه فعال باشد</label><div style="margin-top:10px"><button class="btn btn-primary" onclick="officeSaveTemplateVersion()">ثبت نسخه جدید</button></div><p class="af-hint">ویرایش قالب، نسخه قبلی را تغییر نمیدهد؛ همیشه یک نسخه جدید ساخته میشود.</p></div>':''; |
| 202 | const body=rows.length?rows.map(t=>'<tr><td><strong>'+oe(t.template_key)+'</strong></td><td>'+oe(t.name)+'</td><td>'+Number(t.version||0).toLocaleString('fa-IR')+'</td><td>'+(t.active?'فعال':'غیرفعال')+'</td><td>'+faDate(t.created_at)+'</td><td>'+(canConfigure?'<button class="btn btn-secondary btn-inline" onclick="officePrepareTemplateVersion(\''+oe(t.template_key)+'\')">نسخه جدید</button>':'')+'</td></tr>').join(''):'<tr><td colspan="6" class="af-empty">قالبی تعریف نشده است.</td></tr>'; |
| 203 | root.innerHTML='<div class="af-head"><div><h1>قالبهای نسخهدار نامه</h1><p>هر تغییر یک نسخه جدید میسازد؛ نامه ثبتشده مرجع نسخه استفادهشده را حفظ میکند.</p></div></div>'+form+'<div class="card"><div class="table-responsive"><table><thead><tr><th>کلید</th><th>عنوان</th><th>نسخه</th><th>وضعیت</th><th>ایجاد</th><th></th></tr></thead><tbody>'+body+'</tbody></table></div></div>'; |
| 204 | } |
| 205 | window.officePrepareTemplateVersion=function(key){ |
| 206 | const t=window.officeTemplateCatalog().find(x=>x.template_key===key);if(!t)return; |
| 207 | const keyEl=document.getElementById('office-template-edit-key'),nameEl=document.getElementById('office-template-edit-name'),subEl=document.getElementById('office-template-edit-subject'),bodyEl=document.getElementById('office-template-edit-body'),activeEl=document.getElementById('office-template-edit-active'); |
| 208 | if(keyEl){keyEl.value=t.template_key;keyEl.readOnly=true}if(nameEl)nameEl.value=t.name||'';if(subEl)subEl.value=t.subject_template||'';if(bodyEl)bodyEl.value=t.body_template||'';if(activeEl)activeEl.checked=!!t.active; |
| 209 | }; |
| 210 | window.officeSaveTemplateVersion=async function(){ |
| 211 | if(!canOffice('configure'))return alert('برای مدیریت قالبها دسترسی پیکربندی لازم است.'); |
| 212 | const key=String(document.getElementById('office-template-edit-key')?.value||'').trim().toUpperCase(); |
| 213 | const name=String(document.getElementById('office-template-edit-name')?.value||'').trim(); |
| 214 | const subject=String(document.getElementById('office-template-edit-subject')?.value||''); |
| 215 | const body=String(document.getElementById('office-template-edit-body')?.value||''); |
| 216 | const active=!!document.getElementById('office-template-edit-active')?.checked; |
| 217 | if(!key||!name)return alert('کلید و عنوان قالب الزامی است.'); |
| 218 | const {data,error}=await sb.rpc('office_create_template_version',{p_organization_id:currentUser.organizationId,p_template_key:key,p_name:name,p_subject_template:subject,p_body_template:body,p_active:active}); |
| 219 | if(error){console.error('office template version failed',error);return alert('ثبت نسخه قالب انجام نشد: '+error.message)} |
| 220 | await window.officeLoadTemplateCatalog(true);alert('نسخه '+Number(data||0).toLocaleString('fa-IR')+' قالب ثبت شد.'); |
| 221 | }; |
| 222 | function renderTemplateSelector(){ |
| 223 | if(window.FINORA_OFFICE_TASK!=='new')return; |
| 224 | const subject=document.getElementById('office-subject');if(!subject)return; |
| 225 | let host=document.getElementById('office-template-apply-card'); |
| 226 | if(!host){host=document.createElement('div');host.id='office-template-apply-card';host.className='card';const head=document.querySelector('#view-office .af-head');if(head?.nextSibling)head.parentNode.insertBefore(host,head.nextSibling);else document.getElementById('view-office')?.prepend(host)} |
| 227 | const options=window.officeTemplateCatalog().map(t=>'<option value="'+oe(t.template_key)+'::'+Number(t.version||0)+'">'+oe(t.name)+' · نسخه '+Number(t.version||0).toLocaleString('fa-IR')+'</option>').join(''); |
| 228 | host.innerHTML='<div class="form-row"><div class="form-group" style="grid-column:span 3"><label>قالب نامه</label><select id="office-template-selector" class="form-control"><option value="">— بدون قالب —</option>'+options+'</select></div><div class="form-group" style="align-self:end"><button class="btn btn-secondary" onclick="officeApplyTemplate(document.getElementById(\'office-template-selector\')?.value)">اعمال قالب</button></div></div><input id="office-template-key" type="hidden"><input id="office-template-version" type="hidden"><p id="office-template-provenance" class="af-hint">هنوز قالبی روی این پیشنویس اعمال نشده است.</p>'; |
| 229 | } |
| 230 | window.officeApplyTemplate=function(ref){ |
| 231 | if(window.FINORA_OFFICE_TASK!=='new')return false; |
| 232 | const [key,versionRaw]=String(ref||'').split('::'),version=Number(versionRaw); |
| 233 | const t=window.officeTemplateCatalog().find(x=>x.template_key===key&&Number(x.version)===version); |
| 234 | if(!t)return alert('نسخه قالب انتخابشده در دسترس نیست.'); |
| 235 | const subject=document.getElementById('office-subject'),body=document.getElementById('office-body'),keyEl=document.getElementById('office-template-key'),verEl=document.getElementById('office-template-version'),prov=document.getElementById('office-template-provenance'); |
| 236 | if(!subject||!body||!keyEl||!verEl)return false; |
| 237 | subject.value=t.subject_template||'';body.value=t.body_template||'';keyEl.value=t.template_key;verEl.value=String(t.version); |
| 238 | if(prov)prov.textContent='قالب اعمالشده: '+t.name+' · نسخه '+Number(t.version).toLocaleString('fa-IR')+' — پس از اعمال، متن قابل ویرایش است اما مرجع نسخه حفظ میشود.'; |
| 239 | return true; |
| 240 | }; |
| 241 | const c3OfficeRenderForC4=window.officeRender; |
| 242 | window.officeRender=function(task='inbox'){ |
| 243 | if(task==='templates'){ |
| 244 | c3OfficeRenderForC4('inbox');window.FINORA_OFFICE_TASK='templates';renderTemplateManager();window.officeLoadTemplateCatalog(true);return; |
| 245 | } |
| 246 | const out=c3OfficeRenderForC4(task); |
| 247 | if(task==='new'){window.FINORA_OFFICE_TASK='new';window.officeLoadTemplateCatalog(false).then(()=>renderTemplateSelector())} |
| 248 | return out; |
| 249 | }; |
| 250 | |
| 251 | window.FINORA_APPROVAL_QUEUE=[]; |
| 252 | window.officeApprovalWorkQueue=function(){return Array.isArray(window.FINORA_APPROVAL_QUEUE)?window.FINORA_APPROVAL_QUEUE:[]}; |
| 253 | window.officeLoadApprovalQueue=async function(render=true){ |
| 254 | if(!currentUser?.organizationId)return []; |
| 255 | const {data,error}=await sb.rpc('office_approval_work_queue',{p_organization_id:currentUser.organizationId}); |
| 256 | if(error){console.error('office approval queue failed',error);if(render)alert('دریافت کارتابل تأییدات ناموفق بود: '+error.message);return []} |
| 257 | window.FINORA_APPROVAL_QUEUE=Array.isArray(data)?data:[]; |
| 258 | if(render)renderApprovalWork(); |
| 259 | return window.FINORA_APPROVAL_QUEUE; |
| 260 | }; |
| 261 | window.officeRequestApproval=async function(correspondenceId){ |
| 262 | const x=(datastore.correspondence||[]).find(r=>r.id===correspondenceId); |
| 263 | if(!x||x.status==='draft')return alert('درخواست تأیید فقط برای نامه ثبتشده قابل ایجاد است.'); |
| 264 | if(!(canOffice('edit')||canOffice('refer')))return alert('برای درخواست تأیید دسترسی لازم را ندارید.'); |
| 265 | const {data:members,error}=await sb.from('organization_members').select('id,user_id,position_title,is_owner').eq('organization_id',currentUser.organizationId).eq('status','active'); |
| 266 | if(error)return alert(error.message); |
| 267 | const ids=(members||[]).map(m=>m.user_id),profiles=ids.length?(await sb.from('profiles').select('id,full_name,email').in('id',ids)).data||[]:[]; |
| 268 | const choices=(members||[]).filter(m=>m.user_id!==currentUser.id).map((m,i)=>({n:i+1,m,p:profiles.find(p=>p.id===m.user_id)})); |
| 269 | if(!choices.length)return alert('عضو دیگری برای تأیید در این سازمان وجود ندارد.'); |
| 270 | const pick=Number(prompt('تأییدکننده را انتخاب کنید:\n'+choices.map(x=>x.n+') '+(x.p?.full_name||x.p?.email||x.m.position_title||'کاربر')).join('\n'))); |
| 271 | const chosen=choices.find(x=>x.n===pick);if(!chosen)return; |
| 272 | const note=prompt('یادداشت درخواست تأیید (اختیاری):')||''; |
| 273 | const dueRaw=String(prompt('مهلت تأیید (اختیاری، نمونه 2026-10-01T12:00):')||'').trim(); |
| 274 | let dueAt=null;if(dueRaw){const d=new Date(dueRaw);if(Number.isNaN(d.getTime()))return alert('فرمت مهلت معتبر نیست.');dueAt=d.toISOString()} |
| 275 | const {error:rpcError}=await sb.rpc('office_request_approval',{ |
| 276 | p_organization_id:currentUser.organizationId,p_correspondence_id:correspondenceId, |
| 277 | p_approver_member_id:chosen.m.id,p_note:note,p_due_at:dueAt |
| 278 | }); |
| 279 | if(rpcError){console.error('office approval request failed',rpcError);return alert('درخواست تأیید ثبت نشد: '+rpcError.message)} |
| 280 | await window.officeLoadApprovalQueue(false);alert('درخواست تأیید داخلی با سابقه غیرقابلتغییر ثبت شد.'); |
| 281 | return true; |
| 282 | }; |
| 283 | window.officeActOnApproval=async function(approvalId,action){ |
| 284 | if(!['approved','rejected'].includes(action))return false; |
| 285 | const label=action==='approved'?'تأیید':'رد'; |
| 286 | const note=prompt('یادداشت '+label+' (اختیاری):')||''; |
| 287 | const {error}=await sb.rpc('office_act_on_approval',{ |
| 288 | p_organization_id:currentUser.organizationId,p_approval_id:approvalId,p_action:action,p_note:note |
| 289 | }); |
| 290 | if(error){console.error('office approval decision failed',error);if(/approval content changed/i.test(error.message||''))return alert('محتوای نامه بعد از درخواست تغییر کرده است؛ این درخواست دیگر قابل تصمیم نیست و باید درخواست جدید ایجاد شود.');return alert(label+' انجام نشد: '+error.message)} |
| 291 | await window.officeLoadApprovalQueue(false);renderApprovalWork();alert(label+' با هویت نشست فعلی در سابقه داخلی ثبت شد.'); |
| 292 | return true; |
| 293 | }; |
| 294 | function renderApprovalWork(){ |
| 295 | const root=document.getElementById('view-office');if(!root)return; |
| 296 | const rows=window.officeApprovalWorkQueue(); |
| 297 | const body=rows.length?rows.map(r=>{ |
| 298 | const mine=String(r.approver_user_id||'')===String(currentUser?.id||''); |
| 299 | const state=(r.state==='approved'?'تأییدشده':r.state==='rejected'?'ردشده':'در انتظار')+(r.content_changed?' · محتوا تغییر کرده':''); |
| 300 | const actions=mine&&r.state==='pending'&&!r.content_changed |
| 301 | ?'<button class="btn btn-primary btn-inline" onclick="officeActOnApproval(\''+oe(r.approval_id)+'\',\'approved\')">تأیید</button> <button class="btn btn-secondary btn-inline" onclick="officeActOnApproval(\''+oe(r.approval_id)+'\',\'rejected\')">رد</button>' |
| 302 | :''; |
| 303 | return '<tr><td><strong>'+oe(r.register_number||'—')+'</strong></td><td>'+oe(r.subject||'—')+'</td><td>'+state+(r.overdue?' <strong>· معوق</strong>':'')+'</td><td>'+faDate(r.due_at)+'</td><td>'+oe(r.note||'—')+'</td><td>'+oe(r.decision_aal||'—')+'</td><td><button class="btn btn-secondary btn-inline" onclick="officeOpenRecord(\''+oe(r.correspondence_id)+'\')">نامه</button> '+actions+'</td></tr>' |
| 304 | }).join(''):'<tr><td colspan="7" class="af-empty">درخواست تأییدی برای نمایش وجود ندارد.</td></tr>'; |
| 305 | root.innerHTML='<div class="af-head"><div><h1>تأییدات داخلی</h1><p>درخواست، تأیید و رد با شواهد غیرقابلتغییر ثبت میشود. این قابلیت امضای دیجیتال Qualified یا گواهی معتبر بیرونی نیست.</p></div><div><button class="btn btn-secondary btn-inline" onclick="officeLoadApprovalQueue(true)">بازخوانی</button></div></div><div class="card"><div class="table-responsive"><table><thead><tr><th>نامه</th><th>موضوع</th><th>وضعیت</th><th>مهلت</th><th>یادداشت</th><th>AAL تصمیم</th><th>عملیات</th></tr></thead><tbody>'+body+'</tbody></table></div></div>'; |
| 306 | } |
| 307 | const c4OfficeRenderForC5=window.officeRender; |
| 308 | window.officeRender=function(task='inbox'){ |
| 309 | if(task==='approvals'){c4OfficeRenderForC5('inbox');window.FINORA_OFFICE_TASK='approvals';renderApprovalWork();window.officeLoadApprovalQueue(true);return} |
| 310 | return c4OfficeRenderForC5(task); |
| 311 | }; |
| 312 | const c4OfficeOpenRecordForC5=window.officeOpenRecord; |
| 313 | window.officeOpenRecord=async function(id){ |
| 314 | const result=await c4OfficeOpenRecordForC5(id); |
| 315 | const x=(datastore.correspondence||[]).find(r=>r.id===id); |
| 316 | if(x&&x.status!=='draft'&&(canOffice('edit')||canOffice('refer'))){ |
| 317 | const head=document.querySelector('#view-office .af-head > div:last-child'); |
| 318 | if(head&&!document.getElementById('office-request-approval-btn')){ |
| 319 | const btn=document.createElement('button');btn.id='office-request-approval-btn';btn.className='btn btn-secondary btn-inline';btn.textContent='درخواست تأیید داخلی';btn.onclick=()=>window.officeRequestApproval(id);head.appendChild(btn); |
| 320 | } |
| 321 | } |
| 322 | return result; |
| 323 | }; |
| 324 | |
| 325 | |
| 326 | window.FINORA_SLA_QUEUE=[]; |
| 327 | window.officeSlaWorkQueue=function(){return Array.isArray(window.FINORA_SLA_QUEUE)?window.FINORA_SLA_QUEUE:[]}; |
| 328 | window.officeLoadSlaQueue=async function(render=true){ |
| 329 | if(!currentUser?.organizationId)return []; |
| 330 | const {data,error}=await sb.rpc('office_sla_work_queue',{p_organization_id:currentUser.organizationId}); |
| 331 | if(error){console.error('office SLA queue failed',error);if(render)alert('دریافت کارتابل SLA ناموفق بود: '+error.message);return []} |
| 332 | window.FINORA_SLA_QUEUE=Array.isArray(data)?data:[]; |
| 333 | if(render)renderSlaWork(); |
| 334 | return window.FINORA_SLA_QUEUE; |
| 335 | }; |
| 336 | window.officeEmitSlaEvent=async function(workType,workId,eventName){ |
| 337 | if(!currentUser?.organizationId||!['referral','approval'].includes(workType)||!['sla_reminder','sla_escalated'].includes(eventName))return false; |
| 338 | const label=eventName==='sla_reminder'?'یادآوری داخلی':'تصعید داخلی'; |
| 339 | const {error}=await sb.rpc('office_emit_sla_event',{ |
| 340 | p_organization_id:currentUser.organizationId,p_work_type:workType,p_work_id:workId,p_event:eventName |
| 341 | }); |
| 342 | if(error){ |
| 343 | console.error('office SLA event failed',error); |
| 344 | if(/already emitted for policy window/i.test(error.message||''))return alert(label+' برای بازه سیاست فعلی قبلاً ثبت شده است.'); |
| 345 | if(/24 hours overdue/i.test(error.message||''))return alert('تصعید پس از حداقل ۲۴ ساعت تأخیر مجاز است.'); |
| 346 | if(/pending work required/i.test(error.message||''))return alert('این کار دیگر در وضعیت باز نیست و رویداد SLA جدید برای آن مجاز نیست.'); |
| 347 | return alert(label+' ثبت نشد: '+error.message); |
| 348 | } |
| 349 | await window.officeLoadSlaQueue(true); |
| 350 | alert(label+' بهصورت Evidence داخلی ثبت شد؛ در C6 هیچ ایمیل، پیامک یا webhook بیرونی ارسال نمیشود.'); |
| 351 | return true; |
| 352 | }; |
| 353 | function renderSlaWork(){ |
| 354 | const root=document.getElementById('view-office');if(!root)return; |
| 355 | const rows=window.officeSlaWorkQueue(); |
| 356 | const todayUtc=new Date().toISOString().slice(0,10); |
| 357 | const body=rows.length?rows.map(r=>{ |
| 358 | const type=r.work_type==='approval'?'تأیید':'ارجاع'; |
| 359 | const stateMap={sent:'ارسالشده',acknowledged:'دریافتشده',completed:'تکمیلشده',pending:'در انتظار',approved:'تأییدشده',rejected:'ردشده',stale:'محتوا تغییر کرده'}; |
| 360 | const state=stateMap[r.work_state]||r.work_state||'—'; |
| 361 | const reminderToday=r.last_reminder_at&&String(r.last_reminder_at).slice(0,10)===todayUtc; |
| 362 | const canReminder=r.can_emit&&r.overdue&&['sent','acknowledged','pending'].includes(r.work_state)&&!reminderToday; |
| 363 | const canEscalate=r.can_emit&&r.overdue&&Number(r.overdue_hours||0)>=24&&!r.escalated_at&&['sent','acknowledged','pending'].includes(r.work_state); |
| 364 | const actions='<button class="btn btn-secondary btn-inline" onclick="officeOpenRecord(\''+oe(r.correspondence_id)+'\')">نامه</button> ' |
| 365 | +(canReminder?'<button class="btn btn-secondary btn-inline" onclick="officeEmitSlaEvent(\''+oe(r.work_type)+'\',\''+oe(r.work_id)+'\',\'sla_reminder\')">یادآوری</button> ':'') |
| 366 | +(canEscalate?'<button class="btn btn-primary btn-inline" onclick="officeEmitSlaEvent(\''+oe(r.work_type)+'\',\''+oe(r.work_id)+'\',\'sla_escalated\')">تصعید</button>':''); |
| 367 | return '<tr><td>'+type+'</td><td><strong>'+oe(r.register_number||'—')+'</strong></td><td>'+oe(r.subject||'—')+'</td><td>'+state+(r.overdue?' <strong>· معوق</strong>':'')+'</td><td>'+faDate(r.due_at)+'</td><td>'+Number(r.overdue_hours||0).toLocaleString('fa-IR')+'</td><td>'+faDate(r.last_reminder_at)+'</td><td>'+faDate(r.escalated_at)+'</td><td>'+actions+'</td></tr>'; |
| 368 | }).join(''):'<tr><td colspan="9" class="af-empty">کار دارای مهلت برای نمایش وجود ندارد.</td></tr>'; |
| 369 | root.innerHTML='<div class="af-head"><div><h1>SLA، یادآوری و تصعید</h1><p>وضعیت مهلت از سرور محاسبه میشود. یادآوری و تصعید فقط Evidence داخلی هستند؛ C6 هیچ ارسال ایمیل، پیامک یا webhook بیرونی انجام نمیدهد.</p></div><div><button class="btn btn-secondary btn-inline" onclick="officeLoadSlaQueue(true)">بازخوانی</button></div></div><div class="card"><div class="table-responsive"><table><thead><tr><th>نوع</th><th>نامه</th><th>موضوع</th><th>وضعیت</th><th>مهلت</th><th>ساعت تأخیر</th><th>آخرین یادآوری</th><th>تصعید</th><th>عملیات</th></tr></thead><tbody>'+body+'</tbody></table></div></div>'; |
| 370 | } |
| 371 | const c5OfficeRenderForC6=window.officeRender; |
| 372 | window.officeRender=function(task='inbox'){ |
| 373 | if(task==='sla'){c5OfficeRenderForC6('inbox');window.FINORA_OFFICE_TASK='sla';renderSlaWork();window.officeLoadSlaQueue(true);return} |
| 374 | return c5OfficeRenderForC6(task); |
| 375 | }; |
| 376 | })(); |