سامانه صدور فاکتور و حسابداری
feat: automate accounting dimensions and product coding
Davood Mehraban committed
Oct 7, 2026 at 21:46 UTC
985439e0111edd938214d0523a5867c89c8139aa
9 files changed
+49
-21
PROJECT_STATE.md
+1
-1
@@ -15,7 +15,7 @@ This is high-assurance accounting/ERP software. Posted financial history, tenant
15
The latest user message is the sole source of new instructions. Read AGENTS.md then PROJECT_STATE.md in full; verify live main/head/recent commits/CI and Supabase migrations/RLS before implementation; reconcile discrepancies first. Record each request before implementation and update this file in the same commit as every durable change. Work in verified vertical slices. CI success alone is not completion: real-DOM smoke and accounting-invariant tests must pass; unrun checks are NOT VERIFIED. Every Supabase migration must be archived under supabase/migrations/. Ask the owner before schema/RLS/auth/role changes or destructive data operations; older standing approvals below do not override this requirement. Final reports: Persian, approximately 15 lines maximum, evidence SHAs/run IDs, unverified work and next step. This request authorizes verification and reconciliation; older backlog entries are context, not new implementation instructions.
16
17
## Current change ledger
18
-| 2026-10-07 | Owner requested accounting/product usability refinement from live screenshots: automatic non-user-entered floating-detail codes, contextual in-product guides (especially accounting/chart/dimensions), remove duplicate product internal tax ID and use product code as internal item ID, strengthen in-control product/person search, introduce hierarchical product group/subgroup coding with deterministic 6-digit product codes, and keep sale/purchase commercial-document workspace layout stable while only semantic fields change. | **REQUEST RECORDED / IMPLEMENTATION STARTED** | Baseline main = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`. No destructive data rewrite authorized: existing product/floating codes must remain stable; new automatic coding is additive/default behavior. |
18
+| 2026-10-07 | Owner requested accounting/product usability refinement from live screenshots: automatic non-user-entered floating-detail codes, contextual in-product guides (especially accounting/chart/dimensions), remove duplicate product internal tax ID and use product code as internal item ID, strengthen in-control product/person search, introduce hierarchical product group/subgroup coding with deterministic 6-digit product codes, and keep sale/purchase commercial-document workspace layout stable while only semantic fields change. | **IMPLEMENTED / LOCAL VERIFICATION PASSED / CI PENDING** | Baseline main = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`. Automatic dimension type/value codes, contextual guides, product-code-as-internal-ID, normalized multi-token search, and additive six-digit product coding implemented. Existing historical codes preserved. Local syntax/static/commerce/UX/accounting phases 2–6/Golden checks passed; Real-DOM and protected-branch CI remain pending. |
19
20
| Date | Request / decision | Status | Evidence / next action |
21
|---|---|---|---|
index.html
+6
-5
@@ -519,7 +519,7 @@ body{background:#f6f9fc}
519
<section id="view-products" class="view-pane">
520
<div class="card no-print">
521
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:10px">
522
-<h2 style="font-size:17px">تعریف کالا / خدمت جدید</h2>
522
+<div style="display:flex;align-items:center;gap:8px"><h2 style="font-size:17px">تعریف کالا / خدمت جدید</h2><button type="button" class="btn btn-secondary btn-inline" onclick="finoraShowGuide('products')">؟ راهنما</button></div>
523
<div style="display:flex;gap:8px">
524
<label class="btn btn-secondary btn-inline" style="min-height:36px;padding:4px 12px;font-size:13px">📥 ورود از اکسل<input type="file" id="excel-import-products" style="display:none" onchange="importProductsFromExcel(event)" accept=".xlsx, .xls" /></label>
525
<button class="btn btn-secondary btn-inline" style="min-height:36px;padding:4px 12px;font-size:13px" onclick="downloadProductsExcelTemplate()">📄 نمونه اکسل</button>
@@ -533,14 +533,14 @@ body{background:#f6f9fc}
533
</div>
534
<div class="form-row">
535
<div class="form-group"><label>نوع</label><select id="prod-type-input" class="form-control"><option value="good">کالا (انبارشونده)</option><option value="service">خدمت (غیرانبارشونده)</option></select></div>
536
-<div class="form-group"><label>گروه / دسته</label><input type="text" id="prod-category-input" class="form-control" /></div>
536
+<div class="form-group"><label>گروه / دسته</label><input type="text" id="prod-category-input" class="form-control" list="prod-category-list" placeholder="مثلاً مصالح ساختمانی"><datalist id="prod-category-list"></datalist></div>
537
<div class="form-group"><label>بارکد</label><input type="text" id="prod-barcode-input" class="form-control" /></div>
538
<div class="form-group"><label>حداقل موجودی</label><input type="text" id="prod-min-stock-input" class="form-control" value="0" /></div>
539
</div>
540
<div class="form-row">
541
<div class="form-group"><label>قیمت خرید (<span class="cur-label">ریال</span>)</label><input type="text" inputmode="decimal" id="prod-buy-input" class="form-control" value="0" oninput="handleMoneyInput(this)" /></div>
542
<div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="text" inputmode="decimal" id="prod-sale-input" class="form-control" value="0" oninput="handleMoneyInput(this)" /></div>
543
-<div class="form-group"><label>شناسه کالا/خدمت داخلی</label><input type="text" id="prod-internal-id-input" class="form-control" placeholder="2330004169617" /><small style="color:var(--text-muted)">در سند الکترونیکی بهصورت خودکار استفاده میشود.</small></div><div class="form-group"><label>شناسه کالا/خدمت سامانه مالیاتی (خارجی)</label><input type="text" id="prod-official-id-input" class="form-control" placeholder="در صورت وجود ثبت کنید" /><small style="color:var(--text-muted)">اگر خالی باشد هنگام صدور سند الکترونیکی دریافت میشود.</small></div>
543
+<div class="form-group"><label>شناسه کالا/خدمت سامانه مالیاتی (خارجی)</label><input type="text" id="prod-official-id-input" class="form-control" placeholder="در صورت وجود ثبت کنید" /><small style="color:var(--text-muted)">اگر خالی باشد هنگام صدور سند الکترونیکی دریافت میشود.</small></div>
544
</div>
545
<div style="display:flex;gap:8px;flex-wrap:wrap"><button id="product-save-btn" class="btn btn-success" onclick="commitSaveProduct()">➕ ثبت کالا</button><button id="product-edit-cancel-btn" class="btn btn-secondary" style="display:none" onclick="cancelProductEdit()">انصراف از اصلاح</button></div>
546
</div>
@@ -797,7 +797,7 @@ body{background:#f6f9fc}
797
<div class="form-row">
798
<div class="form-group"><label>واحد</label><input type="text" id="quick-p-unit" class="form-control" value="عدد" /></div>
799
<div class="form-group"><label>قیمت فروش (<span class="cur-label">ریال</span>)</label><input type="text" inputmode="decimal" id="quick-p-price" class="form-control" value="0" oninput="handleMoneyInput(this)" /></div>
800
-<div class="form-group"><label>شناسه کالا/خدمت داخلی</label><input type="text" id="quick-p-internal-id" class="form-control" /></div><div class="form-group"><label>شناسه کالا/خدمت سامانه مالیاتی</label><input type="text" id="quick-p-official-id" class="form-control" /></div>
800
+<div class="form-group"><label>شناسه کالا/خدمت سامانه مالیاتی</label><input type="text" id="quick-p-official-id" class="form-control" /></div>
801
</div>
802
<div style="display:flex;gap:10px;margin-top:12px">
803
<button class="btn btn-success" onclick="saveQuickProduct()">ذخیره و افزودن</button>
@@ -904,7 +904,8 @@ body{background:#f6f9fc}
904
</style>
905
<script src="js/accounting-foundation.js?v=20261007-p0-r1"></script>
906
<script src="js/journal-engine.js?v=20261007-p0-r1"></script>
907
-<script src="js/accounting-foundation-ui.js?v=20261003-chart-v4"></script>
907
+<script src="js/context-help.js?v=20261007-help-v1"></script>
908
+<script src="js/accounting-foundation-ui.js?v=20261007-guidance-v1"></script>
909
<script src="js/accounting-foundation-render.js?v=20260928-phase2-v1"></script>
910
<script src="js/journal-ui.js?v=20261007-p0-r1"></script>
911
<script src="js/drilldown.js?v=20260928-drill-v10"></script>
js/accounting-foundation-ui.js
+2
-2
@@ -10,8 +10,8 @@ function ensureAccountingFoundationView(){
10
<div class="form-group"><label>حساب والد</label><select id="af-account-parent" class="form-control"></select></div><div style="display:flex;gap:8px;flex-wrap:wrap"><button id="af-account-save-btn" class="btn btn-success" onclick="afSaveAccount()">ثبت حساب</button><button id="af-account-edit-cancel" class="btn btn-secondary" style="display:none" onclick="afCancelAccountEdit()">انصراف از اصلاح</button></div>
11
<div class="table-responsive af-space"><table><thead><tr><th>کد</th><th>عنوان / مسیر</th><th>سطح</th><th>نوع</th><th>نقش سیستمی</th><th>ماهیت</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody id="af-accounts-body"></tbody></table></div></div>
12
<div class="card" data-finora-task="rules"><h3>قواعد تفصیلی شناور</h3><div class="form-row"><div class="form-group"><label>حساب</label><select id="af-rule-account" class="form-control"></select></div><div class="form-group"><label>تفصیلی</label><select id="af-rule-dimension" class="form-control"></select></div><div class="form-group"><label>کاربرد</label><select id="af-rule-app" class="form-control"><option value="required">الزامی</option><option value="optional">اختیاری</option><option value="unavailable">غیرمجاز</option></select></div></div><button class="btn btn-primary" onclick="afSaveRule()">ثبت قاعده</button><div id="af-rules-list" class="af-list"></div></div>
13
- <div class="card" data-finora-task="dimensions"><h3>ابعاد تحلیلی / تفصیلیهای شناور</h3><p class="af-hint">چهار جایگاه سازگار با قرارداد: شناور ۱ شعبه، شناور ۲ طرفحساب، شناور ۳ پروژه، شناور ۴ قرارداد/پیمان. موتور داخلی Generic است و میتوانید ابعاد بیشتری هم تعریف کنید. عمق ساختار بعد از ایجاد اولین مقدار قفل میشود و فقط Leaf نهایی قابل ثبت است.</p><div class="form-row"><div class="form-group"><label>کد</label><input id="af-dim-code" class="form-control"></div><div class="form-group"><label>عنوان</label><input id="af-dim-title" class="form-control"></div><div class="form-group"><label>منبع</label><select id="af-dim-source" class="form-control"><option value="manual">دستی</option><option value="contact">اشخاص</option><option value="project">پروژهها</option><option value="branch">شعب</option><option value="contract">قرارداد / پیمان</option><option value="costCenter">مرکز هزینه</option></select></div><div class="form-group"><label>عمق ساختار (Hierarchy Depth)</label><input id="af-dim-depth" type="number" min="1" max="8" value="1" class="form-control"></div></div><button class="btn btn-success" onclick="afSaveDimension()">ثبت تفصیلی</button><div id="af-dimensions-list" class="af-list"></div>
14
- <hr><div class="form-row"><div class="form-group"><label>تفصیلی دستی</label><select id="af-value-dim" class="form-control" onchange="renderAccountingFoundation()"></select></div><div class="form-group"><label>کد مقدار</label><input id="af-value-code" class="form-control"></div><div class="form-group"><label>عنوان مقدار</label><input id="af-value-title" class="form-control"></div><div class="form-group"><label>والد / سطح بالاتر</label><select id="af-value-parent" class="form-control"></select></div></div><button class="btn btn-primary" onclick="afSaveDimensionValue()">ثبت مقدار</button><div id="af-values-list" class="af-list"></div></div>
13
+ <div class="card" data-finora-task="dimensions"><div style="display:flex;justify-content:space-between;gap:8px;align-items:center;flex-wrap:wrap"><h3>ابعاد تحلیلی / تفصیلیهای شناور</h3><button type="button" class="btn btn-secondary btn-inline" onclick="finoraShowGuide(\'dimensions\')">؟ راهنمای تخصصی</button></div><p class="af-hint">چهار جایگاه سازگار با قرارداد: شناور ۱ شعبه، شناور ۲ طرفحساب، شناور ۳ پروژه، شناور ۴ قرارداد/پیمان. موتور داخلی Generic است و میتوانید ابعاد بیشتری هم تعریف کنید. کد تفصیلی توسط سیستم و بهترتیب ساخته میشود؛ کاربر فقط عنوان، منبع و ساختار را تعیین میکند.</p><div class="form-row"><div class="form-group"><label>کد سیستمی</label><input id="af-dim-code" class="form-control" value="خودکار" readonly></div><div class="form-group"><label>عنوان</label><input id="af-dim-title" class="form-control"></div><div class="form-group"><label>منبع</label><select id="af-dim-source" class="form-control"><option value="manual">دستی</option><option value="contact">اشخاص</option><option value="project">پروژهها</option><option value="branch">شعب</option><option value="contract">قرارداد / پیمان</option><option value="costCenter">مرکز هزینه</option></select></div><div class="form-group"><label>عمق ساختار (Hierarchy Depth)</label><input id="af-dim-depth" type="number" min="1" max="8" value="1" class="form-control"></div></div><button class="btn btn-success" onclick="afSaveDimension()">ثبت تفصیلی</button><div id="af-dimensions-list" class="af-list"></div>
14
+ <hr><div class="form-row"><div class="form-group"><label>تفصیلی دستی</label><select id="af-value-dim" class="form-control" onchange="renderAccountingFoundation()"></select></div><div class="form-group"><label>کد مقدار</label><input id="af-value-code" class="form-control" value="خودکار" readonly></div><div class="form-group"><label>عنوان مقدار</label><input id="af-value-title" class="form-control"></div><div class="form-group"><label>والد / سطح بالاتر</label><select id="af-value-parent" class="form-control"></select></div></div><button class="btn btn-primary" onclick="afSaveDimensionValue()">ثبت مقدار</button><div id="af-values-list" class="af-list"></div></div>
15
<div class="af-grid" data-finora-task="fiscal branches"><div class="card" data-finora-task="fiscal"><h3>سال مالی</h3><div class="form-group"><label>عنوان</label><input id="af-fy-title" class="form-control"></div><div class="form-row"><div class="form-group"><label>شروع</label><input id="af-fy-start" class="form-control" placeholder="1405/01/01"></div><div class="form-group"><label>پایان</label><input id="af-fy-end" class="form-control" placeholder="1405/12/29"></div></div><button class="btn btn-success" onclick="afSaveFiscal()">ثبت</button><div id="af-fiscal-list" class="af-list"></div></div>
16
<div class="card" data-finora-task="branches"><h3>شعب</h3><div class="form-row"><div class="form-group"><label>کد</label><input id="af-branch-code" class="form-control"></div><div class="form-group"><label>نام</label><input id="af-branch-name" class="form-control"></div></div><button class="btn btn-success" onclick="afSaveBranch()">ثبت</button><div id="af-branches-list" class="af-list"></div></div></div>
17
<div class="card" data-finora-task="projects"><h3>پروژههای سراسری</h3><p class="af-hint">پروژه یکبار تعریف و به چند طرفحساب متصل میشود.</p><div class="form-row"><div class="form-group"><label>کد</label><input id="af-project-code" class="form-control"></div><div class="form-group"><label>نام</label><input id="af-project-name" class="form-control"></div><div class="form-group"><label>والد</label><select id="af-project-parent" class="form-control"></select></div><div class="form-group"><label>شعبه</label><select id="af-project-branch" class="form-control"></select></div></div><div class="form-group"><label>طرفحسابهای مرتبط</label><select id="af-project-contacts" class="form-control" multiple size="4"></select></div><button class="btn btn-success" onclick="afSaveProject()">ثبت پروژه</button><div id="af-projects-list" class="af-list"></div></div>`;
js/accounting-foundation.js
+4
-2
@@ -179,7 +179,9 @@ function afSaveAccount(){
179
function afDeleteAccount(id){if(!requireWrite())return;if((datastore.journalLines||[]).some(x=>x.accountId===id))return alert('این حساب در دفتر حسابداری استفاده شده و قابل حذف نیست؛ فقط غیرفعالسازی مجاز است.');if((datastore.postingProfiles||[]).some(x=>x.debitAccountId===id||x.creditAccountId===id))return alert('این حساب در پروفایل ثبت خودکار استفاده شده و قابل حذف نیست. ابتدا پروفایل مرتبط را جایگزین کنید.');if(getMyAccounts().some(x=>x.parentId===id))return alert('حساب دارای زیرحساب است.');if(getMyAccountDimensionRules().some(x=>x.accountId===id))return alert('ابتدا قواعد تفصیلی حساب را حذف کنید.');if(confirm('حساب حذف شود؟')){datastore.accounts=datastore.accounts.filter(x=>x.id!==id);saveDatastore();renderAccountingFoundation()}}
180
function afSaveRule(){if(!requireWrite())return;const cid=afNeedCompany(),accountId=document.getElementById('af-rule-account').value,dimensionTypeId=document.getElementById('af-rule-dimension').value,applicability=document.getElementById('af-rule-app').value,a=getMyAccounts().find(x=>x.id===accountId),d=getMyDimensionTypes().find(x=>x.id===dimensionTypeId);if(!cid||!a?.postingAllowed||!d?.active)return alert('حساب ثبتپذیر و تفصیلی فعال انتخاب کنید.');let r=getMyAccountDimensionRules().find(x=>x.accountId===accountId&&x.dimensionTypeId===dimensionTypeId);if(r)r.applicability=applicability;else datastore.accountDimensionRules.push({id:afId('ADR'),ownerUserId:currentUser.id,companyId:cid,accountId,dimensionTypeId,applicability,allowedValuesMode:'all',active:true});saveDatastore();renderAccountingFoundation()}
181
function afDeleteRule(id){if(!requireWrite())return;const rule=getMyAccountDimensionRules().find(x=>x.id===id);if(rule&&(datastore.journalLines||[]).some(l=>l.accountId===rule.accountId))return alert('این حساب دارای سابقه دفتر است؛ تغییر ساختار تفصیلی باید از مسیر نسخهبندی/دوره جدید انجام شود.');datastore.accountDimensionRules=datastore.accountDimensionRules.filter(x=>x.id!==id);saveDatastore();renderAccountingFoundation()}
182
-function afSaveDimension(){if(!requireWrite())return;const cid=afNeedCompany(),code=afCode(document.getElementById('af-dim-code').value).toUpperCase(),title=document.getElementById('af-dim-title').value.trim(),sourceEntity=document.getElementById('af-dim-source').value,maxDepth=Math.max(1,Math.min(8,+document.getElementById('af-dim-depth').value||1));if(!cid||!code||!title)return alert('کد و عنوان الزامی است.');if(getMyDimensionTypes().some(x=>x.code===code))return alert('کد تکراری است.');if(sourceEntity!=='manual'&&maxDepth!==1)return alert('تفصیلی متصل به داده پایه در این فاز عمق ۱ دارد؛ برای ساختار چندسطحی نوع «دستی» را انتخاب کنید.');datastore.dimensionTypes.push({id:afId('DIM'),ownerUserId:currentUser.id,companyId:cid,code,title,maxDepth,depthLocked:false,leafOnlyPosting:true,active:true,sourceType:sourceEntity==='manual'?'manual':'entity-backed',sourceEntity});saveDatastore();renderAccountingFoundation()}
182
+function afNextDimensionCode(){const used=getMyDimensionTypes().map(x=>String(x.code||'')).filter(x=>/^DIM-\d{3}$/.test(x)).map(x=>Number(x.slice(4)));return 'DIM-'+String(Math.max(0,...used)+1).padStart(3,'0')}
183
+function afNextDimensionValueCode(dimensionTypeId,parentId=''){const siblings=getMyDimensionValues().filter(x=>x.dimensionTypeId===dimensionTypeId&&String(x.parentId||'')===String(parentId||'')),used=siblings.map(x=>String(x.code||'').split('.').pop()).filter(x=>/^\d+$/.test(x)).map(Number),seq=String(Math.max(0,...used)+1).padStart(3,'0'),parent=parentId?getMyDimensionValues().find(x=>x.id===parentId):null;return parent?.code?parent.code+'.'+seq:seq}
184
+function afSaveDimension(){if(!requireWrite())return;const cid=afNeedCompany(),code=afNextDimensionCode(),title=document.getElementById('af-dim-title').value.trim(),sourceEntity=document.getElementById('af-dim-source').value,maxDepth=Math.max(1,Math.min(8,+document.getElementById('af-dim-depth').value||1));if(!cid||!title)return alert('عنوان تفصیلی الزامی است.');if(getMyDimensionTypes().some(x=>x.code===code))return alert('کد خودکار تکراری شد؛ صفحه را تازهسازی و دوباره تلاش کنید.');if(sourceEntity!=='manual'&&maxDepth!==1)return alert('تفصیلی متصل به داده پایه در این فاز عمق ۱ دارد؛ برای ساختار چندسطحی نوع «دستی» را انتخاب کنید.');datastore.dimensionTypes.push({id:afId('DIM'),ownerUserId:currentUser.id,companyId:cid,code,title,maxDepth,depthLocked:false,leafOnlyPosting:true,active:true,sourceType:sourceEntity==='manual'?'manual':'entity-backed',sourceEntity});saveDatastore();renderAccountingFoundation()}
185
function afChangeDimensionDepth(id){
186
if(!requireWrite())return;const t=getMyDimensionTypes().find(x=>x.id===id);if(!t||t.sourceEntity!=='manual')return alert('عمق تفصیلی متصل به داده پایه ثابت است.');
187
if(afDimensionHasValues(id))return alert('تا وقتی حتی یک مقدار در این تفصیلی وجود دارد، عمق ساختار قابل تغییر نیست. ابتدا مقادیر بدون ارجاع را حذف کنید.');
@@ -190,7 +192,7 @@ function afDeleteDimension(id){
192
if(!requireWrite())return;if(afDimensionHasValues(id))return alert('این تفصیلی دارای مقدار است و قابل حذف نیست.');if(getMyAccountDimensionRules().some(x=>x.dimensionTypeId===id))return alert('این تفصیلی به حسابها متصل است؛ ابتدا قواعد حساب را حذف کنید.');
193
const t=getMyDimensionTypes().find(x=>x.id===id);if(!t)return;if(confirm('تفصیلی «'+t.title+'» حذف شود؟')){datastore.dimensionTypes=datastore.dimensionTypes.filter(x=>x.id!==id);saveDatastore();renderAccountingFoundation()}
194
}
193
-function afSaveDimensionValue(){if(!requireWrite())return;const cid=afNeedCompany(),dimensionTypeId=document.getElementById('af-value-dim').value,t=getMyDimensionTypes().find(x=>x.id===dimensionTypeId);if(!cid||t?.sourceEntity!=='manual')return alert('فقط تفصیلی دستی مقدار مستقل میپذیرد.');const code=afCode(document.getElementById('af-value-code').value),title=document.getElementById('af-value-title').value.trim(),parentId=document.getElementById('af-value-parent').value;let depth=1;if(parentId){const p=getMyDimensionValues().find(x=>x.id===parentId&&x.dimensionTypeId===dimensionTypeId);if(!p)return alert('والد معتبر نیست.');if((p.depth||1)>=Number(t.maxDepth||1))return alert('این گره در آخرین سطح ساختار است و نمیتواند زیرشاخه داشته باشد.');depth=(p.depth||1)+1}if(!code||!title||depth>t.maxDepth)return alert('کد، عنوان یا عمق معتبر نیست.');if(getMyDimensionValues().some(x=>x.dimensionTypeId===dimensionTypeId&&x.code===code))return alert('کد مقدار در این تفصیلی تکراری است.');datastore.dimensionValues.push({id:afId('DV'),ownerUserId:currentUser.id,companyId:cid,dimensionTypeId,code,title,parentId:parentId||'',depth,active:true,createdAt:new Date().toISOString()});t.depthLocked=true;saveDatastore();renderAccountingFoundation()}
195
+function afSaveDimensionValue(){if(!requireWrite())return;const cid=afNeedCompany(),dimensionTypeId=document.getElementById('af-value-dim').value,t=getMyDimensionTypes().find(x=>x.id===dimensionTypeId);if(!cid||t?.sourceEntity!=='manual')return alert('فقط تفصیلی دستی مقدار مستقل میپذیرد.');const title=document.getElementById('af-value-title').value.trim(),parentId=document.getElementById('af-value-parent').value,code=afNextDimensionValueCode(dimensionTypeId,parentId);let depth=1;if(parentId){const p=getMyDimensionValues().find(x=>x.id===parentId&&x.dimensionTypeId===dimensionTypeId);if(!p)return alert('والد معتبر نیست.');if((p.depth||1)>=Number(t.maxDepth||1))return alert('این گره در آخرین سطح ساختار است و نمیتواند زیرشاخه داشته باشد.');depth=(p.depth||1)+1}if(!code||!title||depth>t.maxDepth)return alert('کد، عنوان یا عمق معتبر نیست.');if(getMyDimensionValues().some(x=>x.dimensionTypeId===dimensionTypeId&&x.code===code))return alert('کد مقدار در این تفصیلی تکراری است.');datastore.dimensionValues.push({id:afId('DV'),ownerUserId:currentUser.id,companyId:cid,dimensionTypeId,code,title,parentId:parentId||'',depth,active:true,createdAt:new Date().toISOString()});t.depthLocked=true;saveDatastore();renderAccountingFoundation()}
196
function afDeleteValue(id){if(!requireWrite())return;const v=getMyDimensionValues().find(x=>x.id===id);if(!v)return;if(getMyDimensionValues().some(x=>x.parentId===id))return alert('این مقدار زیرمجموعه دارد.');if(afDimensionValueReferenced(id))return alert('این مقدار در رکورد دیگری استفاده شده و برای حفظ تاریخچه قابل حذف نیست؛ در فاز ثبت اسناد فقط غیرفعالسازی مجاز خواهد بود.');datastore.dimensionValues=datastore.dimensionValues.filter(x=>x.id!==id);const t=getMyDimensionTypes().find(x=>x.id===v.dimensionTypeId);if(t&&!afDimensionHasValues(t.id))t.depthLocked=false;saveDatastore();renderAccountingFoundation()}
197
function afSaveFiscal(){if(!requireWrite())return;const cid=afNeedCompany(),title=document.getElementById('af-fy-title').value.trim(),startDate=toEnDigits(document.getElementById('af-fy-start').value),endDate=toEnDigits(document.getElementById('af-fy-end').value);if(!cid||!title||!/^\d{4}\/\d{2}\/\d{2}$/.test(startDate)||!/^\d{4}\/\d{2}\/\d{2}$/.test(endDate)||startDate>=endDate)return alert('عنوان و بازه تاریخ شمسی معتبر وارد کنید.');if(getMyFiscalYears().some(x=>!(endDate<x.startDate||startDate>x.endDate)))return alert('بازه سال مالی با سال مالی موجود همپوشانی دارد.');datastore.fiscalYears.push({id:afId('FY'),ownerUserId:currentUser.id,companyId:cid,title,startDate,endDate,status:'open',createdAt:new Date().toISOString()});saveDatastore();renderAccountingFoundation()}
198
function afToggleFiscal(id){if(!requireWrite())return;const f=getMyFiscalYears().find(x=>x.id===id);if(!f)return;if(f.status==='locked'&&!confirm('بازکردن دوره مالی یک عملیات کنترلی حساس است. ادامه میدهید؟'))return;f.status=f.status==='locked'?'open':'locked';f.lockedAt=f.status==='locked'?new Date().toISOString():'';saveDatastore();renderAccountingFoundation()}
js/context-help.js
new
+10
@@ -0,0 +1,10 @@
1
+// Finora contextual help — concise, task-oriented guidance embedded in the product.
2
+(function(){
3
+ const GUIDES={
4
+ accounts:{title:'راهنمای کدینگ حسابداری',html:'<p><b>اصل:</b> حساب کل برای گزارش سطح بالا، معین برای تفکیک و حساب ثبتپذیر برای آرتیکل است. طرفحساب، پروژه و قرارداد را با ساختن حساب جداگانه تکثیر نکنید؛ آنها تفصیلی/بعد تحلیلی هستند.</p><ol><li>قالب پیشنهادی متناسب با فعالیت شرکت را مبنا قرار دهید.</li><li>برای حساب ثبتپذیر، ماهیت و نقش سیستمی را فقط وقتی مشخص کنید که کاربرد آن روشن است.</li><li>حسابی که سابقه دفتر دارد حذف یا بازساخت نمیشود؛ برای حفظ تاریخچه غیرفعال میشود.</li></ol>'},
5
+ dimensions:{title:'راهنمای تفصیلی شناور',html:'<p>تفصیلی شناور یعنی یک بُعد مستقل که میتواند زیر حسابهای مجاز استفاده شود؛ مثل طرفحساب، پروژه، قرارداد یا مرکز هزینه.</p><ol><li>کد را سیستم خودکار میسازد؛ شما کد دستی وارد نمیکنید.</li><li>برای اشخاص/پروژه/شعب/قرارداد از منبع متصل استفاده کنید تا یک داده پایه چندبار ساخته نشود.</li><li>تفصیلی دستی فقط برای دستهای است که داده پایه مستقل ندارد. مقدارهای دستی هم کد ترتیبی خودکار میگیرند.</li><li>در «قواعد تفصیلی شناور» مشخص کنید هر حساب کدام بُعد را الزامی، اختیاری یا غیرمجاز میداند.</li></ol>'},
6
+ products:{title:'راهنمای کدینگ کالا و خدمت',html:'<p>کد داخلی کالا همان <b>کد کالا</b> است و در سند الکترونیکی نیز بهعنوان شناسه داخلی استفاده میشود. شناسه سامانه مالیاتی/خارجی مستقل است.</p><p>برای کالاهای جدید، ساختار پیشنهادی ششرقمی است: <b>دو رقم گروه + چهار رقم توالی کالا</b>. مثال: گروه ۱۱ و اولین کالا = ۱۱۰۰۰۱. کدهای تاریخی موجود تغییر نمیکنند.</p><p>در انتخاب کالا داخل فاکتور، همان فیلد انتخاب قابل تایپ است و روی کد، نام، مشخصه، بارکد، گروه و شناسه خارجی جستجو میکند.</p>'},
7
+ invoices:{title:'راهنمای اسناد تجاری',html:'<p>صفحه فاکتورها یک فضای ثابت دارد. با تغییر نوع سند، فقط نقش طرف حساب، انبار، قیمت پیشفرض و قواعد حسابداری تغییر میکنند؛ جای کنترلهای اصلی نباید جابهجا شود.</p><p>فروش از قیمت فروش و خرید از قیمت خرید پیشفرض استفاده میکند. ثبت آخرین معامله میتواند قیمت پیشفرض همان جهت را بهروز کند.</p>'}
8
+ };
9
+ window.finoraShowGuide=function(key){const g=GUIDES[key]||GUIDES.accounts,old=document.getElementById('finora-context-guide');if(old)old.remove();const m=document.createElement('div');m.id='finora-context-guide';m.className='modal-backdrop active';m.innerHTML='<div class="modal-card" style="max-width:720px;line-height:2"><div style="display:flex;justify-content:space-between;gap:10px;align-items:center"><h3>'+g.title+'</h3><button type="button" class="btn btn-secondary btn-inline" onclick="this.closest(\'.modal-backdrop\').remove()">بستن</button></div><div style="margin-top:12px">'+g.html+'</div></div>';document.body.appendChild(m)};
10
+})();
js/invoices.js
+3
-3
@@ -196,7 +196,7 @@ function openElectronicDocModal(){
196
html+=`<div style="border:1px solid var(--border);border-radius:8px;padding:10px;margin-bottom:8px;background:#f8fafc">
197
<div style="font-weight:bold;font-size:13px;margin-bottom:8px">ردیف ${toPersianDigits(idx+1)}: ${prodName||'—'}</div>
198
<div class="form-row">
199
- <div class="form-group" style="margin-bottom:6px"><label style="font-size:12px">شناسه کالا/خدمت داخلی</label><input type="text" class="form-control edoc-row-internal" data-row="${idx}" value="${esc(prod.internal_id||'')}" readonly /><small style="color:var(--text-muted)">از تعریف کالا/خدمت خوانده میشود.</small></div>
199
+ <div class="form-group" style="margin-bottom:6px"><label style="font-size:12px">شناسه کالا/خدمت داخلی</label><input type="text" class="form-control edoc-row-internal" data-row="${idx}" value="${esc(prod.code||'')}" readonly /><small style="color:var(--text-muted)">از تعریف کالا/خدمت خوانده میشود.</small></div>
200
<div class="form-group" style="margin-bottom:6px"><label style="font-size:12px">شناسه کالا/خدمت سامانه مالیاتی <span style="color:var(--danger)">*</span></label><input type="text" class="form-control edoc-row-official" data-row="${idx}" value="${esc(prod.official_id||'')}" /><small style="color:var(--text-muted)">اگر در تعریف کالا ثبت نشده، اینجا تکمیل آن الزامی است.</small></div>
201
</div>
202
</div>`;
@@ -218,7 +218,7 @@ function openElectronicDocModal(){
218
p.items.forEach((it,idx)=>{
219
const intEl=document.querySelector(`.edoc-row-internal[data-row="${idx}"]`);
220
const offEl=document.querySelector(`.edoc-row-official[data-row="${idx}"]`);
221
- if(intEl){const row=document.querySelectorAll('#invoice-items-table-body tr')[idx],sel=row?.querySelector('.row-product-select'),prod=getMyProducts().find(x=>x.id===sel?.value);intEl.value=prod?.internal_id||it.internalId||'';}
221
+ if(intEl){const row=document.querySelectorAll('#invoice-items-table-body tr')[idx],sel=row?.querySelector('.row-product-select'),prod=getMyProducts().find(x=>x.id===sel?.value);intEl.value=prod?.code||it.internalId||'';}
222
if(offEl){const row=document.querySelectorAll('#invoice-items-table-body tr')[idx],sel=row?.querySelector('.row-product-select'),prod=getMyProducts().find(x=>x.id===sel?.value);offEl.value=prod?.official_id||it.officialId||'';}
223
});
224
}
@@ -275,7 +275,7 @@ function saveElectronicDocToPending(){
275
alert(`«شناسه کالا/خدمت» برای ردیف ${toPersianDigits(idx+1)} اجباری است.`);
276
return;
277
}
278
- items.push({internalId:String(prod.internal_id||intEl?.value||'').trim(),officialId:offVal});
278
+ items.push({internalId:String(prod.code||intEl?.value||'').trim(),officialId:offVal});
279
}
280
const p={
281
uniqueNumber:document.getElementById('edoc-unique-number').value.trim(),
js/products.js
+11
-7
@@ -1,4 +1,9 @@
1
let editingProductId='';
2
+function productCategoryKey(v){return String(v||'').trim().replace(/\s+/g,' ').toLowerCase()}
3
+function productGroupCode(category){const key=productCategoryKey(category);if(!key)return '99';const groups=[...new Set(getMyProducts().map(p=>productCategoryKey(p.category)).filter(Boolean))].sort();const idx=groups.indexOf(key);return String(idx>=0?idx+1:groups.length+1).padStart(2,'0').slice(-2)}
4
+function nextProductCode(category){const prefix=productGroupCode(category),used=getMyProducts().map(p=>String(p.code||'')).filter(c=>/^\d{6}$/.test(c)&&c.startsWith(prefix)).map(c=>Number(c.slice(2)));return prefix+String(Math.max(0,...used)+1).padStart(4,'0')}
5
+function refreshProductCategories(){const dl=document.getElementById('prod-category-list');if(dl)dl.innerHTML=[...new Set(getMyProducts().map(p=>p.category).filter(Boolean))].sort().map(x=>'<option value="'+esc(x)+'"></option>').join('')}
6
+window.nextProductCode=nextProductCode;
7
function syncProductDefaultPrices(items,direction){
8
if(!Array.isArray(items))return false;let changed=false;for(const it of items){const id=it.prodId||it.productId,p=getMyProducts().find(x=>x.id===id),price=Number(it.price||it.unitPrice||0);if(!p||price<=0)continue;const key=direction==='purchase'?'buy_price':'sale_price';if(Number(p[key]||0)!==price){p[key]=price;p.priceUpdatedAt=new Date().toISOString();p.priceUpdatedFrom=direction;changed=true}}return changed;
9
}
@@ -6,16 +11,16 @@ function commitSaveProduct(){
11
if(!requireWrite())return;
12
if(!currentUser)return;
13
const myProducts=getMyProducts();
9
- const code=document.getElementById('prod-code-input').value||(myProducts.length+1).toString();
14
+ const category=document.getElementById('prod-category-input')?.value.trim()||'';const requestedCode=document.getElementById('prod-code-input').value.trim(),code=editingProductId?(requestedCode||getMyProducts().find(x=>x.id===editingProductId)?.code||''):(requestedCode||nextProductCode(category));
15
const name=document.getElementById('prod-name-input').value;
16
const spec=document.getElementById('prod-spec-input').value||'';
17
const unit=document.getElementById('prod-unit-input').value||'عدد';
18
const buy_price=parseFormattedNumber(document.getElementById('prod-buy-input').value);
19
const sale_price=parseFormattedNumber(document.getElementById('prod-sale-input').value);
15
- const internal_id=document.getElementById('prod-internal-id-input').value.trim();
20
+ const internal_id=code;
21
const official_id=document.getElementById('prod-official-id-input')?.value.trim()||'';
22
if(!name){alert('عنوان کالا الزامی است.');return;}
18
- const type=document.getElementById('prod-type-input')?.value||'good',category=document.getElementById('prod-category-input')?.value.trim()||'',barcode=document.getElementById('prod-barcode-input')?.value.trim()||'',min_stock=parseFormattedNumber(document.getElementById('prod-min-stock-input')?.value||0);
23
+ const type=document.getElementById('prod-type-input')?.value||'good',barcode=document.getElementById('prod-barcode-input')?.value.trim()||'',min_stock=parseFormattedNumber(document.getElementById('prod-min-stock-input')?.value||0);
24
if(editingProductId){
25
const row=datastore.products.find(x=>x.id===editingProductId&&x.ownerUserId===currentUser.id);if(!row)return alert('کالا/خدمت برای اصلاح یافت نشد.');
26
Object.assign(row,{code,name,spec,type,category,barcode,unit,buy_price,sale_price,min_stock,internal_id,official_id});editingProductId='';alert('کالا/خدمت اصلاح شد.');
@@ -24,7 +29,6 @@ function commitSaveProduct(){
29
if(!editingProductId)alert('کالا ثبت شد.');
30
document.getElementById('prod-name-input').value='';
31
document.getElementById('prod-spec-input').value='';
27
- document.getElementById('prod-internal-id-input').value='';
32
if(document.getElementById('prod-official-id-input'))document.getElementById('prod-official-id-input').value='';
33
cancelProductEdit(false);
34
refreshAllSurfaces();
@@ -55,7 +59,7 @@ function saveQuickProduct(){
59
const spec=document.getElementById('quick-p-spec').value||'';
60
const unit=document.getElementById('quick-p-unit').value||'عدد';
61
const price=parseFormattedNumber(document.getElementById('quick-p-price').value);
58
- const internal_id=document.getElementById('quick-p-internal-id').value||'';
62
+ const internal_id=code;
63
const official_id=document.getElementById('quick-p-official-id')?.value.trim()||'';
64
if(!name){alert('عنوان کالا الزامی است.');return;}
65
const newId='P_'+Date.now();
@@ -100,10 +104,10 @@ function importProductsFromExcel(event){
104
function editProduct(id){
105
const p=getMyProducts().find(x=>x.id===id);if(!p)return;editingProductId=id;
106
const set=(id,v)=>{const e=document.getElementById(id);if(e)e.value=v??''};
103
- set('prod-code-input',p.code);set('prod-name-input',p.name);set('prod-spec-input',p.spec);set('prod-unit-input',p.unit||'عدد');set('prod-type-input',p.type||'good');set('prod-category-input',p.category);set('prod-barcode-input',p.barcode);set('prod-min-stock-input',p.min_stock||0);set('prod-buy-input',p.buy_price||0);set('prod-sale-input',p.sale_price||0);set('prod-internal-id-input',p.internal_id);set('prod-official-id-input',p.official_id);
107
+ set('prod-code-input',p.code);set('prod-name-input',p.name);set('prod-spec-input',p.spec);set('prod-unit-input',p.unit||'عدد');set('prod-type-input',p.type||'good');set('prod-category-input',p.category);set('prod-barcode-input',p.barcode);set('prod-min-stock-input',p.min_stock||0);set('prod-buy-input',p.buy_price||0);set('prod-sale-input',p.sale_price||0);set('prod-official-id-input',p.official_id);
108
const b=document.getElementById('product-save-btn'),c=document.getElementById('product-edit-cancel-btn');if(b)b.textContent='💾 ذخیره اصلاحات';if(c)c.style.display='inline-flex';
109
}
106
-function cancelProductEdit(clear=true){editingProductId='';const b=document.getElementById('product-save-btn'),c=document.getElementById('product-edit-cancel-btn');if(b)b.textContent='➕ ثبت کالا';if(c)c.style.display='none';if(clear){['prod-code-input','prod-name-input','prod-spec-input','prod-category-input','prod-barcode-input','prod-internal-id-input','prod-official-id-input'].forEach(id=>{const e=document.getElementById(id);if(e)e.value=''});}}
110
+function cancelProductEdit(clear=true){editingProductId='';const b=document.getElementById('product-save-btn'),c=document.getElementById('product-edit-cancel-btn');if(b)b.textContent='➕ ثبت کالا';if(c)c.style.display='none';if(clear){['prod-code-input','prod-name-input','prod-spec-input','prod-category-input','prod-barcode-input','prod-official-id-input'].forEach(id=>{const e=document.getElementById(id);if(e)e.value=''});}}
111
function productKardexRows(id){
112
const out=[];const add=(kind,doc,qty,date,number)=>out.push({kind,doc,qty:Number(qty)||0,date:date||'',number:number||''});
113
getMyPurchases().forEach(x=>(x.items||[]).filter(i=>(i.prodId||i.productId)===id).forEach(i=>add('خرید',x.id,i.qty??i.quantity,x.date,x.number)));
js/ux-hardening-r2.js
+2
-1
@@ -13,8 +13,9 @@
13
}catch(_){}
14
return parts.filter(Boolean).join(' ').toLowerCase();
15
}
16
+ function searchNorm(v){return String(v||'').toLowerCase().replace(/[يى]/g,'ی').replace(/ك/g,'ک').replace(/[۰-۹]/g,d=>'۰۱۲۳۴۵۶۷۸۹'.indexOf(d)).replace(/[أإآ]/g,'ا').replace(/\s+/g,' ').trim()}
17
function comboOptions(select,q){
17
- const query=String(q||'').trim().toLowerCase();return [...select.options].filter(o=>o.value).filter(o=>!query||(o.dataset.search||searchMeta(o.value,o.textContent)).includes(query)).slice(0,60);
18
+ const query=searchNorm(q),tokens=query.split(' ').filter(Boolean);return [...select.options].filter(o=>o.value).map(o=>({o,hay:searchNorm(o.dataset.search||searchMeta(o.value,o.textContent))})).filter(x=>!tokens.length||tokens.every(t=>x.hay.includes(t))).sort((a,b)=>{if(!query)return 0;const as=a.hay.startsWith(query)?0:a.hay.includes(' '+query)?1:2,bs=b.hay.startsWith(query)?0:b.hay.includes(' '+query)?1:2;return as-bs}).slice(0,60).map(x=>x.o);
19
}
20
function comboLabel(o){return String(o?.textContent||'').trim()}
21
window.finoraRefreshSearchableSelect=function(select){
scripts/accounting-product-guidance-check.mjs
new
+10
@@ -0,0 +1,10 @@
1
+import fs from'node:fs';function ok(v,m){if(!v)throw new Error(m)}
2
+const html=fs.readFileSync('index.html','utf8'),af=fs.readFileSync('js/accounting-foundation.js','utf8'),ui=fs.readFileSync('js/accounting-foundation-ui.js','utf8'),p=fs.readFileSync('js/products.js','utf8'),inv=fs.readFileSync('js/invoices.js','utf8'),ux=fs.readFileSync('js/ux-hardening-r2.js','utf8'),help=fs.readFileSync('js/context-help.js','utf8');
3
+ok(ui.includes('کد سیستمی')&&ui.includes('value="خودکار" readonly'),'Floating-detail codes must not be user-entered.');
4
+ok(af.includes('afNextDimensionCode')&&af.includes('afNextDimensionValueCode'),'Dimension type/value codes must be generated.');
5
+ok(help.includes('راهنمای تفصیلی شناور')&&help.includes('راهنمای کدینگ کالا و خدمت'),'Contextual accounting/product guidance must exist.');
6
+ok(!html.includes('id="prod-internal-id-input"')&&!html.includes('id="quick-p-internal-id"'),'Duplicate product internal-id inputs must be removed.');
7
+ok(inv.includes("prod.code||intEl?.value"),'Electronic-document internal item ID must derive from product code.');
8
+ok(p.includes('nextProductCode')&&p.includes("padStart(4,'0')"),'New product code generator must use group prefix plus four-digit sequence.');
9
+ok(ux.includes('searchNorm')&&ux.includes('tokens.every'),'Search must normalize Persian/Arabic forms and match all typed fragments.');
10
+console.log('Accounting/product guidance invariants passed.');