سامانه صدور فاکتور و حسابداری
feat/office-c7-fulltext-ocr-provenance
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 canArchive=canOffice('archive')||canOffice('configure'); |
| 104 | const body=rows.length?rows.map(r=>{ |
| 105 | const tags=Array.isArray(r.tags)?r.tags.join('، '):''; |
| 106 | const classify=canArchive?'<button class="btn btn-secondary btn-inline" onclick="officeClassifyPrompt(\''+oe(r.correspondence_id)+'\')">طبقهبندی</button> ':''; |
| 107 | const link=(canOffice('edit')||canOffice('refer'))?'<button class="btn btn-secondary btn-inline" onclick="officeLinkPrompt(\''+oe(r.correspondence_id)+'\')">ارتباط</button> ':''; |
| 108 | const ocrState=r.ocr_state==='corrected'?'اصلاح انسانی · نسخه '+Number(r.ocr_version||0).toLocaleString('fa-IR'):r.ocr_state==='provider_output'?'خروجی OCR · نسخه '+Number(r.ocr_version||0).toLocaleString('fa-IR'):'بدون متن OCR'; |
| 109 | const ocrActions=canArchive?'<button class="btn btn-secondary btn-inline" onclick="officeRecordOcrText(\''+oe(r.correspondence_id)+'\')">نسخه OCR</button> '+(r.ocr_state!=='none'?'<button class="btn btn-secondary btn-inline" onclick="officeCorrectOcrText(\''+oe(r.correspondence_id)+'\')">اصلاح متن</button> ':''):''; |
| 110 | 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>'+ocrState+(r.ocr_source_engine?' · '+oe(r.ocr_source_engine):'')+'</td><td>'+Number(r.search_rank||0).toLocaleString('fa-IR',{maximumFractionDigits:3})+'</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+link+ocrActions+'</td></tr>' |
| 111 | }).join(''):'<tr><td colspan="9" class="af-empty">مکاتبهای مطابق فیلتر آرشیو یافت نشد.</td></tr>'; |
| 112 | root.innerHTML='<div class="af-head"><div><h1>جستوجوی تماممتن و آرشیو</h1><p>جستوجوی رتبهبندیشده روی شماره، موضوع، طرف مکاتبه، متن نامه، طبقهبندی و آخرین متن OCR. ثبت OCR در C7 فقط provenance/correction است و به معنی تأیید دقت 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="مثال: فاکتور تهران یا "قرارداد خدمات""></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>OCR</th><th>رتبه</th><th>ارتباطها</th><th>عملیات</th></tr></thead><tbody>'+body+'</tbody></table></div></div>'; |
| 113 | } |
| 114 | window.officeLoadArchiveIndex=async function(render=true){ |
| 115 | if(!currentUser?.organizationId)return []; |
| 116 | const q=document.getElementById('office-archive-q')?.value||null; |
| 117 | const folder=document.getElementById('office-archive-folder')?.value||null; |
| 118 | const code=document.getElementById('office-archive-code')?.value||null; |
| 119 | const {data,error}=await sb.rpc('office_archive_full_text_search',{p_organization_id:currentUser.organizationId,p_query:q,p_folder:folder,p_classification_code:code,p_related_to:null}); |
| 120 | if(error){console.error('office archive search failed',error);if(render)alert('جستوجوی آرشیو ناموفق بود: '+error.message);return []} |
| 121 | window.FINORA_ARCHIVE_INDEX=Array.isArray(data)?data:[]; |
| 122 | if(render)renderArchiveIndex(); |
| 123 | return window.FINORA_ARCHIVE_INDEX; |
| 124 | }; |
| 125 | window.officeRecordOcrText=async function(correspondenceId){ |
| 126 | if(!(canOffice('archive')||canOffice('configure')))return alert('برای ثبت متن OCR دسترسی آرشیو لازم است.'); |
| 127 | const engine=String(prompt('نام موتور/منبع OCR:')||'').trim();if(!engine)return false; |
| 128 | const sourceRef=String(prompt('مرجع فایل/اسکن (اختیاری):')||'').trim(); |
| 129 | const rawText=String(prompt('متن خام OCR:')||'').trim();if(!rawText)return false; |
| 130 | const confidenceRaw=String(prompt('Confidence اختیاری بین 0 و 1:')||'').trim(); |
| 131 | let confidence=null;if(confidenceRaw){confidence=Number(confidenceRaw);if(!Number.isFinite(confidence)||confidence<0||confidence>1)return alert('Confidence باید بین 0 و 1 باشد.')} |
| 132 | const {error}=await sb.rpc('office_record_ocr_text',{ |
| 133 | p_organization_id:currentUser.organizationId,p_correspondence_id:correspondenceId,p_mode:'provider_output', |
| 134 | p_raw_text:rawText,p_corrected_text:null,p_source_engine:engine,p_source_ref:sourceRef,p_confidence:confidence |
| 135 | }); |
| 136 | if(error){console.error('office OCR provenance failed',error);return alert('ثبت متن OCR انجام نشد: '+error.message)} |
| 137 | await window.officeLoadArchiveIndex(true); |
| 138 | alert('خروجی OCR با provenance غیرقابلتغییر ثبت شد. دقت OCR فارسی در C7 تأیید نشده است.'); |
| 139 | return true; |
| 140 | }; |
| 141 | window.officeCorrectOcrText=async function(correspondenceId){ |
| 142 | if(!(canOffice('archive')||canOffice('configure')))return alert('برای اصلاح OCR دسترسی آرشیو لازم است.'); |
| 143 | const {data,error}=await sb.rpc('office_latest_ocr_text',{p_organization_id:currentUser.organizationId,p_correspondence_id:correspondenceId}); |
| 144 | if(error)return alert('دریافت متن OCR ناموفق بود: '+error.message); |
| 145 | const latest=Array.isArray(data)?data[0]:null;if(!latest)return alert('برای این نامه هنوز متن OCR ثبت نشده است.'); |
| 146 | const corrected=String(prompt('متن اصلاحشده انسانی:',latest.effective_text||'')||'').trim();if(!corrected)return false; |
| 147 | const {error:saveError}=await sb.rpc('office_record_ocr_text',{ |
| 148 | p_organization_id:currentUser.organizationId,p_correspondence_id:correspondenceId,p_mode:'human_correction', |
| 149 | p_raw_text:null,p_corrected_text:corrected,p_source_engine:null,p_source_ref:null,p_confidence:null |
| 150 | }); |
| 151 | if(saveError){console.error('office OCR correction failed',saveError);return alert('اصلاح متن OCR ثبت نشد: '+saveError.message)} |
| 152 | await window.officeLoadArchiveIndex(true); |
| 153 | alert('اصلاح انسانی بهعنوان نسخه جدید ثبت شد؛ متن خام OCR قبلی حفظ شده است.'); |
| 154 | return true; |
| 155 | }; |
| 156 | window.officeClassifyPrompt=async function(correspondenceId){ |
| 157 | if(!(canOffice('archive')||canOffice('configure')))return alert('برای طبقهبندی آرشیو دسترسی لازم را ندارید.'); |
| 158 | const folder=String(prompt('پوشه آرشیو:')||'').trim(); |
| 159 | const code=String(prompt('کد طبقهبندی:')||'').trim(); |
| 160 | const tags=String(prompt('برچسبها با ویرگول جدا شوند:')||'').split(',').map(x=>x.trim()).filter(Boolean); |
| 161 | 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}); |
| 162 | if(error){console.error('office classification failed',error);return alert('طبقهبندی انجام نشد: '+error.message)} |
| 163 | await window.officeLoadArchiveIndex(true);alert('طبقهبندی آرشیو با سابقه غیرقابلتغییر ثبت شد.'); |
| 164 | }; |
| 165 | window.officeLinkPrompt=async function(sourceId){ |
| 166 | if(!(canOffice('edit')||canOffice('refer')))return alert('برای ایجاد ارتباط نامه دسترسی لازم را ندارید.'); |
| 167 | const choices=(datastore.correspondence||[]).filter(x=>x.id!==sourceId).map((x,i)=>({n:i+1,x})); |
| 168 | if(!choices.length)return alert('نامه دیگری برای ایجاد ارتباط در دسترس نیست.'); |
| 169 | const text=choices.slice(0,50).map(z=>z.n+') '+(z.x.registerNumber||'—')+' · '+(z.x.subject||'بدون موضوع')).join('\n'); |
| 170 | const pick=Number(prompt('نامه مقصد را انتخاب کنید:\n'+text)),chosen=choices.find(z=>z.n===pick);if(!chosen)return; |
| 171 | const relPick=String(prompt('نوع ارتباط: 1 = پاسخ به، 2 = مرتبط')||'').trim(); |
| 172 | const relation=relPick==='1'?'reply_to':relPick==='2'?'related':null;if(!relation)return; |
| 173 | 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}); |
| 174 | if(error){console.error('office relation failed',error);return alert('ایجاد ارتباط انجام نشد: '+error.message)} |
| 175 | await window.officeLoadArchiveIndex(true);alert('ارتباط نامه با سابقه غیرقابلتغییر ثبت شد.'); |
| 176 | }; |
| 177 | const c2OfficeRender=window.officeRender; |
| 178 | window.officeRender=function(task='inbox'){ |
| 179 | if(task==='archive'){ |
| 180 | c2OfficeRender('inbox'); |
| 181 | renderArchiveIndex(); |
| 182 | window.officeLoadArchiveIndex(true); |
| 183 | return; |
| 184 | } |
| 185 | return c2OfficeRender(task); |
| 186 | }; |
| 187 | |
| 188 | window.FINORA_TEMPLATE_CATALOG=[]; |
| 189 | window.officeTemplateCatalog=function(){return Array.isArray(window.FINORA_TEMPLATE_CATALOG)?window.FINORA_TEMPLATE_CATALOG:[]}; |
| 190 | window.officeLoadTemplateCatalog=async function(render=true){ |
| 191 | if(!currentUser?.organizationId)return []; |
| 192 | const includeInactive=window.FINORA_OFFICE_TASK==='templates'&&(canOffice('configure')); |
| 193 | const {data,error}=await sb.rpc('office_template_catalog',{p_organization_id:currentUser.organizationId,p_include_inactive:includeInactive}); |
| 194 | if(error){console.error('office template catalog failed',error);if(render)alert('دریافت قالبهای نامه ناموفق بود: '+error.message);return []} |
| 195 | window.FINORA_TEMPLATE_CATALOG=Array.isArray(data)?data:[]; |
| 196 | if(render){ |
| 197 | if(window.FINORA_OFFICE_TASK==='templates')renderTemplateManager(); |
| 198 | else if(window.FINORA_OFFICE_TASK==='new')renderTemplateSelector(); |
| 199 | } |
| 200 | return window.FINORA_TEMPLATE_CATALOG; |
| 201 | }; |
| 202 | function renderTemplateManager(){ |
| 203 | const root=document.getElementById('view-office');if(!root)return; |
| 204 | const rows=window.officeTemplateCatalog(); |
| 205 | const canConfigure=canOffice('configure'); |
| 206 | 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>':''; |
| 207 | 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>'; |
| 208 | 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>'; |
| 209 | } |
| 210 | window.officePrepareTemplateVersion=function(key){ |
| 211 | const t=window.officeTemplateCatalog().find(x=>x.template_key===key);if(!t)return; |
| 212 | 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'); |
| 213 | 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; |
| 214 | }; |
| 215 | window.officeSaveTemplateVersion=async function(){ |
| 216 | if(!canOffice('configure'))return alert('برای مدیریت قالبها دسترسی پیکربندی لازم است.'); |
| 217 | const key=String(document.getElementById('office-template-edit-key')?.value||'').trim().toUpperCase(); |
| 218 | const name=String(document.getElementById('office-template-edit-name')?.value||'').trim(); |
| 219 | const subject=String(document.getElementById('office-template-edit-subject')?.value||''); |
| 220 | const body=String(document.getElementById('office-template-edit-body')?.value||''); |
| 221 | const active=!!document.getElementById('office-template-edit-active')?.checked; |
| 222 | if(!key||!name)return alert('کلید و عنوان قالب الزامی است.'); |
| 223 | 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}); |
| 224 | if(error){console.error('office template version failed',error);return alert('ثبت نسخه قالب انجام نشد: '+error.message)} |
| 225 | await window.officeLoadTemplateCatalog(true);alert('نسخه '+Number(data||0).toLocaleString('fa-IR')+' قالب ثبت شد.'); |
| 226 | }; |
| 227 | function renderTemplateSelector(){ |
| 228 | if(window.FINORA_OFFICE_TASK!=='new')return; |
| 229 | const subject=document.getElementById('office-subject');if(!subject)return; |
| 230 | let host=document.getElementById('office-template-apply-card'); |
| 231 | 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)} |
| 232 | 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(''); |
| 233 | 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>'; |
| 234 | } |
| 235 | window.officeApplyTemplate=function(ref){ |
| 236 | if(window.FINORA_OFFICE_TASK!=='new')return false; |
| 237 | const [key,versionRaw]=String(ref||'').split('::'),version=Number(versionRaw); |
| 238 | const t=window.officeTemplateCatalog().find(x=>x.template_key===key&&Number(x.version)===version); |
| 239 | if(!t)return alert('نسخه قالب انتخابشده در دسترس نیست.'); |
| 240 | 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'); |
| 241 | if(!subject||!body||!keyEl||!verEl)return false; |
| 242 | subject.value=t.subject_template||'';body.value=t.body_template||'';keyEl.value=t.template_key;verEl.value=String(t.version); |
| 243 | if(prov)prov.textContent='قالب اعمالشده: '+t.name+' · نسخه '+Number(t.version).toLocaleString('fa-IR')+' — پس از اعمال، متن قابل ویرایش است اما مرجع نسخه حفظ میشود.'; |
| 244 | return true; |
| 245 | }; |
| 246 | const c3OfficeRenderForC4=window.officeRender; |
| 247 | window.officeRender=function(task='inbox'){ |
| 248 | if(task==='templates'){ |
| 249 | c3OfficeRenderForC4('inbox');window.FINORA_OFFICE_TASK='templates';renderTemplateManager();window.officeLoadTemplateCatalog(true);return; |
| 250 | } |
| 251 | const out=c3OfficeRenderForC4(task); |
| 252 | if(task==='new'){window.FINORA_OFFICE_TASK='new';window.officeLoadTemplateCatalog(false).then(()=>renderTemplateSelector())} |
| 253 | return out; |
| 254 | }; |
| 255 | |
| 256 | window.FINORA_APPROVAL_QUEUE=[]; |
| 257 | window.officeApprovalWorkQueue=function(){return Array.isArray(window.FINORA_APPROVAL_QUEUE)?window.FINORA_APPROVAL_QUEUE:[]}; |
| 258 | window.officeLoadApprovalQueue=async function(render=true){ |
| 259 | if(!currentUser?.organizationId)return []; |
| 260 | const {data,error}=await sb.rpc('office_approval_work_queue',{p_organization_id:currentUser.organizationId}); |
| 261 | if(error){console.error('office approval queue failed',error);if(render)alert('دریافت کارتابل تأییدات ناموفق بود: '+error.message);return []} |
| 262 | window.FINORA_APPROVAL_QUEUE=Array.isArray(data)?data:[]; |
| 263 | if(render)renderApprovalWork(); |
| 264 | return window.FINORA_APPROVAL_QUEUE; |
| 265 | }; |
| 266 | window.officeRequestApproval=async function(correspondenceId){ |
| 267 | const x=(datastore.correspondence||[]).find(r=>r.id===correspondenceId); |
| 268 | if(!x||x.status==='draft')return alert('درخواست تأیید فقط برای نامه ثبتشده قابل ایجاد است.'); |
| 269 | if(!(canOffice('edit')||canOffice('refer')))return alert('برای درخواست تأیید دسترسی لازم را ندارید.'); |
| 270 | 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'); |
| 271 | if(error)return alert(error.message); |
| 272 | const ids=(members||[]).map(m=>m.user_id),profiles=ids.length?(await sb.from('profiles').select('id,full_name,email').in('id',ids)).data||[]:[]; |
| 273 | 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)})); |
| 274 | if(!choices.length)return alert('عضو دیگری برای تأیید در این سازمان وجود ندارد.'); |
| 275 | const pick=Number(prompt('تأییدکننده را انتخاب کنید:\n'+choices.map(x=>x.n+') '+(x.p?.full_name||x.p?.email||x.m.position_title||'کاربر')).join('\n'))); |
| 276 | const chosen=choices.find(x=>x.n===pick);if(!chosen)return; |
| 277 | const note=prompt('یادداشت درخواست تأیید (اختیاری):')||''; |
| 278 | const dueRaw=String(prompt('مهلت تأیید (اختیاری، نمونه 2026-10-01T12:00):')||'').trim(); |
| 279 | let dueAt=null;if(dueRaw){const d=new Date(dueRaw);if(Number.isNaN(d.getTime()))return alert('فرمت مهلت معتبر نیست.');dueAt=d.toISOString()} |
| 280 | const {error:rpcError}=await sb.rpc('office_request_approval',{ |
| 281 | p_organization_id:currentUser.organizationId,p_correspondence_id:correspondenceId, |
| 282 | p_approver_member_id:chosen.m.id,p_note:note,p_due_at:dueAt |
| 283 | }); |
| 284 | if(rpcError){console.error('office approval request failed',rpcError);return alert('درخواست تأیید ثبت نشد: '+rpcError.message)} |
| 285 | await window.officeLoadApprovalQueue(false);alert('درخواست تأیید داخلی با سابقه غیرقابلتغییر ثبت شد.'); |
| 286 | return true; |
| 287 | }; |
| 288 | window.officeActOnApproval=async function(approvalId,action){ |
| 289 | if(!['approved','rejected'].includes(action))return false; |
| 290 | const label=action==='approved'?'تأیید':'رد'; |
| 291 | const note=prompt('یادداشت '+label+' (اختیاری):')||''; |
| 292 | const {error}=await sb.rpc('office_act_on_approval',{ |
| 293 | p_organization_id:currentUser.organizationId,p_approval_id:approvalId,p_action:action,p_note:note |
| 294 | }); |
| 295 | if(error){console.error('office approval decision failed',error);if(/approval content changed/i.test(error.message||''))return alert('محتوای نامه بعد از درخواست تغییر کرده است؛ این درخواست دیگر قابل تصمیم نیست و باید درخواست جدید ایجاد شود.');return alert(label+' انجام نشد: '+error.message)} |
| 296 | await window.officeLoadApprovalQueue(false);renderApprovalWork();alert(label+' با هویت نشست فعلی در سابقه داخلی ثبت شد.'); |
| 297 | return true; |
| 298 | }; |
| 299 | function renderApprovalWork(){ |
| 300 | const root=document.getElementById('view-office');if(!root)return; |
| 301 | const rows=window.officeApprovalWorkQueue(); |
| 302 | const body=rows.length?rows.map(r=>{ |
| 303 | const mine=String(r.approver_user_id||'')===String(currentUser?.id||''); |
| 304 | const state=(r.state==='approved'?'تأییدشده':r.state==='rejected'?'ردشده':'در انتظار')+(r.content_changed?' · محتوا تغییر کرده':''); |
| 305 | const actions=mine&&r.state==='pending'&&!r.content_changed |
| 306 | ?'<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>' |
| 307 | :''; |
| 308 | 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>' |
| 309 | }).join(''):'<tr><td colspan="7" class="af-empty">درخواست تأییدی برای نمایش وجود ندارد.</td></tr>'; |
| 310 | 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>'; |
| 311 | } |
| 312 | const c4OfficeRenderForC5=window.officeRender; |
| 313 | window.officeRender=function(task='inbox'){ |
| 314 | if(task==='approvals'){c4OfficeRenderForC5('inbox');window.FINORA_OFFICE_TASK='approvals';renderApprovalWork();window.officeLoadApprovalQueue(true);return} |
| 315 | return c4OfficeRenderForC5(task); |
| 316 | }; |
| 317 | const c4OfficeOpenRecordForC5=window.officeOpenRecord; |
| 318 | window.officeOpenRecord=async function(id){ |
| 319 | const result=await c4OfficeOpenRecordForC5(id); |
| 320 | const x=(datastore.correspondence||[]).find(r=>r.id===id); |
| 321 | if(x&&x.status!=='draft'&&(canOffice('edit')||canOffice('refer'))){ |
| 322 | const head=document.querySelector('#view-office .af-head > div:last-child'); |
| 323 | if(head&&!document.getElementById('office-request-approval-btn')){ |
| 324 | 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); |
| 325 | } |
| 326 | } |
| 327 | return result; |
| 328 | }; |
| 329 | |
| 330 | |
| 331 | window.FINORA_SLA_QUEUE=[]; |
| 332 | window.officeSlaWorkQueue=function(){return Array.isArray(window.FINORA_SLA_QUEUE)?window.FINORA_SLA_QUEUE:[]}; |
| 333 | window.officeLoadSlaQueue=async function(render=true){ |
| 334 | if(!currentUser?.organizationId)return []; |
| 335 | const {data,error}=await sb.rpc('office_sla_work_queue',{p_organization_id:currentUser.organizationId}); |
| 336 | if(error){console.error('office SLA queue failed',error);if(render)alert('دریافت کارتابل SLA ناموفق بود: '+error.message);return []} |
| 337 | window.FINORA_SLA_QUEUE=Array.isArray(data)?data:[]; |
| 338 | if(render)renderSlaWork(); |
| 339 | return window.FINORA_SLA_QUEUE; |
| 340 | }; |
| 341 | window.officeEmitSlaEvent=async function(workType,workId,eventName){ |
| 342 | if(!currentUser?.organizationId||!['referral','approval'].includes(workType)||!['sla_reminder','sla_escalated'].includes(eventName))return false; |
| 343 | const label=eventName==='sla_reminder'?'یادآوری داخلی':'تصعید داخلی'; |
| 344 | const {error}=await sb.rpc('office_emit_sla_event',{ |
| 345 | p_organization_id:currentUser.organizationId,p_work_type:workType,p_work_id:workId,p_event:eventName |
| 346 | }); |
| 347 | if(error){ |
| 348 | console.error('office SLA event failed',error); |
| 349 | if(/already emitted for policy window/i.test(error.message||''))return alert(label+' برای بازه سیاست فعلی قبلاً ثبت شده است.'); |
| 350 | if(/24 hours overdue/i.test(error.message||''))return alert('تصعید پس از حداقل ۲۴ ساعت تأخیر مجاز است.'); |
| 351 | if(/pending work required/i.test(error.message||''))return alert('این کار دیگر در وضعیت باز نیست و رویداد SLA جدید برای آن مجاز نیست.'); |
| 352 | return alert(label+' ثبت نشد: '+error.message); |
| 353 | } |
| 354 | await window.officeLoadSlaQueue(true); |
| 355 | alert(label+' بهصورت Evidence داخلی ثبت شد؛ در C6 هیچ ایمیل، پیامک یا webhook بیرونی ارسال نمیشود.'); |
| 356 | return true; |
| 357 | }; |
| 358 | function renderSlaWork(){ |
| 359 | const root=document.getElementById('view-office');if(!root)return; |
| 360 | const rows=window.officeSlaWorkQueue(); |
| 361 | const todayUtc=new Date().toISOString().slice(0,10); |
| 362 | const body=rows.length?rows.map(r=>{ |
| 363 | const type=r.work_type==='approval'?'تأیید':'ارجاع'; |
| 364 | const stateMap={sent:'ارسالشده',acknowledged:'دریافتشده',completed:'تکمیلشده',pending:'در انتظار',approved:'تأییدشده',rejected:'ردشده',stale:'محتوا تغییر کرده'}; |
| 365 | const state=stateMap[r.work_state]||r.work_state||'—'; |
| 366 | const reminderToday=r.last_reminder_at&&String(r.last_reminder_at).slice(0,10)===todayUtc; |
| 367 | const canReminder=r.can_emit&&r.overdue&&['sent','acknowledged','pending'].includes(r.work_state)&&!reminderToday; |
| 368 | const canEscalate=r.can_emit&&r.overdue&&Number(r.overdue_hours||0)>=24&&!r.escalated_at&&['sent','acknowledged','pending'].includes(r.work_state); |
| 369 | const actions='<button class="btn btn-secondary btn-inline" onclick="officeOpenRecord(\''+oe(r.correspondence_id)+'\')">نامه</button> ' |
| 370 | +(canReminder?'<button class="btn btn-secondary btn-inline" onclick="officeEmitSlaEvent(\''+oe(r.work_type)+'\',\''+oe(r.work_id)+'\',\'sla_reminder\')">یادآوری</button> ':'') |
| 371 | +(canEscalate?'<button class="btn btn-primary btn-inline" onclick="officeEmitSlaEvent(\''+oe(r.work_type)+'\',\''+oe(r.work_id)+'\',\'sla_escalated\')">تصعید</button>':''); |
| 372 | 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>'; |
| 373 | }).join(''):'<tr><td colspan="9" class="af-empty">کار دارای مهلت برای نمایش وجود ندارد.</td></tr>'; |
| 374 | 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>'; |
| 375 | } |
| 376 | const c5OfficeRenderForC6=window.officeRender; |
| 377 | window.officeRender=function(task='inbox'){ |
| 378 | if(task==='sla'){c5OfficeRenderForC6('inbox');window.FINORA_OFFICE_TASK='sla';renderSlaWork();window.officeLoadSlaQueue(true);return} |
| 379 | return c5OfficeRenderForC6(task); |
| 380 | }; |
| 381 | })(); |