سامانه صدور فاکتور و حسابداری

feat: add admin identity controls and phone auth

Davood Mehraban committed Oct 7, 2026 at 20:28 UTC e1d01c5cbd46f369daef2cde36c503e134babf08
14 files changed +192 -46
.github/workflows/quality.yml
+7 -1
@@ -66,6 +66,8 @@ jobs:
66 run: node scripts/identity-wave5c-check.mjs
67 - name: Finora branding and login invariants
68 run: node scripts/branding-login-check.mjs
69 + - name: Admin identity, phone auth and dark-mode invariants
70 + run: node scripts/admin-identity-phone-check.mjs
71 - name: Office Slice C1 invariants
72 run: node scripts/office-slice-c1-check.mjs
73 - name: Office Slice C2 invariants
@@ -103,7 +105,7 @@ jobs:
105 - name: Real DOM smoke
106 run: |
107 python3 -m http.server 4173 >/tmp/finora-http.log 2>&1 &
106 - npx playwright test scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/identity-wave5a.spec.js scripts/identity-wave5b.spec.js scripts/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/shell-scroll-ownership.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/chart-completeness.spec.js scripts/accounting-p0-journal.spec.js scripts/ux-hardening-r2.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
108 + npx playwright test scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/identity-wave5a.spec.js scripts/identity-wave5b.spec.js scripts/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/shell-scroll-ownership.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/chart-completeness.spec.js scripts/accounting-p0-journal.spec.js scripts/ux-hardening-r2.spec.js scripts/admin-identity-phone.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
109
110 identity-wave5a-database:
111 runs-on: ubuntu-latest
@@ -137,6 +139,10 @@ jobs:
139 run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002080000_identity_wave5a_bootstrap.sql
140 - name: Execute Wave 5a identity bootstrap assertions
141 run: psql -v ON_ERROR_STOP=1 -f supabase/tests/identity_wave5a_behavior.sql
142 + - name: Apply phone identity profile migration
143 + run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261007163500_phone_identity_profile.sql
144 + - name: Execute phone identity bootstrap assertions
145 + run: psql -v ON_ERROR_STOP=1 -f supabase/tests/phone_identity_behavior.sql
146
147 c8-policy-database:
148 runs-on: ubuntu-latest
PROJECT_STATE.md
+1 -1
@@ -17,7 +17,7 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
17 ## Current change ledger
18 | Date | Request / decision | Status | Evidence / next action |
19 |---|---|---|---|
20 -| 2026-10-07 | Owner requested dark-mode readability repair plus system-admin identity operations: edit license/user/company capacities, create users, issue temporary/reset passwords, preserve self-service password change, and add phone-number signup/login with SMS OTP. | **REQUEST RECORDED / IMPLEMENTATION STARTED** | Baseline `main` = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`; current self-service password change already exists under Settings > Account/password. Admin license editor exists but user-seat value is not currently persisted by `applyLicenseDurationChange`. Phone-only identities are currently blocked by Wave5a trigger because `profiles.email` is NOT NULL and `handle_new_user()` requires email. Scope explicitly authorizes auth/schema work needed for these requested capabilities; no real user creation/password reset will be executed during implementation. SMS delivery remains dependent on configuring a supported Supabase SMS provider/credentials. |`r`n| 2026-10-07 | Owner supplied live screenshots and requested immediate invoice-workspace cleanup: remove redundant top workflow buttons (sale/purchase/pre-invoice) and redundant sale/purchase shortcut buttons beside the document heading; keep Excel import + sample download; keep only the commercial-document type selector with sale, purchase, sales pre-invoice, sales progress statement; replace the separate search-above-select UX with a single in-control searchable product selector that matches product code/name/specification and numeric fragments. | **COMPLETED / MERGED / RELEASE VERIFIED** | Merged to `main` as `6e7fa6e861ebdd89e5712ed7d64bb5fe3128f307`. PR #54 Quality `37644940991` and Security `37644940960` SUCCESS; inspected static logs confirm commercial + UX-R2 + Golden PASS and **60/60 Real-DOM tests**. Main Quality `37645195629`, Security `37645195698`, Release gate `37645411897`, exact gated Pages `37645464262` all SUCCESS. Live `factoreasy.ir` no longer contains the sale/purchase heading shortcuts; live UX bundle contains `finora-combobox-input` and no `finora-select-search`. Four-value document selector and Excel import/sample controls retained. No schema/RLS/auth/role/data mutation. |`r`n| 2026-10-07 | Owner requested the next integrated UX/commerce/settings hardening slice: reuse global projects from counterparty screens instead of per-contact duplicate project records; searchable large selectors across product/contact/project/account lists; refresh sale/purchase default prices after master-data edits and latest transactions; purchase-invoice UI parity with sales while preserving purchase semantics; modal/close/Escape/Enter/button real behavior QA; active-company factory reset for authorized company admin with multi-step destructive warnings; richer settings (hotkeys, quick-zero shortcuts, light/dark/auto theme, data statistics, backup/restore); configurable Excel sample/import/export field selection; and consistent Persian-digit rendering in invoice UI/print. | **IMPLEMENTED LOCALLY / CI + REAL-DOM PENDING** | Baseline `main` = `b88f0f35902cc99ebd09c9fffcd5700ce759ac69`. Implemented global project reuse/attach from counterparties, large-list search, product price-default refresh from latest posted sale/purchase, purchase project/accounting separation and commerce-switch parity, Escape/modal + configurable Ctrl+S, Ctrl+Enter, Enter-save and quick-zero hotkeys, light/dark/auto theme, active-company stats, configurable Excel templates/exports, authorized-manager active-company factory reset that skips ambiguous multi-company legacy rows, and Persian-digit normalization in isolated invoice print. Local syntax, quality, commercial, UX-R2, accounting phases 2-6 and Golden PASS; `git diff --check` PASS. Real-DOM tests added to required CI; production reset not executed. Settings reference image still not supplied, so exact visual parity to that future image is NOT VERIFIED. |
20 +| 2026-10-07 | Owner requested dark-mode readability repair plus system-admin identity operations: edit license/user/company capacities, create users, issue temporary/reset passwords, preserve self-service password change, and add phone-number signup/login with SMS OTP. | **IMPLEMENTED / CI PENDING** | Baseline `main` = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`. Dark theme now explicitly styles card/sidebar/accordion/forms/table text and surfaces for readable contrast. Admin panel adds create-user and temporary-password operations behind JWT + verified `profiles.role=admin` Edge Function; license edit now persists both company and named-user capacities. Login/OTP accepts email or Iranian mobile; self-service username/full-name editor added while existing password change remains. Production migration `phone_identity_profile` applied: profile email nullable, phone identity added, Wave5a bootstrap accepts email or phone, self-profile RPC added. Edge Function `admin-user-management` v1 ACTIVE with JWT verification. RLS inventory unchanged public 18/18, private 3/10. Local syntax/quality/admin-identity/branding/license/Wave5a/UX/Golden PASS and diff-check PASS. No real user was created and no real password was reset. SMS delivery NOT VERIFIED and remains blocked until an SMS provider is enabled/configured in Supabase Auth. |`r`n| 2026-10-07 | Owner supplied live screenshots and requested immediate invoice-workspace cleanup: remove redundant top workflow buttons (sale/purchase/pre-invoice) and redundant sale/purchase shortcut buttons beside the document heading; keep Excel import + sample download; keep only the commercial-document type selector with sale, purchase, sales pre-invoice, sales progress statement; replace the separate search-above-select UX with a single in-control searchable product selector that matches product code/name/specification and numeric fragments. | **COMPLETED / MERGED / RELEASE VERIFIED** | Merged to `main` as `6e7fa6e861ebdd89e5712ed7d64bb5fe3128f307`. PR #54 Quality `37644940991` and Security `37644940960` SUCCESS; inspected static logs confirm commercial + UX-R2 + Golden PASS and **60/60 Real-DOM tests**. Main Quality `37645195629`, Security `37645195698`, Release gate `37645411897`, exact gated Pages `37645464262` all SUCCESS. Live `factoreasy.ir` no longer contains the sale/purchase heading shortcuts; live UX bundle contains `finora-combobox-input` and no `finora-select-search`. Four-value document selector and Excel import/sample controls retained. No schema/RLS/auth/role/data mutation. |`r`n| 2026-10-07 | Owner requested the next integrated UX/commerce/settings hardening slice: reuse global projects from counterparty screens instead of per-contact duplicate project records; searchable large selectors across product/contact/project/account lists; refresh sale/purchase default prices after master-data edits and latest transactions; purchase-invoice UI parity with sales while preserving purchase semantics; modal/close/Escape/Enter/button real behavior QA; active-company factory reset for authorized company admin with multi-step destructive warnings; richer settings (hotkeys, quick-zero shortcuts, light/dark/auto theme, data statistics, backup/restore); configurable Excel sample/import/export field selection; and consistent Persian-digit rendering in invoice UI/print. | **IMPLEMENTED LOCALLY / CI + REAL-DOM PENDING** | Baseline `main` = `b88f0f35902cc99ebd09c9fffcd5700ce759ac69`. Implemented global project reuse/attach from counterparties, large-list search, product price-default refresh from latest posted sale/purchase, purchase project/accounting separation and commerce-switch parity, Escape/modal + configurable Ctrl+S, Ctrl+Enter, Enter-save and quick-zero hotkeys, light/dark/auto theme, active-company stats, configurable Excel templates/exports, authorized-manager active-company factory reset that skips ambiguous multi-company legacy rows, and Persian-digit normalization in isolated invoice print. Local syntax, quality, commercial, UX-R2, accounting phases 2-6 and Golden PASS; `git diff --check` PASS. Real-DOM tests added to required CI; production reset not executed. Settings reference image still not supplied, so exact visual parity to that future image is NOT VERIFIED. |
21 | 2026-10-07 | Owner directed autonomous continuation to finish the remaining Finora development backlog, starting with the agreed P0 accounting core: extensible analytical/floating dimensions, journal UX, context-driven posting rules and end-to-end accounting integration, then continue through remaining verified blockers without routine pauses. | **PR VERIFIED / MERGE PENDING** | P0 adds independent COST_CENTER analytics, role-driven dimension compatibility without rewriting posted history, strict per-fiscal-year journal numbers, voucher type/reference, generic dimension-to-legacy compatibility fields, independent project vs cost-center posting, copy-to-draft, account search, row copy, and live debit/credit/difference totals. Implementation head `de2c58a52cb36bfe54eeb3c90985cd6c94cae812`; PR #52 Quality `37539607474` SUCCESS including Accounting P0 invariant step and Real DOM smoke, Security `37539607498` SUCCESS. Local quality + phases 2-6 + Golden PASS. No schema/RLS/auth/role/destructive production data change. Next: merge after this evidence-state commit rechecks green, then verify main release/deploy exact SHA. |
22 | 2026-10-07 | Owner authorized implementation to completion of the researched commerce/accounting redesign: one invoice workspace in Commerce, context-driven reusable floating counterparties, purchase parity (quick supplier + Excel template), and selected-company factory reset that preserves the company. | **COMPLETED / MERGED / RELEASE VERIFIED** | Merged to `main` as `5ae9117c776a33a3cc39775c68ad0c10e13b9c44`. Push Quality run `37529032595` = success; Security `37529032630` = success; Release gate `37529230156` = success; exact gated Pages deployment `37529272934` = success and deployed the same SHA to `http://factoreasy.ir/`. Live HTML loads `js/commercial-rnd.js?v=20261007-commerce-r1`; live bundle contains factory-reset guard, quick supplier, and Excel-template code. PR Real-DOM/accounting gates were green. No production reset and no schema/RLS/auth/role mutation. |
23 | 2026-10-04 | Continue the recorded chart and taxpayer-reference correction after interrupted sessions. | **MERGED / CONTROLLED DOM + ACCOUNTING VERIFIED / GATED PAGES DEPLOYED** | 62 additive chart rows across all eight templates, including non-current assets and contra accounts; explicit preview/apply for compatible existing templates preserves old accounts and posted history. Actual supplied tax logo and reference-aligned totals/settlement layout; image-ready printing. Local chart invariants and 3 chart DOM tests passed; 2 print DOM tests plus single-page landscape PDF passed; accounting phases 2–6 and Golden passed. Full local DOM: 52/53 passed, Pages artifact failed on external ERR_CERT_AUTHORITY_INVALID; no gate weakened. PR #47 implementation SHA `db9e7f2375e914bfa9e78932e63222af68c4c9d3`: Quality `37170173739` and Security `37170173740` passed; inspected static job `111341365938` confirms 53/53 real-DOM tests, chart invariants, phases 2–6 and Golden passed, including Pages artifact. All three disposable DB jobs passed. Production recheck on 2026-10-04: 79 migrations, latest `20261003033540`; public RLS 18/18, private 3/10. See docs/CHART_OF_ACCOUNTS_RESEARCH_2026-10-03.md and docs/CHART_TAXPAYER_VERIFICATION_2026-10-03.md. No schema/RLS/auth/role or production record mutation. |
index.html
+31 -13
@@ -229,24 +229,24 @@ body{background:#f6f9fc}
229 </div>
230 <div id="auth-form-container">
231 <button class="btn auth-google" onclick="signInWithGoogle()"><span class="auth-google-mark">G</span><span>ادامه با Google</span></button>
232 - <div class="auth-divider">یا با ایمیل</div>
233 - <div class="form-group"><label>ایمیل</label><input type="email" id="auth-email" class="form-control" placeholder="name@example.com" autocomplete="email" autocapitalize="none" dir="ltr" /></div>
232 + <div class="auth-divider">یا با ایمیل / موبایل</div>
233 + <div class="form-group"><label>ایمیل یا شماره موبایل</label><input type="text" id="auth-email" class="form-control" placeholder="name@example.com یا 0912..." autocomplete="username" autocapitalize="none" dir="ltr" /></div>
234 <div class="form-group"><label>رمز عبور</label><input type="password" id="auth-password" class="form-control" placeholder="رمز عبور" autocomplete="current-password" dir="ltr" /></div>
235 <div class="auth-actions">
236 <button class="btn btn-primary" onclick="handleLogin()">ورود با رمز</button>
237 - <button class="btn btn-secondary" onclick="startEmailOtp(false,false)">ورود با کد ایمیل</button>
237 + <button class="btn btn-secondary" onclick="startIdentityOtp(false,false)">ورود با کد یک‌بارمصرف</button>
238 </div>
239 - <button class="btn auth-signup" onclick="startEmailOtp(false,true)">ثبت‌نام با کد ایمیل</button>
240 - <p class="auth-note">ورود با کد ایمیل برای حساب موجود است. ایجاد حساب جدید فقط از مسیر «ثبت‌نام با کد ایمیل» انجام می‌شود.</p>
239 + <button class="btn auth-signup" onclick="startIdentityOtp(false,true)">ثبت‌نام با ایمیل یا موبایل</button>
240 + <p class="auth-note">برای موبایل، ارسال SMS پس از فعال‌سازی سرویس پیامک در Supabase انجام می‌شود. برای ایمیل، کد به صندوق ایمیل ارسال می‌شود.</p>
241 </div>
242 <div id="auth-otp-container" style="display:none">
243 - <p style="font-size:13px;line-height:1.9;margin-bottom:12px">کد یک‌بارمصرف به <strong dir="ltr" id="auth-otp-email-label"></strong> ارسال شد. پوشه‌ی هرزنامه را هم ببینید.</p>
243 + <p style="font-size:13px;line-height:1.9;margin-bottom:12px">کد یک‌بارمصرف به <strong dir="ltr" id="auth-otp-email-label"></strong> ارسال شد. اگر ایمیل استفاده کرده‌اید پوشه هرزنامه را هم بررسی کنید.</p>
244 <div class="form-group"><label>کد تأیید</label><input type="text" id="auth-otp" class="form-control" inputmode="numeric" autocomplete="one-time-code" placeholder="------" dir="ltr" /></div>
245 <div class="auth-actions"><button class="btn btn-primary" onclick="verifyEmailOtp()">تأیید کد</button><button class="btn btn-secondary" onclick="startEmailOtp(true)">ارسال دوباره</button></div>
246 <button class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="backToAuthMain()">بازگشت</button>
247 </div>
248 <div id="auth-setpass-container" style="display:none">
249 - <p style="font-size:13px;line-height:1.9;margin-bottom:12px">ایمیل شما تأیید شد. برای ورودهای بعدی می‌توانید یک رمز عبور تعیین کنید.</p>
249 + <p style="font-size:13px;line-height:1.9;margin-bottom:12px">هویت شما تأیید شد. برای ورودهای بعدی می‌توانید یک رمز عبور تعیین کنید.</p>
250 <div class="form-group"><label>رمز عبور جدید</label><input type="password" id="auth-newpass" class="form-control" placeholder="حداقل ۸ کاراکتر" autocomplete="new-password" dir="ltr" /></div>
251 <div class="form-group"><label>تکرار رمز عبور</label><input type="password" id="auth-newpass2" class="form-control" placeholder="تکرار رمز" autocomplete="new-password" dir="ltr" /></div>
252 <button class="btn btn-primary" style="width:100%;margin-top:16px" onclick="saveNewPassword()">ذخیره رمز و ورود</button>
@@ -647,7 +647,13 @@ body{background:#f6f9fc}
647 <div class="accordion-item" data-finora-task="account">
648 <div class="accordion-header" onclick="toggleAccordion(this)"><span>🔐 حساب کاربری و رمز عبور</span><span>▼</span></div>
649 <div class="accordion-body">
650 -<p style="font-size:13px;color:var(--text-muted);margin-bottom:10px">با تعیین رمز عبور، دفعات بعد می‌توانید علاوه بر ورود با گوگل، مستقیم با ایمیل و رمز عبور هم وارد سامانه شوید.</p>
650 +<p style="font-size:13px;color:var(--text-muted);margin-bottom:10px">نام نمایشی، نام کاربری و رمز عبور حساب خود را از اینجا مدیریت کنید. ورود امن با ایمیل یا موبایل انجام می‌شود.</p>
651 +<div class="form-row">
652 +<div class="form-group"><label>نام و نام خانوادگی</label><input type="text" id="acct-fullname" class="form-control" placeholder="نام نمایشی" /></div>
653 +<div class="form-group"><label>نام کاربری</label><input type="text" id="acct-username" class="form-control" dir="ltr" placeholder="مثلاً davood.mehraban" /></div>
654 +</div>
655 +<button class="btn btn-secondary" onclick="saveMyIdentityProfile()">ذخیره مشخصات حساب</button>
656 +<hr style="border:0;border-top:1px solid var(--border);margin:16px 0">
657 <div class="form-row">
658 <div class="form-group"><label>رمز عبور جدید</label><input type="password" id="acct-newpass" class="form-control" placeholder="حداقل ۸ کاراکتر" /></div>
659 <div class="form-group"><label>تکرار رمز عبور</label><input type="password" id="acct-newpass2" class="form-control" /></div>
@@ -746,9 +752,9 @@ body{background:#f6f9fc}
752 <div class="card">
753 <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:10px">
754 <div><h2 style="font-size:18px;color:var(--danger)">👑 پنل مدیریت مرکزی کاربران و لایسنس‌ها</h2><p style="color:var(--text-muted);font-size:13px;margin-top:4px">تعریف کاربران، تخصیص طرح‌های لایسنس، تمدید، تغییر مدت و لغو اشتراک.</p></div>
749 -<button class="btn btn-primary btn-inline" onclick="refreshAdminPanel()">🔄 تازه‌سازی لیست</button>
755 +<div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-success btn-inline" onclick="adminOpenCreateUser()">➕ ایجاد کاربر جدید</button><button class="btn btn-primary btn-inline" onclick="refreshAdminPanel()">🔄 تازه‌سازی لیست</button></div>
756 </div>
751 -<div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:14px;margin-bottom:20px;font-size:13px;line-height:1.9">کاربران خودشان از صفحه ورود ثبت‌نام می‌کنند و ۱۵ روز آزمایشی می‌گیرند. در این پنل فقط لایسنس‌ها (فعال‌سازی، تمدید، تغییر طرح، لغو) مدیریت می‌شود و کنترل نهایی روی سرور انجام می‌شود.</div>
757 +<div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:14px;margin-bottom:20px;font-size:13px;line-height:1.9">مدیر سیستم می‌تواند کاربر ایجاد کند، رمز موقت تعیین کند و لایسنس، ظرفیت شرکت و ظرفیت کاربران را مدیریت کند. کاربران نیز می‌توانند با ایمیل یا—پس از فعال‌سازی سرویس SMS—با موبایل ثبت‌نام کنند.</div>
758 <div class="table-responsive">
759 <table><thead><tr><th>کاربر</th><th>وضعیت حساب</th><th>نوع اشتراک</th><th>ظرفیت شرکت</th><th>ظرفیت کاربران</th><th>تاریخ شروع</th><th>تاریخ پایان</th><th>روزهای باقیمانده</th><th>عملیات مدیریت لایسنس</th></tr></thead><tbody id="admin-users-table-body"><tr><td colspan="9" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr></tbody></table>
760 </div>
@@ -818,6 +824,18 @@ body{background:#f6f9fc}
824 </div>
825 </div>
826
827 +<div class="modal-backdrop" id="modal-admin-create-user">
828 +<div class="modal-card" style="max-width:620px">
829 +<h3 style="font-size:17px;margin-bottom:8px">ایجاد کاربر جدید</h3>
830 +<p style="font-size:12px;color:var(--text-muted);margin-bottom:14px">یکی از ایمیل یا موبایل کافی است. رمز موقت را به‌صورت امن در اختیار کاربر قرار دهید.</p>
831 +<div class="form-row"><div class="form-group"><label>نام و نام خانوادگی</label><input id="admin-new-fullname" class="form-control"></div><div class="form-group"><label>نام کاربری</label><input id="admin-new-username" class="form-control" dir="ltr"></div></div>
832 +<div class="form-row"><div class="form-group"><label>ایمیل</label><input id="admin-new-email" class="form-control" dir="ltr" type="email"></div><div class="form-group"><label>موبایل</label><input id="admin-new-phone" class="form-control" dir="ltr" placeholder="0912..."></div></div>
833 +<div class="form-group"><label>رمز موقت</label><input id="admin-new-password" class="form-control" dir="ltr" type="password" autocomplete="new-password" placeholder="حداقل ۸ کاراکتر، حرف و عدد"></div>
834 +<div style="display:flex;gap:10px"><button class="btn btn-success" style="flex:1" onclick="adminCreateUser()">ایجاد کاربر</button><button class="btn btn-secondary" style="flex:1" onclick="adminCloseCreateUser()">انصراف</button></div>
835 +</div></div>
836 +<div class="modal-backdrop" id="modal-admin-reset-password">
837 +<div class="modal-card" style="max-width:520px"><h3 id="admin-reset-user-title" style="font-size:17px;margin-bottom:12px">تعیین رمز موقت</h3><input type="hidden" id="admin-reset-user-id"><div class="form-group"><label>رمز موقت جدید</label><input id="admin-reset-password" class="form-control" dir="ltr" type="password" autocomplete="new-password" placeholder="حداقل ۸ کاراکتر، حرف و عدد"></div><p style="font-size:12px;color:var(--text-muted);margin-bottom:14px">این عملیات رمز فعلی کاربر را جایگزین می‌کند. رمز را فقط از مسیر امن به خود کاربر بدهید.</p><div style="display:flex;gap:10px"><button class="btn btn-danger" style="flex:1" onclick="adminSetTemporaryPassword()">تغییر رمز</button><button class="btn btn-secondary" style="flex:1" onclick="adminClosePasswordReset()">انصراف</button></div></div></div>
838 +
839 <div class="modal-backdrop" id="modal-electronic-doc">
840 <div class="modal-card" style="max-width:850px">
841 <h3 style="font-size:16px;margin-bottom:6px">📄 سند الکترونیکی سامانه مودیان</h3>
@@ -870,8 +888,8 @@ body{background:#f6f9fc}
888 <div class="dock-tab" data-view="view-settings" onclick="switchView('view-settings')"><span>⚙️</span><span>تنظیمات</span></div>
889 </nav>
890
873 -<script src="js/core.js?v=20260928-security-v4"></script>
874 -<script src="js/admin.js"></script>
891 +<script src="js/core.js?v=20261007-identity-v1"></script>
892 +<script src="js/admin.js?v=20261007-admin-identity-v1"></script>
893 <script src="js/sync.js?v=20260928-data-v4"></script>
894 <script src="js/ui.js?v=20261002-shell-scroll-ownership-v2"></script>
895 <script src="js/invoices.js?v=20260928-phase3-final"></script>
@@ -915,7 +933,7 @@ body{background:#f6f9fc}
933 <script src="js/enterprise-iran.js?v=20260930-iran-erp-v1"></script>
934 <script src="js/enterprise-iran-v2.js?v=20260930-iran-erp-v2"></script>
935 <script src="js/selfcheck.js?v=20260928-release-1-0"></script>
918 -<script src="js/ux-hardening-r2.js?v=20261007-ux-r3"></script>
936 +<script src="js/ux-hardening-r2.js?v=20261007-ux-r4"></script>
937
938 </body>
939 </html>
js/admin.js
+17 -3
@@ -4,7 +4,7 @@ async function renderAdminPanel(){
4 if(!tbody||!currentUser||currentUser.role!=='admin')return;
5 tbody.innerHTML='<tr><td colspan="9" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr>';
6 const [p,l]=await Promise.all([
7 - sb.from('profiles').select('id,email,username,full_name,role,created_at').order('created_at',{ascending:false}),
7 + sb.from('profiles').select('id,email,phone,username,full_name,role,created_at').order('created_at',{ascending:false}),
8 sb.from('licenses').select('*')
9 ]);
10 if(p.error||l.error){tbody.innerHTML='<tr><td colspan="9" style="text-align:center;padding:20px;color:var(--danger)">خطا در دریافت لیست کاربران.</td></tr>';return;}
@@ -23,7 +23,7 @@ async function renderAdminPanel(){
23 const endJalali=sub.type==='lifetime'?'نامحدود':formatToJalali(sub.endDate);
24 const remDaysText=sub.type==='lifetime'?'نامحدود':toPersianDigits(Math.max(0,remDays))+' روز';
25 const uid=esc(u.id);
26 - const capacity=Math.max(1,Number(u.lic?.max_companies||1)),userCapacity=Math.max(1,Number(u.lic?.max_users||1));return `<tr><td><strong>${esc(u.full_name||u.email||u.username||'—')}</strong><small style="display:block;color:var(--text-muted)">${esc(u.email||'')}</small> ${u.role==='admin'?'<span class="badge badge-info">مدیر سیستم</span>':''}</td><td>${statusBadge}</td><td>${esc(planLabels[sub.type]||sub.type)}</td><td><strong>${toPersianDigits(capacity)}</strong> شرکت</td><td><strong>${toPersianDigits(userCapacity)}</strong> کاربر</td><td>${formatToJalali(sub.startDate)}</td><td>${endJalali}</td><td>${remDaysText}</td><td style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn btn-success btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminActivateLicense('${uid}')">فعال‌سازی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="openLicenseEditModal('${uid}')">اصلاح لایسنس</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminExtendSubscription('${uid}', 30)">+۳۰ روز</button>${sub.status!=='cancelled'?`<button class="btn btn-danger btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminCancelSubscription('${uid}')">لغو اشتراک</button>`:''}</td></tr>`;
26 + const capacity=Math.max(1,Number(u.lic?.max_companies||1)),userCapacity=Math.max(1,Number(u.lic?.max_users||1));return `<tr><td><strong>${esc(u.full_name||u.email||u.phone||u.username||'—')}</strong><small style="display:block;color:var(--text-muted)" dir="ltr">${esc(u.email||u.phone||'')}</small><small style="display:block;color:var(--text-muted)">@${esc(u.username||'—')}</small> ${u.role==='admin'?'<span class="badge badge-info">مدیر سیستم</span>':''}</td><td>${statusBadge}</td><td>${esc(planLabels[sub.type]||sub.type)}</td><td><strong>${toPersianDigits(capacity)}</strong> شرکت</td><td><strong>${toPersianDigits(userCapacity)}</strong> کاربر</td><td>${formatToJalali(sub.startDate)}</td><td>${endJalali}</td><td>${remDaysText}</td><td style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn btn-success btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminActivateLicense('${uid}')">فعال‌سازی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="openLicenseEditModal('${uid}')">اصلاح لایسنس</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminOpenPasswordReset('${uid}')">تعیین رمز موقت</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminExtendSubscription('${uid}', 30)">+۳۰ روز</button>${sub.status!=='cancelled'?`<button class="btn btn-danger btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminCancelSubscription('${uid}')">لغو اشتراک</button>`:''}</td></tr>`;
27 }).join('');
28 }
29 function refreshAdminPanel(){renderAdminPanel();}
@@ -51,7 +51,7 @@ function openLicenseEditModal(uid){
51 document.getElementById('modal-admin-license-edit').classList.add('active');
52 }
53 function closeLicenseEditModal(){document.getElementById('modal-admin-license-edit').classList.remove('active');}
54 -async function applyLicenseDurationChange(){const uid=document.getElementById('modal-license-target-username').value,plan=document.getElementById('modal-license-duration-select').value,u=adminUsersCache.find(x=>x.id===uid),ready=!!(u?.lic&&Object.prototype.hasOwnProperty.call(u.lic,'max_companies')),cap=Math.max(1,Math.min(1000,Number(document.getElementById('modal-license-company-limit')?.value||1)));closeLicenseEditModal();const ok=await adminRpc('admin_set_license',{target:uid,new_plan:plan,new_status:'active'},'');if(!ok)return false;if(ready)return adminRpc('admin_set_company_limit',{target:uid,new_max_companies:cap},'لایسنس و ظرفیت شرکت کاربر اعمال شد.');alert('طرح لایسنس اعمال شد. ظرفیت شرکت فعلاً روی پیش‌فرض ۱ باقی می‌ماند تا Migration ظرفیت شرکت در سرور اعمال شود.');return true;}
54 +async function applyLicenseDurationChange(){const uid=document.getElementById('modal-license-target-username').value,plan=document.getElementById('modal-license-duration-select').value,u=adminUsersCache.find(x=>x.id===uid),companyReady=!!(u?.lic&&Object.prototype.hasOwnProperty.call(u.lic,'max_companies')),userReady=!!(u?.lic&&Object.prototype.hasOwnProperty.call(u.lic,'max_users')),cap=Math.max(1,Math.min(1000,Number(document.getElementById('modal-license-company-limit')?.value||1))),users=Math.max(1,Math.min(100000,Number(document.getElementById('modal-license-user-limit')?.value||1)));closeLicenseEditModal();if(!await adminRpc('admin_set_license',{target:uid,new_plan:plan,new_status:'active'},''))return false;if(companyReady&&!await adminRpc('admin_set_company_limit',{target:uid,new_max_companies:cap},''))return false;if(userReady&&!await adminRpc('admin_set_user_limit',{target:uid,new_max_users:users},''))return false;alert('لایسنس، ظرفیت شرکت و ظرفیت کاربران اعمال شد.');renderAdminPanel();return true;}
55 function adminExtendSubscription(uid,days){
56 const u=adminUsersCache.find(x=>x.id===uid);
57 if(u&&u.lic&&u.lic.plan==='lifetime'){alert('این حساب دائمی است و نیازی به تمدید ندارد.');return;}
@@ -62,3 +62,17 @@ function adminCancelSubscription(uid){
62 if(!confirm('آیا از لغو اشتراک کاربر '+(u?(u.email||u.username):'')+' اطمینان دارید؟'))return;
63 return adminRpc('admin_cancel_license',{target:uid},'اشتراک کاربر لغو شد.');
64 }
65 +
66 +function adminOpenCreateUser(){['admin-new-fullname','admin-new-username','admin-new-email','admin-new-phone','admin-new-password'].forEach(id=>{const e=document.getElementById(id);if(e)e.value=''});document.getElementById('modal-admin-create-user')?.classList.add('active')}
67 +function adminCloseCreateUser(){document.getElementById('modal-admin-create-user')?.classList.remove('active')}
68 +async function adminInvokeIdentity(body){
69 + const {data,error}=await sb.functions.invoke('admin-user-management',{body});if(error){alert('خطا در مدیریت کاربر: '+(error.message||'عملیات ناموفق بود.'));return null}if(data?.error){alert('خطا: '+data.error);return null}return data;
70 +}
71 +async function adminCreateUser(){
72 + const full_name=String(document.getElementById('admin-new-fullname')?.value||'').trim(),username=String(document.getElementById('admin-new-username')?.value||'').trim(),email=normalizeEmail(document.getElementById('admin-new-email')?.value),phone=normalizePhone(document.getElementById('admin-new-phone')?.value),password=String(document.getElementById('admin-new-password')?.value||'');
73 + if(!email&&!phone)return alert('ایمیل یا شماره موبایل را وارد کنید.');if(email&&!EMAIL_RE.test(email))return alert('ایمیل معتبر نیست.');if(phone&&!PHONE_RE.test(phone))return alert('شماره موبایل را با فرمت 09xxxxxxxxx یا +989xxxxxxxxx وارد کنید.');if(!isStrongPassword(password))return alert('رمز موقت حداقل ۸ کاراکتر و شامل حرف و عدد باشد.');
74 + const data=await adminInvokeIdentity({action:'create',full_name,username,email,phone,password});if(!data)return;adminCloseCreateUser();alert('کاربر ایجاد شد. می‌توانید لایسنس و ظرفیت او را از همین جدول تنظیم کنید.');renderAdminPanel();
75 +}
76 +function adminOpenPasswordReset(uid){const u=adminUsersCache.find(x=>x.id===uid);if(!u)return;document.getElementById('admin-reset-user-id').value=uid;document.getElementById('admin-reset-user-title').textContent='تعیین رمز موقت برای '+(u.full_name||u.email||u.phone||u.username||'کاربر');document.getElementById('admin-reset-password').value='';document.getElementById('modal-admin-reset-password')?.classList.add('active')}
77 +function adminClosePasswordReset(){document.getElementById('modal-admin-reset-password')?.classList.remove('active')}
78 +async function adminSetTemporaryPassword(){const user_id=document.getElementById('admin-reset-user-id').value,password=String(document.getElementById('admin-reset-password').value||'');if(!isStrongPassword(password))return alert('رمز موقت حداقل ۸ کاراکتر و شامل حرف و عدد باشد.');if(!confirm('رمز ورود این کاربر تغییر کند؟'))return;const data=await adminInvokeIdentity({action:'set_password',user_id,password});if(!data)return;adminClosePasswordReset();alert('رمز موقت کاربر با موفقیت تنظیم شد.')}
js/core.js
+33 -24
@@ -43,10 +43,12 @@ let currentUser=null;
43 let authBusy=false;
44
45 const EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
46 +const PHONE_RE=/^(?:\+98|0)?9\d{9}$/;
47 const OTP_RE=/^[0-9]{6,10}$/;
47 -let otpEmail='',otpCooldownUntil=0,otpCreateUser=false,pendingAuthUser=null;
48 +let otpIdentity='',otpIdentityType='email',otpCooldownUntil=0,otpCreateUser=false,pendingAuthUser=null;
49
50 function normalizeEmail(raw){return String(raw||'').trim().toLowerCase();}
51 +function normalizePhone(raw){const v=toEnDigits(String(raw||'')).replace(/[\s()-]/g,'');if(/^09\d{9}$/.test(v))return '+98'+v.slice(1);if(/^9\d{9}$/.test(v))return '+98'+v;return v;}
52 function isStrongPassword(v){const s=String(v||'');return s.length>=8&&/[A-Za-z]/.test(s)&&/[0-9]/.test(s);}
53 function toEnDigits(s){
54 return String(s||'').replace(/[۰-۹]/g,d=>'۰۱۲۳۴۵۶۷۸۹'.indexOf(d)).replace(/[٠-٩]/g,d=>'٠١٢٣٤٥٦٧٨٩'.indexOf(d));
@@ -55,10 +57,10 @@ const PROFESSIONAL_ROLE_LABELS={business_owner:'مالک / مدیر کسب‌و
57 function buildUserFromRows(profile,lic){
58 const hasLicense=!!lic;
59 const sub=hasLicense?{type:lic.plan,startDate:lic.starts_at,endDate:lic.ends_at,status:lic.status}:{type:'none',startDate:null,endDate:null,status:'unavailable'};
58 - return {id:profile.id,email:profile.email||'',fullName:profile.full_name||'',username:profile.username||profile.email||'',role:profile.role,maxCompanies:hasLicense?Math.max(1,Number(lic.max_companies||1)):1,licenseCapacityServerReady:hasLicense&&Object.prototype.hasOwnProperty.call(lic,'max_companies'),subscription:sub,subscriptionType:sub.type,subscriptionStart:sub.startDate,subscriptionEnd:sub.endDate,licenseStatus:sub.status};
60 + return {id:profile.id,email:profile.email||'',phone:profile.phone||'',fullName:profile.full_name||'',username:profile.username||profile.email||profile.phone||'',role:profile.role,maxCompanies:hasLicense?Math.max(1,Number(lic.max_companies||1)):1,licenseCapacityServerReady:hasLicense&&Object.prototype.hasOwnProperty.call(lic,'max_companies'),subscription:sub,subscriptionType:sub.type,subscriptionStart:sub.startDate,subscriptionEnd:sub.endDate,licenseStatus:sub.status};
61 }
62 async function fetchCurrentUser(authUser){
61 - const p=await sb.from('profiles').select('id,email,username,full_name,role').eq('id',authUser.id).single();
63 + const p=await sb.from('profiles').select('id,email,phone,username,full_name,role').eq('id',authUser.id).single();
64 if(p.error)throw p.error;
65 return buildUserFromRows(p.data,null);
66 }
@@ -77,12 +79,12 @@ function requireWrite(){
79 function authMsg(err){
80 const m=(err&&err.message)||'';
81 const c=(err&&(err.code||err.error_code))||'';
80 - if(c==='invalid_credentials'||/Invalid login credentials/i.test(m))return 'ایمیل یا رمز عبور اشتباه است. اگر رمز ندارید یا فراموش کرده‌اید، «ادامه با کد ایمیل» را بزنید.';
82 + if(c==='invalid_credentials'||/Invalid login credentials/i.test(m))return 'ایمیل/موبایل یا رمز عبور اشتباه است. اگر رمز ندارید، «ورود با کد یک‌بارمصرف» را بزنید.';
83 if(c==='otp_expired'||/expired|invalid.*token|token.*invalid/i.test(m))return 'کد اشتباه است یا منقضی شده. دوباره کد بگیرید.';
84 if(c==='over_email_send_rate_limit'||c==='over_request_rate_limit'||/rate limit|too many|security purposes/i.test(m))return 'تعداد درخواست‌ها زیاد است؛ چند دقیقه بعد دوباره تلاش کنید.';
85 if(c==='email_address_invalid'||/email address.*invalid|unable to validate email/i.test(m))return 'آدرس ایمیل معتبر نیست.';
86 if(c==='email_not_confirmed'||/Email not confirmed/i.test(m))return 'ایمیل هنوز تأیید نشده است. از «ادامه با کد ایمیل» استفاده کنید.';
85 - if(c==='validation_failed'&&/provider/i.test(m)||/provider is not enabled|unsupported provider/i.test(m))return 'ورود با Google هنوز در سرور فعال نشده است.';
87 + if(/phone provider|sms provider|phone.*disabled|sms.*disabled/i.test(m))return 'ورود با موبایل آماده است اما سرویس SMS پروژه هنوز فعال/پیکربندی نشده است.';if(c==='validation_failed'&&/provider/i.test(m)||/provider is not enabled|unsupported provider/i.test(m))return 'ارائه‌دهنده ورود انتخاب‌شده هنوز در سرور فعال نشده است.';
88 if(c==='weak_password'||/password.*(weak|short|at least)/i.test(m))return 'رمز عبور ضعیف است؛ حداقل ۸ کاراکتر و ترکیب حروف و عدد استفاده کنید.';
89 if(c==='same_password'||/different from the old password/i.test(m))return 'رمز جدید باید با رمز قبلی فرق داشته باشد.';
90 if(/fetch|network|load failed|timeout|abort/i.test(m))return 'ارتباط با سرور برقرار نشد. اتصال اینترنت/VPN را بررسی کنید و دوباره تلاش کنید.';
@@ -119,13 +121,14 @@ async function initAuthSystem(){
121 }
122 async function handleLogin(){
123 if(authBusy)return;
122 - const email=normalizeEmail(document.getElementById('auth-email').value);
123 - const pass=document.getElementById('auth-password').value;
124 - if(!EMAIL_RE.test(email)){alert('آدرس ایمیل معتبر وارد کنید.');return;}
125 - if(!pass){alert('رمز عبور را وارد کنید؛ یا «ادامه با کد ایمیل» را بزنید.');return;}
124 + const raw=String(document.getElementById('auth-email').value||'').trim(),pass=document.getElementById('auth-password').value;
125 + const email=normalizeEmail(raw),phone=normalizePhone(raw),isEmail=EMAIL_RE.test(email),isPhone=PHONE_RE.test(phone);
126 + if(!isEmail&&!isPhone){alert('ایمیل یا شماره موبایل معتبر وارد کنید.');return;}
127 + if(!pass){alert('رمز عبور را وارد کنید؛ یا ورود با کد یک‌بارمصرف را بزنید.');return;}
128 authBusy=true;
129 try{
128 - const {data,error}=await sb.auth.signInWithPassword({email,password:pass});
130 + const credentials=isEmail?{email,password:pass}:{phone,password:pass};
131 + const {data,error}=await sb.auth.signInWithPassword(credentials);
132 if(error)throw error;
133 await enterApp(data.user);
134 }catch(err){alert(authMsg(err));}
@@ -139,22 +142,21 @@ async function signInWithGoogle(){
142 if(error)throw error;
143 }catch(err){authBusy=false;alert(authMsg(err));}
144 }
142 -async function startEmailOtp(isResend,createUser){
145 +async function startEmailOtp(isResend,createUser){return startIdentityOtp(isResend,createUser)}
146 +async function startIdentityOtp(isResend,createUser){
147 if(authBusy)return;
144 - const email=normalizeEmail(isResend===true?otpEmail:document.getElementById('auth-email').value);
145 - if(!EMAIL_RE.test(email)){alert('آدرس ایمیل معتبر وارد کنید.');return;}
148 + const raw=isResend===true?otpIdentity:String(document.getElementById('auth-email').value||'').trim(),email=normalizeEmail(raw),phone=normalizePhone(raw);
149 + const type=isResend===true?otpIdentityType:(EMAIL_RE.test(email)?'email':(PHONE_RE.test(phone)?'phone':''));
150 + if(!type){alert('ایمیل یا شماره موبایل معتبر وارد کنید.');return;}
151 if(Date.now()<otpCooldownUntil){alert('لطفاً حدود یک دقیقه بین درخواست‌ها صبر کنید.');return;}
147 - const allowCreate=isResend===true?otpCreateUser:createUser===true;
152 + const allowCreate=isResend===true?otpCreateUser:createUser===true,identity=type==='email'?email:phone;
153 authBusy=true;
154 try{
150 - const {error}=await sb.auth.signInWithOtp({email,options:{shouldCreateUser:allowCreate}});
151 - if(error)throw error;
152 - otpEmail=email;otpCreateUser=allowCreate;otpCooldownUntil=Date.now()+60000;
153 - document.getElementById('auth-otp-email-label').innerText=email;
154 - document.getElementById('auth-otp').value='';
155 - showAuthPanel('otp');
156 - }catch(err){alert(authMsg(err));}
157 - finally{authBusy=false;}
155 + const payload=type==='email'?{email,options:{shouldCreateUser:allowCreate}}:{phone,options:{shouldCreateUser:allowCreate}};
156 + const {error}=await sb.auth.signInWithOtp(payload);if(error)throw error;
157 + otpIdentity=identity;otpIdentityType=type;otpCreateUser=allowCreate;otpCooldownUntil=Date.now()+60000;
158 + document.getElementById('auth-otp-email-label').innerText=identity;document.getElementById('auth-otp').value='';showAuthPanel('otp');
159 + }catch(err){alert(authMsg(err));}finally{authBusy=false;}
160 }
161 async function verifyEmailOtp(){
162 if(authBusy)return;
@@ -162,7 +164,8 @@ async function verifyEmailOtp(){
164 if(!OTP_RE.test(token)){alert('کد را فقط با عدد و کامل وارد کنید.');return;}
165 authBusy=true;
166 try{
165 - const {data,error}=await sb.auth.verifyOtp({email:otpEmail,token,type:'email'});
167 + const verify=otpIdentityType==='email'?{email:otpIdentity,token,type:'email'}:{phone:otpIdentity,token,type:'sms'};
168 + const {data,error}=await sb.auth.verifyOtp(verify);
169 if(error)throw error;
170 const u=data.user;
171 const hasPassword=!!(u&&u.user_metadata&&u.user_metadata.has_password===true);
@@ -218,7 +221,7 @@ async function enterApp(authUser){
221 const authScreen=document.getElementById('auth-screen');
222 if(authScreen)authScreen.style.display='none';
223 const userLabel=document.getElementById('logged-user-label');
221 - if(userLabel)userLabel.innerText='کاربر: '+(currentUser.fullName||currentUser.email||currentUser.username)+(currentUser.role==='admin'?' (مدیر سیستم)':'');
224 + if(userLabel)userLabel.innerText='کاربر: '+(currentUser.fullName||currentUser.email||currentUser.phone||currentUser.username)+(currentUser.role==='admin'?' (مدیر سیستم)':'');const acctName=document.getElementById('acct-fullname'),acctUser=document.getElementById('acct-username');if(acctName)acctName.value=currentUser.fullName||'';if(acctUser)acctUser.value=currentUser.username||'';
225 // Admin visibility is derived from the verified role (see canShowShellCommand in ui.js), not from a DOM element.
226 document.body.classList.toggle('is-admin',currentUser.role==='admin');
227 try{refreshAllSurfaces();}catch(e){console.error('refreshAllSurfaces failed',e);}
@@ -252,3 +255,9 @@ function updateLicenseDisplay(user){
255 badge.className='badge badge-warning';badge.innerText=`وضعیت اشتراک : آزمایشی تا تاریخ ${formatToJalali(sub.endDate)}`;
256 }
257 }
258 +
259 +async function saveMyIdentityProfile(){
260 + if(!currentUser)return;const username=String(document.getElementById('acct-username')?.value||'').trim().toLowerCase(),full=String(document.getElementById('acct-fullname')?.value||'').trim();
261 + const {error}=await sb.rpc('update_my_identity_profile',{new_username:username,new_full_name:full||null});if(error){alert('خطا در ذخیره نام کاربری: '+(error.message||''));return}
262 + currentUser.username=username;if(full)currentUser.fullName=full;alert('مشخصات حساب ذخیره شد.');
263 +}
js/ux-hardening-r2.js
+1 -1
@@ -37,7 +37,7 @@
37 const modals=[...document.querySelectorAll('.modal-backdrop.active')];if(!modals.length)return false;const m=modals[modals.length-1],cancel=[...m.querySelectorAll('button')].find(b=>/انصراف|بستن|لغو|✕/.test(b.textContent||''));if(cancel){cancel.click();return true}m.classList.remove('active');return true;
38 }
39 window.finoraCloseTopModal=closeTopModal;
40 - const THEME_CSS=`body.finora-theme-dark{--bg:#07111f;--surface:#0f1b2d;--card:#122238;--text:#e6edf7;--text-muted:#9db0c9;--border:#263a55;--primary:#22b8c7;color:var(--text);background:var(--bg)}body.finora-theme-dark .card,body.finora-theme-dark .modal-card,body.finora-theme-dark input,body.finora-theme-dark select,body.finora-theme-dark textarea{background:#122238!important;color:#e6edf7!important;border-color:#2b405d!important}body.finora-theme-dark table th,body.finora-theme-dark table td{border-color:#2b405d!important}body.finora-theme-dark .form-row[style*="background"]{background:#0d1a2c!important}`;
40 + const THEME_CSS=`body.finora-theme-dark{--bg:#07111f;--surface:#0f1b2d;--card:#122238;--card-bg:#122238;--text:#f1f5f9;--text-muted:#b7c5d8;--border:#36506f;--primary:#38c5d3;color:var(--text);background:var(--bg);color-scheme:dark}body.finora-theme-dark .main-surface,body.finora-theme-dark .sidebar,body.finora-theme-dark .card,body.finora-theme-dark .modal-card,body.finora-theme-dark .accordion-item,body.finora-theme-dark .accordion-body,body.finora-theme-dark .accordion-header,body.finora-theme-dark input,body.finora-theme-dark select,body.finora-theme-dark textarea{background:#122238!important;color:#f1f5f9!important;border-color:#36506f!important}body.finora-theme-dark .form-group label,body.finora-theme-dark th,body.finora-theme-dark td,body.finora-theme-dark h1,body.finora-theme-dark h2,body.finora-theme-dark h3,body.finora-theme-dark h4,body.finora-theme-dark strong,body.finora-theme-dark .sidebar-menu li a{color:#f1f5f9!important}body.finora-theme-dark table th{background:#192d47!important}body.finora-theme-dark table td{background:#102038!important}body.finora-theme-dark table th,body.finora-theme-dark table td{border-color:#36506f!important}body.finora-theme-dark .btn-secondary{background:#29415f!important;color:#f8fafc!important}body.finora-theme-dark [style*="background:#eff6ff"],body.finora-theme-dark [style*="background: #eff6ff"],body.finora-theme-dark .form-row[style*="background"]{background:#172c46!important;color:#f1f5f9!important;border-color:#36506f!important}body.finora-theme-dark input::placeholder,body.finora-theme-dark textarea::placeholder{color:#91a4bd!important;opacity:1}`;
41 function ensureThemeCss(){if($('finora-theme-r2-css'))return;const s=document.createElement('style');s.id='finora-theme-r2-css';s.textContent=THEME_CSS;document.head.appendChild(s)}
42 function resolveTheme(mode){if(mode==='dark'||mode==='light')return mode;const h=new Date().getHours();return h>=7&&h<19?'light':'dark'}
43 window.finoraApplyTheme=function(){ensureThemeCss();const mode=getMySettings()?.ui_theme||'auto',r=resolveTheme(mode);document.body.classList.toggle('finora-theme-dark',r==='dark');document.documentElement.dataset.finoraTheme=r}
scripts/admin-identity-phone-check.mjs new
+11
@@ -0,0 +1,11 @@
1 +import fs from 'node:fs';
2 +function ok(v,m){if(!v)throw new Error(m)}
3 +const html=fs.readFileSync('index.html','utf8'),core=fs.readFileSync('js/core.js','utf8'),admin=fs.readFileSync('js/admin.js','utf8'),ux=fs.readFileSync('js/ux-hardening-r2.js','utf8'),sql=fs.readFileSync('supabase/migrations/20261007163500_phone_identity_profile.sql','utf8'),edge=fs.readFileSync('supabase/functions/admin-user-management/index.ts','utf8');
4 +ok(html.includes('ایجاد کاربر جدید')&&html.includes('modal-admin-reset-password'),'Admin must expose create-user and temporary-password controls.');
5 +ok(admin.includes("admin_set_user_limit")&&admin.includes('new_max_users:users'),'License edit must persist named-user capacity.');
6 +ok(admin.includes("sb.functions.invoke('admin-user-management'")&&edge.includes('profile?.role!=="admin"'),'Privileged identity mutations must use an admin-verified server boundary.');
7 +ok(edge.includes('admin.auth.admin.createUser')&&edge.includes('admin.auth.admin.updateUserById'),'Server boundary must support user creation and password reset.');
8 +ok(core.includes("signInWithPassword(credentials)")&&core.includes("{phone,password:pass}")&&core.includes("type:'sms'"),'Client auth must support phone password and SMS OTP.');
9 +ok(sql.includes('alter column email drop not null')&&sql.includes('add column if not exists phone')&&sql.includes('update_my_identity_profile'),'Database identity bootstrap must support phone-only users and self-service username.');
10 +ok(ux.includes('--card-bg:#122238')&&ux.includes('.form-group label')&&ux.includes('table td{background:#102038'),'Dark theme must explicitly preserve readable surfaces and text.');
11 +console.log('Admin identity, phone auth and dark-mode invariants passed.');
scripts/admin-identity-phone.spec.js new
+9
@@ -0,0 +1,9 @@
1 +import{test,expect}from'@playwright/test';import path from'node:path';
2 +test('dark mode keeps settings labels, fields and tables readable',async({page})=>{
3 + await page.setContent('<body><main class="main-surface"><div class="card"><div class="form-group"><label>نام</label><input class="form-control" value="نمونه"></div><table><thead><tr><th>کاربر</th></tr></thead><tbody><tr><td>داود</td></tr></tbody></table></div></main><section id="view-settings"></section></body>');
4 + await page.addScriptTag({content:"var currentUser={id:'U1'},datastore={settings:[{ownerUserId:'U1',ui_theme:'dark'}],products:[],contacts:[],companies:[],accounts:[],projects:[],invoices:[],purchases:[],cheques:[],journalVouchers:[]};var FINORA_MODULES={settings:{groups:[]}};function getMySettings(){return datastore.settings[0]}function getMyProducts(){return []}function getMyContacts(){return []}function getMyCompanies(){return []}function getMyAccounts(){return []}function getMyGlobalProjects(){return []}function requireWrite(){return true}function saveDatastore(){}function toggleAccordion(){}function esc(v){return String(v)}"});
5 + await page.addScriptTag({path:path.resolve('js/ux-hardening-r2.js')});await page.evaluate(()=>{document.dispatchEvent(new Event('DOMContentLoaded'));finoraApplyTheme()});
6 + await expect(page.locator('body')).toHaveClass(/finora-theme-dark/);
7 + const colors=await page.evaluate(()=>({label:getComputedStyle(document.querySelector('label')).color,input:getComputedStyle(document.querySelector('input')).color,td:getComputedStyle(document.querySelector('td')).color,bg:getComputedStyle(document.querySelector('td')).backgroundColor}));
8 + expect(colors.label).toBe('rgb(241, 245, 249)');expect(colors.input).toBe('rgb(241, 245, 249)');expect(colors.td).toBe('rgb(241, 245, 249)');expect(colors.bg).toBe('rgb(16, 32, 56)');
9 +});
scripts/identity-wave5a-check.mjs
+1 -1
@@ -2,7 +2,7 @@ import fs from 'node:fs';import assert from 'node:assert/strict';
2 const core=fs.readFileSync('js/core.js','utf8'),invite=fs.readFileSync('js/organization-invitations.js','utf8'),html=fs.readFileSync('index.html','utf8'),migration=fs.readFileSync('supabase/migrations/20261002080000_identity_wave5a_bootstrap.sql','utf8');
3 assert(!core.includes("sb.from('licenses').select('*').eq('user_id',authUser.id).single()"),'base identity bootstrap must not require personal license');
4 assert(core.includes('shouldCreateUser:allowCreate'),'OTP creation must be explicitly mode-bound');
5 -assert(html.includes('startEmailOtp(false,false)')&&html.includes('startEmailOtp(false,true)'),'OTP login/signup actions must be explicit');
5 +assert(html.includes('startIdentityOtp(false,false)')&&html.includes('startIdentityOtp(false,true)'),'OTP login/signup actions must be explicit for email or phone');
6 assert(invite.indexOf('await window.processFinoraInvitationFromUrl();')<invite.indexOf('return baseEnterAppInvitation(authUser);'),'invitation must be accepted before organization bootstrap');
7 for(const s of ['insert into public.organizations','insert into public.organization_members','insert into public.licenses','organization_id'])assert(migration.includes(s),s+' missing');
8 console.log('Wave 5a identity/bootstrap invariants passed');
scripts/ux-hardening-r2-check.mjs
+1 -1
@@ -8,7 +8,7 @@ const purchases=fs.readFileSync('js/purchases.js','utf8');
8 const commerce=fs.readFileSync('js/commercial-rnd.js','utf8');
9 const print=fs.readFileSync('js/print.js','utf8');
10 const ok=(v,m)=>{if(!v)throw new Error(m)};
11 -ok(index.includes('js/ux-hardening-r2.js?v=20261007-ux-r3'),'UX R2 module must be loaded.');
11 +ok(index.includes('js/ux-hardening-r2.js?v=20261007-ux-r4'),'UX R2 module must be loaded.');
12 ok(projects.includes('getMyGlobalProjects')&&projects.includes('attachExistingProject')&&projects.includes('linkedContactIds'),'Counterparty project management must reuse global project master data.');
13 ok(projects.includes('createAndAttachProject')&&projects.includes('openProjectAttachModal'),'Counterparty project UI must support select-existing or create-new in place.');
14 ok(ux.includes('select.options.length<8')&&ux.includes('finora-combobox-input')&&ux.includes('finora-combobox-option')&&!ux.includes('finora-select-search'),'Large selectors must use one integrated searchable combobox, not a separate search field plus select.');
supabase/functions/admin-user-management/index.ts new
+34
@@ -0,0 +1,34 @@
1 +import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
2 +const cors={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"authorization, x-client-info, apikey, content-type","Content-Type":"application/json"};
3 +const json=(status:number,body:unknown)=>new Response(JSON.stringify(body),{status,headers:cors});
4 +Deno.serve(async(req)=>{
5 + if(req.method==="OPTIONS")return new Response("ok",{headers:cors});
6 + if(req.method!=="POST")return json(405,{error:"method_not_allowed"});
7 + const url=Deno.env.get("SUPABASE_URL")!,anon=Deno.env.get("SUPABASE_ANON_KEY")!,service=Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
8 + const auth=req.headers.get("Authorization")||"";
9 + const caller=createClient(url,anon,{global:{headers:{Authorization:auth}},auth:{persistSession:false}});
10 + const {data:{user},error:userErr}=await caller.auth.getUser();
11 + if(userErr||!user)return json(401,{error:"unauthorized"});
12 + const admin=createClient(url,service,{auth:{persistSession:false,autoRefreshToken:false}});
13 + const {data:profile}=await admin.from("profiles").select("role").eq("id",user.id).single();
14 + if(profile?.role!=="admin")return json(403,{error:"admin_required"});
15 + let body:any={};try{body=await req.json()}catch{return json(400,{error:"invalid_json"})}
16 + const action=String(body.action||"");
17 + if(action==="create"){
18 + const full_name=String(body.full_name||"").trim().slice(0,120),username=String(body.username||"").trim().toLowerCase();
19 + const password=String(body.password||"");if(password.length<8||!/[A-Za-z]/.test(password)||!/[0-9]/.test(password))return json(400,{error:"weak_password"});
20 + const email=String(body.email||"").trim().toLowerCase(),phone=String(body.phone||"").trim();
21 + if(!email&&!phone)return json(400,{error:"email_or_phone_required"});
22 + const attrs:any={password,user_metadata:{full_name,username}};if(email){attrs.email=email;attrs.email_confirm=true}else{attrs.phone=phone;attrs.phone_confirm=true}
23 + const {data,error}=await admin.auth.admin.createUser(attrs);if(error)return json(400,{error:error.message});
24 + return json(200,{ok:true,user_id:data.user?.id});
25 + }
26 + if(action==="set_password"){
27 + const target=String(body.user_id||""),password=String(body.password||"");
28 + if(!target)return json(400,{error:"user_id_required"});
29 + if(password.length<8||!/[A-Za-z]/.test(password)||!/[0-9]/.test(password))return json(400,{error:"weak_password"});
30 + const {error}=await admin.auth.admin.updateUserById(target,{password,user_metadata:{force_password_change:true}});if(error)return json(400,{error:error.message});
31 + return json(200,{ok:true});
32 + }
33 + return json(400,{error:"unsupported_action"});
34 +});
\ No newline at end of file
supabase/migrations/20261007163500_phone_identity_profile.sql new
+36
@@ -0,0 +1,36 @@
1 +-- Phone-capable identity bootstrap and self-service profile aliases.
2 +alter table public.profiles alter column email drop not null;
3 +alter table public.profiles add column if not exists phone text;
4 +create unique index if not exists profiles_phone_unique on public.profiles(phone) where phone is not null;
5 +
6 +create or replace function public.handle_new_user()
7 +returns trigger
8 +language plpgsql security definer set search_path=''
9 +as $$
10 +declare v_username text;v_org_name text;v_org_id uuid;v_identity text;
11 +begin
12 + v_identity:=coalesce(nullif(lower(new.email),''),nullif(new.phone,''));
13 + if v_identity is null then raise exception 'Finora requires an email or phone identity for signup';end if;
14 + v_username:=lower(coalesce(nullif(new.raw_user_meta_data->>'username',''),case when new.email is not null then split_part(new.email,'@',1) else regexp_replace(new.phone,'[^0-9+]','','g') end));
15 + v_org_name:=left(coalesce(nullif(trim(new.raw_user_meta_data->>'full_name'),''),nullif(trim(new.raw_user_meta_data->>'name'),''),nullif(v_username,''),'Finora')||' - شخصی',160);
16 + insert into public.profiles(id,email,phone,username,role,full_name)
17 + values(new.id,case when new.email is null then null else lower(new.email) end,new.phone,v_username,'user',nullif(trim(coalesce(new.raw_user_meta_data->>'full_name',new.raw_user_meta_data->>'name','')),''));
18 + insert into public.organizations(owner_user_id,name,status) values(new.id,v_org_name,'active') returning id into v_org_id;
19 + insert into public.organization_members(organization_id,user_id,status,is_owner) values(v_org_id,new.id,'active',true);
20 + insert into public.licenses(user_id,organization_id,plan,status,starts_at,ends_at,max_companies,max_users,modules,limits)
21 + values(new.id,v_org_id,'trial','trial',current_date,current_date+15,1,1,array['full_suite']::text[],'{}'::jsonb);
22 + return new;
23 +end $$;
24 +revoke all on function public.handle_new_user() from public,anon,authenticated;
25 +
26 +create or replace function public.update_my_identity_profile(new_username text,new_full_name text default null)
27 +returns void language plpgsql security definer set search_path='' as $$
28 +declare v_uid uuid:=auth.uid();v_username text:=lower(trim(coalesce(new_username,'')));
29 +begin
30 + if v_uid is null then raise exception 'Authentication required';end if;
31 + if v_username !~ '^[a-z0-9_.-]{3,40}$' then raise exception 'Username must be 3-40 latin letters, digits, dot, underscore or dash';end if;
32 + if exists(select 1 from public.profiles where lower(username)=v_username and id<>v_uid) then raise exception 'Username already in use';end if;
33 + update public.profiles set username=v_username,full_name=coalesce(nullif(trim(new_full_name),''),full_name) where id=v_uid;
34 +end $$;
35 +revoke all on function public.update_my_identity_profile(text,text) from public,anon;
36 +grant execute on function public.update_my_identity_profile(text,text) to authenticated;
supabase/tests/identity_wave5a_bootstrap.sql
+2 -1
@@ -4,7 +4,8 @@ do $$ begin
4 if not exists(select 1 from pg_roles where rolname='authenticated') then create role authenticated nologin; end if;
5 end $$;
6 create schema if not exists auth;
7 -create table auth.users(id uuid primary key,email text,raw_user_meta_data jsonb not null default '{}'::jsonb);
7 +create or replace function auth.uid() returns uuid language sql stable as $$ select null::uuid $$;
8 +create table auth.users(id uuid primary key,email text,phone text,raw_user_meta_data jsonb not null default '{}'::jsonb);
9 create table public.profiles(id uuid primary key references auth.users(id) on delete cascade,username text,role text not null default 'user',created_at timestamptz not null default now(),email text not null,full_name text);
10 create table public.organizations(id uuid primary key default gen_random_uuid(),owner_user_id uuid not null references public.profiles(id) on delete restrict,name text not null check(char_length(trim(name)) between 1 and 160),status text not null default 'active' check(status in('active','suspended')),created_at timestamptz not null default now(),updated_at timestamptz not null default now());
11 create table public.organization_members(id uuid primary key default gen_random_uuid(),organization_id uuid not null references public.organizations(id) on delete cascade,user_id uuid not null references public.profiles(id) on delete cascade,unit_id uuid,position_title text,status text not null default 'active' check(status in('active','suspended','left')),is_owner boolean not null default false,created_at timestamptz not null default now(),updated_at timestamptz not null default now(),unique(organization_id,user_id));
supabase/tests/phone_identity_behavior.sql new
+8
@@ -0,0 +1,8 @@
1 +do $$
2 +declare u uuid:=gen_random_uuid();
3 +begin
4 + insert into auth.users(id,email,phone,raw_user_meta_data) values(u,null,'+989121234567','{"full_name":"Phone User","username":"phone.user"}'::jsonb);
5 + if not exists(select 1 from public.profiles where id=u and email is null and phone='+989121234567' and username='phone.user') then raise exception 'phone profile bootstrap failed';end if;
6 + if not exists(select 1 from public.organizations where owner_user_id=u) then raise exception 'phone organization bootstrap failed';end if;
7 + if not exists(select 1 from public.licenses where user_id=u and max_companies=1 and max_users=1) then raise exception 'phone license bootstrap failed';end if;
8 +end $$;