@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 8040699
Fork 0

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

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 17:00 UTC

Add split js/ modules: core, admin, sync, ui (part 1/4)

davoodmehraban89 committed Sep 26, 2026 at 03:40 UTC 8040699ecc2df845bec3468d1445d5505f1ed4c0
4 files changed +558
js/admin.js new
+65
@@ -0,0 +1,65 @@
1 +let adminUsersCache=[];
2 +async function renderAdminPanel(){
3 + const tbody=document.getElementById('admin-users-table-body');
4 + if(!tbody||!currentUser||currentUser.role!=='admin')return;
5 + tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr>';
6 + const [p,l]=await Promise.all([
7 + sb.from('profiles').select('id,email,username,role,created_at').order('created_at',{ascending:false}),
8 + sb.from('licenses').select('user_id,plan,status,starts_at,ends_at')
9 + ]);
10 + if(p.error||l.error){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px;color:var(--danger)">خطا در دریافت لیست کاربران.</td></tr>';return;}
11 + const lic=new Map((l.data||[]).map(x=>[x.user_id,x]));
12 + adminUsersCache=(p.data||[]).map(u=>Object.assign({},u,{lic:lic.get(u.id)||null}));
13 + if(adminUsersCache.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px">هیچ کاربری یافت نشد.</td></tr>';return;}
14 + const planLabels={monthly:'طرح ۱ ماهه',three_months:'طرح ۳ ماهه',annual:'طرح ۱ ساله',lifetime:'دائمی (Lifetime)',trial:'آزمایشی (Trial)'};
15 + tbody.innerHTML=adminUsersCache.map(u=>{
16 + const sub=u.lic?{type:u.lic.plan,startDate:u.lic.starts_at,endDate:u.lic.ends_at,status:u.lic.status}:{type:'trial',startDate:'',endDate:'',status:'cancelled'};
17 + const remDays=getRemainingDays(sub.endDate);
18 + const isExp=remDays<=0&&sub.type!=='lifetime';
19 + let statusBadge='';
20 + if(sub.status==='cancelled')statusBadge='<span class="badge badge-danger">لغو شده</span>';
21 + else if(sub.status==='active')statusBadge=isExp?'<span class="badge badge-danger">منقضی شده</span>':'<span class="badge badge-success">فعال</span>';
22 + else statusBadge=isExp?'<span class="badge badge-danger">آزمایشی منقضی</span>':'<span class="badge badge-warning">آزمایشی</span>';
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 + return `<tr><td><strong>${esc(u.email||u.username||'—')}</strong> ${u.role==='admin'?'<span class="badge badge-info">مدیر</span>':''}</td><td>${statusBadge}</td><td>${esc(planLabels[sub.type]||sub.type)}</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>`;
27 + }).join('');
28 +}
29 +function refreshAdminPanel(){renderAdminPanel();}
30 +async function adminRpc(name,args,okMsg){
31 + const {error}=await sb.rpc(name,args);
32 + if(error){alert('خطا: '+(error.message||'عملیات ناموفق بود.'));return false;}
33 + if(okMsg)alert(okMsg);
34 + if(currentUser&&args.target===currentUser.id){try{currentUser=await fetchCurrentUser({id:currentUser.id});updateLicenseDisplay(currentUser);}catch(e){}}
35 + renderAdminPanel();
36 + return true;
37 +}
38 +function adminActivateLicense(uid){
39 + return adminRpc('admin_set_license',{target:uid,new_plan:'monthly',days:30,new_status:'active'},'لایسنس ۱ ماهه فعال شد.');
40 +}
41 +function openLicenseEditModal(uid){
42 + const u=adminUsersCache.find(x=>x.id===uid);if(!u)return;
43 + document.getElementById('modal-license-target-username').value=uid;
44 + document.getElementById('modal-license-user-title').innerText='تغییر مدت و نوع لایسنس: '+(u.email||u.username);
45 + const cur=u.lic&&u.lic.plan!=='trial'?u.lic.plan:'monthly';
46 + document.getElementById('modal-license-duration-select').value=cur;
47 + document.getElementById('modal-admin-license-edit').classList.add('active');
48 +}
49 +function closeLicenseEditModal(){document.getElementById('modal-admin-license-edit').classList.remove('active');}
50 +function applyLicenseDurationChange(){
51 + const uid=document.getElementById('modal-license-target-username').value;
52 + const plan=document.getElementById('modal-license-duration-select').value;
53 + closeLicenseEditModal();
54 + return adminRpc('admin_set_license',{target:uid,new_plan:plan,new_status:'active'},'طرح لایسنس کاربر تغییر یافت.');
55 +}
56 +function adminExtendSubscription(uid,days){
57 + const u=adminUsersCache.find(x=>x.id===uid);
58 + if(u&&u.lic&&u.lic.plan==='lifetime'){alert('این حساب دائمی است و نیازی به تمدید ندارد.');return;}
59 + return adminRpc('admin_extend_license',{target:uid,days},'اشتراک کاربر '+days+' روز تمدید شد.');
60 +}
61 +function adminCancelSubscription(uid){
62 + const u=adminUsersCache.find(x=>x.id===uid);
63 + if(!confirm('آیا از لغو اشتراک کاربر '+(u?(u.email||u.username):'')+' اطمینان دارید؟'))return;
64 + return adminRpc('admin_cancel_license',{target:uid},'اشتراک کاربر لغو شد.');
65 +}
js/core.js new
+245
@@ -0,0 +1,245 @@
1 +const STORAGE_KEY = 'easy_factor_commercial_v4_7';
2 +const AUTH_KEY = 'easy_factor_auth_users_v4_7';
3 +
4 +window.pendingElectronicDoc = null;
5 +
6 +function toPersianDigits(str){if(str===null||str===undefined)return '';return String(str).replace(/[0-9]/g,d=>'۰۱۲۳۴۵۶۷۸۹'[d]);}
7 +function formatToJalali(dateInput){
8 + if(!dateInput)return '—';
9 + let dateObj;
10 + if(dateInput instanceof Date)dateObj=dateInput;
11 + else if(typeof dateInput==='string'&&dateInput.includes('/'))return toPersianDigits(dateInput);
12 + else{const str=String(dateInput).split('T')[0];const parts=str.split('-');if(parts.length===3)dateObj=new Date(parseInt(parts[0]),parseInt(parts[1])-1,parseInt(parts[2]),12,0,0);else dateObj=new Date(dateInput);}
13 + if(isNaN(dateObj.getTime()))return toPersianDigits(String(dateInput));
14 + return new Intl.DateTimeFormat('fa-IR-u-ca-persian',{year:'numeric',month:'2-digit',day:'2-digit'}).format(dateObj);
15 +}
16 +function getRemainingDays(endDateStr){
17 + if(!endDateStr)return 0;
18 + if(String(endDateStr).startsWith('2099'))return Infinity;
19 + const str=String(endDateStr).split('T')[0];const parts=str.split('-');
20 + if(parts.length!==3)return 0;
21 + const end=new Date(parseInt(parts[0]),parseInt(parts[1])-1,parseInt(parts[2]),23,59,59);
22 + return Math.ceil((end.getTime()-new Date().getTime())/(1000*60*60*24));
23 +}
24 +function addDaysToDate(baseDateStr,days){
25 + let d;
26 + if(baseDateStr){const parts=String(baseDateStr).split('T')[0].split('-');d=new Date(parseInt(parts[0]),parseInt(parts[1])-1,parseInt(parts[2]),12,0,0);}
27 + else{const tp=todayISO().split('-');d=new Date(parseInt(tp[0]),parseInt(tp[1])-1,parseInt(tp[2]),12,0,0);}
28 + if(isNaN(d.getTime()))d=new Date();
29 + d.setDate(d.getDate()+days);
30 + return d.toISOString().split('T')[0];
31 +}
32 +
33 +const SUPABASE_URL='https://hcsixhqbyuhpshfwqpjx.supabase.co';
34 +const SUPABASE_KEY='sb_publishable_2y8IsGdhqeLDPkEp7mBF4w_X4yji16D'; // publishable (public by design); access is enforced by RLS on the server
35 +const sb=window.supabase.createClient(SUPABASE_URL,SUPABASE_KEY,{auth:{persistSession:true,autoRefreshToken:true,detectSessionInUrl:true,flowType:'pkce'}});
36 +const ID_RE=/^[A-Za-z0-9_-]{1,64}$/;
37 +const COLLS=['companies','contacts','products','invoices','cheques','expenses','settings'];
38 +
39 +function esc(v){return String(v==null?'':v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');}
40 +function todayISO(){return new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Tehran',year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());}
41 +
42 +let currentUser=null;
43 +let authBusy=false;
44 +
45 +const EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
46 +const OTP_RE=/^[0-9]{6,10}$/;
47 +let otpEmail='',otpCooldownUntil=0,pendingAuthUser=null;
48 +
49 +function normalizeEmail(raw){return String(raw||'').trim().toLowerCase();}
50 +function toEnDigits(s){
51 + return String(s||'').replace(/[۰-۹]/g,d=>'۰۱۲۳۴۵۶۷۸۹'.indexOf(d)).replace(/[٠-٩]/g,d=>'٠١٢٣٤٥٦٧٨٩'.indexOf(d));
52 +}
53 +function buildUserFromRows(profile,lic){
54 + const sub={type:lic.plan,startDate:lic.starts_at,endDate:lic.ends_at,status:lic.status};
55 + return {id:profile.id,email:profile.email||'',fullName:profile.full_name||'',username:profile.username||profile.email||'',role:profile.role,subscription:sub,subscriptionType:sub.type,subscriptionStart:sub.startDate,subscriptionEnd:sub.endDate,licenseStatus:sub.status};
56 +}
57 +async function fetchCurrentUser(authUser){
58 + const [p,l]=await Promise.all([
59 + sb.from('profiles').select('id,email,username,full_name,role').eq('id',authUser.id).single(),
60 + sb.from('licenses').select('plan,status,starts_at,ends_at').eq('user_id',authUser.id).single()
61 + ]);
62 + if(p.error)throw p.error;
63 + if(l.error)throw l.error;
64 + return buildUserFromRows(p.data,l.data);
65 +}
66 +function canWrite(){
67 + if(!currentUser)return false;
68 + const s=currentUser.subscription||{};
69 + if(s.status!=='active'&&s.status!=='trial')return false;
70 + if(s.type==='lifetime')return true;
71 + return String(s.endDate||'')>=todayISO();
72 +}
73 +function requireWrite(){
74 + if(canWrite())return true;
75 + alert('اشتراک شما منقضی یا لغو شده است؛ امکان ثبت یا ویرایش اطلاعات وجود ندارد. اطلاعات قبلی شما همچنان قابل مشاهده و پشتیبان‌گیری است. برای تمدید با پشتیبانی تماس بگیرید.');
76 + return false;
77 +}
78 +function authMsg(err){
79 + const m=(err&&err.message)||'';
80 + const c=(err&&(err.code||err.error_code))||'';
81 + if(c==='invalid_credentials'||/Invalid login credentials/i.test(m))return 'ایمیل یا رمز عبور اشتباه است. اگر رمز ندارید یا فراموش کرده‌اید، «ادامه با کد ایمیل» را بزنید.';
82 + if(c==='otp_expired'||/expired|invalid.*token|token.*invalid/i.test(m))return 'کد اشتباه است یا منقضی شده. دوباره کد بگیرید.';
83 + if(c==='over_email_send_rate_limit'||c==='over_request_rate_limit'||/rate limit|too many|security purposes/i.test(m))return 'تعداد درخواست‌ها زیاد است؛ چند دقیقه بعد دوباره تلاش کنید.';
84 + if(c==='email_address_invalid'||/email address.*invalid|unable to validate email/i.test(m))return 'آدرس ایمیل معتبر نیست.';
85 + if(c==='email_not_confirmed'||/Email not confirmed/i.test(m))return 'ایمیل هنوز تأیید نشده است. از «ادامه با کد ایمیل» استفاده کنید.';
86 + if(c==='validation_failed'&&/provider/i.test(m)||/provider is not enabled|unsupported provider/i.test(m))return 'ورود با Google هنوز در سرور فعال نشده است.';
87 + if(c==='weak_password'||/password.*(weak|short|at least)/i.test(m))return 'رمز عبور ضعیف است؛ حداقل ۸ کاراکتر و ترکیب حروف و عدد استفاده کنید.';
88 + if(c==='same_password'||/different from the old password/i.test(m))return 'رمز جدید باید با رمز قبلی فرق داشته باشد.';
89 + if(/fetch|network|load failed|timeout|abort/i.test(m))return 'ارتباط با سرور برقرار نشد. اتصال اینترنت/VPN را بررسی کنید و دوباره تلاش کنید.';
90 + return 'خطا: '+m;
91 +}
92 +function showAuthPanel(name){
93 + const ids={main:'auth-form-container',otp:'auth-otp-container',setpass:'auth-setpass-container'};
94 + Object.keys(ids).forEach(k=>{const el=document.getElementById(ids[k]);if(el)el.style.display=(k===name)?'block':'none';});
95 +}
96 +function backToAuthMain(){pendingAuthUser=null;showAuthPanel('main');}
97 +function reportOAuthReturnError(){
98 + try{
99 + const q=new URLSearchParams(window.location.search);
100 + const h=new URLSearchParams((window.location.hash||'').replace(/^#/,''));
101 + const desc=q.get('error_description')||h.get('error_description');
102 + if(desc){
103 + alert('ورود با Google انجام نشد: '+desc.replace(/\+/g,' '));
104 + window.history.replaceState({},document.title,window.location.pathname);
105 + }
106 + }catch(e){}
107 +}
108 +async function initAuthSystem(){
109 + // Remove the legacy plaintext user database that older versions kept in this browser.
110 + try{localStorage.removeItem(AUTH_KEY);}catch(e){}
111 + try{sessionStorage.removeItem('easy_factor_session_v4_7');}catch(e){}
112 + reportOAuthReturnError();
113 + sb.auth.onAuthStateChange(ev=>{if(ev==='SIGNED_OUT'&&currentUser){window.location.reload();}});
114 + try{
115 + const {data}=await sb.auth.getSession();
116 + if(data&&data.session){await enterApp(data.session.user);return;}
117 + }catch(e){console.error(e);}
118 + document.getElementById('auth-screen').style.display='flex';
119 + showAuthPanel('main');
120 +}
121 +async function handleLogin(){
122 + if(authBusy)return;
123 + const email=normalizeEmail(document.getElementById('auth-email').value);
124 + const pass=document.getElementById('auth-password').value;
125 + if(!EMAIL_RE.test(email)){alert('آدرس ایمیل معتبر وارد کنید.');return;}
126 + if(!pass){alert('رمز عبور را وارد کنید؛ یا «ادامه با کد ایمیل» را بزنید.');return;}
127 + authBusy=true;
128 + try{
129 + const {data,error}=await sb.auth.signInWithPassword({email,password:pass});
130 + if(error)throw error;
131 + await enterApp(data.user);
132 + }catch(err){alert(authMsg(err));}
133 + finally{authBusy=false;}
134 +}
135 +async function signInWithGoogle(){
136 + if(authBusy)return;
137 + authBusy=true;
138 + try{
139 + const {error}=await sb.auth.signInWithOAuth({provider:'google',options:{redirectTo:window.location.origin+window.location.pathname,queryParams:{prompt:'select_account'}}});
140 + if(error)throw error;
141 + }catch(err){authBusy=false;alert(authMsg(err));}
142 +}
143 +async function startEmailOtp(isResend){
144 + if(authBusy)return;
145 + const email=normalizeEmail(isResend===true?otpEmail:document.getElementById('auth-email').value);
146 + if(!EMAIL_RE.test(email)){alert('آدرس ایمیل معتبر وارد کنید.');return;}
147 + if(Date.now()<otpCooldownUntil){alert('لطفاً حدود یک دقیقه بین درخواست‌ها صبر کنید.');return;}
148 + authBusy=true;
149 + try{
150 + const {error}=await sb.auth.signInWithOtp({email,options:{shouldCreateUser:true}});
151 + if(error)throw error;
152 + otpEmail=email;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;}
158 +}
159 +async function verifyEmailOtp(){
160 + if(authBusy)return;
161 + const token=toEnDigits(document.getElementById('auth-otp').value).replace(/\s/g,'');
162 + if(!OTP_RE.test(token)){alert('کد را فقط با عدد و کامل وارد کنید.');return;}
163 + authBusy=true;
164 + try{
165 + const {data,error}=await sb.auth.verifyOtp({email:otpEmail,token,type:'email'});
166 + if(error)throw error;
167 + const u=data.user;
168 + const hasPassword=!!(u&&u.user_metadata&&u.user_metadata.has_password===true);
169 + if(!hasPassword){
170 + pendingAuthUser=u;
171 + document.getElementById('auth-newpass').value='';
172 + document.getElementById('auth-newpass2').value='';
173 + showAuthPanel('setpass');
174 + return;
175 + }
176 + await enterApp(u);
177 + }catch(err){alert(authMsg(err));}
178 + finally{authBusy=false;}
179 +}
180 +async function saveNewPassword(){
181 + if(authBusy)return;
182 + const p1=document.getElementById('auth-newpass').value;
183 + const p2=document.getElementById('auth-newpass2').value;
184 + if(p1.length<8){alert('رمز عبور باید حداقل ۸ کاراکتر باشد.');return;}
185 + if(p1!==p2){alert('تکرار رمز عبور با رمز اصلی یکی نیست.');return;}
186 + authBusy=true;
187 + try{
188 + const {data,error}=await sb.auth.updateUser({password:p1,data:{has_password:true}});
189 + if(error)throw error;
190 + const u=(data&&data.user)||pendingAuthUser;
191 + pendingAuthUser=null;
192 + alert('رمز عبور ذخیره شد. دفعات بعد می‌توانید با ایمیل و رمز وارد شوید.');
193 + await enterApp(u);
194 + }catch(err){alert(authMsg(err));}
195 + finally{authBusy=false;}
196 +}
197 +async function skipSetPassword(){
198 + if(authBusy||!pendingAuthUser)return;
199 + const u=pendingAuthUser;pendingAuthUser=null;
200 + authBusy=true;
201 + try{await enterApp(u);}finally{authBusy=false;}
202 +}
203 +async function enterApp(authUser){
204 + try{
205 + currentUser=await fetchCurrentUser(authUser);
206 + await pullAll();
207 + }catch(err){
208 + console.error(err);
209 + currentUser=null;
210 + alert('خطا در بارگذاری اطلاعات حساب. اتصال اینترنت را بررسی کنید و دوباره وارد شوید.');
211 + document.getElementById('auth-screen').style.display='flex';
212 + showAuthPanel('main');
213 + return;
214 + }
215 + document.getElementById('auth-screen').style.display='none';
216 + document.getElementById('logged-user-label').innerText='کاربر: '+(currentUser.fullName||currentUser.email||currentUser.username)+(currentUser.role==='admin'?' (مدیر سیستم)':'');
217 + document.getElementById('menu-admin-panel').style.display=(currentUser.role==='admin')?'block':'none';
218 + refreshAllSurfaces();
219 + maybeMigrateLegacyData();
220 +}
221 +async function handleLogout(){
222 + if(syncPending&&!confirm('تغییرات ذخیره‌نشده وجود دارد. با خروج ممکن است از بین برود. خارج شوم؟'))return;
223 + try{await sb.auth.signOut();}catch(e){}
224 + window.location.reload();
225 +}
226 +
227 +function updateLicenseDisplay(user){
228 + if(!user)return;
229 + const badge=document.getElementById('user-license-status-badge');
230 + const detailsBox=document.getElementById('dashboard-license-details');
231 + if(detailsBox){detailsBox.style.display='none';detailsBox.innerHTML='';}
232 + const sub=user.subscription||{type:user.subscriptionType||'trial',startDate:user.subscriptionStart||user.createdAt,endDate:user.subscriptionEnd,status:user.licenseStatus||'trial'};
233 + const remDays=getRemainingDays(sub.endDate);
234 + const isExpired=remDays<=0&&sub.type!=='lifetime';
235 + const hasActiveLicense=(sub.status==='active')&&(sub.type==='lifetime'||!isExpired)&&(sub.type!=='trial');
236 + if(!badge)return;
237 + if(hasActiveLicense){
238 + badge.className='badge badge-success';
239 + badge.innerText=(sub.type==='lifetime')?'وضعیت اشتراک : نامحدود':`وضعیت اشتراک : تا تاریخ ${formatToJalali(sub.endDate)}`;
240 + }else if(isExpired||sub.status==='cancelled'){
241 + badge.className='badge badge-danger';badge.innerText='وضعیت اشتراک : منقضی شده';
242 + }else{
243 + badge.className='badge badge-warning';badge.innerText=`وضعیت اشتراک : آزمایشی تا تاریخ ${formatToJalali(sub.endDate)}`;
244 + }
245 +}
js/sync.js new
+191
@@ -0,0 +1,191 @@
1 +let datastore={companies:[],contacts:[],products:[],invoices:[],cheques:[],expenses:[],settings:[]};
2 +function getMyProducts(){return !currentUser?[]:datastore.products.filter(p=>p.ownerUserId===currentUser.id);}
3 +function getMyContacts(){return !currentUser?[]:datastore.contacts.filter(c=>c.ownerUserId===currentUser.id);}
4 +function getMyCompanies(){return !currentUser?[]:datastore.companies.filter(c=>c.ownerUserId===currentUser.id);}
5 +function getMyInvoices(){return !currentUser?[]:datastore.invoices.filter(i=>i.ownerUserId===currentUser.id);}
6 +function getMyCheques(){return !currentUser?[]:datastore.cheques.filter(c=>c.ownerUserId===currentUser.id);}
7 +function getMyExpenses(){return !currentUser?[]:datastore.expenses.filter(e=>e.ownerUserId===currentUser.id);}
8 +function getMySettings(){
9 + if(!currentUser)return{invoice_kind:'non_formal',vat_mode:'none',vat_rate:10,default_company_id:'',currency_mode:'rial',currency_custom:''};
10 + if(!Array.isArray(datastore.settings))datastore.settings=[];
11 + let s=datastore.settings.find(item=>item.ownerUserId===currentUser.id);
12 + if(!s){s={ownerUserId:currentUser.id,invoice_kind:'non_formal',vat_mode:'none',vat_rate:10,default_company_id:'',currency_mode:'rial',currency_custom:''};datastore.settings.push(s);}
13 + if(typeof s.currency_mode==='undefined')s.currency_mode='rial';
14 + if(typeof s.currency_custom==='undefined')s.currency_custom='';
15 + return s;
16 +}
17 +// ---------- Cloud data layer (Supabase). UI code keeps using `datastore`; this layer syncs it. ----------
18 +const syncSnap=new Map();
19 +let syncTimer=null,syncRunning=false,syncAgain=false,syncPending=false,syncFailCount=0;
20 +
21 +function keyOfRecord(coll,item){return coll==='settings'?'main':String(item&&item.id!=null?item.id:'');}
22 +function stripOwner(item){const c=Object.assign({},item);delete c.ownerUserId;return c;}
23 +function setSyncBadge(state){
24 + const el=document.getElementById('sync-badge');if(!el)return;
25 + const map={saved:['✔ ذخیره شد','#059669'],saving:['⏳ در حال ذخیره…','#d97706'],error:['⚠️ ذخیره نشد؛ تلاش مجدد…','#dc2626']};
26 + const m=map[state];if(!m)return;
27 + el.textContent=m[0];el.style.background=m[1];el.style.display='block';
28 + clearTimeout(setSyncBadge._t);
29 + if(state==='saved')setSyncBadge._t=setTimeout(()=>{el.style.display='none';},2000);
30 +}
31 +async function pullAll(){
32 + const uid=currentUser.id;
33 + const fresh={};COLLS.forEach(k=>{fresh[k]=[];});
34 + const snap=new Map();
35 + const page=1000;let from=0;
36 + for(;;){
37 + const {data,error}=await sb.from('records').select('collection,id,data').order('collection').order('id').range(from,from+page-1);
38 + if(error)throw error;
39 + (data||[]).forEach(r=>{
40 + if(!fresh[r.collection])return;
41 + const obj=(r.data&&typeof r.data==='object'&&!Array.isArray(r.data))?r.data:{};
42 + obj.id=r.id;
43 + snap.set(r.collection+'|'+r.id,JSON.stringify(stripOwner(obj)));
44 + obj.ownerUserId=uid;
45 + fresh[r.collection].push(obj);
46 + });
47 + if(!data||data.length<page)break;
48 + from+=page;
49 + }
50 + datastore=fresh;
51 + syncSnap.clear();snap.forEach((v,k)=>syncSnap.set(k,v));
52 +}
53 +function computeDiff(){
54 + const uid=currentUser.id;const up=[];const seen=new Set();
55 + COLLS.forEach(coll=>{(datastore[coll]||[]).forEach(item=>{
56 + if(!item||item.ownerUserId!==uid)return;
57 + const id=keyOfRecord(coll,item);
58 + if(!ID_RE.test(id)){console.warn('skipped record with invalid id',coll,id);return;}
59 + const key=coll+'|'+id;seen.add(key);
60 + const payload=stripOwner(item);const s=JSON.stringify(payload);
61 + if(syncSnap.get(key)!==s)up.push({key,coll,id,payload,s});
62 + });});
63 + const del=[];syncSnap.forEach((v,k)=>{if(!seen.has(k))del.push(k);});
64 + return {up,del};
65 +}
66 +function scheduleSync(ms){clearTimeout(syncTimer);syncTimer=setTimeout(runSync,ms);}
67 +async function runSync(){
68 + if(!currentUser)return;
69 + if(syncRunning){syncAgain=true;return;}
70 + syncRunning=true;
71 + try{
72 + let guardLoops=0;
73 + do{
74 + syncAgain=false;
75 + const {up,del}=computeDiff();
76 + if(up.length===0&&del.length===0)break;
77 + setSyncBadge('saving');
78 + for(let i=0;i<up.length;i+=200){
79 + const chunk=up.slice(i,i+200);
80 + const {error}=await sb.from('records').upsert(chunk.map(r=>({owner_id:currentUser.id,collection:r.coll,id:r.id,data:r.payload})),{onConflict:'owner_id,collection,id'});
81 + if(error)throw error;
82 + chunk.forEach(r=>syncSnap.set(r.key,r.s));
83 + }
84 + const byColl={};
85 + del.forEach(k=>{const j=k.indexOf('|');const c=k.slice(0,j),id=k.slice(j+1);(byColl[c]=byColl[c]||[]).push(id);});
86 + for(const c of Object.keys(byColl)){
87 + const ids=byColl[c];
88 + for(let i=0;i<ids.length;i+=100){
89 + const part=ids.slice(i,i+100);
90 + const {error}=await sb.from('records').delete().eq('collection',c).in('id',part);
91 + if(error)throw error;
92 + part.forEach(id=>syncSnap.delete(c+'|'+id));
93 + }
94 + }
95 + syncFailCount=0;
96 + guardLoops++;
97 + }while(guardLoops<5);
98 + const d=computeDiff();
99 + syncPending=(d.up.length>0||d.del.length>0);
100 + if(syncPending){scheduleSync(500);}else{setSyncBadge('saved');}
101 + }catch(err){
102 + console.error('sync error',err);
103 + await handleSyncError(err);
104 + }finally{syncRunning=false;}
105 +}
106 +async function handleSyncError(err){
107 + const msg=String((err&&err.message)||'');
108 + if((err&&err.code==='42501')||/row-level security/i.test(msg)){
109 + setSyncBadge('error');
110 + syncPending=false;
111 + alert('اشتراک شما منقضی یا لغو شده است؛ تغییرات ثبت نشد. برای تمدید با پشتیبانی تماس بگیرید.');
112 + try{currentUser=await fetchCurrentUser({id:currentUser.id});await pullAll();}catch(e){console.error(e);}
113 + refreshAllSurfaces();
114 + return;
115 + }
116 + syncFailCount++;syncPending=true;setSyncBadge('error');
117 + scheduleSync(Math.min(30000,2000*syncFailCount));
118 +}
119 +function saveDatastore(){
120 + if(!currentUser)return false;
121 + if(!canWrite()){
122 + requireWrite();
123 + pullAll().then(()=>refreshAllSurfaces()).catch(()=>{});
124 + return false;
125 + }
126 + syncPending=true;setSyncBadge('saving');scheduleSync(300);
127 + return true;
128 +}
129 +window.addEventListener('beforeunload',e=>{if(syncPending){e.preventDefault();e.returnValue='';}});
130 +document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='hidden'&&syncPending){clearTimeout(syncTimer);runSync();}});
131 +
132 +// ---------- Untrusted input handling (backup files, legacy local data) ----------
133 +function neutralize(v){
134 + if(typeof v==='string')return v.replace(/</g,'<').replace(/>/g,'>');
135 + if(Array.isArray(v))return v.map(neutralize);
136 + if(v&&typeof v==='object'){const o={};Object.keys(v).forEach(k=>{if(k==='__proto__'||k==='constructor'||k==='prototype')return;o[k]=neutralize(v[k]);});return o;}
137 + return v;
138 +}
139 +function safeId(raw,prefix){
140 + let s=String(raw==null?'':raw).replace(/[^A-Za-z0-9_-]/g,'_').slice(0,64);
141 + if(!s)s=prefix+'_'+Date.now().toString(36)+Math.random().toString(36).slice(2,6);
142 + return s;
143 +}
144 +function absorbRecords(imported){
145 + const uid=currentUser.id;let count=0;
146 + ['companies','contacts','products','invoices','cheques','expenses'].forEach(key=>{
147 + if(!Array.isArray(imported[key]))return;
148 + imported[key].forEach(raw=>{
149 + if(!raw||typeof raw!=='object')return;
150 + const item=neutralize(raw);
151 + item.id=safeId(item.id,key.slice(0,3));
152 + item.ownerUserId=uid;
153 + const idx=datastore[key].findIndex(x=>x.id===item.id&&x.ownerUserId===uid);
154 + if(idx>=0)datastore[key][idx]=item;else datastore[key].push(item);
155 + count++;
156 + });
157 + });
158 + if(imported.settings&&typeof imported.settings==='object'&&!Array.isArray(imported.settings)){
159 + const s=getMySettings();Object.assign(s,neutralize(imported.settings),{ownerUserId:uid,id:'main'});
160 + }
161 + return count;
162 +}
163 +function maybeMigrateLegacyData(){
164 + try{
165 + const flag='finora_legacy_done_'+currentUser.id;
166 + if(localStorage.getItem(flag))return;
167 + const rawOld=localStorage.getItem(STORAGE_KEY);
168 + if(!rawOld)return;
169 + let old;try{old=JSON.parse(rawOld);}catch(e){return;}
170 + const isSeed=it=>it&&it.ownerUserId==='user_admin'&&['COMP-1','C-1','P-1','P-2'].includes(it.id);
171 + const clean={};let n=0;
172 + ['companies','contacts','products','invoices','cheques','expenses'].forEach(k=>{
173 + clean[k]=(old&&Array.isArray(old[k])?old[k]:[]).filter(it=>!isSeed(it));
174 + n+=clean[k].length;
175 + });
176 + if(n===0){localStorage.setItem(flag,'1');return;}
177 + if(!confirm('اطلاعات ذخیره‌شده‌ی نسخه‌ی قبلی در این مرورگر پیدا شد ('+n+' مورد). به حساب ابری شما منتقل شود؟')){return;}
178 + if(!requireWrite())return;
179 + absorbRecords(clean);
180 + saveDatastore();refreshAllSurfaces();
181 + localStorage.setItem(flag,'1');
182 + alert('اطلاعات قبلی به حساب ابری منتقل شد. نسخه‌ی محلی روی این مرورگر دست‌نخورده باقی می‌ماند.');
183 + }catch(e){console.error(e);}
184 +}
185 +function initDatastore(){refreshAllSurfaces();}
186 +
187 +function getJalaliDate(){return new Intl.DateTimeFormat('fa-IR-u-ca-persian',{dateStyle:'full'}).format(new Date());}
188 +function getJalaliNumeric(){return new Intl.DateTimeFormat('fa-IR-u-ca-persian',{year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());}
189 +function getCurrencyLabel(){const s=getMySettings();if(s.currency_mode==='toman')return 'تومان';if(s.currency_mode==='custom')return (s.currency_custom||'').trim()||'واحد پول';return 'ریال';}
190 +function refreshCurrencyLabels(){const label=getCurrencyLabel();document.querySelectorAll('.cur-label').forEach(el=>{el.innerText=label;});}
191 +function handleCurrencyModeChange(){const mode=document.getElementById('def-currency-mode').value;document.getElementById('box-currency-custom').style.display=(mode==='custom')?'block':'none';}
js/ui.js new
+57
@@ -0,0 +1,57 @@
1 +function switchView(viewId){
2 + document.querySelectorAll('.view-pane').forEach(el=>el.classList.remove('active'));
3 + const target=document.getElementById(viewId);
4 + if(target)target.classList.add('active');
5 + document.querySelectorAll('.nav-link').forEach(btn=>btn.classList.toggle('active',btn.getAttribute('data-view')===viewId));
6 + const dockViews=['view-dashboard','view-invoices','view-products','view-contacts','view-cheques','view-settings'];
7 + document.querySelectorAll('.dock-tab').forEach((dock,idx)=>{dock.classList.toggle('active',dockViews[idx]===viewId);});
8 + if(viewId==='view-admin')renderAdminPanel();
9 + if(viewId==='view-reports')renderFinancialReports();
10 + window.scrollTo({top:0,behavior:'smooth'});
11 +}
12 +function toggleAccordion(headerEl){headerEl.parentElement.classList.toggle('open');}
13 +function refreshAllSurfaces(){
14 + const dashDate=document.getElementById('dashboard-date-display');
15 + if(dashDate)dashDate.innerText=getJalaliDate();
16 + const invDate=document.getElementById('invoice-date-input');
17 + if(invDate&&!invDate.value)invDate.value=getJalaliNumeric();
18 + updateLicenseDisplay(currentUser);
19 + renderCompanies();renderContacts();renderProducts();renderInvoices();
20 + renderDashboard();renderCheques();renderExpenses();
21 + applyDefaultSettingsToForm();
22 + handleContactEntityChange();
23 + handleCurrencyModeChange();
24 + refreshCurrencyLabels();
25 +}
26 +function formatEntityName(rawName,entityType,customPrefix=''){
27 + let trimmed=(rawName||'').trim();
28 + if(entityType==='legal'){
29 + if(!trimmed.startsWith('شرکت')&&!trimmed.startsWith('موسسه')&&!trimmed.startsWith('سازمان')&&!trimmed.startsWith('اداره'))trimmed='شرکت '+trimmed;
30 + }else if(entityType==='natural'&&customPrefix){
31 + if(!trimmed.startsWith(customPrefix))trimmed=customPrefix+' '+trimmed;
32 + }
33 + return trimmed;
34 +}
35 +function applyEntityTypeToForm(entity,opts){
36 + const {prefixId,nameId,econId,regId,nationalLabelId}=opts;
37 + const prefixBox=document.getElementById(prefixId);
38 + const nameBox=document.getElementById(nameId);
39 + const econBox=document.getElementById(econId);
40 + const regBox=document.getElementById(regId);
41 + const natLabel=document.getElementById(nationalLabelId);
42 + if(entity==='legal'){
43 + if(prefixBox)prefixBox.style.display='none';
44 + if(nameBox)nameBox.style.gridColumn='span 3';
45 + if(econBox)econBox.style.display='block';
46 + if(regBox)regBox.style.display='block';
47 + if(natLabel)natLabel.innerText='شناسه ملی';
48 + }else{
49 + if(prefixBox)prefixBox.style.display='block';
50 + if(nameBox)nameBox.style.gridColumn='span 2';
51 + if(econBox)econBox.style.display='none';
52 + if(regBox)regBox.style.display='none';
53 + if(natLabel)natLabel.innerText='کد ملی';
54 + }
55 +}
56 +function handleContactEntityChange(){const el=document.getElementById('contact-entity-type');if(!el)return;applyEntityTypeToForm(el.value,{prefixId:'box-contact-prefix',nameId:'box-contact-name',econId:'box-contact-economic',regId:'box-contact-reg',nationalLabelId:'label-contact-national'});}
57 +function handleQuickCEntityChange(){const el=document.getElementById('quick-c-entity');if(!el)return;applyEntityTypeToForm(el.value,{prefixId:'box-quick-c-prefix',nameId:'box-quick-c-name',econId:'box-quick-c-economic',regId:'box-quick-c-reg',nationalLabelId:'label-quick-c-national'});}